
		var WB_USER_IP = "193.136.192.149";
		var WB_DEBUG_MODE = (WB_USER_IP == "192.168.1.140");
		var WB_SAVE_URL = "http://sitepro4.mychrome.pt/pt-BR/save/";
		CKEDITOR_BASEPATH = "http://sitepro4.mychrome.pt/modules/builder/js/lib/ckeditor/";
		;

/** jQuery **/
/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;

return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){
return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
;

/** jQueryBrowser **/
/*!
 * jQuery Browser Plugin 0.1.0
 * https://github.com/gabceb/jquery-browser-plugin
 *
 * Original jquery-browser code Copyright 2005, 2015 jQuery Foundation, Inc. and other contributors
 * http://jquery.org/license
 *
 * Modifications Copyright 2015 Gabriel Cebrian
 * https://github.com/gabceb
 *
 * Released under the MIT license
 *
 * Date: 23-11-2015
 */!function(a){"function"==typeof define&&define.amd?define(["jquery"],function(b){return a(b)}):"object"==typeof module&&"object"==typeof module.exports?module.exports=a(require("jquery")):a(window.jQuery)}(function(a){"use strict";function b(a){void 0===a&&(a=window.navigator.userAgent),a=a.toLowerCase();var b=/(edge)\/([\w.]+)/.exec(a)||/(opr)[\/]([\w.]+)/.exec(a)||/(chrome)[ \/]([\w.]+)/.exec(a)||/(iemobile)[\/]([\w.]+)/.exec(a)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[],c=/(ipad)/.exec(a)||/(ipod)/.exec(a)||/(windows phone)/.exec(a)||/(iphone)/.exec(a)||/(kindle)/.exec(a)||/(silk)/.exec(a)||/(android)/.exec(a)||/(win)/.exec(a)||/(mac)/.exec(a)||/(linux)/.exec(a)||/(cros)/.exec(a)||/(playbook)/.exec(a)||/(bb)/.exec(a)||/(blackberry)/.exec(a)||[],d={},e={browser:b[5]||b[3]||b[1]||"",version:b[2]||b[4]||"0",versionNumber:b[4]||b[2]||"0",platform:c[0]||""};if(e.browser&&(d[e.browser]=!0,d.version=e.version,d.versionNumber=parseInt(e.versionNumber,10)),e.platform&&(d[e.platform]=!0),(d.android||d.bb||d.blackberry||d.ipad||d.iphone||d.ipod||d.kindle||d.playbook||d.silk||d["windows phone"])&&(d.mobile=!0),(d.cros||d.mac||d.linux||d.win)&&(d.desktop=!0),(d.chrome||d.opr||d.safari)&&(d.webkit=!0),d.rv||d.iemobile){var f="msie";e.browser=f,d[f]=!0}if(d.edge){delete d.edge;var g="msedge";e.browser=g,d[g]=!0}if(d.safari&&d.blackberry){var h="blackberry";e.browser=h,d[h]=!0}if(d.safari&&d.playbook){var i="playbook";e.browser=i,d[i]=!0}if(d.bb){var j="blackberry";e.browser=j,d[j]=!0}if(d.opr){var k="opera";e.browser=k,d[k]=!0}if(d.safari&&d.android){var l="android";e.browser=l,d[l]=!0}if(d.safari&&d.kindle){var m="kindle";e.browser=m,d[m]=!0}if(d.safari&&d.silk){var n="silk";e.browser=n,d[n]=!0}return d.name=e.browser,d.platform=e.platform,d}return window.jQBrowser=b(window.navigator.userAgent),window.jQBrowser.uaMatch=b,a&&(a.browser=window.jQBrowser),window.jQBrowser});;

/** Twitter Bootstrap **/
/*!
 * Bootstrap v3.3.5 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */

/*!
 * Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=c877038203e2893857c8)
 * Config saved to config.json and https://gist.github.com/c877038203e2893857c8
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(t){"use strict";var e=t.fn.jquery.split(" ")[0].split(".");if(e[0]<2&&e[1]<9||1==e[0]&&9==e[1]&&e[2]<1||e[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(t){"use strict";function e(e){return this.each(function(){var i=t(this),n=i.data("bs.alert");n||i.data("bs.alert",n=new o(this)),"string"==typeof e&&n[e].call(i)})}var i='[data-dismiss="alert"]',o=function(e){t(e).on("click",i,this.close)};o.VERSION="3.3.6",o.TRANSITION_DURATION=150,o.prototype.close=function(e){function i(){a.detach().trigger("closed.bs.alert").remove()}var n=t(this),s=n.attr("data-target");s||(s=n.attr("href"),s=s&&s.replace(/.*(?=#[^\s]*$)/,""));var a=t(s);e&&e.preventDefault(),a.length||(a=n.closest(".alert")),a.trigger(e=t.Event("close.bs.alert")),e.isDefaultPrevented()||(a.removeClass("in"),t.support.transition&&a.hasClass("fade")?a.one("bsTransitionEnd",i).emulateTransitionEnd(o.TRANSITION_DURATION):i())};var n=t.fn.alert;t.fn.alert=e,t.fn.alert.Constructor=o,t.fn.alert.noConflict=function(){return t.fn.alert=n,this},t(document).on("click.bs.alert.data-api",i,o.prototype.close)}(jQuery),+function(t){"use strict";function e(e){return this.each(function(){var o=t(this),n=o.data("bs.button"),s="object"==typeof e&&e;n||o.data("bs.button",n=new i(this,s)),"toggle"==e?n.toggle():e&&n.setState(e)})}var i=function(e,o){this.$element=t(e),this.options=t.extend({},i.DEFAULTS,o),this.isLoading=!1};i.VERSION="3.3.6",i.DEFAULTS={loadingText:"loading..."},i.prototype.setState=function(e){var i="disabled",o=this.$element,n=o.is("input")?"val":"html",s=o.data();e+="Text",null==s.resetText&&o.data("resetText",o[n]()),setTimeout(t.proxy(function(){o[n](null==s[e]?this.options[e]:s[e]),"loadingText"==e?(this.isLoading=!0,o.addClass(i).attr(i,i)):this.isLoading&&(this.isLoading=!1,o.removeClass(i).removeAttr(i))},this),0)},i.prototype.toggle=function(){var t=!0,e=this.$element.closest('[data-toggle="buttons"]');if(e.length){var i=this.$element.find("input");"radio"==i.prop("type")?(i.prop("checked")&&(t=!1),e.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==i.prop("type")&&(i.prop("checked")!==this.$element.hasClass("active")&&(t=!1),this.$element.toggleClass("active")),i.prop("checked",this.$element.hasClass("active")),t&&i.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var o=t.fn.button;t.fn.button=e,t.fn.button.Constructor=i,t.fn.button.noConflict=function(){return t.fn.button=o,this},t(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(i){var o=t(i.target);o.hasClass("btn")||(o=o.closest(".btn")),e.call(o,"toggle"),t(i.target).is('input[type="radio"]')||t(i.target).is('input[type="checkbox"]')||i.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(e){t(e.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(e.type))})}(jQuery),+function(t){"use strict";function e(e){return this.each(function(){var o=t(this),n=o.data("bs.carousel"),s=t.extend({},i.DEFAULTS,o.data(),"object"==typeof e&&e),a="string"==typeof e?e:s.slide;n||o.data("bs.carousel",n=new i(this,s)),"number"==typeof e?n.to(e):a?n[a]():s.interval&&n.pause().cycle()})}var i=function(e,i){this.$element=t(e),this.$indicators=this.$element.find(".carousel-indicators"),this.options=i,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",t.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",t.proxy(this.pause,this)).on("mouseleave.bs.carousel",t.proxy(this.cycle,this))};i.VERSION="3.3.6",i.TRANSITION_DURATION=600,i.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},i.prototype.keydown=function(t){if(!/input|textarea/i.test(t.target.tagName)){switch(t.which){case 37:this.prev();break;case 39:this.next();break;default:return}t.preventDefault()}},i.prototype.cycle=function(e){return e||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(t.proxy(this.next,this),this.options.interval)),this},i.prototype.getItemIndex=function(t){return this.$items=t.parent().children(".item"),this.$items.index(t||this.$active)},i.prototype.getItemForDirection=function(t,e){var i=this.getItemIndex(e),o="prev"==t&&0===i||"next"==t&&i==this.$items.length-1;if(o&&!this.options.wrap)return e;var n="prev"==t?-1:1,s=(i+n)%this.$items.length;return this.$items.eq(s)},i.prototype.to=function(t){var e=this,i=this.getItemIndex(this.$active=this.$element.find(".item.active"));return t>this.$items.length-1||0>t?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){e.to(t)}):i==t?this.pause().cycle():this.slide(t>i?"next":"prev",this.$items.eq(t))},i.prototype.pause=function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&t.support.transition&&(this.$element.trigger(t.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},i.prototype.next=function(){return this.sliding?void 0:this.slide("next")},i.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},i.prototype.slide=function(e,o){var n=this.$element.find(".item.active"),s=o||this.getItemForDirection(e,n),a=this.interval,r="next"==e?"left":"right",l=this;if(s.hasClass("active"))return this.sliding=!1;var h=s[0],d=t.Event("slide.bs.carousel",{relatedTarget:h,direction:r});if(this.$element.trigger(d),!d.isDefaultPrevented()){if(this.sliding=!0,a&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var p=t(this.$indicators.children()[this.getItemIndex(s)]);p&&p.addClass("active")}var c=t.Event("slid.bs.carousel",{relatedTarget:h,direction:r});return t.support.transition&&this.$element.hasClass("slide")?(s.addClass(e),s[0].offsetWidth,n.addClass(r),s.addClass(r),n.one("bsTransitionEnd",function(){s.removeClass([e,r].join(" ")).addClass("active"),n.removeClass(["active",r].join(" ")),l.sliding=!1,setTimeout(function(){l.$element.trigger(c)},0)}).emulateTransitionEnd(i.TRANSITION_DURATION)):(n.removeClass("active"),s.addClass("active"),this.sliding=!1,this.$element.trigger(c)),a&&this.cycle(),this}};var o=t.fn.carousel;t.fn.carousel=e,t.fn.carousel.Constructor=i,t.fn.carousel.noConflict=function(){return t.fn.carousel=o,this};var n=function(i){var o,n=t(this),s=t(n.attr("data-target")||(o=n.attr("href"))&&o.replace(/.*(?=#[^\s]+$)/,""));if(s.hasClass("carousel")){var a=t.extend({},s.data(),n.data()),r=n.attr("data-slide-to");r&&(a.interval=!1),e.call(s,a),r&&s.data("bs.carousel").to(r),i.preventDefault()}};t(document).on("click.bs.carousel.data-api","[data-slide]",n).on("click.bs.carousel.data-api","[data-slide-to]",n),t(window).on("load",function(){t('[data-ride="carousel"]').each(function(){var i=t(this);e.call(i,i.data())})})}(jQuery),+function(t){"use strict";function e(e){var i=e.attr("data-target");i||(i=e.attr("href"),i=i&&/#[A-Za-z]/.test(i)&&i.replace(/.*(?=#[^\s]*$)/,""));var o=i&&t(i);return o&&o.length?o:e.parent()}function i(i){i&&3===i.which||(t(n).remove(),t(s).each(function(){var o=t(this),n=e(o),s={relatedTarget:this};n.hasClass("open")&&(i&&"click"==i.type&&/input|textarea/i.test(i.target.tagName)&&t.contains(n[0],i.target)||(n.trigger(i=t.Event("hide.bs.dropdown",s)),i.isDefaultPrevented()||(o.attr("aria-expanded","false"),n.removeClass("open").trigger(t.Event("hidden.bs.dropdown",s)))))}))}function o(e){return this.each(function(){var i=t(this),o=i.data("bs.dropdown");o||i.data("bs.dropdown",o=new a(this)),"string"==typeof e&&o[e].call(i)})}var n=".dropdown-backdrop",s='[data-toggle="dropdown"]',a=function(e){t(e).on("click.bs.dropdown",this.toggle)};a.VERSION="3.3.6",a.prototype.toggle=function(o){var n=t(this);if(!n.is(".disabled, :disabled")){var s=e(n),a=s.hasClass("open");if(i(),!a){"ontouchstart"in document.documentElement&&!s.closest(".navbar-nav").length&&t(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(t(this)).on("click",i);var r={relatedTarget:this};if(s.trigger(o=t.Event("show.bs.dropdown",r)),o.isDefaultPrevented())return;n.trigger("focus").attr("aria-expanded","true"),s.toggleClass("open").trigger(t.Event("shown.bs.dropdown",r))}return!1}},a.prototype.keydown=function(i){if(/(38|40|27|32)/.test(i.which)&&!/input|textarea/i.test(i.target.tagName)){var o=t(this);if(i.preventDefault(),i.stopPropagation(),!o.is(".disabled, :disabled")){var n=e(o),a=n.hasClass("open");if(!a&&27!=i.which||a&&27==i.which)return 27==i.which&&n.find(s).trigger("focus"),o.trigger("click");var r=" li:not(.disabled):visible a",l=n.find(".dropdown-menu"+r);if(l.length){var h=l.index(i.target);38==i.which&&h>0&&h--,40==i.which&&h<l.length-1&&h++,~h||(h=0),l.eq(h).trigger("focus")}}}};var r=t.fn.dropdown;t.fn.dropdown=o,t.fn.dropdown.Constructor=a,t.fn.dropdown.noConflict=function(){return t.fn.dropdown=r,this},t(document).on("click.bs.dropdown.data-api",i).on("click.bs.dropdown.data-api",".dropdown form",function(t){t.stopPropagation()}).on("click.bs.dropdown.data-api",s,a.prototype.toggle).on("keydown.bs.dropdown.data-api",s,a.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",a.prototype.keydown)}(jQuery),+function(t){"use strict";function e(e,o){return this.each(function(){var n=t(this),s=n.data("bs.modal"),a=t.extend({},i.DEFAULTS,n.data(),"object"==typeof e&&e);s||n.data("bs.modal",s=new i(this,a)),"string"==typeof e?s[e](o):a.show&&s.show(o)})}var i=function(e,i){this.options=i,this.$body=t(document.body),this.$element=t(e),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,t.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};i.VERSION="3.3.6",i.TRANSITION_DURATION=300,i.BACKDROP_TRANSITION_DURATION=150,i.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},i.prototype.toggle=function(t){return this.isShown?this.hide():this.show(t)},i.prototype.show=function(e){var o=this,n=t.Event("show.bs.modal",{relatedTarget:e});this.$element.trigger(n),this.isShown||n.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',t.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){o.$element.one("mouseup.dismiss.bs.modal",function(e){t(e.target).is(o.$element)&&(o.ignoreBackdropClick=!0)})}),this.backdrop(function(){var n=t.support.transition&&o.$element.hasClass("fade");o.$element.parent().length||o.$element.appendTo(o.$body),o.$element.show().scrollTop(0),o.adjustDialog(),n&&o.$element[0].offsetWidth,o.$element.addClass("in"),o.enforceFocus();var s=t.Event("shown.bs.modal",{relatedTarget:e});n?o.$dialog.one("bsTransitionEnd",function(){o.$element.trigger("focus").trigger(s)}).emulateTransitionEnd(i.TRANSITION_DURATION):o.$element.trigger("focus").trigger(s)}))},i.prototype.hide=function(e){e&&e.preventDefault(),e=t.Event("hide.bs.modal"),this.$element.trigger(e),this.isShown&&!e.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),t(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),t.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",t.proxy(this.hideModal,this)).emulateTransitionEnd(i.TRANSITION_DURATION):this.hideModal())},i.prototype.enforceFocus=function(){t(document).off("focusin.bs.modal").on("focusin.bs.modal",t.proxy(function(t){this.$element[0]===t.target||this.$element.has(t.target).length||this.$element.trigger("focus")},this))},i.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",t.proxy(function(t){27==t.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},i.prototype.resize=function(){this.isShown?t(window).on("resize.bs.modal",t.proxy(this.handleUpdate,this)):t(window).off("resize.bs.modal")},i.prototype.hideModal=function(){var t=this;this.$element.hide(),this.backdrop(function(){t.$body.removeClass("modal-open"),t.resetAdjustments(),t.resetScrollbar(),t.$element.trigger("hidden.bs.modal")})},i.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},i.prototype.backdrop=function(e){var o=this,n=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var s=t.support.transition&&n;if(this.$backdrop=t(document.createElement("div")).addClass("modal-backdrop "+n).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",t.proxy(function(t){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(t.target===t.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),s&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!e)return;s?this.$backdrop.one("bsTransitionEnd",e).emulateTransitionEnd(i.BACKDROP_TRANSITION_DURATION):e()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var a=function(){o.removeBackdrop(),e&&e()};t.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",a).emulateTransitionEnd(i.BACKDROP_TRANSITION_DURATION):a()}else e&&e()},i.prototype.handleUpdate=function(){this.adjustDialog()},i.prototype.adjustDialog=function(){var t=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&t?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!t?this.scrollbarWidth:""})},i.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},i.prototype.checkScrollbar=function(){var t=window.innerWidth;if(!t){var e=document.documentElement.getBoundingClientRect();t=e.right-Math.abs(e.left)}this.bodyIsOverflowing=document.body.clientWidth<t,this.scrollbarWidth=this.measureScrollbar()},i.prototype.setScrollbar=function(){var t=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",t+this.scrollbarWidth)},i.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},i.prototype.measureScrollbar=function(){var t=document.createElement("div");t.className="modal-scrollbar-measure",this.$body.append(t);var e=t.offsetWidth-t.clientWidth;return this.$body[0].removeChild(t),e};var o=t.fn.modal;t.fn.modal=e,t.fn.modal.Constructor=i,t.fn.modal.noConflict=function(){return t.fn.modal=o,this},t(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(i){var o=t(this),n=o.attr("href"),s=t(o.attr("data-target")||n&&n.replace(/.*(?=#[^\s]+$)/,"")),a=s.data("bs.modal")?"toggle":t.extend({remote:!/#/.test(n)&&n},s.data(),o.data());o.is("a")&&i.preventDefault(),s.one("show.bs.modal",function(t){t.isDefaultPrevented()||s.one("hidden.bs.modal",function(){o.is(":visible")&&o.trigger("focus")})}),e.call(s,a,this)})}(jQuery),+function(t){"use strict";function e(e){return this.each(function(){var o=t(this),n=o.data("bs.tooltip"),s="object"==typeof e&&e;(n||!/destroy|hide/.test(e))&&(n||o.data("bs.tooltip",n=new i(this,s)),"string"==typeof e&&n[e]())})}var i=function(t,e){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",t,e)};i.VERSION="3.3.6",i.TRANSITION_DURATION=150,i.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},i.prototype.init=function(e,i,o){if(this.enabled=!0,this.type=e,this.$element=t(i),this.options=this.getOptions(o),this.$viewport=this.options.viewport&&t(t.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var n=this.options.trigger.split(" "),s=n.length;s--;){var a=n[s];if("click"==a)this.$element.on("click."+this.type,this.options.selector,t.proxy(this.toggle,this));else if("manual"!=a){var r="hover"==a?"mouseenter":"focusin",l="hover"==a?"mouseleave":"focusout";this.$element.on(r+"."+this.type,this.options.selector,t.proxy(this.enter,this)),this.$element.on(l+"."+this.type,this.options.selector,t.proxy(this.leave,this))}}this.options.selector?this._options=t.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},i.prototype.getDefaults=function(){return i.DEFAULTS},i.prototype.getOptions=function(e){return e=t.extend({},this.getDefaults(),this.$element.data(),e),e.delay&&"number"==typeof e.delay&&(e.delay={show:e.delay,hide:e.delay}),e},i.prototype.getDelegateOptions=function(){var e={},i=this.getDefaults();return this._options&&t.each(this._options,function(t,o){i[t]!=o&&(e[t]=o)}),e},i.prototype.enter=function(e){var i=e instanceof this.constructor?e:t(e.currentTarget).data("bs."+this.type);return i||(i=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,i)),e instanceof t.Event&&(i.inState["focusin"==e.type?"focus":"hover"]=!0),i.tip().hasClass("in")||"in"==i.hoverState?void(i.hoverState="in"):(clearTimeout(i.timeout),i.hoverState="in",i.options.delay&&i.options.delay.show?void(i.timeout=setTimeout(function(){"in"==i.hoverState&&i.show()},i.options.delay.show)):i.show())},i.prototype.isInStateTrue=function(){for(var t in this.inState)if(this.inState[t])return!0;return!1},i.prototype.leave=function(e){var i=e instanceof this.constructor?e:t(e.currentTarget).data("bs."+this.type);return i||(i=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,i)),e instanceof t.Event&&(i.inState["focusout"==e.type?"focus":"hover"]=!1),i.isInStateTrue()?void 0:(clearTimeout(i.timeout),i.hoverState="out",i.options.delay&&i.options.delay.hide?void(i.timeout=setTimeout(function(){"out"==i.hoverState&&i.hide()},i.options.delay.hide)):i.hide())},i.prototype.show=function(){var e=t.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(e);var o=t.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(e.isDefaultPrevented()||!o)return;var n=this,s=this.tip(),a=this.getUID(this.type);this.setContent(),s.attr("id",a),this.$element.attr("aria-describedby",a),this.options.animation&&s.addClass("fade");var r="function"==typeof this.options.placement?this.options.placement.call(this,s[0],this.$element[0]):this.options.placement,l=/\s?auto?\s?/i,h=l.test(r);h&&(r=r.replace(l,"")||"top"),s.detach().css({top:0,left:0,display:"block"}).addClass(r).data("bs."+this.type,this),this.options.container?s.appendTo(this.options.container):s.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var d=this.getPosition(),p=s[0].offsetWidth,c=s[0].offsetHeight;if(h){var f=r,u=this.getPosition(this.$viewport);r="bottom"==r&&d.bottom+c>u.bottom?"top":"top"==r&&d.top-c<u.top?"bottom":"right"==r&&d.right+p>u.width?"left":"left"==r&&d.left-p<u.left?"right":r,s.removeClass(f).addClass(r)}var g=this.getCalculatedOffset(r,d,p,c);this.applyPlacement(g,r);var v=function(){var t=n.hoverState;n.$element.trigger("shown.bs."+n.type),n.hoverState=null,"out"==t&&n.leave(n)};t.support.transition&&this.$tip.hasClass("fade")?s.one("bsTransitionEnd",v).emulateTransitionEnd(i.TRANSITION_DURATION):v()}},i.prototype.applyPlacement=function(e,i){var o=this.tip(),n=o[0].offsetWidth,s=o[0].offsetHeight,a=parseInt(o.css("margin-top"),10),r=parseInt(o.css("margin-left"),10);isNaN(a)&&(a=0),isNaN(r)&&(r=0),e.top+=a,e.left+=r,t.offset.setOffset(o[0],t.extend({using:function(t){o.css({top:Math.round(t.top),left:Math.round(t.left)})}},e),0),o.addClass("in");var l=o[0].offsetWidth,h=o[0].offsetHeight;"top"==i&&h!=s&&(e.top=e.top+s-h);var d=this.getViewportAdjustedDelta(i,e,l,h);d.left?e.left+=d.left:e.top+=d.top;var p=/top|bottom/.test(i),c=p?2*d.left-n+l:2*d.top-s+h,f=p?"offsetWidth":"offsetHeight";o.offset(e),this.replaceArrow(c,o[0][f],p)},i.prototype.replaceArrow=function(t,e,i){this.arrow().css(i?"left":"top",50*(1-t/e)+"%").css(i?"top":"left","")},i.prototype.setContent=function(){var t=this.tip(),e=this.getTitle();t.find(".tooltip-inner")[this.options.html?"html":"text"](e),t.removeClass("fade in top bottom left right")},i.prototype.hide=function(e){function o(){"in"!=n.hoverState&&s.detach(),n.$element.removeAttr("aria-describedby").trigger("hidden.bs."+n.type),e&&e()}var n=this,s=t(this.$tip),a=t.Event("hide.bs."+this.type);return this.$element.trigger(a),a.isDefaultPrevented()?void 0:(s.removeClass("in"),t.support.transition&&s.hasClass("fade")?s.one("bsTransitionEnd",o).emulateTransitionEnd(i.TRANSITION_DURATION):o(),this.hoverState=null,this)},i.prototype.fixTitle=function(){var t=this.$element;(t.attr("title")||"string"!=typeof t.attr("data-original-title"))&&t.attr("data-original-title",t.attr("title")||"").attr("title","")},i.prototype.hasContent=function(){return this.getTitle()},i.prototype.getPosition=function(e){e=e||this.$element;var i=e[0],o="BODY"==i.tagName,n=i.getBoundingClientRect();null==n.width&&(n=t.extend({},n,{width:n.right-n.left,height:n.bottom-n.top}));var s=o?{top:0,left:0}:e.offset(),a={scroll:o?document.documentElement.scrollTop||document.body.scrollTop:e.scrollTop()},r=o?{width:t(window).width(),height:t(window).height()}:null;return t.extend({},n,a,r,s)},i.prototype.getCalculatedOffset=function(t,e,i,o){return"bottom"==t?{top:e.top+e.height,left:e.left+e.width/2-i/2}:"top"==t?{top:e.top-o,left:e.left+e.width/2-i/2}:"left"==t?{top:e.top+e.height/2-o/2,left:e.left-i}:{top:e.top+e.height/2-o/2,left:e.left+e.width}},i.prototype.getViewportAdjustedDelta=function(t,e,i,o){var n={top:0,left:0};if(!this.$viewport)return n;var s=this.options.viewport&&this.options.viewport.padding||0,a=this.getPosition(this.$viewport);if(/right|left/.test(t)){var r=e.top-s-a.scroll,l=e.top+s-a.scroll+o;r<a.top?n.top=a.top-r:l>a.top+a.height&&(n.top=a.top+a.height-l)}else{var h=e.left-s,d=e.left+s+i;h<a.left?n.left=a.left-h:d>a.right&&(n.left=a.left+a.width-d)}return n},i.prototype.getTitle=function(){var t,e=this.$element,i=this.options;return t=e.attr("data-original-title")||("function"==typeof i.title?i.title.call(e[0]):i.title)},i.prototype.getUID=function(t){do t+=~~(1e6*Math.random());while(document.getElementById(t));return t},i.prototype.tip=function(){if(!this.$tip&&(this.$tip=t(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},i.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},i.prototype.enable=function(){this.enabled=!0},i.prototype.disable=function(){this.enabled=!1},i.prototype.toggleEnabled=function(){this.enabled=!this.enabled},i.prototype.toggle=function(e){var i=this;e&&(i=t(e.currentTarget).data("bs."+this.type),i||(i=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,i))),e?(i.inState.click=!i.inState.click,i.isInStateTrue()?i.enter(i):i.leave(i)):i.tip().hasClass("in")?i.leave(i):i.enter(i)},i.prototype.destroy=function(){var t=this;clearTimeout(this.timeout),this.hide(function(){t.$element.off("."+t.type).removeData("bs."+t.type),t.$tip&&t.$tip.detach(),t.$tip=null,t.$arrow=null,t.$viewport=null})};var o=t.fn.tooltip;t.fn.tooltip=e,t.fn.tooltip.Constructor=i,t.fn.tooltip.noConflict=function(){return t.fn.tooltip=o,this}}(jQuery),+function(t){"use strict";function e(e){return this.each(function(){var o=t(this),n=o.data("bs.popover"),s="object"==typeof e&&e;(n||!/destroy|hide/.test(e))&&(n||o.data("bs.popover",n=new i(this,s)),"string"==typeof e&&n[e]())})}var i=function(t,e){this.init("popover",t,e)};if(!t.fn.tooltip)throw new Error("Popover requires tooltip.js");i.VERSION="3.3.6",i.DEFAULTS=t.extend({},t.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),i.prototype=t.extend({},t.fn.tooltip.Constructor.prototype),i.prototype.constructor=i,i.prototype.getDefaults=function(){return i.DEFAULTS},i.prototype.setContent=function(){var t=this.tip(),e=this.getTitle(),i=this.getContent();t.find(".popover-title")[this.options.html?"html":"text"](e),t.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof i?"html":"append":"text"](i),t.removeClass("fade top bottom left right in"),t.find(".popover-title").html()||t.find(".popover-title").hide()},i.prototype.hasContent=function(){return this.getTitle()||this.getContent()},i.prototype.getContent=function(){var t=this.$element,e=this.options;return t.attr("data-content")||("function"==typeof e.content?e.content.call(t[0]):e.content)},i.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var o=t.fn.popover;t.fn.popover=e,t.fn.popover.Constructor=i,t.fn.popover.noConflict=function(){return t.fn.popover=o,this}}(jQuery),+function(t){"use strict";function e(e){return this.each(function(){var o=t(this),n=o.data("bs.tab");n||o.data("bs.tab",n=new i(this)),"string"==typeof e&&n[e]()})}var i=function(e){this.element=t(e)};i.VERSION="3.3.6",i.TRANSITION_DURATION=150,i.prototype.show=function(){var e=this.element,i=e.closest("ul:not(.dropdown-menu)"),o=e.data("target");if(o||(o=e.attr("href"),o=o&&o.replace(/.*(?=#[^\s]*$)/,"")),!e.parent("li").hasClass("active")){var n=i.find(".active:last a"),s=t.Event("hide.bs.tab",{relatedTarget:e[0]}),a=t.Event("show.bs.tab",{relatedTarget:n[0]});if(n.trigger(s),e.trigger(a),!a.isDefaultPrevented()&&!s.isDefaultPrevented()){var r=t(o);this.activate(e.closest("li"),i),this.activate(r,r.parent(),function(){n.trigger({type:"hidden.bs.tab",relatedTarget:e[0]}),e.trigger({type:"shown.bs.tab",relatedTarget:n[0]})})}}},i.prototype.activate=function(e,o,n){function s(){a.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),e.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),r?(e[0].offsetWidth,e.addClass("in")):e.removeClass("fade"),e.parent(".dropdown-menu").length&&e.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),n&&n()}var a=o.find("> .active"),r=n&&t.support.transition&&(a.length&&a.hasClass("fade")||!!o.find("> .fade").length);a.length&&r?a.one("bsTransitionEnd",s).emulateTransitionEnd(i.TRANSITION_DURATION):s(),a.removeClass("in")};var o=t.fn.tab;t.fn.tab=e,t.fn.tab.Constructor=i,t.fn.tab.noConflict=function(){return t.fn.tab=o,this};var n=function(i){i.preventDefault(),e.call(t(this),"show")};t(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',n).on("click.bs.tab.data-api",'[data-toggle="pill"]',n)}(jQuery),+function(t){"use strict";function e(e){return this.each(function(){var o=t(this),n=o.data("bs.affix"),s="object"==typeof e&&e;n||o.data("bs.affix",n=new i(this,s)),"string"==typeof e&&n[e]()})}var i=function(e,o){this.options=t.extend({},i.DEFAULTS,o),this.$target=t(this.options.target).on("scroll.bs.affix.data-api",t.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",t.proxy(this.checkPositionWithEventLoop,this)),this.$element=t(e),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};i.VERSION="3.3.6",i.RESET="affix affix-top affix-bottom",i.DEFAULTS={offset:0,target:window},i.prototype.getState=function(t,e,i,o){var n=this.$target.scrollTop(),s=this.$element.offset(),a=this.$target.height();if(null!=i&&"top"==this.affixed)return i>n?"top":!1;if("bottom"==this.affixed)return null!=i?n+this.unpin<=s.top?!1:"bottom":t-o>=n+a?!1:"bottom";var r=null==this.affixed,l=r?n:s.top,h=r?a:e;return null!=i&&i>=n?"top":null!=o&&l+h>=t-o?"bottom":!1},i.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(i.RESET).addClass("affix");var t=this.$target.scrollTop(),e=this.$element.offset();return this.pinnedOffset=e.top-t},i.prototype.checkPositionWithEventLoop=function(){setTimeout(t.proxy(this.checkPosition,this),1)},i.prototype.checkPosition=function(){if(this.$element.is(":visible")){var e=this.$element.height(),o=this.options.offset,n=o.top,s=o.bottom,a=Math.max(t(document).height(),t(document.body).height());"object"!=typeof o&&(s=n=o),"function"==typeof n&&(n=o.top(this.$element)),"function"==typeof s&&(s=o.bottom(this.$element));var r=this.getState(a,e,n,s);if(this.affixed!=r){null!=this.unpin&&this.$element.css("top","");var l="affix"+(r?"-"+r:""),h=t.Event(l+".bs.affix");if(this.$element.trigger(h),h.isDefaultPrevented())return;this.affixed=r,this.unpin="bottom"==r?this.getPinnedOffset():null,this.$element.removeClass(i.RESET).addClass(l).trigger(l.replace("affix","affixed")+".bs.affix")}"bottom"==r&&this.$element.offset({top:a-e-s})}};var o=t.fn.affix;t.fn.affix=e,t.fn.affix.Constructor=i,t.fn.affix.noConflict=function(){return t.fn.affix=o,this},t(window).on("load",function(){t('[data-spy="affix"]').each(function(){var i=t(this),o=i.data();o.offset=o.offset||{},null!=o.offsetBottom&&(o.offset.bottom=o.offsetBottom),null!=o.offsetTop&&(o.offset.top=o.offsetTop),e.call(i,o)})})}(jQuery),+function(t){"use strict";function e(e){var i,o=e.attr("data-target")||(i=e.attr("href"))&&i.replace(/.*(?=#[^\s]+$)/,"");return t(o)}function i(e){return this.each(function(){var i=t(this),n=i.data("bs.collapse"),s=t.extend({},o.DEFAULTS,i.data(),"object"==typeof e&&e);!n&&s.toggle&&/show|hide/.test(e)&&(s.toggle=!1),n||i.data("bs.collapse",n=new o(this,s)),"string"==typeof e&&n[e]()})}var o=function(e,i){this.$element=t(e),this.options=t.extend({},o.DEFAULTS,i),this.$trigger=t('[data-toggle="collapse"][href="#'+e.id+'"],[data-toggle="collapse"][data-target="#'+e.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};o.VERSION="3.3.6",o.TRANSITION_DURATION=350,o.DEFAULTS={toggle:!0},o.prototype.dimension=function(){var t=this.$element.hasClass("width");return t?"width":"height"},o.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var e,n=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(n&&n.length&&(e=n.data("bs.collapse"),e&&e.transitioning))){var s=t.Event("show.bs.collapse");if(this.$element.trigger(s),!s.isDefaultPrevented()){n&&n.length&&(i.call(n,"hide"),e||n.data("bs.collapse",null));var a=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[a](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var r=function(){this.$element.removeClass("collapsing").addClass("collapse in")[a](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!t.support.transition)return r.call(this);var l=t.camelCase(["scroll",a].join("-"));this.$element.one("bsTransitionEnd",t.proxy(r,this)).emulateTransitionEnd(o.TRANSITION_DURATION)[a](this.$element[0][l]);
}}}},o.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var e=t.Event("hide.bs.collapse");if(this.$element.trigger(e),!e.isDefaultPrevented()){var i=this.dimension();this.$element[i](this.$element[i]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var n=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return t.support.transition?void this.$element[i](0).one("bsTransitionEnd",t.proxy(n,this)).emulateTransitionEnd(o.TRANSITION_DURATION):n.call(this)}}},o.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},o.prototype.getParent=function(){return t(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(t.proxy(function(i,o){var n=t(o);this.addAriaAndCollapsedClass(e(n),n)},this)).end()},o.prototype.addAriaAndCollapsedClass=function(t,e){var i=t.hasClass("in");t.attr("aria-expanded",i),e.toggleClass("collapsed",!i).attr("aria-expanded",i)};var n=t.fn.collapse;t.fn.collapse=i,t.fn.collapse.Constructor=o,t.fn.collapse.noConflict=function(){return t.fn.collapse=n,this},t(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(o){var n=t(this);n.attr("data-target")||o.preventDefault();var s=e(n),a=s.data("bs.collapse"),r=a?"toggle":n.data();i.call(s,r)})}(jQuery),+function(t){"use strict";function e(i,o){this.$body=t(document.body),this.$scrollElement=t(t(i).is(document.body)?window:i),this.options=t.extend({},e.DEFAULTS,o),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",t.proxy(this.process,this)),this.refresh(),this.process()}function i(i){return this.each(function(){var o=t(this),n=o.data("bs.scrollspy"),s="object"==typeof i&&i;n||o.data("bs.scrollspy",n=new e(this,s)),"string"==typeof i&&n[i]()})}e.VERSION="3.3.6",e.DEFAULTS={offset:10},e.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},e.prototype.refresh=function(){var e=this,i="offset",o=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),t.isWindow(this.$scrollElement[0])||(i="position",o=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var e=t(this),n=e.data("target")||e.attr("href"),s=/^#./.test(n)&&t(n);return s&&s.length&&s.is(":visible")&&[[s[i]().top+o,n]]||null}).sort(function(t,e){return t[0]-e[0]}).each(function(){e.offsets.push(this[0]),e.targets.push(this[1])})},e.prototype.process=function(){var t,e=this.$scrollElement.scrollTop()+this.options.offset,i=this.getScrollHeight(),o=this.options.offset+i-this.$scrollElement.height(),n=this.offsets,s=this.targets,a=this.activeTarget;if(this.scrollHeight!=i&&this.refresh(),e>=o)return a!=(t=s[s.length-1])&&this.activate(t);if(a&&e<n[0])return this.activeTarget=null,this.clear();for(t=n.length;t--;)a!=s[t]&&e>=n[t]&&(void 0===n[t+1]||e<n[t+1])&&this.activate(s[t])},e.prototype.activate=function(e){this.activeTarget=e,this.clear();var i=this.selector+'[data-target="'+e+'"],'+this.selector+'[href="'+e+'"]',o=t(i).parents("li").addClass("active");o.parent(".dropdown-menu").length&&(o=o.closest("li.dropdown").addClass("active")),o.trigger("activate.bs.scrollspy")},e.prototype.clear=function(){t(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var o=t.fn.scrollspy;t.fn.scrollspy=i,t.fn.scrollspy.Constructor=e,t.fn.scrollspy.noConflict=function(){return t.fn.scrollspy=o,this},t(window).on("load.bs.scrollspy.data-api",function(){t('[data-spy="scroll"]').each(function(){var e=t(this);i.call(e,e.data())})})}(jQuery),+function(t){"use strict";function e(){var t=document.createElement("bootstrap"),e={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var i in e)if(void 0!==t.style[i])return{end:e[i]};return!1}t.fn.emulateTransitionEnd=function(e){var i=!1,o=this;t(this).one("bsTransitionEnd",function(){i=!0});var n=function(){i||t(o).trigger(t.support.transition.end)};return setTimeout(n,e),this},t(function(){t.support.transition=e(),t.support.transition&&(t.event.special.bsTransitionEnd={bindType:t.support.transition.end,delegateType:t.support.transition.end,handle:function(e){return t(e.target).is(this)?e.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery);;

/** jQueryUI **/
/*! jQuery UI - v1.9.2 - 2012-12-21
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */

(function(e,t){function i(t,n){var r,i,o,u=t.nodeName.toLowerCase();return"area"===u?(r=t.parentNode,i=r.name,!t.href||!i||r.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap=#"+i+"]")[0],!!o&&s(o))):(/input|select|textarea|button|object/.test(u)?!t.disabled:"a"===u?t.href||n:n)&&s(t)}function s(t){return e.expr.filters.visible(t)&&!e(t).parents().andSelf().filter(function(){return e.css(this,"visibility")==="hidden"}).length}var n=0,r=/^ui-id-\d+$/;e.ui=e.ui||{};if(e.ui.version)return;e.extend(e.ui,{version:"1.9.2",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({_focus:e.fn.focus,focus:function(t,n){return typeof t=="number"?this.each(function(){var r=this;setTimeout(function(){e(r).focus(),n&&n.call(r)},t)}):this._focus.apply(this,arguments)},scrollParent:function(){var t;return e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?t=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):t=this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length){var r=e(this[0]),i,s;while(r.length&&r[0]!==document){i=r.css("position");if(i==="absolute"||i==="relative"||i==="fixed"){s=parseInt(r.css("zIndex"),10);if(!isNaN(s)&&s!==0)return s}r=r.parent()}}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++n)})},removeUniqueId:function(){return this.each(function(){r.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),r=isNaN(n);return(r||n>=0)&&i(t,!r)}}),e(function(){var t=document.body,n=t.appendChild(n=document.createElement("div"));n.offsetHeight,e.extend(n.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),e.support.minHeight=n.offsetHeight===100,e.support.selectstart="onselectstart"in n,t.removeChild(n).style.display="none"}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function u(t,n,r,s){return e.each(i,function(){n-=parseFloat(e.css(t,"padding"+this))||0,r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var i=r==="Width"?["Left","Right"]:["Top","Bottom"],s=r.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?o["inner"+r].call(this):this.each(function(){e(this).css(s,u(this,n)+"px")})},e.fn["outer"+r]=function(t,n){return typeof t!="number"?o["outer"+r].call(this,t):this.each(function(){e(this).css(s,u(this,t,!0,n)+"px")})}}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),function(){var t=/msie ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||[];e.ui.ie=t.length?!0:!1,e.ui.ie6=parseFloat(t[1],10)===6}(),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n){var r,i=e.plugins[t];if(!i||!e.element[0].parentNode||e.element[0].parentNode.nodeType===11)return;for(r=0;r<i.length;r++)e.options[i[r][0]]&&i[r][1].apply(e.element,n)}},contains:e.contains,hasScroll:function(t,n){if(e(t).css("overflow")==="hidden")return!1;var r=n&&n==="left"?"scrollLeft":"scrollTop",i=!1;return t[r]>0?!0:(t[r]=1,i=t[r]>0,t[r]=0,i)},isOverAxis:function(e,t,n){return e>t&&e<t+n},isOver:function(t,n,r,i,s,o){return e.ui.isOverAxis(t,r,s)&&e.ui.isOverAxis(n,i,o)}})})(jQuery);(function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n=0,r;(r=t[n])!=null;n++)try{e(r).triggerHandler("remove")}catch(s){}i(t)},e.widget=function(t,n,r){var i,s,o,u,a=t.split(".")[0];t=t.split(".")[1],i=a+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[a]=e[a]||{},s=e[a][t],o=e[a][t]=function(e,t){if(!this._createWidget)return new o(e,t);arguments.length&&this._createWidget(e,t)},e.extend(o,s,{version:r.version,_proto:e.extend({},r),_childConstructors:[]}),u=new n,u.options=e.widget.extend({},u.options),e.each(r,function(t,i){e.isFunction(i)&&(r[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},r=function(e){return n.prototype[t].apply(this,e)};return function(){var t=this._super,n=this._superApply,s;return this._super=e,this._superApply=r,s=i.apply(this,arguments),this._super=t,this._superApply=n,s}}())}),o.prototype=e.widget.extend(u,{widgetEventPrefix:s?u.widgetEventPrefix:t},r,{constructor:o,namespace:a,widgetName:t,widgetBaseClass:i,widgetFullName:i}),s?(e.each(s._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,o,n._proto)}),delete s._childConstructors):n._childConstructors.push(o),e.widget.bridge(t,o)},e.widget.extend=function(n){var i=r.call(arguments,1),s=0,o=i.length,u,a;for(;s<o;s++)for(u in i[s])a=i[s][u],i[s].hasOwnProperty(u)&&a!==t&&(e.isPlainObject(a)?n[u]=e.isPlainObject(n[u])?e.widget.extend({},n[u],a):e.widget.extend({},a):n[u]=a);return n},e.widget.bridge=function(n,i){var s=i.prototype.widgetFullName||n;e.fn[n]=function(o){var u=typeof o=="string",a=r.call(arguments,1),f=this;return o=!u&&a.length?e.widget.extend.apply(null,[o].concat(a)):o,u?this.each(function(){var r,i=e.data(this,s);if(!i)return e.error("cannot call methods on "+n+" prior to initialization; "+"attempted to call method '"+o+"'");if(!e.isFunction(i[o])||o.charAt(0)==="_")return e.error("no such method '"+o+"' for "+n+" widget instance");r=i[o].apply(i,a);if(r!==i&&r!==t)return f=r&&r.jquery?f.pushStack(r.get()):r,!1}):this.each(function(){var t=e.data(this,s);t?t.option(o||{})._init():e.data(this,s,new i(o,this))}),f}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0],this.element=e(r),this.uuid=n++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),r!==this&&(e.data(r,this.widgetName,this),e.data(r,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}}),this.document=e(r.style?r.ownerDocument:r.document||r),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i=n,s,o,u;if(arguments.length===0)return e.widget.extend({},this.options);if(typeof n=="string"){i={},s=n.split("."),n=s.shift();if(s.length){o=i[n]=e.widget.extend({},this.options[n]);for(u=0;u<s.length-1;u++)o[s[u]]=o[s[u]]||{},o=o[s[u]];n=s.pop();if(r===t)return o[n]===t?null:o[n];o[n]=r}else{if(r===t)return this.options[n]===t?null:this.options[n];i[n]=r}}return this._setOptions(i),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,e==="disabled"&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(t,n,r){var i,s=this;typeof t!="boolean"&&(r=n,n=t,t=!1),r?(n=i=e(n),this.bindings=this.bindings.add(n)):(r=n,n=this.element,i=this.widget()),e.each(r,function(r,o){function u(){if(!t&&(s.options.disabled===!0||e(this).hasClass("ui-state-disabled")))return;return(typeof o=="string"?s[o]:o).apply(s,arguments)}typeof o!="string"&&(u.guid=o.guid=o.guid||u.guid||e.guid++);var a=r.match(/^(\w+)\s*(.*)$/),f=a[1]+s.eventNamespace,l=a[2];l?i.delegate(l,f,u):n.bind(f,u)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return(typeof e=="string"?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,s,o=this.options[t];r=r||{},n=e.Event(n),n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),n.target=this.element[0],s=n.originalEvent;if(s)for(i in s)i in n||(n[i]=s[i]);return this.element.trigger(n,r),!(e.isFunction(o)&&o.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,s){typeof i=="string"&&(i={effect:i});var o,u=i?i===!0||typeof i=="number"?n:i.effect||n:t;i=i||{},typeof i=="number"&&(i={duration:i}),o=!e.isEmptyObject(i),i.complete=s,i.delay&&r.delay(i.delay),o&&e.effects&&(e.effects.effect[u]||e.uiBackCompat!==!1&&e.effects[u])?r[t](i):u!==t&&r[u]?r[u](i.duration,i.easing,s):r.queue(function(n){e(this)[t](),s&&s.call(r[0]),n()})}}),e.uiBackCompat!==!1&&(e.Widget.prototype._getCreateOptions=function(){return e.metadata&&e.metadata.get(this.element[0])[this.widgetName]})})(jQuery);(function(e,t){var n=!1;e(document).mouseup(function(e){n=!1}),e.widget("ui.mouse",{version:"1.9.2",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent"))return e.removeData(n.target,t.widgetName+".preventClickEvent"),n.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(n)return;this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var r=this,i=t.which===1,s=typeof this.options.cancel=="string"&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;if(!i||s||!this._mouseCapture(t))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(t)!==!1;if(!this._mouseStarted)return t.preventDefault(),!0}return!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return r._mouseMove(e)},this._mouseUpDelegate=function(e){return r._mouseUp(e)},e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),n=!0,!0},_mouseMove:function(t){return!e.ui.ie||document.documentMode>=9||!!t.button?this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted):this._mouseUp(t)},_mouseUp:function(t){return e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(e){return this.mouseDelayMet},_mouseStart:function(e){},_mouseDrag:function(e){},_mouseStop:function(e){},_mouseCapture:function(e){return!0}})})(jQuery);(function(e,t){function h(e,t,n){return[parseInt(e[0],10)*(l.test(e[0])?t/100:1),parseInt(e[1],10)*(l.test(e[1])?n/100:1)]}function p(t,n){return parseInt(e.css(t,n),10)||0}e.ui=e.ui||{};var n,r=Math.max,i=Math.abs,s=Math.round,o=/left|center|right/,u=/top|center|bottom/,a=/[\+\-]\d+%?/,f=/^\w+/,l=/%$/,c=e.fn.position;e.position={scrollbarWidth:function(){if(n!==t)return n;var r,i,s=e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return e("body").append(s),r=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,r===i&&(i=s[0].clientWidth),s.remove(),n=r-i},getScrollInfo:function(t){var n=t.isWindow?"":t.element.css("overflow-x"),r=t.isWindow?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&&t.width<t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&&t.height<t.element[0].scrollHeight;return{width:i?e.position.scrollbarWidth():0,height:s?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]);return{element:n,isWindow:r,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return c.apply(this,arguments);t=e.extend({},t);var n,l,d,v,m,g=e(t.of),y=e.position.getWithinInfo(t.within),b=e.position.getScrollInfo(y),w=g[0],E=(t.collision||"flip").split(" "),S={};return w.nodeType===9?(l=g.width(),d=g.height(),v={top:0,left:0}):e.isWindow(w)?(l=g.width(),d=g.height(),v={top:g.scrollTop(),left:g.scrollLeft()}):w.preventDefault?(t.at="left top",l=d=0,v={top:w.pageY,left:w.pageX}):(l=g.outerWidth(),d=g.outerHeight(),v=g.offset()),m=e.extend({},v),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=o.test(e[0])?e.concat(["center"]):u.test(e[0])?["center"].concat(e):["center","center"]),e[0]=o.test(e[0])?e[0]:"center",e[1]=u.test(e[1])?e[1]:"center",n=a.exec(e[0]),r=a.exec(e[1]),S[this]=[n?n[0]:0,r?r[0]:0],t[this]=[f.exec(e[0])[0],f.exec(e[1])[0]]}),E.length===1&&(E[1]=E[0]),t.at[0]==="right"?m.left+=l:t.at[0]==="center"&&(m.left+=l/2),t.at[1]==="bottom"?m.top+=d:t.at[1]==="center"&&(m.top+=d/2),n=h(S.at,l,d),m.left+=n[0],m.top+=n[1],this.each(function(){var o,u,a=e(this),f=a.outerWidth(),c=a.outerHeight(),w=p(this,"marginLeft"),x=p(this,"marginTop"),T=f+w+p(this,"marginRight")+b.width,N=c+x+p(this,"marginBottom")+b.height,C=e.extend({},m),k=h(S.my,a.outerWidth(),a.outerHeight());t.my[0]==="right"?C.left-=f:t.my[0]==="center"&&(C.left-=f/2),t.my[1]==="bottom"?C.top-=c:t.my[1]==="center"&&(C.top-=c/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=s(C.left),C.top=s(C.top)),o={marginLeft:w,marginTop:x},e.each(["left","top"],function(r,i){e.ui.position[E[r]]&&e.ui.position[E[r]][i](C,{targetWidth:l,targetHeight:d,elemWidth:f,elemHeight:c,collisionPosition:o,collisionWidth:T,collisionHeight:N,offset:[n[0]+k[0],n[1]+k[1]],my:t.my,at:t.at,within:y,elem:a})}),e.fn.bgiframe&&a.bgiframe(),t.using&&(u=function(e){var n=v.left-C.left,s=n+l-f,o=v.top-C.top,u=o+d-c,h={target:{element:g,left:v.left,top:v.top,width:l,height:d},element:{element:a,left:C.left,top:C.top,width:f,height:c},horizontal:s<0?"left":n>0?"right":"center",vertical:u<0?"top":o>0?"bottom":"middle"};l<f&&i(n+s)<l&&(h.horizontal="center"),d<c&&i(o+u)<d&&(h.vertical="middle"),r(i(n),i(s))>r(i(o),i(u))?h.important="horizontal":h.important="vertical",t.using.call(this,e,h)}),a.offset(e.extend(C,{using:u}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,i=n.isWindow?n.scrollLeft:n.offset.left,s=n.width,o=e.left-t.collisionPosition.marginLeft,u=i-o,a=o+t.collisionWidth-s-i,f;t.collisionWidth>s?u>0&&a<=0?(f=e.left+u+t.collisionWidth-s-i,e.left+=u-f):a>0&&u<=0?e.left=i:u>a?e.left=i+s-t.collisionWidth:e.left=i:u>0?e.left+=u:a>0?e.left-=a:e.left=r(e.left-o,e.left)},top:function(e,t){var n=t.within,i=n.isWindow?n.scrollTop:n.offset.top,s=t.within.height,o=e.top-t.collisionPosition.marginTop,u=i-o,a=o+t.collisionHeight-s-i,f;t.collisionHeight>s?u>0&&a<=0?(f=e.top+u+t.collisionHeight-s-i,e.top+=u-f):a>0&&u<=0?e.top=i:u>a?e.top=i+s-t.collisionHeight:e.top=i:u>0?e.top+=u:a>0?e.top-=a:e.top=r(e.top-o,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,s=n.width,o=n.isWindow?n.scrollLeft:n.offset.left,u=e.left-t.collisionPosition.marginLeft,a=u-o,f=u+t.collisionWidth-s-o,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a<0){p=e.left+l+c+h+t.collisionWidth-s-r;if(p<0||p<i(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-o;if(d>0||i(d)<f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,s=n.height,o=n.isWindow?n.scrollTop:n.offset.top,u=e.top-t.collisionPosition.marginTop,a=u-o,f=u+t.collisionHeight-s-o,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;a<0?(v=e.top+c+h+p+t.collisionHeight-s-r,e.top+c+h+p>a&&(v<0||v<i(a))&&(e.top+=c+h+p)):f>0&&(d=e.top-t.collisionPosition.marginTop+c+h+p-o,e.top+c+h+p>f&&(d>0||i(d)<f)&&(e.top+=c+h+p))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,n,r,i,s,o=document.getElementsByTagName("body")[0],u=document.createElement("div");t=document.createElement(o?"div":"body"),r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(s in r)t.style[s]=r[s];t.appendChild(u),n=o||document.documentElement,n.insertBefore(t,n.firstChild),u.style.cssText="position: absolute; left: 10.7432222px;",i=e(u).offset().left,e.support.offsetFractions=i>10&&i<11,t.innerHTML="",n.removeChild(t)}(),e.uiBackCompat!==!1&&function(e){var n=e.fn.position;e.fn.position=function(r){if(!r||!r.offset)return n.call(this,r);var i=r.offset.split(" "),s=r.at.split(" ");return i.length===1&&(i[1]=i[0]),/^\d/.test(i[0])&&(i[0]="+"+i[0]),/^\d/.test(i[1])&&(i[1]="+"+i[1]),s.length===1&&(/left|center|right/.test(s[0])?s[1]="center":(s[1]=s[0],s[0]="center")),n.call(this,e.extend(r,{at:s[0]+i[0]+" "+s[1]+i[1],offset:t}))}}(jQuery)})(jQuery);(function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var n=this.options;return this.helper||n.disabled||e(t.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(t),this.handle?(e(n.iframeFix===!0?"iframe":n.iframeFix).each(function(){e('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var n=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,n.cursorAt&&this._adjustOffsetFromHelper(n.cursorAt),n.containment&&this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,n){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute");if(!n){var r=this._uiHash();if(this._trigger("drag",t,r)===!1)return this._mouseUp({}),!1;this.position=r.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";return e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var n=!1;e.ui.ddmanager&&!this.options.dropBehaviour&&(n=e.ui.ddmanager.drop(this,t)),this.dropped&&(n=this.dropped,this.dropped=!1);var r=this.element[0],i=!1;while(r&&(r=r.parentNode))r==document&&(i=!0);if(!i&&this.options.helper==="original")return!1;if(this.options.revert=="invalid"&&!n||this.options.revert=="valid"&&n||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,n)){var s=this;e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){s._trigger("stop",t)!==!1&&s._clear()})}else this._trigger("stop",t)!==!1&&this._clear();return!1},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){var n=!this.options.handle||!e(this.options.handle,this.element).length?!0:!1;return e(this.options.handle,this.element).find("*").andSelf().each(function(){this==t.target&&(n=!0)}),n},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t])):n.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return r.parents("body").length||r.appendTo(n.appendTo=="parent"?this.element[0].parentNode:n.appendTo),r[0]!=this.element[0]&&!/(fixed|absolute)/.test(r.css("position"))&&r.css("position","absolute"),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&&(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[t.containment=="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t.containment=="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(t.containment=="document"?0:e(window).scrollLeft())+e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(t.containment=="document"?0:e(window).scrollTop())+(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)&&t.containment.constructor!=Array){var n=e(t.containment),r=n[0];if(!r)return;var i=n.offset(),s=e(r).css("overflow")!="hidden";this.containment=[(parseInt(e(r).css("borderLeftWidth"),10)||0)+(parseInt(e(r).css("paddingLeft"),10)||0),(parseInt(e(r).css("borderTopWidth"),10)||0)+(parseInt(e(r).css("paddingTop"),10)||0),(s?Math.max(r.scrollWidth,r.offsetWidth):r.offsetWidth)-(parseInt(e(r).css("borderLeftWidth"),10)||0)-(parseInt(e(r).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(s?Math.max(r.scrollHeight,r.offsetHeight):r.offsetHeight)-(parseInt(e(r).css("borderTopWidth"),10)||0)-(parseInt(e(r).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=n}else t.containment.constructor==Array&&(this.containment=t.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName),s=t.pageX,o=t.pageY;if(this.originalPosition){var u;if(this.containment){if(this.relative_container){var a=this.relative_container.offset();u=[this.containment[0]+a.left,this.containment[1]+a.top,this.containment[2]+a.left,this.containment[3]+a.top]}else u=this.containment;t.pageX-this.offset.click.left<u[0]&&(s=u[0]+this.offset.click.left),t.pageY-this.offset.click.top<u[1]&&(o=u[1]+this.offset.click.top),t.pageX-this.offset.click.left>u[2]&&(s=u[2]+this.offset.click.left),t.pageY-this.offset.click.top>u[3]&&(o=u[3]+this.offset.click.top)}if(n.grid){var f=n.grid[1]?this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1]:this.originalPageY;o=u?f-this.offset.click.top<u[1]||f-this.offset.click.top>u[3]?f-this.offset.click.top<u[1]?f+n.grid[1]:f-n.grid[1]:f:f;var l=n.grid[0]?this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0]:this.originalPageX;s=u?l-this.offset.click.left<u[0]||l-this.offset.click.left>u[2]?l-this.offset.click.left<u[0]?l+n.grid[0]:l-n.grid[0]:l:l}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,n,r){return r=r||this._uiHash(),e.ui.plugin.call(this,t,[n,r]),t=="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,n,r)},plugins:{},_uiHash:function(e){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,n){var r=e(this).data("draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"sortable");n&&!n.options.disabled&&(r.sortables.push({instance:n,shouldRevert:n.options.revert}),n.refreshPositions(),n._trigger("activate",t,s))})},stop:function(t,n){var r=e(this).data("draggable"),i=e.extend({},n,{item:r.element});e.each(r.sortables,function(){this.instance.isOver?(this.instance.isOver=0,r.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,r.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,i))})},drag:function(t,n){var r=e(this).data("draggable"),i=this,s=function(t){var n=this.offset.click.top,r=this.offset.click.left,i=this.positionAbs.top,s=this.positionAbs.left,o=t.height,u=t.width,a=t.top,f=t.left;return e.ui.isOver(i+n,s+r,a,f,o,u)};e.each(r.sortables,function(s){var o=!1,u=this;this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(o=!0,e.each(r.sortables,function(){return this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this!=u&&this.instance._intersectsWith(this.instance.containerCache)&&e.ui.contains(u.instance.element[0],this.instance.element[0])&&(o=!1),o})),o?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return n.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=r.offset.click.top,this.instance.offset.click.left=r.offset.click.left,this.instance.offset.parent.left-=r.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=r.offset.parent.top-this.instance.offset.parent.top,r._trigger("toSortable",t),r.dropped=this.instance.element,r.currentItem=r.element,this.instance.fromOutside=r),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),r._trigger("fromSortable",t),r.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,n){var r=e("body"),i=e(this).data("draggable").options;r.css("cursor")&&(i._cursor=r.css("cursor")),r.css("cursor",i.cursor)},stop:function(t,n){var r=e(this).data("draggable").options;r._cursor&&e("body").css("cursor",r._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("opacity")&&(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("draggable").options;r._opacity&&e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(t,n){var r=e(this).data("draggable");r.scrollParent[0]!=document&&r.scrollParent[0].tagName!="HTML"&&(r.overflowOffset=r.scrollParent.offset())},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=!1;if(r.scrollParent[0]!=document&&r.scrollParent[0].tagName!="HTML"){if(!i.axis||i.axis!="x")r.overflowOffset.top+r.scrollParent[0].offsetHeight-t.pageY<i.scrollSensitivity?r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop+i.scrollSpeed:t.pageY-r.overflowOffset.top<i.scrollSensitivity&&(r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop-i.scrollSpeed);if(!i.axis||i.axis!="y")r.overflowOffset.left+r.scrollParent[0].offsetWidth-t.pageX<i.scrollSensitivity?r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft+i.scrollSpeed:t.pageX-r.overflowOffset.left<i.scrollSensitivity&&(r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft-i.scrollSpeed)}else{if(!i.axis||i.axis!="x")t.pageY-e(document).scrollTop()<i.scrollSensitivity?s=e(document).scrollTop(e(document).scrollTop()-i.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<i.scrollSensitivity&&(s=e(document).scrollTop(e(document).scrollTop()+i.scrollSpeed));if(!i.axis||i.axis!="y")t.pageX-e(document).scrollLeft()<i.scrollSensitivity?s=e(document).scrollLeft(e(document).scrollLeft()-i.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<i.scrollSensitivity&&(s=e(document).scrollLeft(e(document).scrollLeft()+i.scrollSpeed))}s!==!1&&e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(r,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,n){var r=e(this).data("draggable"),i=r.options;r.snapElements=[],e(i.snap.constructor!=String?i.snap.items||":data(draggable)":i.snap).each(function(){var t=e(this),n=t.offset();this!=r.element[0]&&r.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:n.top,left:n.left})})},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=i.snapTolerance,o=n.offset.left,u=o+r.helperProportions.width,a=n.offset.top,f=a+r.helperProportions.height;for(var l=r.snapElements.length-1;l>=0;l--){var c=r.snapElements[l].left,h=c+r.snapElements[l].width,p=r.snapElements[l].top,d=p+r.snapElements[l].height;if(!(c-s<o&&o<h+s&&p-s<a&&a<d+s||c-s<o&&o<h+s&&p-s<f&&f<d+s||c-s<u&&u<h+s&&p-s<a&&a<d+s||c-s<u&&u<h+s&&p-s<f&&f<d+s)){r.snapElements[l].snapping&&r.options.snap.release&&r.options.snap.release.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=!1;continue}if(i.snapMode!="inner"){var v=Math.abs(p-f)<=s,m=Math.abs(d-a)<=s,g=Math.abs(c-u)<=s,y=Math.abs(h-o)<=s;v&&(n.position.top=r._convertPositionTo("relative",{top:p-r.helperProportions.height,left:0}).top-r.margins.top),m&&(n.position.top=r._convertPositionTo("relative",{top:d,left:0}).top-r.margins.top),g&&(n.position.left=r._convertPositionTo("relative",{top:0,left:c-r.helperProportions.width}).left-r.margins.left),y&&(n.position.left=r._convertPositionTo("relative",{top:0,left:h}).left-r.margins.left)}var b=v||m||g||y;if(i.snapMode!="outer"){var v=Math.abs(p-a)<=s,m=Math.abs(d-f)<=s,g=Math.abs(c-o)<=s,y=Math.abs(h-u)<=s;v&&(n.position.top=r._convertPositionTo("relative",{top:p,left:0}).top-r.margins.top),m&&(n.position.top=r._convertPositionTo("relative",{top:d-r.helperProportions.height,left:0}).top-r.margins.top),g&&(n.position.left=r._convertPositionTo("relative",{top:0,left:c}).left-r.margins.left),y&&(n.position.left=r._convertPositionTo("relative",{top:0,left:h-r.helperProportions.width}).left-r.margins.left)}!r.snapElements[l].snapping&&(v||m||g||y||b)&&r.options.snap.snap&&r.options.snap.snap.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=v||m||g||y||b}}}),e.ui.plugin.add("draggable","stack",{start:function(t,n){var r=e(this).data("draggable").options,i=e.makeArray(e(r.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!i.length)return;var s=parseInt(i[0].style.zIndex)||0;e(i).each(function(e){this.style.zIndex=s+e}),this[0].style.zIndex=s+i.length}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("zIndex")&&(i._zIndex=r.css("zIndex")),r.css("zIndex",i.zIndex)},stop:function(t,n){var r=e(this).data("draggable").options;r._zIndex&&e(n.helper).css("zIndex",r._zIndex)}})})(jQuery);(function(e,t){e.widget("ui.droppable",{version:"1.9.2",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var t=this.options,n=t.accept;this.isover=0,this.isout=1,this.accept=e.isFunction(n)?n:function(e){return e.is(n)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},e.ui.ddmanager.droppables[t.scope]=e.ui.ddmanager.droppables[t.scope]||[],e.ui.ddmanager.droppables[t.scope].push(this),t.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];for(var n=0;n<t.length;n++)t[n]==this&&t.splice(n,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,n){t=="accept"&&(this.accept=e.isFunction(n)?n:function(e){return e.is(n)}),e.Widget.prototype._setOption.apply(this,arguments)},_activate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),n&&this._trigger("activate",t,this.ui(n))},_deactivate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),n&&this._trigger("deactivate",t,this.ui(n))},_over:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(n)))},_out:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(n)))},_drop:function(t,n){var r=n||e.ui.ddmanager.current;if(!r||(r.currentItem||r.element)[0]==this.element[0])return!1;var i=!1;return this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"droppable");if(t.options.greedy&&!t.options.disabled&&t.options.scope==r.options.scope&&t.accept.call(t.element[0],r.currentItem||r.element)&&e.ui.intersect(r,e.extend(t,{offset:t.element.offset()}),t.options.tolerance))return i=!0,!1}),i?!1:this.accept.call(this.element[0],r.currentItem||r.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(r)),this.element):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(t,n,r){if(!n.offset)return!1;var i=(t.positionAbs||t.position.absolute).left,s=i+t.helperProportions.width,o=(t.positionAbs||t.position.absolute).top,u=o+t.helperProportions.height,a=n.offset.left,f=a+n.proportions.width,l=n.offset.top,c=l+n.proportions.height;switch(r){case"fit":return a<=i&&s<=f&&l<=o&&u<=c;case"intersect":return a<i+t.helperProportions.width/2&&s-t.helperProportions.width/2<f&&l<o+t.helperProportions.height/2&&u-t.helperProportions.height/2<c;case"pointer":var h=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,p=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,d=e.ui.isOver(p,h,l,a,n.proportions.height,n.proportions.width);return d;case"touch":return(o>=l&&o<=c||u>=l&&u<=c||o<l&&u>c)&&(i>=a&&i<=f||s>=a&&s<=f||i<a&&s>f);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r=e.ui.ddmanager.droppables[t.options.scope]||[],i=n?n.type:null,s=(t.currentItem||t.element).find(":data(droppable)").andSelf();e:for(var o=0;o<r.length;o++){if(r[o].options.disabled||t&&!r[o].accept.call(r[o].element[0],t.currentItem||t.element))continue;for(var u=0;u<s.length;u++)if(s[u]==r[o].element[0]){r[o].proportions.height=0;continue e}r[o].visible=r[o].element.css("display")!="none";if(!r[o].visible)continue;i=="mousedown"&&r[o]._activate.call(r[o],n),r[o].offset=r[o].element.offset(),r[o].proportions={width:r[o].element[0].offsetWidth,height:r[o].element[0].offsetHeight}}},drop:function(t,n){var r=!1;return e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options)return;!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance)&&(r=this._drop.call(this,n)||r),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=1,this.isover=0,this._deactivate.call(this,n))}),r},dragStart:function(t,n){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)})},drag:function(t,n){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,n),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var r=e.ui.intersect(t,this,this.options.tolerance),i=!r&&this.isover==1?"isout":r&&this.isover==0?"isover":null;if(!i)return;var s;if(this.options.greedy){var o=this.options.scope,u=this.element.parents(":data(droppable)").filter(function(){return e.data(this,"droppable").options.scope===o});u.length&&(s=e.data(u[0],"droppable"),s.greedyChild=i=="isover"?1:0)}s&&i=="isover"&&(s.isover=0,s.isout=1,s._out.call(s,n)),this[i]=1,this[i=="isout"?"isover":"isout"]=0,this[i=="isover"?"_over":"_out"].call(this,n),s&&i=="isout"&&(s.isout=0,s.isover=1,s._over.call(s,n))})},dragStop:function(t,n){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)}}})(jQuery);(function(e,t){e.widget("ui.resizable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var t=this,n=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!n.aspectRatio,aspectRatio:n.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:n.helper||n.ghost||n.animate?n.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=n.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var r=this.handles.split(",");this.handles={};for(var i=0;i<r.length;i++){var s=e.trim(r[i]),o="ui-resizable-"+s,u=e('<div class="ui-resizable-handle '+o+'"></div>');u.css({zIndex:n.zIndex}),"se"==s&&u.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(u)}}this._renderAxis=function(t){t=t||this.element;for(var n in this.handles){this.handles[n].constructor==String&&(this.handles[n]=e(this.handles[n],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var r=e(this.handles[n],this.element),i=0;i=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth();var s=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");t.css(s,i),this._proportionallyResize()}if(!e(this.handles[n]).length)continue}},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!t.resizing){if(this.className)var e=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);t.axis=e&&e[1]?e[1]:"se"}}),n.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(n.disabled)return;e(this).removeClass("ui-resizable-autohide"),t._handles.show()}).mouseleave(function(){if(n.disabled)return;t.resizing||(e(this).addClass("ui-resizable-autohide"),t._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){t(this.element);var n=this.element;this.originalElement.css({position:n.css("position"),width:n.outerWidth(),height:n.outerHeight(),top:n.css("top"),left:n.css("left")}).insertAfter(n),n.remove()}return this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_mouseCapture:function(t){var n=!1;for(var r in this.handles)e(this.handles[r])[0]==t.target&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(t){var r=this.options,i=this.element.position(),s=this.element;this.resizing=!0,this.documentScroll={top:e(document).scrollTop(),left:e(document).scrollLeft()},(s.is(".ui-draggable")||/absolute/.test(s.css("position")))&&s.css({position:"absolute",top:i.top,left:i.left}),this._renderProxy();var o=n(this.helper.css("left")),u=n(this.helper.css("top"));r.containment&&(o+=e(r.containment).scrollLeft()||0,u+=e(r.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:o,top:u},this.size=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalSize=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalPosition={left:o,top:u},this.sizeDiff={width:s.outerWidth()-s.width(),height:s.outerHeight()-s.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof r.aspectRatio=="number"?r.aspectRatio:this.originalSize.width/this.originalSize.height||1;var a=e(".ui-resizable-"+this.axis).css("cursor");return e("body").css("cursor",a=="auto"?this.axis+"-resize":a),s.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(e){var t=this.helper,n=this.options,r={},i=this,s=this.originalMousePosition,o=this.axis,u=e.pageX-s.left||0,a=e.pageY-s.top||0,f=this._change[o];if(!f)return!1;var l=f.apply(this,[e,u,a]);this._updateVirtualBoundaries(e.shiftKey);if(this._aspectRatio||e.shiftKey)l=this._updateRatio(l,e);return l=this._respectSize(l,e),this._propagate("resize",e),t.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",e,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n=this.options,r=this;if(this._helper){var i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:r.sizeDiff.height,u=s?0:r.sizeDiff.width,a={width:r.helper.width()-u,height:r.helper.height()-o},f=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,l=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;n.animate||this.element.css(e.extend(a,{top:l,left:f})),r.helper.height(r.size.height),r.helper.width(r.size.width),this._helper&&!n.animate&&this._proportionallyResize()}return e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t=this.options,n,i,s,o,u;u={minWidth:r(t.minWidth)?t.minWidth:0,maxWidth:r(t.maxWidth)?t.maxWidth:Infinity,minHeight:r(t.minHeight)?t.minHeight:0,maxHeight:r(t.maxHeight)?t.maxHeight:Infinity};if(this._aspectRatio||e)n=u.minHeight*this.aspectRatio,s=u.minWidth/this.aspectRatio,i=u.maxHeight*this.aspectRatio,o=u.maxWidth/this.aspectRatio,n>u.minWidth&&(u.minWidth=n),s>u.minHeight&&(u.minHeight=s),i<u.maxWidth&&(u.maxWidth=i),o<u.maxHeight&&(u.maxHeight=o);this._vBoundaries=u},_updateCache:function(e){var t=this.options;this.offset=this.helper.offset(),r(e.left)&&(this.position.left=e.left),r(e.top)&&(this.position.top=e.top),r(e.height)&&(this.size.height=e.height),r(e.width)&&(this.size.width=e.width)},_updateRatio:function(e,t){var n=this.options,i=this.position,s=this.size,o=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&&(e.height=e.width/this.aspectRatio),o=="sw"&&(e.left=i.left+(s.width-e.width),e.top=null),o=="nw"&&(e.top=i.top+(s.height-e.height),e.left=i.left+(s.width-e.width)),e},_respectSize:function(e,t){var n=this.helper,i=this._vBoundaries,s=this._aspectRatio||t.shiftKey,o=this.axis,u=r(e.width)&&i.maxWidth&&i.maxWidth<e.width,a=r(e.height)&&i.maxHeight&&i.maxHeight<e.height,f=r(e.width)&&i.minWidth&&i.minWidth>e.width,l=r(e.height)&&i.minHeight&&i.minHeight>e.height;f&&(e.width=i.minWidth),l&&(e.height=i.minHeight),u&&(e.width=i.maxWidth),a&&(e.height=i.maxHeight);var c=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,p=/sw|nw|w/.test(o),d=/nw|ne|n/.test(o);f&&p&&(e.left=c-i.minWidth),u&&p&&(e.left=c-i.maxWidth),l&&d&&(e.top=h-i.minHeight),a&&d&&(e.top=h-i.maxHeight);var v=!e.width&&!e.height;return v&&!e.left&&e.top?e.top=null:v&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){var t=this.options;if(!this._proportionallyResizeElements.length)return;var n=this.helper||this.element;for(var r=0;r<this._proportionallyResizeElements.length;r++){var i=this._proportionallyResizeElements[r];if(!this.borderDif){var s=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],o=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];this.borderDif=e.map(s,function(e,t){var n=parseInt(e,10)||0,r=parseInt(o[t],10)||0;return n+r})}i.css({height:n.height()-this.borderDif[0]-this.borderDif[2]||0,width:n.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset();if(this._helper){this.helper=this.helper||e('<div style="overflow:hidden;"></div>');var r=e.ui.ie6?1:0,i=e.ui.ie6?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+i,height:this.element.outerHeight()+i,position:"absolute",left:this.elementOffset.left-r+"px",top:this.elementOffset.top-r+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(e,t,n){return{width:this.originalSize.width+t}},w:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{top:s.top+n,height:i.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!="resize"&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","alsoResize",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=function(t){e(t).each(function(){var t=e(this);t.data("resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};typeof i.alsoResize=="object"&&!i.alsoResize.parentNode?i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)}):s(i.alsoResize)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0},a=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("resizable-alsoresize"),s={},o=r&&r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var n=(i[t]||0)+(u[t]||0);n&&n>=0&&(s[t]=n||null)}),t.css(s)})};typeof i.alsoResize=="object"&&!i.alsoResize.nodeType?e.each(i.alsoResize,function(e,t){a(e,t)}):a(i.alsoResize)},stop:function(t,n){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","animate",{stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r._proportionallyResizeElements,o=s.length&&/textarea/i.test(s[0].nodeName),u=o&&e.ui.hasScroll(s[0],"left")?0:r.sizeDiff.height,a=o?0:r.sizeDiff.width,f={width:r.size.width-a,height:r.size.height-u},l=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,c=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;r.element.animate(e.extend(f,c&&l?{top:c,left:l}:{}),{duration:i.animateDuration,easing:i.animateEasing,step:function(){var n={width:parseInt(r.element.css("width"),10),height:parseInt(r.element.css("height"),10),top:parseInt(r.element.css("top"),10),left:parseInt(r.element.css("left"),10)};s&&s.length&&e(s[0]).css({width:n.width,height:n.height}),r._updateCache(n),r._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(t,r){var i=e(this).data("resizable"),s=i.options,o=i.element,u=s.containment,a=u instanceof e?u.get(0):/parent/.test(u)?o.parent().get(0):u;if(!a)return;i.containerElement=e(a);if(/document/.test(u)||u==document)i.containerOffset={left:0,top:0},i.containerPosition={left:0,top:0},i.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight};else{var f=e(a),l=[];e(["Top","Right","Left","Bottom"]).each(function(e,t){l[e]=n(f.css("padding"+t))}),i.containerOffset=f.offset(),i.containerPosition=f.position(),i.containerSize={height:f.innerHeight()-l[3],width:f.innerWidth()-l[1]};var c=i.containerOffset,h=i.containerSize.height,p=i.containerSize.width,d=e.ui.hasScroll(a,"left")?a.scrollWidth:p,v=e.ui.hasScroll(a)?a.scrollHeight:h;i.parentData={element:a,left:c.left,top:c.top,width:d,height:v}}},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.containerSize,o=r.containerOffset,u=r.size,a=r.position,f=r._aspectRatio||t.shiftKey,l={top:0,left:0},c=r.containerElement;c[0]!=document&&/static/.test(c.css("position"))&&(l=o),a.left<(r._helper?o.left:0)&&(r.size.width=r.size.width+(r._helper?r.position.left-o.left:r.position.left-l.left),f&&(r.size.height=r.size.width/r.aspectRatio),r.position.left=i.helper?o.left:0),a.top<(r._helper?o.top:0)&&(r.size.height=r.size.height+(r._helper?r.position.top-o.top:r.position.top),f&&(r.size.width=r.size.height*r.aspectRatio),r.position.top=r._helper?o.top:0),r.offset.left=r.parentData.left+r.position.left,r.offset.top=r.parentData.top+r.position.top;var h=Math.abs((r._helper?r.offset.left-l.left:r.offset.left-l.left)+r.sizeDiff.width),p=Math.abs((r._helper?r.offset.top-l.top:r.offset.top-o.top)+r.sizeDiff.height),d=r.containerElement.get(0)==r.element.parent().get(0),v=/relative|absolute/.test(r.containerElement.css("position"));d&&v&&(h-=r.parentData.left),h+r.size.width>=r.parentData.width&&(r.size.width=r.parentData.width-h,f&&(r.size.height=r.size.width/r.aspectRatio)),p+r.size.height>=r.parentData.height&&(r.size.height=r.parentData.height-p,f&&(r.size.width=r.size.height*r.aspectRatio))},stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.position,o=r.containerOffset,u=r.containerPosition,a=r.containerElement,f=e(r.helper),l=f.offset(),c=f.outerWidth()-r.sizeDiff.width,h=f.outerHeight()-r.sizeDiff.height;r._helper&&!i.animate&&/relative/.test(a.css("position"))&&e(this).css({left:l.left-u.left-o.left,width:c,height:h}),r._helper&&!i.animate&&/static/.test(a.css("position"))&&e(this).css({left:l.left-u.left-o.left,width:c,height:h})}}),e.ui.plugin.add("resizable","ghost",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size;r.ghost=r.originalElement.clone(),r.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof i.ghost=="string"?i.ghost:""),r.ghost.appendTo(r.helper)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&&r.ghost.css({position:"relative",height:r.size.height,width:r.size.width})},stop:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&&r.helper&&r.helper.get(0).removeChild(r.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size,o=r.originalSize,u=r.originalPosition,a=r.axis,f=i._aspectRatio||t.shiftKey;i.grid=typeof i.grid=="number"?[i.grid,i.grid]:i.grid;var l=Math.round((s.width-o.width)/(i.grid[0]||1))*(i.grid[0]||1),c=Math.round((s.height-o.height)/(i.grid[1]||1))*(i.grid[1]||1);/^(se|s|e)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c):/^(ne)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c):/^(sw)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.left=u.left-l):(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c,r.position.left=u.left-l)}});var n=function(e){return parseInt(e,10)||0},r=function(e){return!isNaN(parseInt(e,10))}})(jQuery);(function(e,t){e.widget("ui.selectable",e.ui.mouse,{version:"1.9.2",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var t=this;this.element.addClass("ui-selectable"),this.dragged=!1;var n;this.refresh=function(){n=e(t.options.filter,t.element[0]),n.addClass("ui-selectee"),n.each(function(){var t=e(this),n=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:n.left,top:n.top,right:n.left+t.outerWidth(),bottom:n.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=n.addClass("ui-selectee"),this._mouseInit(),this.helper=e("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(t){var n=this;this.opos=[t.pageX,t.pageY];if(this.options.disabled)return;var r=this.options;this.selectees=e(r.filter,this.element[0]),this._trigger("start",t),e(r.appendTo).append(this.helper),this.helper.css({left:t.clientX,top:t.clientY,width:0,height:0}),r.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var r=e.data(this,"selectable-item");r.startselected=!0,!t.metaKey&&!t.ctrlKey&&(r.$element.removeClass("ui-selected"),r.selected=!1,r.$element.addClass("ui-unselecting"),r.unselecting=!0,n._trigger("unselecting",t,{unselecting:r.element}))}),e(t.target).parents().andSelf().each(function(){var r=e.data(this,"selectable-item");if(r){var i=!t.metaKey&&!t.ctrlKey||!r.$element.hasClass("ui-selected");return r.$element.removeClass(i?"ui-unselecting":"ui-selected").addClass(i?"ui-selecting":"ui-unselecting"),r.unselecting=!i,r.selecting=i,r.selected=i,i?n._trigger("selecting",t,{selecting:r.element}):n._trigger("unselecting",t,{unselecting:r.element}),!1}})},_mouseDrag:function(t){var n=this;this.dragged=!0;if(this.options.disabled)return;var r=this.options,i=this.opos[0],s=this.opos[1],o=t.pageX,u=t.pageY;if(i>o){var a=o;o=i,i=a}if(s>u){var a=u;u=s,s=a}return this.helper.css({left:i,top:s,width:o-i,height:u-s}),this.selectees.each(function(){var a=e.data(this,"selectable-item");if(!a||a.element==n.element[0])return;var f=!1;r.tolerance=="touch"?f=!(a.left>o||a.right<i||a.top>u||a.bottom<s):r.tolerance=="fit"&&(f=a.left>i&&a.right<o&&a.top>s&&a.bottom<u),f?(a.selected&&(a.$element.removeClass("ui-selected"),a.selected=!1),a.unselecting&&(a.$element.removeClass("ui-unselecting"),a.unselecting=!1),a.selecting||(a.$element.addClass("ui-selecting"),a.selecting=!0,n._trigger("selecting",t,{selecting:a.element}))):(a.selecting&&((t.metaKey||t.ctrlKey)&&a.startselected?(a.$element.removeClass("ui-selecting"),a.selecting=!1,a.$element.addClass("ui-selected"),a.selected=!0):(a.$element.removeClass("ui-selecting"),a.selecting=!1,a.startselected&&(a.$element.addClass("ui-unselecting"),a.unselecting=!0),n._trigger("unselecting",t,{unselecting:a.element}))),a.selected&&!t.metaKey&&!t.ctrlKey&&!a.startselected&&(a.$element.removeClass("ui-selected"),a.selected=!1,a.$element.addClass("ui-unselecting"),a.unselecting=!0,n._trigger("unselecting",t,{unselecting:a.element})))}),!1},_mouseStop:function(t){var n=this;this.dragged=!1;var r=this.options;return e(".ui-unselecting",this.element[0]).each(function(){var r=e.data(this,"selectable-item");r.$element.removeClass("ui-unselecting"),r.unselecting=!1,r.startselected=!1,n._trigger("unselected",t,{unselected:r.element})}),e(".ui-selecting",this.element[0]).each(function(){var r=e.data(this,"selectable-item");r.$element.removeClass("ui-selecting").addClass("ui-selected"),r.selecting=!1,r.selected=!0,r.startselected=!0,n._trigger("selected",t,{selected:r.element})}),this._trigger("stop",t),this.helper.remove(),!1}})})(jQuery);(function(e,t){e.widget("ui.sortable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?e.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){t==="disabled"?(this.options[t]=n,this.widget().toggleClass("ui-sortable-disabled",!!n)):e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(t);var i=null,s=e(t.target).parents().each(function(){if(e.data(this,r.widgetName+"-item")==r)return i=e(this),!1});e.data(t.target,r.widgetName+"-item")==r&&(i=e(t.target));if(!i)return!1;if(this.options.handle&&!n){var o=!1;e(this.options.handle,i).find("*").andSelf().each(function(){this==t.target&&(o=!0)});if(!o)return!1}return this.currentItem=i,this._removeCurrentsFromItems(),!0},_mouseStart:function(t,n,r){var i=this.options;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),i.containment&&this._setContainment(),i.cursor&&(e("body").css("cursor")&&(this._storedCursor=e("body").css("cursor")),e("body").css("cursor",i.cursor)),i.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",i.opacity)),i.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",i.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(var s=this.containers.length-1;s>=0;s--)this.containers[s]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var n=this.options,r=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<n.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+n.scrollSpeed:t.pageY-this.overflowOffset.top<n.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-n.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<n.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+n.scrollSpeed:t.pageX-this.overflowOffset.left<n.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-n.scrollSpeed)):(t.pageY-e(document).scrollTop()<n.scrollSensitivity?r=e(document).scrollTop(e(document).scrollTop()-n.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<n.scrollSensitivity&&(r=e(document).scrollTop(e(document).scrollTop()+n.scrollSpeed)),t.pageX-e(document).scrollLeft()<n.scrollSensitivity?r=e(document).scrollLeft(e(document).scrollLeft()-n.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<n.scrollSensitivity&&(r=e(document).scrollLeft(e(document).scrollLeft()+n.scrollSpeed))),r!==!1&&e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(var i=this.items.length-1;i>=0;i--){var s=this.items[i],o=s.item[0],u=this._intersectsWithPointer(s);if(!u)continue;if(s.instance!==this.currentContainer)continue;if(o!=this.currentItem[0]&&this.placeholder[u==1?"next":"prev"]()[0]!=o&&!e.contains(this.placeholder[0],o)&&(this.options.type=="semi-dynamic"?!e.contains(this.element[0],o):!0)){this.direction=u==1?"down":"up";if(this.options.tolerance!="pointer"&&!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,n){if(!t)return;e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset();this.reverting=!0,e(this.helper).animate({left:i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1},cancel:function(){if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))}),!r.length&&t.key&&r.push(t.key+"="),r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")}),r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,s=e.left,o=s+e.width,u=e.top,a=u+e.height,f=this.offset.click.top,l=this.offset.click.left,c=r+f>u&&r+f<a&&t+l>s&&t+l<o;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?c:s<t+this.helperProportions.width/2&&n-this.helperProportions.width/2<o&&u<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<a},_intersectsWithPointer:function(t){var n=this.options.axis==="x"||e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),r=this.options.axis==="y"||e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),i=n&&r,s=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return i?this.floating?o&&o=="right"||s=="down"?2:1:s&&(s=="down"?2:1):!1},_intersectsWithSides:function(t){var n=e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),r=e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),i=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return this.floating&&s?s=="right"&&r||s=="left"&&!r:i&&(i=="down"&&n||i=="up"&&!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return e!=0&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return e!=0&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor==String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){var n=[],r=[],i=this._connectWith();if(i&&t)for(var s=i.length-1;s>=0;s--){var o=e(i[s]);for(var u=o.length-1;u>=0;u--){var a=e.data(o[u],this.widgetName);a&&a!=this&&!a.options.disabled&&r.push([e.isFunction(a.options.items)?a.options.items.call(a.element):e(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a])}}r.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var s=r.length-1;s>=0;s--)r[s][0].each(function(){n.push(this)});return e(n)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;n<t.length;n++)if(t[n]==e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var n=this.items,r=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],i=this._connectWith();if(i&&this.ready)for(var s=i.length-1;s>=0;s--){var o=e(i[s]);for(var u=o.length-1;u>=0;u--){var a=e.data(o[u],this.widgetName);a&&a!=this&&!a.options.disabled&&(r.push([e.isFunction(a.options.items)?a.options.items.call(a.element[0],t,{item:this.currentItem}):e(a.options.items,a.element),a]),this.containers.push(a))}}for(var s=r.length-1;s>=0;s--){var f=r[s][1],l=r[s][0];for(var u=0,c=l.length;u<c;u++){var h=e(l[u]);h.data(this.widgetName+"-item",f),n.push({item:h,instance:f,width:0,height:0,left:0,top:0})}}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var n=this.items.length-1;n>=0;n--){var r=this.items[n];if(r.instance!=this.currentContainer&&this.currentContainer&&r.item[0]!=this.currentItem[0])continue;var i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item;t||(r.width=i.outerWidth(),r.height=i.outerHeight());var s=i.offset();r.left=s.left,r.top=s.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var n=this.containers.length-1;n>=0;n--){var s=this.containers[n].element.offset();this.containers[n].containerCache.left=s.left,this.containers[n].containerCache.top=s.top,this.containers[n].containerCache.width=this.containers[n].element.outerWidth(),this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(t){t=t||this;var n=t.options;if(!n.placeholder||n.placeholder.constructor==String){var r=n.placeholder;n.placeholder={element:function(){var n=e(document.createElement(t.currentItem[0].nodeName)).addClass(r||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return r||(n.style.visibility="hidden"),n},update:function(e,i){if(r&&!n.forcePlaceholderSize)return;i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}}}t.placeholder=e(n.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),n.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var n=null,r=null;for(var i=this.containers.length-1;i>=0;i--){if(e.contains(this.currentItem[0],this.containers[i].element[0]))continue;if(this._intersectsWith(this.containers[i].containerCache)){if(n&&e.contains(this.containers[i].element[0],n.element[0]))continue;n=this.containers[i],r=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0)}if(!n)return;if(this.containers.length===1)this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1;else{var s=1e4,o=null,u=this.containers[r].floating?"left":"top",a=this.containers[r].floating?"width":"height",f=this.positionAbs[u]+this.offset.click[u];for(var l=this.items.length-1;l>=0;l--){if(!e.contains(this.containers[r].element[0],this.items[l].item[0]))continue;if(this.items[l].item[0]==this.currentItem[0])continue;var c=this.items[l].item.offset()[u],h=!1;Math.abs(c-f)>Math.abs(c+this.items[l][a]-f)&&(h=!0,c+=this.items[l][a]),Math.abs(c-f)<s&&(s=Math.abs(c-f),o=this.items[l],this.direction=h?"up":"down")}if(!o&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[r],o?this._rearrange(t,o,null,!0):this._rearrange(t,null,this.containers[r].element,!0),this._trigger("change",t,this._uiHash()),this.containers[r]._trigger("change",t,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):n.helper=="clone"?this.currentItem.clone():this.currentItem;return r.parents("body").length||e(n.appendTo!="parent"?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]),r[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(r[0].style.width==""||n.forceHelperSize)&&r.width(this.currentItem.width()),(r[0].style.height==""||n.forceHelperSize)&&r.height(this.currentItem.height()),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&&(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)){var n=e(t.containment)[0],r=e(t.containment).offset(),i=e(n).css("overflow")!="hidden";this.containment=[r.left+(parseInt(e(n).css("borderLeftWidth"),10)||0)+(parseInt(e(n).css("paddingLeft"),10)||0)-this.margins.left,r.top+(parseInt(e(n).css("borderTopWidth"),10)||0)+(parseInt(e(n).css("paddingTop"),10)||0)-this.margins.top,r.left+(i?Math.max(n.scrollWidth,n.offsetWidth):n.offsetWidth)-(parseInt(e(n).css("borderLeftWidth"),10)||0)-(parseInt(e(n).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,r.top+(i?Math.max(n.scrollHeight,n.offsetHeight):n.offsetHeight)-(parseInt(e(n).css("borderTopWidth"),10)||0)-(parseInt(e(n).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var s=t.pageX,o=t.pageY;if(this.originalPosition){this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(s=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(s=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top));if(n.grid){var u=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1];o=this.containment?u-this.offset.click.top<this.containment[1]||u-this.offset.click.top>this.containment[3]?u-this.offset.click.top<this.containment[1]?u+n.grid[1]:u-n.grid[1]:u:u;var a=this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0];s=this.containment?a-this.offset.click.left<this.containment[0]||a-this.offset.click.left>this.containment[2]?a-this.offset.click.left<this.containment[0]?a+n.grid[0]:a-n.grid[0]:a:a}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i==this.counter&&this.refreshPositions(!r)})},_clear:function(t,n){this.reverting=!1;var r=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var i in this._storedCSS)if(this._storedCSS[i]=="auto"||this._storedCSS[i]=="static")this._storedCSS[i]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!n&&r.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!n&&r.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(n||(r.push(function(e){this._trigger("remove",e,this._uiHash())}),r.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),r.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))));for(var i=this.containers.length-1;i>=0;i--)n||r.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over&&(r.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over=0);this._storedCursor&&e("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!n){this._trigger("beforeStop",t,this._uiHash());for(var i=0;i<r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}n||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!n){for(var i=0;i<r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})})(jQuery);(function(e,t){var n=0,r={},i={};r.height=r.paddingTop=r.paddingBottom=r.borderTopWidth=r.borderBottomWidth="hide",i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="show",e.widget("ui.accordion",{version:"1.9.2",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var t=this.accordionId="ui-accordion-"+(this.element.attr("id")||++n),r=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset"),this.headers=this.element.find(r.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this._hoverable(this.headers),this._focusable(this.headers),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").hide(),!r.collapsible&&(r.active===!1||r.active==null)&&(r.active=0),r.active<0&&(r.active+=this.headers.length),this.active=this._findActive(r.active).addClass("ui-accordion-header-active ui-state-active").toggleClass("ui-corner-all ui-corner-top"),this.active.next().addClass("ui-accordion-content-active").show(),this._createIcons(),this.refresh(),this.element.attr("role","tablist"),this.headers.attr("role","tab").each(function(n){var r=e(this),i=r.attr("id"),s=r.next(),o=s.attr("id");i||(i=t+"-header-"+n,r.attr("id",i)),o||(o=t+"-panel-"+n,s.attr("id",o)),r.attr("aria-controls",o),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false",tabIndex:-1}).next().attr({"aria-expanded":"false","aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true",tabIndex:0}).next().attr({"aria-expanded":"true","aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._on(this.headers,{keydown:"_keydown"}),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._setupEvents(r.event)},_getCreateEventData:function(){return{header:this.active,content:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("<span>").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),e=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this.options.heightStyle!=="content"&&e.css("height","")},_setOption:function(e,t){if(e==="active"){this._activate(t);return}e==="event"&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),e==="collapsible"&&!t&&this.options.active===!1&&this._activate(0),e==="icons"&&(this._destroyIcons(),t&&this._createIcons()),e==="disabled"&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)},_keydown:function(t){if(t.altKey||t.ctrlKey)return;var n=e.ui.keyCode,r=this.headers.length,i=this.headers.index(t.target),s=!1;switch(t.keyCode){case n.RIGHT:case n.DOWN:s=this.headers[(i+1)%r];break;case n.LEFT:case n.UP:s=this.headers[(i-1+r)%r];break;case n.SPACE:case n.ENTER:this._eventHandler(t);break;case n.HOME:s=this.headers[0];break;case n.END:s=this.headers[r-1]}s&&(e(t.target).attr("tabIndex",-1),e(s).attr("tabIndex",0),s.focus(),t.preventDefault())},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t,n,r=this.options.heightStyle,i=this.element.parent();r==="fill"?(e.support.minHeight||(n=i.css("overflow"),i.css("overflow","hidden")),t=i.height(),this.element.siblings(":visible").each(function(){var n=e(this),r=n.css("position");if(r==="absolute"||r==="fixed")return;t-=n.outerHeight(!0)}),n&&i.css("overflow",n),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):r==="auto"&&(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).css("height","").height())}).height(t))},_activate:function(t){var n=this._findActive(t)[0];if(n===this.active[0])return;n=n||this.active[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return typeof t=="number"?this.headers.eq(t):e()},_setupEvents:function(t){var n={};if(!t)return;e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._on(this.headers,n)},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i[0]===r[0],o=s&&n.collapsible,u=o?e():i.next(),a=r.next(),f={oldHeader:r,oldPanel:a,newHeader:o?e():i,newPanel:u};t.preventDefault();if(s&&!n.collapsible||this._trigger("beforeActivate",t,f)===!1)return;n.active=o?!1:this.headers.index(i),this.active=s?e():i,this._toggle(f),r.removeClass("ui-accordion-header-active ui-state-active"),n.icons&&r.children(".ui-accordion-header-icon").removeClass(n.icons.activeHeader).addClass(n.icons.header),s||(i.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),n.icons&&i.children(".ui-accordion-header-icon").removeClass(n.icons.header).addClass(n.icons.activeHeader),i.next().addClass("ui-accordion-content-active"))},_toggle:function(t){var n=t.newPanel,r=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=n,this.prevHide=r,this.options.animate?this._animate(n,r,t):(r.hide(),n.show(),this._toggleComplete(t)),r.attr({"aria-expanded":"false","aria-hidden":"true"}),r.prev().attr("aria-selected","false"),n.length&&r.length?r.prev().attr("tabIndex",-1):n.length&&this.headers.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),n.attr({"aria-expanded":"true","aria-hidden":"false"}).prev().attr({"aria-selected":"true",tabIndex:0})},_animate:function(e,t,n){var s,o,u,a=this,f=0,l=e.length&&(!t.length||e.index()<t.index()),c=this.options.animate||{},h=l&&c.down||c,p=function(){a._toggleComplete(n)};typeof h=="number"&&(u=h),typeof h=="string"&&(o=h),o=o||h.easing||c.easing,u=u||h.duration||c.duration;if(!t.length)return e.animate(i,u,o,p);if(!e.length)return t.animate(r,u,o,p);s=e.show().outerHeight(),t.animate(r,{duration:u,easing:o,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(i,{duration:u,easing:o,complete:p,step:function(e,n){n.now=Math.round(e),n.prop!=="height"?f+=n.now:a.options.heightStyle!=="content"&&(n.now=Math.round(s-t.outerHeight()-f),f=0)}})},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&&(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}}),e.uiBackCompat!==!1&&(function(e,t){e.extend(t.options,{navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}});var n=t._create;t._create=function(){if(this.options.navigation){var t=this,r=this.element.find(this.options.header),i=r.next(),s=r.add(i).find("a").filter(this.options.navigationFilter)[0];s&&r.add(i).each(function(n){if(e.contains(this,s))return t.options.active=Math.floor(n/2),!1})}n.call(this)}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options,{heightStyle:null,autoHeight:!0,clearStyle:!1,fillSpace:!1});var n=t._create,r=t._setOption;e.extend(t,{_create:function(){this.options.heightStyle=this.options.heightStyle||this._mergeHeightStyle(),n.call(this)},_setOption:function(e){if(e==="autoHeight"||e==="clearStyle"||e==="fillSpace")this.options.heightStyle=this._mergeHeightStyle();r.apply(this,arguments)},_mergeHeightStyle:function(){var e=this.options;if(e.fillSpace)return"fill";if(e.clearStyle)return"content";if(e.autoHeight)return"auto"}})}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options.icons,{activeHeader:null,headerSelected:"ui-icon-triangle-1-s"});var n=t._createIcons;t._createIcons=function(){this.options.icons&&(this.options.icons.activeHeader=this.options.icons.activeHeader||this.options.icons.headerSelected),n.call(this)}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){t.activate=t._activate;var n=t._findActive;t._findActive=function(e){return e===-1&&(e=!1),e&&typeof e!="number"&&(e=this.headers.index(this.headers.filter(e)),e===-1&&(e=!1)),n.call(this,e)}}(jQuery,jQuery.ui.accordion.prototype),jQuery.ui.accordion.prototype.resize=jQuery.ui.accordion.prototype.refresh,function(e,t){e.extend(t.options,{change:null,changestart:null});var n=t._trigger;t._trigger=function(e,t,r){var i=n.apply(this,arguments);return i?(e==="beforeActivate"?i=n.call(this,"changestart",t,{oldHeader:r.oldHeader,oldContent:r.oldPanel,newHeader:r.newHeader,newContent:r.newPanel}):e==="activate"&&(i=n.call(this,"change",t,{oldHeader:r.oldHeader,oldContent:r.oldPanel,newHeader:r.newHeader,newContent:r.newPanel})),i):!1}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options,{animate:null,animated:"slide"});var n=t._create;t._create=function(){var e=this.options;e.animate===null&&(e.animated?e.animated==="slide"?e.animate=300:e.animated==="bounceslide"?e.animate={duration:200,down:{easing:"easeOutBounce",duration:1e3}}:e.animate=e.animated:e.animate=!1),n.call(this)}}(jQuery,jQuery.ui.accordion.prototype))})(jQuery);(function(e,t){var n=0;e.widget("ui.autocomplete",{version:"1.9.2",defaultElement:"<input>",options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},pending:0,_create:function(){var t,n,r;this.isMultiLine=this._isMultiLine(),this.valueMethod=this.element[this.element.is("input,textarea")?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(i){if(this.element.prop("readOnly")){t=!0,r=!0,n=!0;return}t=!1,r=!1,n=!1;var s=e.ui.keyCode;switch(i.keyCode){case s.PAGE_UP:t=!0,this._move("previousPage",i);break;case s.PAGE_DOWN:t=!0,this._move("nextPage",i);break;case s.UP:t=!0,this._keyEvent("previous",i);break;case s.DOWN:t=!0,this._keyEvent("next",i);break;case s.ENTER:case s.NUMPAD_ENTER:this.menu.active&&(t=!0,i.preventDefault(),this.menu.select(i));break;case s.TAB:this.menu.active&&this.menu.select(i);break;case s.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(i),i.preventDefault());break;default:n=!0,this._searchTimeout(i)}},keypress:function(r){if(t){t=!1,r.preventDefault();return}if(n)return;var i=e.ui.keyCode;switch(r.keyCode){case i.PAGE_UP:this._move("previousPage",r);break;case i.PAGE_DOWN:this._move("nextPage",r);break;case i.UP:this._keyEvent("previous",r);break;case i.DOWN:this._keyEvent("next",r)}},input:function(e){if(r){r=!1,e.preventDefault();return}this._searchTimeout(e)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}clearTimeout(this.searching),this.close(e),this._change(e)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete").appendTo(this.document.find(this.options.appendTo||"body")[0]).menu({input:e(),role:null}).zIndex(this.element.zIndex()+1).hide().data("menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var n=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(r){r.target!==t.element[0]&&r.target!==n&&!e.contains(n,r.target)&&t.close()})})},menufocus:function(t,n){if(this.isNewMenu){this.isNewMenu=!1;if(t.originalEvent&&/^mouse/.test(t.originalEvent.type)){this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)});return}}var r=n.item.data("ui-autocomplete-item")||n.item.data("item.autocomplete");!1!==this._trigger("focus",t,{item:r})?t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(r.value):this.liveRegion.text(r.value)},menuselect:function(e,t){var n=t.item.data("ui-autocomplete-item")||t.item.data("item.autocomplete"),r=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=r,this._delay(function(){this.previous=r,this.selectedItem=n})),!1!==this._trigger("select",e,{item:n})&&this._value(n.value),this.term=this._value(),this.close(e),this.selectedItem=n}}),this.liveRegion=e("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertAfter(this.element),e.fn.bgiframe&&this.menu.element.bgiframe(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),e==="source"&&this._initSource(),e==="appendTo"&&this.menu.element.appendTo(this.document.find(t||"body")[0]),e==="disabled"&&t&&this.xhr&&this.xhr.abort()},_isMultiLine:function(){return this.element.is("textarea")?!0:this.element.is("input")?!1:this.element.prop("isContentEditable")},_initSource:function(){var t,n,r=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(n,r){r(e.ui.autocomplete.filter(t,n.term))}):typeof this.options.source=="string"?(n=this.options.source,this.source=function(t,i){r.xhr&&r.xhr.abort(),r.xhr=e.ajax({url:n,data:t,dataType:"json",success:function(e){i(e)},error:function(){i([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){e=e!=null?e:this._value(),this.term=this._value();if(e.length<this.options.minLength)return this.close(t);if(this._trigger("search",t)===!1)return;return this._search(e)},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var e=this,t=++n;return function(r){t===n&&e.__response(r),e.pending--,e.pending||e.element.removeClass("ui-autocomplete-loading")}},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return typeof t=="string"?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var n=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(n,t),this.menu.refresh(),n.show(),this._resizeMenu(),n.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,n){var r=this;e.each(n,function(e,n){r._renderItemData(t,n)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,n){return e("<li>").append(e("<a>").text(n.label)).appendTo(t)},_move:function(e,t){if(!this.menu.element.is(":visible")){this.search(null,t);return}if(this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)){this._value(this.term),this.menu.blur();return}this.menu[e](t)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(e,t),t.preventDefault()}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,n){var r=new RegExp(e.ui.autocomplete.escapeRegex(n),"i");return e.grep(t,function(e){return r.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments);if(this.options.disabled||this.cancelSearch)return;e&&e.length?t=this.options.messages.results(e.length):t=this.options.messages.noResults,this.liveRegion.text(t)}})})(jQuery);(function(e,t){var n,r,i,s,o="ui-button ui-widget ui-state-default ui-corner-all",u="ui-state-hover ui-state-active ",a="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",f=function(){var t=e(this).find(":ui-button");setTimeout(function(){t.button("refresh")},1)},l=function(t){var n=t.name,r=t.form,i=e([]);return n&&(r?i=e(r).find("[name='"+n+"']"):i=e("[name='"+n+"']",t.ownerDocument).filter(function(){return!this.form})),i};e.widget("ui.button",{version:"1.9.2",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,f),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var t=this,u=this.options,a=this.type==="checkbox"||this.type==="radio",c=a?"":"ui-state-active",h="ui-state-focus";u.label===null&&(u.label=this.type==="input"?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(o).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){if(u.disabled)return;this===n&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){if(u.disabled)return;e(this).removeClass(c)}).bind("click"+this.eventNamespace,function(e){u.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this.element.bind("focus"+this.eventNamespace,function(){t.buttonElement.addClass(h)}).bind("blur"+this.eventNamespace,function(){t.buttonElement.removeClass(h)}),a&&(this.element.bind("change"+this.eventNamespace,function(){if(s)return;t.refresh()}),this.buttonElement.bind("mousedown"+this.eventNamespace,function(e){if(u.disabled)return;s=!1,r=e.pageX,i=e.pageY}).bind("mouseup"+this.eventNamespace,function(e){if(u.disabled)return;if(r!==e.pageX||i!==e.pageY)s=!0})),this.type==="checkbox"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).toggleClass("ui-state-active"),t.buttonElement.attr("aria-pressed",t.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).addClass("ui-state-active"),t.buttonElement.attr("aria-pressed","true");var n=t.element[0];l(n).not(n).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).addClass("ui-state-active"),n=this,t.document.one("mouseup",function(){n=null})}).bind("mouseup"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).removeClass("ui-state-active")}).bind("keydown"+this.eventNamespace,function(t){if(u.disabled)return!1;(t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active")}).bind("keyup"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",u.disabled),this._resetButton()},_determineButtonType:function(){var e,t,n;this.element.is("[type=checkbox]")?this.type="checkbox":this.element.is("[type=radio]")?this.type="radio":this.element.is("input")?this.type="input":this.type="button",this.type==="checkbox"||this.type==="radio"?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),n=this.element.is(":checked"),n&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",n)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(o+" "+u+" "+a).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){this._super(e,t);if(e==="disabled"){t?this.element.prop("disabled",!0):this.element.prop("disabled",!1);return}this._resetButton()},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),this.type==="radio"?l(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var t=this.buttonElement.removeClass(a),n=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),r=this.options.icons,i=r.primary&&r.secondary,s=[];r.primary||r.secondary?(this.options.text&&s.push("ui-button-text-icon"+(i?"s":r.primary?"-primary":"-secondary")),r.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+r.primary+"'></span>"),r.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+r.secondary+"'></span>"),this.options.text||(s.push(i?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(n)))):s.push("ui-button-text-only"),t.addClass(s.join(" "))}}),e.widget("ui.buttonset",{version:"1.9.2",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){e==="disabled"&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function($,undefined){function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}function bindHover(e){var t="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.delegate(t,"mouseout",function(){$(this).removeClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!=-1&&$(this).removeClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!=-1&&$(this).removeClass("ui-datepicker-next-hover")}).delegate(t,"mouseover",function(){$.datepicker._isDisabledDatepicker(instActive.inline?e.parent()[0]:instActive.input[0])||($(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),$(this).addClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!=-1&&$(this).addClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!=-1&&$(this).addClass("ui-datepicker-next-hover"))})}function extendRemove(e,t){$.extend(e,t);for(var n in t)if(t[n]==null||t[n]==undefined)e[n]=t[n];return e}$.extend($.ui,{datepicker:{version:"1.9.2"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return extendRemove(this._defaults,e||{}),this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(e,t){var n=e[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:n,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:t,dpDiv:t?bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')):this.dpDiv}},_connectDatepicker:function(e,t){var n=$(e);t.append=$([]),t.trigger=$([]);if(n.hasClass(this.markerClassName))return;this._attachments(n,t),n.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(e,n,r){t.settings[n]=r}).bind("getData.datepicker",function(e,n){return this._get(t,n)}),this._autoSize(t),$.data(e,PROP_NAME,t),t.settings.disabled&&this._disableDatepicker(e)},_attachments:function(e,t){var n=this._get(t,"appendText"),r=this._get(t,"isRTL");t.append&&t.append.remove(),n&&(t.append=$('<span class="'+this._appendClass+'">'+n+"</span>"),e[r?"before":"after"](t.append)),e.unbind("focus",this._showDatepicker),t.trigger&&t.trigger.remove();var i=this._get(t,"showOn");(i=="focus"||i=="both")&&e.focus(this._showDatepicker);if(i=="button"||i=="both"){var s=this._get(t,"buttonText"),o=this._get(t,"buttonImage");t.trigger=$(this._get(t,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:o,alt:s,title:s}):$('<button type="button"></button>').addClass(this._triggerClass).html(o==""?s:$("<img/>").attr({src:o,alt:s,title:s}))),e[r?"before":"after"](t.trigger),t.trigger.click(function(){return $.datepicker._datepickerShowing&&$.datepicker._lastInput==e[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=e[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(e[0])):$.datepicker._showDatepicker(e[0]),!1})}},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t=new Date(2009,11,20),n=this._get(e,"dateFormat");if(n.match(/[DM]/)){var r=function(e){var t=0,n=0;for(var r=0;r<e.length;r++)e[r].length>t&&(t=e[r].length,n=r);return n};t.setMonth(r(this._get(e,n.match(/MM/)?"monthNames":"monthNamesShort"))),t.setDate(r(this._get(e,n.match(/DD/)?"dayNames":"dayNamesShort"))+20-t.getDay())}e.input.attr("size",this._formatDate(e,t).length)}},_inlineDatepicker:function(e,t){var n=$(e);if(n.hasClass(this.markerClassName))return;n.addClass(this.markerClassName).append(t.dpDiv).bind("setData.datepicker",function(e,n,r){t.settings[n]=r}).bind("getData.datepicker",function(e,n){return this._get(t,n)}),$.data(e,PROP_NAME,t),this._setDate(t,this._getDefaultDate(t),!0),this._updateDatepicker(t),this._updateAlternate(t),t.settings.disabled&&this._disableDatepicker(e),t.dpDiv.css("display","block")},_dialogDatepicker:function(e,t,n,r,i){var s=this._dialogInst;if(!s){this.uuid+=1;var o="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+o+'" style="position: absolute; top: -100px; width: 0px;"/>'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),s=this._dialogInst=this._newInst(this._dialogInput,!1),s.settings={},$.data(this._dialogInput[0],PROP_NAME,s)}extendRemove(s.settings,r||{}),t=t&&t.constructor==Date?this._formatDate(s,t):t,this._dialogInput.val(t),this._pos=i?i.length?i:[i.pageX,i.pageY]:null;if(!this._pos){var u=document.documentElement.clientWidth,a=document.documentElement.clientHeight,f=document.documentElement.scrollLeft||document.body.scrollLeft,l=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[u/2-100+f,a/2-150+l]}return this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),s.settings.onSelect=n,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,s),this},_destroyDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();$.removeData(e,PROP_NAME),r=="input"?(n.append.remove(),n.trigger.remove(),t.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(r=="div"||r=="span")&&t.removeClass(this.markerClassName).empty()},_enableDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();if(r=="input")e.disabled=!1,n.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(r=="div"||r=="span"){var i=t.children("."+this._inlineClass);i.children().removeClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)}this._disabledInputs=$.map(this._disabledInputs,function(t){return t==e?null:t})},_disableDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();if(r=="input")e.disabled=!0,n.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(r=="div"||r=="span"){var i=t.children("."+this._inlineClass);i.children().addClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)}this._disabledInputs=$.map(this._disabledInputs,function(t){return t==e?null:t}),this._disabledInputs[this._disabledInputs.length]=e},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;t<this._disabledInputs.length;t++)if(this._disabledInputs[t]==e)return!0;return!1},_getInst:function(e){try{return $.data(e,PROP_NAME)}catch(t){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,t,n){var r=this._getInst(e);if(arguments.length==2&&typeof t=="string")return t=="defaults"?$.extend({},$.datepicker._defaults):r?t=="all"?$.extend({},r.settings):this._get(r,t):null;var i=t||{};typeof t=="string"&&(i={},i[t]=n);if(r){this._curInst==r&&this._hideDatepicker();var s=this._getDateDatepicker(e,!0),o=this._getMinMaxDate(r,"min"),u=this._getMinMaxDate(r,"max");extendRemove(r.settings,i),o!==null&&i.dateFormat!==undefined&&i.minDate===undefined&&(r.settings.minDate=this._formatDate(r,o)),u!==null&&i.dateFormat!==undefined&&i.maxDate===undefined&&(r.settings.maxDate=this._formatDate(r,u)),this._attachments($(e),r),this._autoSize(r),this._setDate(r,s),this._updateAlternate(r),this._updateDatepicker(r)}},_changeDatepicker:function(e,t,n){this._optionDatepicker(e,t,n)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var n=this._getInst(e);n&&(this._setDate(n,t),this._updateDatepicker(n),this._updateAlternate(n))},_getDateDatepicker:function(e,t){var n=this._getInst(e);return n&&!n.inline&&this._setDateFromField(n,t),n?this._getDate(n):null},_doKeyDown:function(e){var t=$.datepicker._getInst(e.target),n=!0,r=t.dpDiv.is(".ui-datepicker-rtl");t._keyEvent=!0;if($.datepicker._datepickerShowing)switch(e.keyCode){case 9:$.datepicker._hideDatepicker(),n=!1;break;case 13:var i=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",t.dpDiv);i[0]&&$.datepicker._selectDay(e.target,t.selectedMonth,t.selectedYear,i[0]);var s=$.datepicker._get(t,"onSelect");if(s){var o=$.datepicker._formatDate(t);s.apply(t.input?t.input[0]:null,[o,t])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(e.target,e.ctrlKey?-$.datepicker._get(t,"stepBigMonths"):-$.datepicker._get(t,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(e.target,e.ctrlKey?+$.datepicker._get(t,"stepBigMonths"):+$.datepicker._get(t,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&$.datepicker._clearDate(e.target),n=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&$.datepicker._gotoToday(e.target),n=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,r?1:-1,"D"),n=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&$.datepicker._adjustDate(e.target,e.ctrlKey?-$.datepicker._get(t,"stepBigMonths"):-$.datepicker._get(t,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,-7,"D"),n=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,r?-1:1,"D"),n=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&$.datepicker._adjustDate(e.target,e.ctrlKey?+$.datepicker._get(t,"stepBigMonths"):+$.datepicker._get(t,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,7,"D"),n=e.ctrlKey||e.metaKey;break;default:n=!1}else e.keyCode==36&&e.ctrlKey?$.datepicker._showDatepicker(this):n=!1;n&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var t=$.datepicker._getInst(e.target);if($.datepicker._get(t,"constrainInput")){var n=$.datepicker._possibleChars($.datepicker._get(t,"dateFormat")),r=String.fromCharCode(e.charCode==undefined?e.keyCode:e.charCode);return e.ctrlKey||e.metaKey||r<" "||!n||n.indexOf(r)>-1}},_doKeyUp:function(e){var t=$.datepicker._getInst(e.target);if(t.input.val()!=t.lastVal)try{var n=$.datepicker.parseDate($.datepicker._get(t,"dateFormat"),t.input?t.input.val():null,$.datepicker._getFormatConfig(t));n&&($.datepicker._setDateFromField(t),$.datepicker._updateAlternate(t),$.datepicker._updateDatepicker(t))}catch(r){$.datepicker.log(r)}return!0},_showDatepicker:function(e){e=e.target||e,e.nodeName.toLowerCase()!="input"&&(e=$("input",e.parentNode)[0]);if($.datepicker._isDisabledDatepicker(e)||$.datepicker._lastInput==e)return;var t=$.datepicker._getInst(e);$.datepicker._curInst&&$.datepicker._curInst!=t&&($.datepicker._curInst.dpDiv.stop(!0,!0),t&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var n=$.datepicker._get(t,"beforeShow"),r=n?n.apply(e,[e,t]):{};if(r===!1)return;extendRemove(t.settings,r),t.lastVal=null,$.datepicker._lastInput=e,$.datepicker._setDateFromField(t),$.datepicker._inDialog&&(e.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(e),$.datepicker._pos[1]+=e.offsetHeight);var i=!1;$(e).parents().each(function(){return i|=$(this).css("position")=="fixed",!i});var s={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,t.dpDiv.empty(),t.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(t),s=$.datepicker._checkOffset(t,s,i),t.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":i?"fixed":"absolute",display:"none",left:s.left+"px",top:s.top+"px"});if(!t.inline){var o=$.datepicker._get(t,"showAnim"),u=$.datepicker._get(t,"duration"),a=function(){var e=t.dpDiv.find("iframe.ui-datepicker-cover");if(!!e.length){var n=$.datepicker._getBorders(t.dpDiv);e.css({left:-n[0],top:-n[1],width:t.dpDiv.outerWidth(),height:t.dpDiv.outerHeight()})}};t.dpDiv.zIndex($(e).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&($.effects.effect[o]||$.effects[o])?t.dpDiv.show(o,$.datepicker._get(t,"showOptions"),u,a):t.dpDiv[o||"show"](o?u:null,a),(!o||!u)&&a(),t.input.is(":visible")&&!t.input.is(":disabled")&&t.input.focus(),$.datepicker._curInst=t}},_updateDatepicker:function(e){this.maxRows=4;var t=$.datepicker._getBorders(e.dpDiv);instActive=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var n=e.dpDiv.find("iframe.ui-datepicker-cover");!n.length||n.css({left:-t[0],top:-t[1],width:e.dpDiv.outerWidth(),height:e.dpDiv.outerHeight()}),e.dpDiv.find("."+this._dayOverClass+" a").mouseover();var r=this._getNumberOfMonths(e),i=r[1],s=17;e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),i>1&&e.dpDiv.addClass("ui-datepicker-multi-"+i).css("width",s*i+"em"),e.dpDiv[(r[0]!=1||r[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e==$.datepicker._curInst&&$.datepicker._datepickerShowing&&e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&e.input[0]!=document.activeElement&&e.input.focus();if(e.yearshtml){var o=e.yearshtml;setTimeout(function(){o===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),o=e.yearshtml=null},0)}},_getBorders:function(e){var t=function(e){return{thin:1,medium:2,thick:3}[e]||e};return[parseFloat(t(e.css("border-left-width"))),parseFloat(t(e.css("border-top-width")))]},_checkOffset:function(e,t,n){var r=e.dpDiv.outerWidth(),i=e.dpDiv.outerHeight(),s=e.input?e.input.outerWidth():0,o=e.input?e.input.outerHeight():0,u=document.documentElement.clientWidth+(n?0:$(document).scrollLeft()),a=document.documentElement.clientHeight+(n?0:$(document).scrollTop());return t.left-=this._get(e,"isRTL")?r-s:0,t.left-=n&&t.left==e.input.offset().left?$(document).scrollLeft():0,t.top-=n&&t.top==e.input.offset().top+o?$(document).scrollTop():0,t.left-=Math.min(t.left,t.left+r>u&&u>r?Math.abs(t.left+r-u):0),t.top-=Math.min(t.top,t.top+i>a&&a>i?Math.abs(i+o):0),t},_findPos:function(e){var t=this._getInst(e),n=this._get(t,"isRTL");while(e&&(e.type=="hidden"||e.nodeType!=1||$.expr.filters.hidden(e)))e=e[n?"previousSibling":"nextSibling"];var r=$(e).offset();return[r.left,r.top]},_hideDatepicker:function(e){var t=this._curInst;if(!t||e&&t!=$.data(e,PROP_NAME))return;if(this._datepickerShowing){var n=this._get(t,"showAnim"),r=this._get(t,"duration"),i=function(){$.datepicker._tidyDialog(t)};$.effects&&($.effects.effect[n]||$.effects[n])?t.dpDiv.hide(n,$.datepicker._get(t,"showOptions"),r,i):t.dpDiv[n=="slideDown"?"slideUp":n=="fadeIn"?"fadeOut":"hide"](n?r:null,i),n||i(),this._datepickerShowing=!1;var s=this._get(t,"onClose");s&&s.apply(t.input?t.input[0]:null,[t.input?t.input.val():"",t]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(!$.datepicker._curInst)return;var t=$(e.target),n=$.datepicker._getInst(t[0]);(t[0].id!=$.datepicker._mainDivId&&t.parents("#"+$.datepicker._mainDivId).length==0&&!t.hasClass($.datepicker.markerClassName)&&!t.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||t.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=n)&&$.datepicker._hideDatepicker()},_adjustDate:function(e,t,n){var r=$(e),i=this._getInst(r[0]);if(this._isDisabledDatepicker(r[0]))return;this._adjustInstDate(i,t+(n=="M"?this._get(i,"showCurrentAtPos"):0),n),this._updateDatepicker(i)},_gotoToday:function(e){var t=$(e),n=this._getInst(t[0]);if(this._get(n,"gotoCurrent")&&n.currentDay)n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear;else{var r=new Date;n.selectedDay=r.getDate(),n.drawMonth=n.selectedMonth=r.getMonth(),n.drawYear=n.selectedYear=r.getFullYear()}this._notifyChange(n),this._adjustDate(t)},_selectMonthYear:function(e,t,n){var r=$(e),i=this._getInst(r[0]);i["selected"+(n=="M"?"Month":"Year")]=i["draw"+(n=="M"?"Month":"Year")]=parseInt(t.options[t.selectedIndex].value,10),this._notifyChange(i),this._adjustDate(r)},_selectDay:function(e,t,n,r){var i=$(e);if($(r).hasClass(this._unselectableClass)||this._isDisabledDatepicker(i[0]))return;var s=this._getInst(i[0]);s.selectedDay=s.currentDay=$("a",r).html(),s.selectedMonth=s.currentMonth=t,s.selectedYear=s.currentYear=n,this._selectDate(e,this._formatDate(s,s.currentDay,s.currentMonth,s.currentYear))},_clearDate:function(e){var t=$(e),n=this._getInst(t[0]);this._selectDate(t,"")},_selectDate:function(e,t){var n=$(e),r=this._getInst(n[0]);t=t!=null?t:this._formatDate(r),r.input&&r.input.val(t),this._updateAlternate(r);var i=this._get(r,"onSelect");i?i.apply(r.input?r.input[0]:null,[t,r]):r.input&&r.input.trigger("change"),r.inline?this._updateDatepicker(r):(this._hideDatepicker(),this._lastInput=r.input[0],typeof r.input[0]!="object"&&r.input.focus(),this._lastInput=null)},_updateAlternate:function(e){var t=this._get(e,"altField");if(t){var n=this._get(e,"altFormat")||this._get(e,"dateFormat"),r=this._getDate(e),i=this.formatDate(n,r,this._getFormatConfig(e));$(t).each(function(){$(this).val(i)})}},noWeekends:function(e){var t=e.getDay();return[t>0&&t<6,""]},iso8601Week:function(e){var t=new Date(e.getTime());t.setDate(t.getDate()+4-(t.getDay()||7));var n=t.getTime();return t.setMonth(0),t.setDate(1),Math.floor(Math.round((n-t)/864e5)/7)+1},parseDate:function(e,t,n){if(e==null||t==null)throw"Invalid arguments";t=typeof t=="object"?t.toString():t+"";if(t=="")return null;var r=(n?n.shortYearCutoff:null)||this._defaults.shortYearCutoff;r=typeof r!="string"?r:(new Date).getFullYear()%100+parseInt(r,10);var i=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,s=(n?n.dayNames:null)||this._defaults.dayNames,o=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,u=(n?n.monthNames:null)||this._defaults.monthNames,a=-1,f=-1,l=-1,c=-1,h=!1,p=function(t){var n=y+1<e.length&&e.charAt(y+1)==t;return n&&y++,n},d=function(e){var n=p(e),r=e=="@"?14:e=="!"?20:e=="y"&&n?4:e=="o"?3:2,i=new RegExp("^\\d{1,"+r+"}"),s=t.substring(g).match(i);if(!s)throw"Missing number at position "+g;return g+=s[0].length,parseInt(s[0],10)},v=function(e,n,r){var i=$.map(p(e)?r:n,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)}),s=-1;$.each(i,function(e,n){var r=n[1];if(t.substr(g,r.length).toLowerCase()==r.toLowerCase())return s=n[0],g+=r.length,!1});if(s!=-1)return s+1;throw"Unknown name at position "+g},m=function(){if(t.charAt(g)!=e.charAt(y))throw"Unexpected literal at position "+g;g++},g=0;for(var y=0;y<e.length;y++)if(h)e.charAt(y)=="'"&&!p("'")?h=!1:m();else switch(e.charAt(y)){case"d":l=d("d");break;case"D":v("D",i,s);break;case"o":c=d("o");break;case"m":f=d("m");break;case"M":f=v("M",o,u);break;case"y":a=d("y");break;case"@":var b=new Date(d("@"));a=b.getFullYear(),f=b.getMonth()+1,l=b.getDate();break;case"!":var b=new Date((d("!")-this._ticksTo1970)/1e4);a=b.getFullYear(),f=b.getMonth()+1,l=b.getDate();break;case"'":p("'")?m():h=!0;break;default:m()}if(g<t.length){var w=t.substr(g);if(!/^\s+/.test(w))throw"Extra/unparsed characters found in date: "+w}a==-1?a=(new Date).getFullYear():a<100&&(a+=(new Date).getFullYear()-(new Date).getFullYear()%100+(a<=r?0:-100));if(c>-1){f=1,l=c;do{var E=this._getDaysInMonth(a,f-1);if(l<=E)break;f++,l-=E}while(!0)}var b=this._daylightSavingAdjust(new Date(a,f-1,l));if(b.getFullYear()!=a||b.getMonth()+1!=f||b.getDate()!=l)throw"Invalid date";return b},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(e,t,n){if(!t)return"";var r=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,i=(n?n.dayNames:null)||this._defaults.dayNames,s=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,o=(n?n.monthNames:null)||this._defaults.monthNames,u=function(t){var n=h+1<e.length&&e.charAt(h+1)==t;return n&&h++,n},a=function(e,t,n){var r=""+t;if(u(e))while(r.length<n)r="0"+r;return r},f=function(e,t,n,r){return u(e)?r[t]:n[t]},l="",c=!1;if(t)for(var h=0;h<e.length;h++)if(c)e.charAt(h)=="'"&&!u("'")?c=!1:l+=e.charAt(h);else switch(e.charAt(h)){case"d":l+=a("d",t.getDate(),2);break;case"D":l+=f("D",t.getDay(),r,i);break;case"o":l+=a("o",Math.round(((new Date(t.getFullYear(),t.getMonth(),t.getDate())).getTime()-(new Date(t.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":l+=a("m",t.getMonth()+1,2);break;case"M":l+=f("M",t.getMonth(),s,o);break;case"y":l+=u("y")?t.getFullYear():(t.getYear()%100<10?"0":"")+t.getYear()%100;break;case"@":l+=t.getTime();break;case"!":l+=t.getTime()*1e4+this._ticksTo1970;break;case"'":u("'")?l+="'":c=!0;break;default:l+=e.charAt(h)}return l},_possibleChars:function(e){var t="",n=!1,r=function(t){var n=i+1<e.length&&e.charAt(i+1)==t;return n&&i++,n};for(var i=0;i<e.length;i++)if(n)e.charAt(i)=="'"&&!r("'")?n=!1:t+=e.charAt(i);else switch(e.charAt(i)){case"d":case"m":case"y":case"@":t+="0123456789";break;case"D":case"M":return null;case"'":r("'")?t+="'":n=!0;break;default:t+=e.charAt(i)}return t},_get:function(e,t){return e.settings[t]!==undefined?e.settings[t]:this._defaults[t]},_setDateFromField:function(e,t){if(e.input.val()==e.lastVal)return;var n=this._get(e,"dateFormat"),r=e.lastVal=e.input?e.input.val():null,i,s;i=s=this._getDefaultDate(e);var o=this._getFormatConfig(e);try{i=this.parseDate(n,r,o)||s}catch(u){this.log(u),r=t?"":r}e.selectedDay=i.getDate(),e.drawMonth=e.selectedMonth=i.getMonth(),e.drawYear=e.selectedYear=i.getFullYear(),e.currentDay=r?i.getDate():0,e.currentMonth=r?i.getMonth():0,e.currentYear=r?i.getFullYear():0,this._adjustInstDate(e)},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(e,t,n){var r=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},i=function(t){try{return $.datepicker.parseDate($.datepicker._get(e,"dateFormat"),t,$.datepicker._getFormatConfig(e))}catch(n){}var r=(t.toLowerCase().match(/^c/)?$.datepicker._getDate(e):null)||new Date,i=r.getFullYear(),s=r.getMonth(),o=r.getDate(),u=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,a=u.exec(t);while(a){switch(a[2]||"d"){case"d":case"D":o+=parseInt(a[1],10);break;case"w":case"W":o+=parseInt(a[1],10)*7;break;case"m":case"M":s+=parseInt(a[1],10),o=Math.min(o,$.datepicker._getDaysInMonth(i,s));break;case"y":case"Y":i+=parseInt(a[1],10),o=Math.min(o,$.datepicker._getDaysInMonth(i,s))}a=u.exec(t)}return new Date(i,s,o)},s=t==null||t===""?n:typeof t=="string"?i(t):typeof t=="number"?isNaN(t)?n:r(t):new Date(t.getTime());return s=s&&s.toString()=="Invalid Date"?n:s,s&&(s.setHours(0),s.setMinutes(0),s.setSeconds(0),s.setMilliseconds(0)),this._daylightSavingAdjust(s)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,n){var r=!t,i=e.selectedMonth,s=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),(i!=e.selectedMonth||s!=e.selectedYear)&&!n&&this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(r?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&e.input.val()==""?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(e){var t=this._get(e,"stepMonths"),n="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(n,-t,"M")},next:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(n,+t,"M")},hide:function(){window["DP_jQuery_"+dpuuid].datepicker._hideDatepicker()},today:function(){window["DP_jQuery_"+dpuuid].datepicker._gotoToday(n)},selectDay:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectDay(n,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(n,this,"M"),!1},selectYear:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(n,this,"Y"),!1}};$(this).bind(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t=new Date;t=this._daylightSavingAdjust(new Date(t.getFullYear(),t.getMonth(),t.getDate()));var n=this._get(e,"isRTL"),r=this._get(e,"showButtonPanel"),i=this._get(e,"hideIfNoPrevNext"),s=this._get(e,"navigationAsDateFormat"),o=this._getNumberOfMonths(e),u=this._get(e,"showCurrentAtPos"),a=this._get(e,"stepMonths"),f=o[0]!=1||o[1]!=1,l=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),c=this._getMinMaxDate(e,"min"),h=this._getMinMaxDate(e,"max"),p=e.drawMonth-u,d=e.drawYear;p<0&&(p+=12,d--);if(h){var v=this._daylightSavingAdjust(new Date(h.getFullYear(),h.getMonth()-o[0]*o[1]+1,h.getDate()));v=c&&v<c?c:v;while(this._daylightSavingAdjust(new Date(d,p,1))>v)p--,p<0&&(p=11,d--)}e.drawMonth=p,e.drawYear=d;var m=this._get(e,"prevText");m=s?this.formatDate(m,this._daylightSavingAdjust(new Date(d,p-a,1)),this._getFormatConfig(e)):m;var g=this._canAdjustMonth(e,-1,d,p)?'<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click" title="'+m+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"e":"w")+'">'+m+"</span></a>":i?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+m+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"e":"w")+'">'+m+"</span></a>",y=this._get(e,"nextText");y=s?this.formatDate(y,this._daylightSavingAdjust(new Date(d,p+a,1)),this._getFormatConfig(e)):y;var b=this._canAdjustMonth(e,1,d,p)?'<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click" title="'+y+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"w":"e")+'">'+y+"</span></a>":i?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+y+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"w":"e")+'">'+y+"</span></a>",w=this._get(e,"currentText"),E=this._get(e,"gotoCurrent")&&e.currentDay?l:t;w=s?this.formatDate(w,E,this._getFormatConfig(e)):w;var S=e.inline?"":'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">'+this._get(e,"closeText")+"</button>",x=r?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(n?S:"")+(this._isInRange(e,E)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click">'+w+"</button>":"")+(n?"":S)+"</div>":"",T=parseInt(this._get(e,"firstDay"),10);T=isNaN(T)?0:T;var N=this._get(e,"showWeek"),C=this._get(e,"dayNames"),k=this._get(e,"dayNamesShort"),L=this._get(e,"dayNamesMin"),A=this._get(e,"monthNames"),O=this._get(e,"monthNamesShort"),M=this._get(e,"beforeShowDay"),_=this._get(e,"showOtherMonths"),D=this._get(e,"selectOtherMonths"),P=this._get(e,"calculateWeek")||this.iso8601Week,H=this._getDefaultDate(e),B="";for(var j=0;j<o[0];j++){var F="";this.maxRows=4;for(var I=0;I<o[1];I++){var q=this._daylightSavingAdjust(new Date(d,p,e.selectedDay)),R=" ui-corner-all",U="";if(f){U+='<div class="ui-datepicker-group';if(o[1]>1)switch(I){case 0:U+=" ui-datepicker-group-first",R=" ui-corner-"+(n?"right":"left");break;case o[1]-1:U+=" ui-datepicker-group-last",R=" ui-corner-"+(n?"left":"right");break;default:U+=" ui-datepicker-group-middle",R=""}U+='">'}U+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+R+'">'+(/all|left/.test(R)&&j==0?n?b:g:"")+(/all|right/.test(R)&&j==0?n?g:b:"")+this._generateMonthYearHeader(e,p,d,c,h,j>0||I>0,A,O)+'</div><table class="ui-datepicker-calendar"><thead>'+"<tr>";var z=N?'<th class="ui-datepicker-week-col">'+this._get(e,"weekHeader")+"</th>":"";for(var W=0;W<7;W++){var X=(W+T)%7;z+="<th"+((W+T+6)%7>=5?' class="ui-datepicker-week-end"':"")+">"+'<span title="'+C[X]+'">'+L[X]+"</span></th>"}U+=z+"</tr></thead><tbody>";var V=this._getDaysInMonth(d,p);d==e.selectedYear&&p==e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,V));var J=(this._getFirstDayOfMonth(d,p)-T+7)%7,K=Math.ceil((J+V)/7),Q=f?this.maxRows>K?this.maxRows:K:K;this.maxRows=Q;var G=this._daylightSavingAdjust(new Date(d,p,1-J));for(var Y=0;Y<Q;Y++){U+="<tr>";var Z=N?'<td class="ui-datepicker-week-col">'+this._get(e,"calculateWeek")(G)+"</td>":"";for(var W=0;W<7;W++){var et=M?M.apply(e.input?e.input[0]:null,[G]):[!0,""],tt=G.getMonth()!=p,nt=tt&&!D||!et[0]||c&&G<c||h&&G>h;Z+='<td class="'+((W+T+6)%7>=5?" ui-datepicker-week-end":"")+(tt?" ui-datepicker-other-month":"")+(G.getTime()==q.getTime()&&p==e.selectedMonth&&e._keyEvent||H.getTime()==G.getTime()&&H.getTime()==q.getTime()?" "+this._dayOverClass:"")+(nt?" "+this._unselectableClass+" ui-state-disabled":"")+(tt&&!_?"":" "+et[1]+(G.getTime()==l.getTime()?" "+this._currentClass:"")+(G.getTime()==t.getTime()?" ui-datepicker-today":""))+'"'+((!tt||_)&&et[2]?' title="'+et[2]+'"':"")+(nt?"":' data-handler="selectDay" data-event="click" data-month="'+G.getMonth()+'" data-year="'+G.getFullYear()+'"')+">"+(tt&&!_?"&#xa0;":nt?'<span class="ui-state-default">'+G.getDate()+"</span>":'<a class="ui-state-default'+(G.getTime()==t.getTime()?" ui-state-highlight":"")+(G.getTime()==l.getTime()?" ui-state-active":"")+(tt?" ui-priority-secondary":"")+'" href="#">'+G.getDate()+"</a>")+"</td>",G.setDate(G.getDate()+1),G=this._daylightSavingAdjust(G)}U+=Z+"</tr>"}p++,p>11&&(p=0,d++),U+="</tbody></table>"+(f?"</div>"+(o[0]>0&&I==o[1]-1?'<div class="ui-datepicker-row-break"></div>':""):""),F+=U}B+=F}return B+=x+($.ui.ie6&&!e.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':""),e._keyEvent=!1,B},_generateMonthYearHeader:function(e,t,n,r,i,s,o,u){var a=this._get(e,"changeMonth"),f=this._get(e,"changeYear"),l=this._get(e,"showMonthAfterYear"),c='<div class="ui-datepicker-title">',h="";if(s||!a)h+='<span class="ui-datepicker-month">'+o[t]+"</span>";else{var p=r&&r.getFullYear()==n,d=i&&i.getFullYear()==n;h+='<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">';for(var v=0;v<12;v++)(!p||v>=r.getMonth())&&(!d||v<=i.getMonth())&&(h+='<option value="'+v+'"'+(v==t?' selected="selected"':"")+">"+u[v]+"</option>");h+="</select>"}l||(c+=h+(s||!a||!f?"&#xa0;":""));if(!e.yearshtml){e.yearshtml="";if(s||!f)c+='<span class="ui-datepicker-year">'+n+"</span>";else{var m=this._get(e,"yearRange").split(":"),g=(new Date).getFullYear(),y=function(e){var t=e.match(/c[+-].*/)?n+parseInt(e.substring(1),10):e.match(/[+-].*/)?g+parseInt(e,10):parseInt(e,10);return isNaN(t)?g:t},b=y(m[0]),w=Math.max(b,y(m[1]||""));b=r?Math.max(b,r.getFullYear()):b,w=i?Math.min(w,i.getFullYear()):w,e.yearshtml+='<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">';for(;b<=w;b++)e.yearshtml+='<option value="'+b+'"'+(b==n?' selected="selected"':"")+">"+b+"</option>";e.yearshtml+="</select>",c+=e.yearshtml,e.yearshtml=null}}return c+=this._get(e,"yearSuffix"),l&&(c+=(s||!a||!f?"&#xa0;":"")+h),c+="</div>",c},_adjustInstDate:function(e,t,n){var r=e.drawYear+(n=="Y"?t:0),i=e.drawMonth+(n=="M"?t:0),s=Math.min(e.selectedDay,this._getDaysInMonth(r,i))+(n=="D"?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(r,i,s)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),(n=="M"||n=="Y")&&this._notifyChange(e)},_restrictMinMax:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max"),i=n&&t<n?n:t;return i=r&&i>r?r:i,i},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return t==null?[1,1]:typeof t=="number"?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return(new Date(e,t,1)).getDay()},_canAdjustMonth:function(e,t,n,r){var i=this._getNumberOfMonths(e),s=this._daylightSavingAdjust(new Date(n,r+(t<0?t:i[0]*i[1]),1));return t<0&&s.setDate(this._getDaysInMonth(s.getFullYear(),s.getMonth())),this._isInRange(e,s)},_isInRange:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max");return(!n||t.getTime()>=n.getTime())&&(!r||t.getTime()<=r.getTime())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t=typeof t!="string"?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,n,r){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var i=t?typeof t=="object"?t:this._daylightSavingAdjust(new Date(r,n,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),i,this._getFormatConfig(e))}}),$.fn.datepicker=function(e){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find(document.body).append($.datepicker.dpDiv),$.datepicker.initialized=!0);var t=Array.prototype.slice.call(arguments,1);return typeof e!="string"||e!="isDisabled"&&e!="getDate"&&e!="widget"?e=="option"&&arguments.length==2&&typeof arguments[1]=="string"?$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this[0]].concat(t)):this.each(function(){typeof e=="string"?$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this].concat(t)):$.datepicker._attachDatepicker(this,e)}):$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this[0]].concat(t))},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.9.2",window["DP_jQuery_"+dpuuid]=$})(jQuery);(function(e,t){var n="ui-dialog ui-widget ui-widget-content ui-corner-all ",r={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},i={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};e.widget("ui.dialog",{version:"1.9.2",options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var n=e(this).css(t).offset().top;n<0&&e(this).css("top",t.top-n)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&&(this.originalTitle=""),this.oldPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.options.title=this.options.title||this.originalTitle;var t=this,r=this.options,i=r.title||"&#160;",s,o,u,a,f;s=(this.uiDialog=e("<div>")).addClass(n+r.dialogClass).css({display:"none",outline:0,zIndex:r.zIndex}).attr("tabIndex",-1).keydown(function(n){r.closeOnEscape&&!n.isDefaultPrevented()&&n.keyCode&&n.keyCode===e.ui.keyCode.ESCAPE&&(t.close(n),n.preventDefault())}).mousedown(function(e){t.moveToTop(!1,e)}).appendTo("body"),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(s),o=(this.uiDialogTitlebar=e("<div>")).addClass("ui-dialog-titlebar  ui-widget-header  ui-corner-all  ui-helper-clearfix").bind("mousedown",function(){s.focus()}).prependTo(s),u=e("<a href='#'></a>").addClass("ui-dialog-titlebar-close  ui-corner-all").attr("role","button").click(function(e){e.preventDefault(),t.close(e)}).appendTo(o),(this.uiDialogTitlebarCloseText=e("<span>")).addClass("ui-icon ui-icon-closethick").text(r.closeText).appendTo(u),a=e("<span>").uniqueId().addClass("ui-dialog-title").html(i).prependTo(o),f=(this.uiDialogButtonPane=e("<div>")).addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),(this.uiButtonSet=e("<div>")).addClass("ui-dialog-buttonset").appendTo(f),s.attr({role:"dialog","aria-labelledby":a.attr("id")}),o.find("*").add(o).disableSelection(),this._hoverable(u),this._focusable(u),r.draggable&&e.fn.draggable&&this._makeDraggable(),r.resizable&&e.fn.resizable&&this._makeResizable(),this._createButtons(r.buttons),this._isOpen=!1,e.fn.bgiframe&&s.bgiframe(),this._on(s,{keydown:function(t){if(!r.modal||t.keyCode!==e.ui.keyCode.TAB)return;var n=e(":tabbable",s),i=n.filter(":first"),o=n.filter(":last");if(t.target===o[0]&&!t.shiftKey)return i.focus(1),!1;if(t.target===i[0]&&t.shiftKey)return o.focus(1),!1}})},_init:function(){this.options.autoOpen&&this.open()},_destroy:function(){var e,t=this.oldPosition;this.overlay&&this.overlay.destroy(),this.uiDialog.hide(),this.element.removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},close:function(t){var n=this,r,i;if(!this._isOpen)return;if(!1===this._trigger("beforeClose",t))return;return this._isOpen=!1,this.overlay&&this.overlay.destroy(),this.options.hide?this._hide(this.uiDialog,this.options.hide,function(){n._trigger("close",t)}):(this.uiDialog.hide(),this._trigger("close",t)),e.ui.dialog.overlay.resize(),this.options.modal&&(r=0,e(".ui-dialog").each(function(){this!==n.uiDialog[0]&&(i=e(this).css("z-index"),isNaN(i)||(r=Math.max(r,i)))}),e.ui.dialog.maxZ=r),this},isOpen:function(){return this._isOpen},moveToTop:function(t,n){var r=this.options,i;return r.modal&&!t||!r.stack&&!r.modal?this._trigger("focus",n):(r.zIndex>e.ui.dialog.maxZ&&(e.ui.dialog.maxZ=r.zIndex),this.overlay&&(e.ui.dialog.maxZ+=1,e.ui.dialog.overlay.maxZ=e.ui.dialog.maxZ,this.overlay.$el.css("z-index",e.ui.dialog.overlay.maxZ)),i={scrollTop:this.element.scrollTop(),scrollLeft:this.element.scrollLeft()},e.ui.dialog.maxZ+=1,this.uiDialog.css("z-index",e.ui.dialog.maxZ),this.element.attr(i),this._trigger("focus",n),this)},open:function(){if(this._isOpen)return;var t,n=this.options,r=this.uiDialog;return this._size(),this._position(n.position),r.show(n.show),this.overlay=n.modal?new e.ui.dialog.overlay(this):null,this.moveToTop(!0),t=this.element.find(":tabbable"),t.length||(t=this.uiDialogButtonPane.find(":tabbable"),t.length||(t=r)),t.eq(0).focus(),this._isOpen=!0,this._trigger("open"),this},_createButtons:function(t){var n=this,r=!1;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),typeof t=="object"&&t!==null&&e.each(t,function(){return!(r=!0)}),r?(e.each(t,function(t,r){var i,s;r=e.isFunction(r)?{click:r,text:t}:r,r=e.extend({type:"button"},r),s=r.click,r.click=function(){s.apply(n.element[0],arguments)},i=e("<button></button>",r).appendTo(n.uiButtonSet),e.fn.button&&i.button()}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog)):this.uiDialog.removeClass("ui-dialog-buttons")},_makeDraggable:function(){function r(e){return{position:e.position,offset:e.offset}}var t=this,n=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(n,i){e(this).addClass("ui-dialog-dragging"),t._trigger("dragStart",n,r(i))},drag:function(e,n){t._trigger("drag",e,r(n))},stop:function(i,s){n.position=[s.position.left-t.document.scrollLeft(),s.position.top-t.document.scrollTop()],e(this).removeClass("ui-dialog-dragging"),t._trigger("dragStop",i,r(s)),e.ui.dialog.overlay.resize()}})},_makeResizable:function(n){function u(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}n=n===t?this.options.resizable:n;var r=this,i=this.options,s=this.uiDialog.css("position"),o=typeof n=="string"?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:i.maxWidth,maxHeight:i.maxHeight,minWidth:i.minWidth,minHeight:this._minHeight(),handles:o,start:function(t,n){e(this).addClass("ui-dialog-resizing"),r._trigger("resizeStart",t,u(n))},resize:function(e,t){r._trigger("resize",e,u(t))},stop:function(t,n){e(this).removeClass("ui-dialog-resizing"),i.height=e(this).height(),i.width=e(this).width(),r._trigger("resizeStop",t,u(n)),e.ui.dialog.overlay.resize()}}).css("position",s).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var e=this.options;return e.height==="auto"?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(t){var n=[],r=[0,0],i;if(t){if(typeof t=="string"||typeof t=="object"&&"0"in t)n=t.split?t.split(" "):[t[0],t[1]],n.length===1&&(n[1]=n[0]),e.each(["left","top"],function(e,t){+n[e]===n[e]&&(r[e]=n[e],n[e]=t)}),t={my:n[0]+(r[0]<0?r[0]:"+"+r[0])+" "+n[1]+(r[1]<0?r[1]:"+"+r[1]),at:n.join(" ")};t=e.extend({},e.ui.dialog.prototype.options.position,t)}else t=e.ui.dialog.prototype.options.position;i=this.uiDialog.is(":visible"),i||this.uiDialog.show(),this.uiDialog.position(t),i||this.uiDialog.hide()},_setOptions:function(t){var n=this,s={},o=!1;e.each(t,function(e,t){n._setOption(e,t),e in r&&(o=!0),e in i&&(s[e]=t)}),o&&this._size(),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",s)},_setOption:function(t,r){var i,s,o=this.uiDialog;switch(t){case"buttons":this._createButtons(r);break;case"closeText":this.uiDialogTitlebarCloseText.text(""+r);break;case"dialogClass":o.removeClass(this.options.dialogClass).addClass(n+r);break;case"disabled":r?o.addClass("ui-dialog-disabled"):o.removeClass("ui-dialog-disabled");break;case"draggable":i=o.is(":data(draggable)"),i&&!r&&o.draggable("destroy"),!i&&r&&this._makeDraggable();break;case"position":this._position(r);break;case"resizable":s=o.is(":data(resizable)"),s&&!r&&o.resizable("destroy"),s&&typeof r=="string"&&o.resizable("option","handles",r),!s&&r!==!1&&this._makeResizable(r);break;case"title":e(".ui-dialog-title",this.uiDialogTitlebar).html(""+(r||"&#160;"))}this._super(t,r)},_size:function(){var t,n,r,i=this.options,s=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),i.minWidth>i.width&&(i.width=i.minWidth),t=this.uiDialog.css({height:"auto",width:i.width}).outerHeight(),n=Math.max(0,i.minHeight-t),i.height==="auto"?e.support.minHeight?this.element.css({minHeight:n,height:"auto"}):(this.uiDialog.show(),r=this.element.css("height","auto").height(),s||this.uiDialog.hide(),this.element.height(Math.max(r,n))):this.element.height(Math.max(i.height-t,0)),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}}),e.extend(e.ui.dialog,{uuid:0,maxZ:0,getTitleId:function(e){var t=e.attr("id");return t||(this.uuid+=1,t=this.uuid),"ui-dialog-title-"+t},overlay:function(t){this.$el=e.ui.dialog.overlay.create(t)}}),e.extend(e.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:e.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(e){return e+".dialog-overlay"}).join(" "),create:function(t){this.instances.length===0&&(setTimeout(function(){e.ui.dialog.overlay.instances.length&&e(document).bind(e.ui.dialog.overlay.events,function(t){if(e(t.target).zIndex()<e.ui.dialog.overlay.maxZ)return!1})},1),e(window).bind("resize.dialog-overlay",e.ui.dialog.overlay.resize));var n=this.oldInstances.pop()||e("<div>").addClass("ui-widget-overlay");return e(document).bind("keydown.dialog-overlay",function(r){var i=e.ui.dialog.overlay.instances;i.length!==0&&i[i.length-1]===n&&t.options.closeOnEscape&&!r.isDefaultPrevented()&&r.keyCode&&r.keyCode===e.ui.keyCode.ESCAPE&&(t.close(r),r.preventDefault())}),n.appendTo(document.body).css({width:this.width(),height:this.height()}),e.fn.bgiframe&&n.bgiframe(),this.instances.push(n),n},destroy:function(t){var n=e.inArray(t,this.instances),r=0;n!==-1&&this.oldInstances.push(this.instances.splice(n,1)[0]),this.instances.length===0&&e([document,window]).unbind(".dialog-overlay"),t.height(0).width(0).remove(),e.each(this.instances,function(){r=Math.max(r,this.css("z-index"))}),this.maxZ=r},height:function(){var t,n;return e.ui.ie?(t=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),n=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),t<n?e(window).height()+"px":t+"px"):e(document).height()+"px"},width:function(){var t,n;return e.ui.ie?(t=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),n=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth),t<n?e(window).width()+"px":t+"px"):e(document).width()+"px"},resize:function(){var t=e([]);e.each(e.ui.dialog.overlay.instances,function(){t=t.add(this)}),t.css({width:0,height:0}).css({width:e.ui.dialog.overlay.width(),height:e.ui.dialog.overlay.height()})}}),e.extend(e.ui.dialog.overlay.prototype,{destroy:function(){e.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);(function(e,t){var n=!1;e.widget("ui.menu",{version:"1.9.2",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,e.proxy(function(e){this.options.disabled&&e.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(e){e.preventDefault()},"click .ui-state-disabled > a":function(e){e.preventDefault()},"click .ui-menu-item:has(a)":function(t){var r=e(t.target).closest(".ui-menu-item");!n&&r.not(".ui-state-disabled").length&&(n=!0,this.select(t),r.has(".ui-menu").length?this.expand(t):this.element.is(":focus")||(this.element.trigger("focus",[!0]),this.active&&this.active.parents(".ui-menu").length===1&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){var n=e(t.currentTarget);n.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(t,n)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var n=this.active||this.element.children(".ui-menu-item").eq(0);t||this.focus(e,n)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){e(t.target).closest(".ui-menu").length||this.collapseAll(t),n=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").andSelf().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){function a(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var n,r,i,s,o,u=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:u=!1,r=this.previousFilter||"",i=String.fromCharCode(t.keyCode),s=!1,clearTimeout(this.filterTimer),i===r?s=!0:i=r+i,o=new RegExp("^"+a(i),"i"),n=this.activeMenu.children(".ui-menu-item").filter(function(){return o.test(e(this).children("a").text())}),n=s&&n.index(this.active.next())!==-1?this.active.nextAll(".ui-menu-item"):n,n.length||(i=String.fromCharCode(t.keyCode),o=new RegExp("^"+a(i),"i"),n=this.activeMenu.children(".ui-menu-item").filter(function(){return o.test(e(this).children("a").text())})),n.length?(this.focus(t,n),n.length>1?(this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}u&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(e):this.select(e))},refresh:function(){var t,n=this.options.icons.submenu,r=this.element.find(this.options.menus);r.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),r=t.prev("a"),i=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);r.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",r.attr("id"))}),t=r.add(this.element),t.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),t.children(":not(.ui-menu-item)").each(function(){var t=e(this);/[^\-—–\s]/.test(t.text())||t.addClass("ui-widget-content ui-menu-divider")}),t.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},focus:function(e,t){var n,r;this.blur(e,e&&e.type==="focus"),this._scrollIntoView(t),this.active=t.first(),r=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",r.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),e&&e.type==="keydown"?this._close():this.timer=this._delay(function(){this._close()},this.delay),n=t.children(".ui-menu"),n.length&&/^mouse/.test(e.type)&&this._startOpening(n),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var n,r,i,s,o,u;this._hasScroll()&&(n=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,r=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,i=t.offset().top-this.activeMenu.offset().top-n-r,s=this.activeMenu.scrollTop(),o=this.activeMenu.height(),u=t.height(),i<0?this.activeMenu.scrollTop(s+i):i+u>o&&this.activeMenu.scrollTop(s+i-o+u))},blur:function(e,t){t||clearTimeout(this.timer);if(!this.active)return;this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active})},_startOpening:function(e){clearTimeout(this.timer);if(e.attr("aria-hidden")!=="true")return;this.timer=this._delay(function(){this._close(),this._open(e)},this.delay)},_open:function(t){var n=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(n)},collapseAll:function(t,n){clearTimeout(this.timer),this.timer=this._delay(function(){var r=n?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));r.length||(r=this.element),this._close(r),this.blur(t),this.activeMenu=r},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,n){var r;this.active&&(e==="first"||e==="last"?r=this.active[e==="first"?"prevAll":"nextAll"](".ui-menu-item").eq(-1):r=this.active[e+"All"](".ui-menu-item").eq(0));if(!r||!r.length||!this.active)r=this.activeMenu.children(".ui-menu-item")[t]();this.focus(n,r)},nextPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isLastItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r-i<0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())},previousPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isFirstItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r+i>0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item").first())},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var n={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,n)}})})(jQuery);(function(e,t){e.widget("ui.progressbar",{version:"1.9.2",options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()}),this.valueDiv=e("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this.oldValue=this._value(),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(e){return e===t?this._value():(this._setOption("value",e),this)},_setOption:function(e,t){e==="value"&&(this.options.value=t,this._refreshValue(),this._value()===this.options.max&&this._trigger("complete")),this._super(e,t)},_value:function(){var e=this.options.value;return typeof e!="number"&&(e=0),Math.min(this.options.max,Math.max(this.min,e))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var e=this.value(),t=this._percentage();this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),this.valueDiv.toggle(e>this.min).toggleClass("ui-corner-right",e===this.options.max).width(t.toFixed(0)+"%"),this.element.attr("aria-valuenow",e)}})})(jQuery);(function(e,t){var n=5;e.widget("ui.slider",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null},_create:function(){var t,r,i=this.options,s=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),o="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",u=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"+(i.disabled?" ui-slider-disabled ui-disabled":"")),this.range=e([]),i.range&&(i.range===!0&&(i.values||(i.values=[this._valueMin(),this._valueMin()]),i.values.length&&i.values.length!==2&&(i.values=[i.values[0],i.values[0]])),this.range=e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(i.range==="min"||i.range==="max"?" ui-slider-range-"+i.range:""))),r=i.values&&i.values.length||1;for(t=s.length;t<r;t++)u.push(o);this.handles=s.add(e(u.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(e){e.preventDefault()}).mouseenter(function(){i.disabled||e(this).addClass("ui-state-hover")}).mouseleave(function(){e(this).removeClass("ui-state-hover")}).focus(function(){i.disabled?e(this).blur():(e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),e(this).addClass("ui-state-focus"))}).blur(function(){e(this).removeClass("ui-state-focus")}),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)}),this._on(this.handles,{keydown:function(t){var r,i,s,o,u=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:t.preventDefault();if(!this._keySliding){this._keySliding=!0,e(t.target).addClass("ui-state-active"),r=this._start(t,u);if(r===!1)return}}o=this.options.step,this.options.values&&this.options.values.length?i=s=this.values(u):i=s=this.value();switch(t.keyCode){case e.ui.keyCode.HOME:s=this._valueMin();break;case e.ui.keyCode.END:s=this._valueMax();break;case e.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+o);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-o)}this._slide(t,u,s)},keyup:function(t){var n=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,n),this._change(t,n),e(t.target).removeClass("ui-state-active"))}}),this._refreshValue(),this._animateOff=!1},_destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var n,r,i,s,o,u,a,f,l=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),n={x:t.pageX,y:t.pageY},r=this._normValueFromMouse(n),i=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var n=Math.abs(r-l.values(t));i>n&&(i=n,s=e(this),o=t)}),c.range===!0&&this.values(1)===c.min&&(o+=1,s=e(this.handles[o])),u=this._start(t,o),u===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,s.addClass("ui-state-active").focus(),a=s.offset(),f=!e(t.target).parents().andSelf().is(".ui-slider-handle"),this._clickOffset=f?{left:0,top:0}:{left:t.pageX-a.left-s.width()/2,top:t.pageY-a.top-s.height()/2-(parseInt(s.css("borderTopWidth"),10)||0)-(parseInt(s.css("borderBottomWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,r),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},n=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,n),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,n,r,i,s;return this.orientation==="horizontal"?(t=this.elementSize.width,n=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,n=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),r=n/t,r>1&&(r=1),r<0&&(r=0),this.orientation==="vertical"&&(r=1-r),i=this._valueMax()-this._valueMin(),s=this._valueMin()+r*i,this._trimAlignValue(s)},_start:function(e,t){var n={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("start",e,n)},_slide:function(e,t,n){var r,i,s;this.options.values&&this.options.values.length?(r=this.values(t?0:1),this.options.values.length===2&&this.options.range===!0&&(t===0&&n>r||t===1&&n<r)&&(n=r),n!==this.values(t)&&(i=this.values(),i[t]=n,s=this._trigger("slide",e,{handle:this.handles[t],value:n,values:i}),r=this.values(t?0:1),s!==!1&&this.values(t,n,!0))):n!==this.value()&&(s=this._trigger("slide",e,{handle:this.handles[t],value:n}),s!==!1&&this.value(n))},_stop:function(e,t){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("stop",e,n)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("change",e,n)}},value:function(e){if(arguments.length){this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(t,n){var r,i,s;if(arguments.length>1){this.options.values[t]=this._trimAlignValue(n),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();r=this.options.values,i=arguments[0];for(s=0;s<r.length;s+=1)r[s]=this._trimAlignValue(i[s]),this._change(null,s);this._refreshValue()},_setOption:function(t,n){var r,i=0;e.isArray(this.options.values)&&(i=this.options.values.length),e.Widget.prototype._setOption.apply(this,arguments);switch(t){case"disabled":n?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.prop("disabled",!0),this.element.addClass("ui-disabled")):(this.handles.prop("disabled",!1),this.element.removeClass("ui-disabled"));break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(r=0;r<i;r+=1)this._change(null,r);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e),e},_values:function(e){var t,n,r;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t),t;n=this.options.values.slice();for(r=0;r<n.length;r+=1)n[r]=this._trimAlignValue(n[r]);return n},_trimAlignValue:function(e){if(e<=this._valueMin())return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,n=(e-this._valueMin())%t,r=e-n;return Math.abs(n)*2>=t&&(r+=n>0?t:-t),parseFloat(r.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var t,n,r,i,s,o=this.options.range,u=this.options,a=this,f=this._animateOff?!1:u.animate,l={};this.options.values&&this.options.values.length?this.handles.each(function(r){n=(a.values(r)-a._valueMin())/(a._valueMax()-a._valueMin())*100,l[a.orientation==="horizontal"?"left":"bottom"]=n+"%",e(this).stop(1,1)[f?"animate":"css"](l,u.animate),a.options.range===!0&&(a.orientation==="horizontal"?(r===0&&a.range.stop(1,1)[f?"animate":"css"]({left:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({width:n-t+"%"},{queue:!1,duration:u.animate})):(r===0&&a.range.stop(1,1)[f?"animate":"css"]({bottom:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({height:n-t+"%"},{queue:!1,duration:u.animate}))),t=n}):(r=this.value(),i=this._valueMin(),s=this._valueMax(),n=s!==i?(r-i)/(s-i)*100:0,l[this.orientation==="horizontal"?"left":"bottom"]=n+"%",this.handle.stop(1,1)[f?"animate":"css"](l,u.animate),o==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[f?"animate":"css"]({width:n+"%"},u.animate),o==="max"&&this.orientation==="horizontal"&&this.range[f?"animate":"css"]({width:100-n+"%"},{queue:!1,duration:u.animate}),o==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[f?"animate":"css"]({height:n+"%"},u.animate),o==="max"&&this.orientation==="vertical"&&this.range[f?"animate":"css"]({height:100-n+"%"},{queue:!1,duration:u.animate}))}})})(jQuery);(function(e){function t(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger("change")}}e.widget("ui.spinner",{version:"1.9.2",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var t={},n=this.element;return e.each(["min","max","step"],function(e,r){var i=n.attr(r);i!==undefined&&i.length&&(t[r]=i)}),t},_events:{keydown:function(e){this._start(e)&&this._keydown(e)&&e.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}this._refresh(),this.previous!==this.element.val()&&this._trigger("change",e)},mousewheel:function(e,t){if(!t)return;if(!this.spinning&&!this._start(e))return!1;this._spin((t>0?1:-1)*this.options.step,e),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(e)},100),e.preventDefault()},"mousedown .ui-spinner-button":function(t){function r(){var e=this.element[0]===this.document[0].activeElement;e||(this.element.focus(),this.previous=n,this._delay(function(){this.previous=n}))}var n;n=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),t.preventDefault(),r.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,r.call(this)});if(this._start(t)===!1)return;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){if(!e(t.currentTarget).hasClass("ui-state-active"))return;if(this._start(t)===!1)return!1;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var e=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=e.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(e.height()*.5)&&e.height()>0&&e.height(e.height()),this.options.disabled&&this.disable()},_keydown:function(t){var n=this.options,r=e.ui.keyCode;switch(t.keyCode){case r.UP:return this._repeat(null,1,t),!0;case r.DOWN:return this._repeat(null,-1,t),!0;case r.PAGE_UP:return this._repeat(null,n.page,t),!0;case r.PAGE_DOWN:return this._repeat(null,-n.page,t),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>&#9650;</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>&#9660;</span>"+"</a>"},_start:function(e){return!this.spinning&&this._trigger("start",e)===!1?!1:(this.counter||(this.counter=1),this.spinning=!0,!0)},_repeat:function(e,t,n){e=e||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,t,n)},e),this._spin(t*this.options.step,n)},_spin:function(e,t){var n=this.value()||0;this.counter||(this.counter=1),n=this._adjustValue(n+e*this._increment(this.counter));if(!this.spinning||this._trigger("spin",t,{value:n})!==!1)this._value(n),this.counter++},_increment:function(t){var n=this.options.incremental;return n?e.isFunction(n)?n(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var e=this._precisionOf(this.options.step);return this.options.min!==null&&(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=e.toString(),n=t.indexOf(".");return n===-1?0:t.length-n-1},_adjustValue:function(e){var t,n,r=this.options;return t=r.min!==null?r.min:0,n=e-t,n=Math.round(n/r.step)*r.step,e=t+n,e=parseFloat(e.toFixed(this._precision())),r.max!==null&&e>r.max?r.max:r.min!==null&&e<r.min?r.min:e},_stop:function(e){if(!this.spinning)return;clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",e)},_setOption:function(e,t){if(e==="culture"||e==="numberFormat"){var n=this._parse(this.element.val());this.options[e]=t,this.element.val(this._format(n));return}(e==="max"||e==="min"||e==="step")&&typeof t=="string"&&(t=this._parse(t)),this._super(e,t),e==="disabled"&&(t?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:t(function(e){this._super(e),this._value(this.element.val())}),_parse:function(e){return typeof e=="string"&&e!==""&&(e=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(e,10,this.options.culture):+e),e===""||isNaN(e)?null:e},_format:function(e){return e===""?"":window.Globalize&&this.options.numberFormat?Globalize.format(e,this.options.numberFormat,this.options.culture):e},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(e,t){var n;e!==""&&(n=this._parse(e),n!==null&&(t||(n=this._adjustValue(n)),e=this._format(n))),this.element.val(e),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:t(function(e){this._stepUp(e)}),_stepUp:function(e){this._spin((e||1)*this.options.step)},stepDown:t(function(e){this._stepDown(e)}),_stepDown:function(e){this._spin((e||1)*-this.options.step)},pageUp:t(function(e){this._stepUp((e||1)*this.options.page)}),pageDown:t(function(e){this._stepDown((e||1)*this.options.page)}),value:function(e){if(!arguments.length)return this._parse(this.element.val());t(this._value).call(this,e)},widget:function(){return this.uiSpinner}})})(jQuery);(function(e,t){function i(){return++n}function s(e){return e.hash.length>1&&e.href.replace(r,"")===location.href.replace(r,"").replace(/\s/g,"%20")}var n=0,r=/#.*$/;e.widget("ui.tabs",{version:"1.9.2",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var t=this,n=this.options,r=n.active,i=location.hash.substring(1);this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",n.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&&t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs();if(r===null){i&&this.tabs.each(function(t,n){if(e(n).attr("aria-controls")===i)return r=t,!1}),r===null&&(r=this.tabs.index(this.tabs.filter(".ui-tabs-active")));if(r===null||r===-1)r=this.tabs.length?0:!1}r!==!1&&(r=this.tabs.index(this.tabs.eq(r)),r===-1&&(r=n.collapsible?!1:0)),n.active=r,!n.collapsible&&n.active===!1&&this.anchors.length&&(n.active=0),e.isArray(n.disabled)&&(n.disabled=e.unique(n.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return t.tabs.index(e)}))).sort()),this.options.active!==!1&&this.anchors.length?this.active=this._findActive(this.options.active):this.active=e(),this._refresh(),this.active.length&&this.load(n.active)},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(t){var n=e(this.document[0].activeElement).closest("li"),r=this.tabs.index(n),i=!0;if(this._handlePageNav(t))return;switch(t.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:r++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:i=!1,r--;break;case e.ui.keyCode.END:r=this.anchors.length-1;break;case e.ui.keyCode.HOME:r=0;break;case e.ui.keyCode.SPACE:t.preventDefault(),clearTimeout(this.activating),this._activate(r);return;case e.ui.keyCode.ENTER:t.preventDefault(),clearTimeout(this.activating),this._activate(r===this.options.active?!1:r);return;default:return}t.preventDefault(),clearTimeout(this.activating),r=this._focusNextTab(r,i),t.ctrlKey||(n.attr("aria-selected","false"),this.tabs.eq(r).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",r)},this.delay))},_panelKeydown:function(t){if(this._handlePageNav(t))return;t.ctrlKey&&t.keyCode===e.ui.keyCode.UP&&(t.preventDefault(),this.active.focus())},_handlePageNav:function(t){if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_UP)return this._activate(this._focusNextTab(this.options.active-1,!1)),!0;if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_DOWN)return this._activate(this._focusNextTab(this.options.active+1,!0)),!0},_findNextTab:function(t,n){function i(){return t>r&&(t=0),t<0&&(t=r),t}var r=this.tabs.length-1;while(e.inArray(i(),this.options.disabled)!==-1)t=n?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,t){if(e==="active"){this._activate(t);return}if(e==="disabled"){this._setupDisabled(t);return}this._super(e,t),e==="collapsible"&&(this.element.toggleClass("ui-tabs-collapsible",t),!t&&this.options.active===!1&&this._activate(0)),e==="event"&&this._setupEvents(t),e==="heightStyle"&&this._setupHeightStyle(t)},_tabId:function(e){return e.attr("aria-controls")||"ui-tabs-"+i()},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,n=this.tablist.children(":has(a[href])");t.disabled=e.map(n.filter(".ui-state-disabled"),function(e){return n.index(e)}),this._processTabs(),t.active===!1||!this.anchors.length?(t.active=!1,this.active=e()):this.active.length&&!e.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return e("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(n,r){var i,o,u,a=e(r).uniqueId().attr("id"),f=e(r).closest("li"),l=f.attr("aria-controls");s(r)?(i=r.hash,o=t.element.find(t._sanitizeSelector(i))):(u=t._tabId(f),i="#"+u,o=t.element.find(i),o.length||(o=t._createPanel(u),o.insertAfter(t.panels[n-1]||t.tablist)),o.attr("aria-live","polite")),o.length&&(t.panels=t.panels.add(o)),l&&f.data("ui-tabs-aria-controls",l),f.attr({"aria-controls":i.substring(1),"aria-labelledby":a}),o.attr("aria-labelledby",a)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("<div>").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1);for(var n=0,r;r=this.tabs[n];n++)t===!0||e.inArray(n,t)!==-1?e(r).addClass("ui-state-disabled").attr("aria-disabled","true"):e(r).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var n={click:function(e){e.preventDefault()}};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,n),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var n,r,i=this.element.parent();t==="fill"?(e.support.minHeight||(r=i.css("overflow"),i.css("overflow","hidden")),n=i.height(),this.element.siblings(":visible").each(function(){var t=e(this),r=t.css("position");if(r==="absolute"||r==="fixed")return;n-=t.outerHeight(!0)}),r&&i.css("overflow",r),this.element.children().not(this.panels).each(function(){n-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,n-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):t==="auto"&&(n=0,this.panels.each(function(){n=Math.max(n,e(this).height("").height())}).height(n))},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i.closest("li"),o=s[0]===r[0],u=o&&n.collapsible,a=u?e():this._getPanelForTab(s),f=r.length?this._getPanelForTab(r):e(),l={oldTab:r,oldPanel:f,newTab:u?e():s,newPanel:a};t.preventDefault();if(s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||o&&!n.collapsible||this._trigger("beforeActivate",t,l)===!1)return;n.active=u?!1:this.tabs.index(s),this.active=o?e():s,this.xhr&&this.xhr.abort(),!f.length&&!a.length&&e.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&&this.load(this.tabs.index(s),t),this._toggle(t,l)},_toggle:function(t,n){function o(){r.running=!1,r._trigger("activate",t,n)}function u(){n.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),i.length&&r.options.show?r._show(i,r.options.show,o):(i.show(),o())}var r=this,i=n.newPanel,s=n.oldPanel;this.running=!0,s.length&&this.options.hide?this._hide(s,this.options.hide,function(){n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u()}):(n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),s.hide(),u()),s.attr({"aria-expanded":"false","aria-hidden":"true"}),n.oldTab.attr("aria-selected","false"),i.length&&s.length?n.oldTab.attr("tabIndex",-1):i.length&&this.tabs.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),i.attr({"aria-expanded":"true","aria-hidden":"false"}),n.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(t){var n,r=this._findActive(t);if(r[0]===this.active[0])return;r.length||(r=this.active),n=r.find(".ui-tabs-anchor")[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return typeof e=="string"&&(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeData("href.tabs").removeData("load.tabs").removeUniqueId(),this.tabs.add(this.panels).each(function(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var t=e(this),n=t.data("ui-tabs-aria-controls");n?t.attr("aria-controls",n):t.removeAttr("aria-controls")}),this.panels.show(),this.options.heightStyle!=="content"&&this.panels.css("height","")},enable:function(n){var r=this.options.disabled;if(r===!1)return;n===t?r=!1:(n=this._getIndex(n),e.isArray(r)?r=e.map(r,function(e){return e!==n?e:null}):r=e.map(this.tabs,function(e,t){return t!==n?t:null})),this._setupDisabled(r)},disable:function(n){var r=this.options.disabled;if(r===!0)return;if(n===t)r=!0;else{n=this._getIndex(n);if(e.inArray(n,r)!==-1)return;e.isArray(r)?r=e.merge([n],r).sort():r=[n]}this._setupDisabled(r)},load:function(t,n){t=this._getIndex(t);var r=this,i=this.tabs.eq(t),o=i.find(".ui-tabs-anchor"),u=this._getPanelForTab(i),a={tab:i,panel:u};if(s(o[0]))return;this.xhr=e.ajax(this._ajaxSettings(o,n,a)),this.xhr&&this.xhr.statusText!=="canceled"&&(i.addClass("ui-tabs-loading"),u.attr("aria-busy","true"),this.xhr.success(function(e){setTimeout(function(){u.html(e),r._trigger("load",n,a)},1)}).complete(function(e,t){setTimeout(function(){t==="abort"&&r.panels.stop(!1,!0),i.removeClass("ui-tabs-loading"),u.removeAttr("aria-busy"),e===r.xhr&&delete r.xhr},1)}))},_ajaxSettings:function(t,n,r){var i=this;return{url:t.attr("href"),beforeSend:function(t,s){return i._trigger("beforeLoad",n,e.extend({jqXHR:t,ajaxSettings:s},r))}}},_getPanelForTab:function(t){var n=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+n))}}),e.uiBackCompat!==!1&&(e.ui.tabs.prototype._ui=function(e,t){return{tab:e,panel:t,index:this.anchors.index(e)}},e.widget("ui.tabs",e.ui.tabs,{url:function(e,t){this.anchors.eq(e).attr("href",t)}}),e.widget("ui.tabs",e.ui.tabs,{options:{ajaxOptions:null,cache:!1},_create:function(){this._super();var t=this;this._on({tabsbeforeload:function(n,r){if(e.data(r.tab[0],"cache.tabs")){n.preventDefault();return}r.jqXHR.success(function(){t.options.cache&&e.data(r.tab[0],"cache.tabs",!0)})}})},_ajaxSettings:function(t,n,r){var i=this.options.ajaxOptions;return e.extend({},i,{error:function(e,t){try{i.error(e,t,r.tab.closest("li").index(),r.tab[0])}catch(n){}}},this._superApply(arguments))},_setOption:function(e,t){e==="cache"&&t===!1&&this.anchors.removeData("cache.tabs"),this._super(e,t)},_destroy:function(){this.anchors.removeData("cache.tabs"),this._super()},url:function(e){this.anchors.eq(e).removeData("cache.tabs"),this._superApply(arguments)}}),e.widget("ui.tabs",e.ui.tabs,{abort:function(){this.xhr&&this.xhr.abort()}}),e.widget("ui.tabs",e.ui.tabs,{options:{spinner:"<em>Loading&#8230;</em>"},_create:function(){this._super(),this._on({tabsbeforeload:function(e,t){if(e.target!==this.element[0]||!this.options.spinner)return;var n=t.tab.find("span"),r=n.html();n.html(this.options.spinner),t.jqXHR.complete(function(){n.html(r)})}})}}),e.widget("ui.tabs",e.ui.tabs,{options:{enable:null,disable:null},enable:function(t){var n=this.options,r;if(t&&n.disabled===!0||e.isArray(n.disabled)&&e.inArray(t,n.disabled)!==-1)r=!0;this._superApply(arguments),r&&this._trigger("enable",null,this._ui(this.anchors[t],this.panels[t]))},disable:function(t){var n=this.options,r;if(t&&n.disabled===!1||e.isArray(n.disabled)&&e.inArray(t,n.disabled)===-1)r=!0;this._superApply(arguments),r&&this._trigger("disable",null,this._ui(this.anchors[t],this.panels[t]))}}),e.widget("ui.tabs",e.ui.tabs,{options:{add:null,remove:null,tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},add:function(n,r,i){i===t&&(i=this.anchors.length);var s,o,u=this.options,a=e(u.tabTemplate.replace(/#\{href\}/g,n).replace(/#\{label\}/g,r)),f=n.indexOf("#")?this._tabId(a):n.replace("#","");return a.addClass("ui-state-default ui-corner-top").data("ui-tabs-destroy",!0),a.attr("aria-controls",f),s=i>=this.tabs.length,o=this.element.find("#"+f),o.length||(o=this._createPanel(f),s?i>0?o.insertAfter(this.panels.eq(-1)):o.appendTo(this.element):o.insertBefore(this.panels[i])),o.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").hide(),s?a.appendTo(this.tablist):a.insertBefore(this.tabs[i]),u.disabled=e.map(u.disabled,function(e){return e>=i?++e:e}),this.refresh(),this.tabs.length===1&&u.active===!1&&this.option("active",0),this._trigger("add",null,this._ui(this.anchors[i],this.panels[i])),this},remove:function(t){t=this._getIndex(t);var n=this.options,r=this.tabs.eq(t).remove(),i=this._getPanelForTab(r).remove();return r.hasClass("ui-tabs-active")&&this.anchors.length>2&&this._activate(t+(t+1<this.anchors.length?1:-1)),n.disabled=e.map(e.grep(n.disabled,function(e){return e!==t}),function(e){return e>=t?--e:e}),this.refresh(),this._trigger("remove",null,this._ui(r.find("a")[0],i[0])),this}}),e.widget("ui.tabs",e.ui.tabs,{length:function(){return this.anchors.length}}),e.widget("ui.tabs",e.ui.tabs,{options:{idPrefix:"ui-tabs-"},_tabId:function(t){var n=t.is("li")?t.find("a[href]"):t;return n=n[0],e(n).closest("li").attr("aria-controls")||n.title&&n.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF\-]/g,"")||this.options.idPrefix+i()}}),e.widget("ui.tabs",e.ui.tabs,{options:{panelTemplate:"<div></div>"},_createPanel:function(t){return e(this.options.panelTemplate).attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)}}),e.widget("ui.tabs",e.ui.tabs,{_create:function(){var e=this.options;e.active===null&&e.selected!==t&&(e.active=e.selected===-1?!1:e.selected),this._super(),e.selected=e.active,e.selected===!1&&(e.selected=-1)},_setOption:function(e,t){if(e!=="selected")return this._super(e,t);var n=this.options;this._super("active",t===-1?!1:t),n.selected=n.active,n.selected===!1&&(n.selected=-1)},_eventHandler:function(){this._superApply(arguments),this.options.selected=this.options.active,this.options.selected===!1&&(this.options.selected=-1)}}),e.widget("ui.tabs",e.ui.tabs,{options:{show:null,select:null},_create:function(){this._super(),this.options.active!==!1&&this._trigger("show",null,this._ui(this.active.find(".ui-tabs-anchor")[0],this._getPanelForTab(this.active)[0]))},_trigger:function(e,t,n){var r,i,s=this._superApply(arguments);return s?(e==="beforeActivate"?(r=n.newTab.length?n.newTab:n.oldTab,i=n.newPanel.length?n.newPanel:n.oldPanel,s=this._super("select",t,{tab:r.find(".ui-tabs-anchor")[0],panel:i[0],index:r.closest("li").index()})):e==="activate"&&n.newTab.length&&(s=this._super("show",t,{tab:n.newTab.find(".ui-tabs-anchor")[0],panel:n.newPanel[0],index:n.newTab.closest("li").index()})),s):!1}}),e.widget("ui.tabs",e.ui.tabs,{select:function(e){e=this._getIndex(e);if(e===-1){if(!this.options.collapsible||this.options.selected===-1)return;e=this.options.selected}this.anchors.eq(e).trigger(this.options.event+this.eventNamespace)}}),function(){var t=0;e.widget("ui.tabs",e.ui.tabs,{options:{cookie:null},_create:function(){var e=this.options,t;e.active==null&&e.cookie&&(t=parseInt(this._cookie(),10),t===-1&&(t=!1),e.active=t),this._super()},_cookie:function(n){var r=[this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+ ++t)];return arguments.length&&(r.push(n===!1?-1:n),r.push(this.options.cookie)),e.cookie.apply(null,r)},_refresh:function(){this._super(),this.options.cookie&&this._cookie(this.options.active,this.options.cookie)},_eventHandler:function(){this._superApply(arguments),this.options.cookie&&this._cookie(this.options.active,this.options.cookie)},_destroy:function(){this._super(),this.options.cookie&&this._cookie(null,this.options.cookie)}})}(),e.widget("ui.tabs",e.ui.tabs,{_trigger:function(t,n,r){var i=e.extend({},r);return t==="load"&&(i.panel=i.panel[0],i.tab=i.tab.find(".ui-tabs-anchor")[0]),this._super(t,n,i)}}),e.widget("ui.tabs",e.ui.tabs,{options:{fx:null},_getFx:function(){var t,n,r=this.options.fx;return r&&(e.isArray(r)?(t=r[0],n=r[1]):t=n=r),r?{show:n,hide:t}:null},_toggle:function(e,t){function o(){n.running=!1,n._trigger("activate",e,t)}function u(){t.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),r.length&&s.show?r.animate(s.show,s.show.duration,function(){o()}):(r.show(),o())}var n=this,r=t.newPanel,i=t.oldPanel,s=this._getFx();if(!s)return this._super(e,t);n.running=!0,i.length&&s.hide?i.animate(s.hide,s.hide.duration,function(){t.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u()}):(t.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),i.hide(),u())}}))})(jQuery);jQuery.effects||function(e,t){var n=e.uiBackCompat!==!1,r="ui-effects-";e.effects={effect:{}},function(t,n){function p(e,t,n){var r=a[t.type]||{};return e==null?n||!t.def?null:t.def:(e=r.floor?~~e:parseFloat(e),isNaN(e)?t.def:r.mod?(e+r.mod)%r.mod:0>e?0:r.max<e?r.max:e)}function d(e){var n=o(),r=n._rgba=[];return e=e.toLowerCase(),h(s,function(t,i){var s,o=i.re.exec(e),a=o&&i.parse(o),f=i.space||"rgba";if(a)return s=n[f](a),n[u[f].cache]=s[u[f].cache],r=n._rgba=s._rgba,!1}),r.length?(r.join()==="0,0,0,0"&&t.extend(r,c.transparent),n):c[e]}function v(e,t,n){return n=(n+1)%1,n*6<1?e+(t-e)*n*6:n*2<1?t:n*3<2?e+(t-e)*(2/3-n)*6:e}var r="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "),i=/^([\-+])=\s*(\d+\.?\d*)/,s=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1],e[2],e[3],e[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1]*2.55,e[2]*2.55,e[3]*2.55,e[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(e){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(e){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(e){return[e[1],e[2]/100,e[3]/100,e[4]]}}],o=t.Color=function(e,n,r,i){return new t.Color.fn.parse(e,n,r,i)},u={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},a={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},f=o.support={},l=t("<p>")[0],c,h=t.each;l.style.cssText="background-color:rgba(1,1,1,.5)",f.rgba=l.style.backgroundColor.indexOf("rgba")>-1,h(u,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),o.fn=t.extend(o.prototype,{parse:function(r,i,s,a){if(r===n)return this._rgba=[null,null,null,null],this;if(r.jquery||r.nodeType)r=t(r).css(i),i=n;var f=this,l=t.type(r),v=this._rgba=[];i!==n&&(r=[r,i,s,a],l="array");if(l==="string")return this.parse(d(r)||c._default);if(l==="array")return h(u.rgba.props,function(e,t){v[t.idx]=p(r[t.idx],t)}),this;if(l==="object")return r instanceof o?h(u,function(e,t){r[t.cache]&&(f[t.cache]=r[t.cache].slice())}):h(u,function(t,n){var i=n.cache;h(n.props,function(e,t){if(!f[i]&&n.to){if(e==="alpha"||r[e]==null)return;f[i]=n.to(f._rgba)}f[i][t.idx]=p(r[e],t,!0)}),f[i]&&e.inArray(null,f[i].slice(0,3))<0&&(f[i][3]=1,n.from&&(f._rgba=n.from(f[i])))}),this},is:function(e){var t=o(e),n=!0,r=this;return h(u,function(e,i){var s,o=t[i.cache];return o&&(s=r[i.cache]||i.to&&i.to(r._rgba)||[],h(i.props,function(e,t){if(o[t.idx]!=null)return n=o[t.idx]===s[t.idx],n})),n}),n},_space:function(){var e=[],t=this;return h(u,function(n,r){t[r.cache]&&e.push(n)}),e.pop()},transition:function(e,t){var n=o(e),r=n._space(),i=u[r],s=this.alpha()===0?o("transparent"):this,f=s[i.cache]||i.to(s._rgba),l=f.slice();return n=n[i.cache],h(i.props,function(e,r){var i=r.idx,s=f[i],o=n[i],u=a[r.type]||{};if(o===null)return;s===null?l[i]=o:(u.mod&&(o-s>u.mod/2?s+=u.mod:s-o>u.mod/2&&(s-=u.mod)),l[i]=p((o-s)*t+s,r))}),this[r](l)},blend:function(e){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=o(e)._rgba;return o(t.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var e="rgba(",n=t.map(this._rgba,function(e,t){return e==null?t>2?1:0:e});return n[3]===1&&(n.pop(),e="rgb("),e+n.join()+")"},toHslaString:function(){var e="hsla(",n=t.map(this.hsla(),function(e,t){return e==null&&(e=t>2?1:0),t&&t<3&&(e=Math.round(e*100)+"%"),e});return n[3]===1&&(n.pop(),e="hsl("),e+n.join()+")"},toHexString:function(e){var n=this._rgba.slice(),r=n.pop();return e&&n.push(~~(r*255)),"#"+t.map(n,function(e){return e=(e||0).toString(16),e.length===1?"0"+e:e}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}}),o.fn.parse.prototype=o.fn,u.hsla.to=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=e[3],s=Math.max(t,n,r),o=Math.min(t,n,r),u=s-o,a=s+o,f=a*.5,l,c;return o===s?l=0:t===s?l=60*(n-r)/u+360:n===s?l=60*(r-t)/u+120:l=60*(t-n)/u+240,f===0||f===1?c=f:f<=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},u.hsla.from=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/360,n=e[1],r=e[2],i=e[3],s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;return[Math.round(v(o,s,t+1/3)*255),Math.round(v(o,s,t)*255),Math.round(v(o,s,t-1/3)*255),i]},h(u,function(e,r){var s=r.props,u=r.cache,a=r.to,f=r.from;o.fn[e]=function(e){a&&!this[u]&&(this[u]=a(this._rgba));if(e===n)return this[u].slice();var r,i=t.type(e),l=i==="array"||i==="object"?e:arguments,c=this[u].slice();return h(s,function(e,t){var n=l[i==="object"?e:t.idx];n==null&&(n=c[t.idx]),c[t.idx]=p(n,t)}),f?(r=o(f(c)),r[u]=c,r):o(c)},h(s,function(n,r){if(o.fn[n])return;o.fn[n]=function(s){var o=t.type(s),u=n==="alpha"?this._hsla?"hsla":"rgba":e,a=this[u](),f=a[r.idx],l;return o==="undefined"?f:(o==="function"&&(s=s.call(this,f),o=t.type(s)),s==null&&r.empty?this:(o==="string"&&(l=i.exec(s),l&&(s=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[r.idx]=s,this[u](a)))}})}),h(r,function(e,n){t.cssHooks[n]={set:function(e,r){var i,s,u="";if(t.type(r)!=="string"||(i=d(r))){r=o(i||r);if(!f.rgba&&r._rgba[3]!==1){s=n==="backgroundColor"?e.parentNode:e;while((u===""||u==="transparent")&&s&&s.style)try{u=t.css(s,"backgroundColor"),s=s.parentNode}catch(a){}r=r.blend(u&&u!=="transparent"?u:"_default")}r=r.toRgbaString()}try{e.style[n]=r}catch(l){}}},t.fx.step[n]=function(e){e.colorInit||(e.start=o(e.elem,n),e.end=o(e.end),e.colorInit=!0),t.cssHooks[n].set(e.elem,e.start.transition(e.end,e.pos))}}),t.cssHooks.borderColor={expand:function(e){var t={};return h(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},c=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(){var t=this.ownerDocument.defaultView?this.ownerDocument.defaultView.getComputedStyle(this,null):this.currentStyle,n={},r,i;if(t&&t.length&&t[0]&&t[t[0]]){i=t.length;while(i--)r=t[i],typeof t[r]=="string"&&(n[e.camelCase(r)]=t[r])}else for(r in t)typeof t[r]=="string"&&(n[r]=t[r]);return n}function s(t,n){var i={},s,o;for(s in n)o=n[s],t[s]!==o&&!r[s]&&(e.fx.step[s]||!isNaN(parseFloat(o)))&&(i[s]=o);return i}var n=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,n){e.fx.step[n]=function(e){if(e.end!=="none"&&!e.setAttr||e.pos===1&&!e.setAttr)jQuery.style(e.elem,n,e.end),e.setAttr=!0}}),e.effects.animateClass=function(t,r,o,u){var a=e.speed(r,o,u);return this.queue(function(){var r=e(this),o=r.attr("class")||"",u,f=a.children?r.find("*").andSelf():r;f=f.map(function(){var t=e(this);return{el:t,start:i.call(this)}}),u=function(){e.each(n,function(e,n){t[n]&&r[n+"Class"](t[n])})},u(),f=f.map(function(){return this.end=i.call(this.el[0]),this.diff=s(this.start,this.end),this}),r.attr("class",o),f=f.map(function(){var t=this,n=e.Deferred(),r=jQuery.extend({},a,{queue:!1,complete:function(){n.resolve(t)}});return this.el.animate(this.diff,r),n.promise()}),e.when.apply(e,f.get()).done(function(){u(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),a.complete.call(r[0])})})},e.fn.extend({_addClass:e.fn.addClass,addClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{add:t},n,r,i):this._addClass(t)},_removeClass:e.fn.removeClass,removeClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{remove:t},n,r,i):this._removeClass(t)},_toggleClass:e.fn.toggleClass,toggleClass:function(n,r,i,s,o){return typeof r=="boolean"||r===t?i?e.effects.animateClass.call(this,r?{add:n}:{remove:n},i,s,o):this._toggleClass(n,r):e.effects.animateClass.call(this,{toggle:n},r,i,s)},switchClass:function(t,n,r,i,s){return e.effects.animateClass.call(this,{add:n,remove:t},r,i,s)}})}(),function(){function i(t,n,r,i){e.isPlainObject(t)&&(n=t,t=t.effect),t={effect:t},n==null&&(n={}),e.isFunction(n)&&(i=n,r=null,n={});if(typeof n=="number"||e.fx.speeds[n])i=r,r=n,n={};return e.isFunction(r)&&(i=r,r=null),n&&e.extend(t,n),r=r||n.duration,t.duration=e.fx.off?0:typeof r=="number"?r:r in e.fx.speeds?e.fx.speeds[r]:e.fx.speeds._default,t.complete=i||n.complete,t}function s(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&&!e.effects.effect[t]?n&&e.effects[t]?!1:!0:!1}e.extend(e.effects,{version:"1.9.2",save:function(e,t){for(var n=0;n<t.length;n++)t[n]!==null&&e.data(r+t[n],e[0].style[t[n]])},restore:function(e,n){var i,s;for(s=0;s<n.length;s++)n[s]!==null&&(i=e.data(r+n[s]),i===t&&(i=""),e.css(n[s],i))},setMode:function(e,t){return t==="toggle"&&(t=e.is(":hidden")?"show":"hide"),t},getBaseline:function(e,t){var n,r;switch(e[0]){case"top":n=0;break;case"middle":n=.5;break;case"bottom":n=1;break;default:n=e[0]/t.height}switch(e[1]){case"left":r=0;break;case"center":r=.5;break;case"right":r=1;break;default:r=e[1]/t.width}return{x:r,y:n}},createWrapper:function(t){if(t.parent().is(".ui-effects-wrapper"))return t.parent();var n={width:t.outerWidth(!0),height:t.outerHeight(!0),"float":t.css("float")},r=e("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),i={width:t.width(),height:t.height()},s=document.activeElement;try{s.id}catch(o){s=document.body}return t.wrap(r),(t[0]===s||e.contains(t[0],s))&&e(s).focus(),r=t.parent(),t.css("position")==="static"?(r.css({position:"relative"}),t.css({position:"relative"})):(e.extend(n,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,r){n[r]=t.css(r),isNaN(parseInt(n[r],10))&&(n[r]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(i),r.css(n).show()},removeWrapper:function(t){var n=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),(t[0]===n||e.contains(t[0],n))&&e(n).focus()),t},setTransition:function(t,n,r,i){return i=i||{},e.each(n,function(e,n){var s=t.cssUnit(n);s[0]>0&&(i[n]=s[0]*r+s[1])}),i}}),e.fn.extend({effect:function(){function a(n){function u(){e.isFunction(i)&&i.call(r[0]),e.isFunction(n)&&n()}var r=e(this),i=t.complete,s=t.mode;(r.is(":hidden")?s==="hide":s==="show")?u():o.call(r[0],t,u)}var t=i.apply(this,arguments),r=t.mode,s=t.queue,o=e.effects.effect[t.effect],u=!o&&n&&e.effects[t.effect];return e.fx.off||!o&&!u?r?this[r](t.duration,t.complete):this.each(function(){t.complete&&t.complete.call(this)}):o?s===!1?this.each(a):this.queue(s||"fx",a):u.call(this,{options:t,duration:t.duration,callback:t.complete,mode:t.mode})},_show:e.fn.show,show:function(e){if(s(e))return this._show.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(s(e))return this._hide.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(s(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=i.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)},cssUnit:function(t){var n=this.css(t),r=[];return e.each(["em","px","%","pt"],function(e,t){n.indexOf(t)>0&&(r=[parseFloat(n),t])}),r}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,n){t[n]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return e===0||e===1?e:-Math.pow(2,8*(e-1))*Math.sin(((e-1)*80-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){var t,n=4;while(e<((t=Math.pow(2,--n))-1)/11);return 1/Math.pow(4,3-n)-7.5625*Math.pow((t*3-2)/22-e,2)}}),e.each(t,function(t,n){e.easing["easeIn"+t]=n,e.easing["easeOut"+t]=function(e){return 1-n(1-e)},e.easing["easeInOut"+t]=function(e){return e<.5?n(e*2)/2:1-n(e*-2+2)/2}})}()}(jQuery);(function(e,t){var n=/up|down|vertical/,r=/up|left|vertical|horizontal/;e.effects.effect.blind=function(t,i){var s=e(this),o=["position","top","bottom","left","right","height","width"],u=e.effects.setMode(s,t.mode||"hide"),a=t.direction||"up",f=n.test(a),l=f?"height":"width",c=f?"top":"left",h=r.test(a),p={},d=u==="show",v,m,g;s.parent().is(".ui-effects-wrapper")?e.effects.save(s.parent(),o):e.effects.save(s,o),s.show(),v=e.effects.createWrapper(s).css({overflow:"hidden"}),m=v[l](),g=parseFloat(v.css(c))||0,p[l]=d?m:0,h||(s.css(f?"bottom":"right",0).css(f?"top":"left","auto").css({position:"absolute"}),p[c]=d?g:m+g),d&&(v.css(l,0),h||v.css(c,g+m)),v.animate(p,{duration:t.duration,easing:t.easing,queue:!1,complete:function(){u==="hide"&&s.hide(),e.effects.restore(s,o),e.effects.removeWrapper(s),i()}})}})(jQuery);(function(e,t){e.effects.effect.bounce=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=s==="hide",u=s==="show",a=t.direction||"up",f=t.distance,l=t.times||5,c=l*2+(u||o?1:0),h=t.duration/c,p=t.easing,d=a==="up"||a==="down"?"top":"left",v=a==="up"||a==="left",m,g,y,b=r.queue(),w=b.length;(u||o)&&i.push("opacity"),e.effects.save(r,i),r.show(),e.effects.createWrapper(r),f||(f=r[d==="top"?"outerHeight":"outerWidth"]()/3),u&&(y={opacity:1},y[d]=0,r.css("opacity",0).css(d,v?-f*2:f*2).animate(y,h,p)),o&&(f/=Math.pow(2,l-1)),y={},y[d]=0;for(m=0;m<l;m++)g={},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p).animate(y,h,p),f=o?f*2:f/2;o&&(g={opacity:0},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p)),r.queue(function(){o&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),w>1&&b.splice.apply(b,[1,0].concat(b.splice(w,c+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.clip=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"vertical",a=u==="vertical",f=a?"height":"width",l=a?"top":"left",c={},h,p,d;e.effects.save(r,i),r.show(),h=e.effects.createWrapper(r).css({overflow:"hidden"}),p=r[0].tagName==="IMG"?h:r,d=p[f](),o&&(p.css(f,0),p.css(l,d/2)),c[f]=o?d:0,c[l]=o?0:d/2,p.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){o||r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.drop=function(t,n){var r=e(this),i=["position","top","bottom","left","right","opacity","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left"?"pos":"neg",l={opacity:o?1:0},c;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),c=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0)/2,o&&r.css("opacity",0).css(a,f==="pos"?-c:c),l[a]=(o?f==="pos"?"+=":"-=":f==="pos"?"-=":"+=")+c,r.animate(l,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.explode=function(t,n){function y(){c.push(this),c.length===r*i&&b()}function b(){s.css({visibility:"visible"}),e(c).remove(),u||s.hide(),n()}var r=t.pieces?Math.round(Math.sqrt(t.pieces)):3,i=r,s=e(this),o=e.effects.setMode(s,t.mode||"hide"),u=o==="show",a=s.show().css("visibility","hidden").offset(),f=Math.ceil(s.outerWidth()/i),l=Math.ceil(s.outerHeight()/r),c=[],h,p,d,v,m,g;for(h=0;h<r;h++){v=a.top+h*l,g=h-(r-1)/2;for(p=0;p<i;p++)d=a.left+p*f,m=p-(i-1)/2,s.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-p*f,top:-h*l}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:f,height:l,left:d+(u?m*f:0),top:v+(u?g*l:0),opacity:u?0:1}).animate({left:d+(u?0:m*f),top:v+(u?0:g*l),opacity:u?1:0},t.duration||500,t.easing,y)}}})(jQuery);(function(e,t){e.effects.effect.fade=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"toggle");r.animate({opacity:i},{queue:!1,duration:t.duration,easing:t.easing,complete:n})}})(jQuery);(function(e,t){e.effects.effect.fold=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=s==="hide",a=t.size||15,f=/([0-9]+)%/.exec(a),l=!!t.horizFirst,c=o!==l,h=c?["width","height"]:["height","width"],p=t.duration/2,d,v,m={},g={};e.effects.save(r,i),r.show(),d=e.effects.createWrapper(r).css({overflow:"hidden"}),v=c?[d.width(),d.height()]:[d.height(),d.width()],f&&(a=parseInt(f[1],10)/100*v[u?0:1]),o&&d.css(l?{height:0,width:a}:{height:a,width:0}),m[h[0]]=o?v[0]:a,g[h[1]]=o?v[1]:0,d.animate(m,p,t.easing).animate(g,p,t.easing,function(){u&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()})}})(jQuery);(function(e,t){e.effects.effect.highlight=function(t,n){var r=e(this),i=["backgroundImage","backgroundColor","opacity"],s=e.effects.setMode(r,t.mode||"show"),o={backgroundColor:r.css("backgroundColor")};s==="hide"&&(o.opacity=0),e.effects.save(r,i),r.show().css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(o,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),n()}})}})(jQuery);(function(e,t){e.effects.effect.pulsate=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"show"),s=i==="show",o=i==="hide",u=s||i==="hide",a=(t.times||5)*2+(u?1:0),f=t.duration/a,l=0,c=r.queue(),h=c.length,p;if(s||!r.is(":visible"))r.css("opacity",0).show(),l=1;for(p=1;p<a;p++)r.animate({opacity:l},f,t.easing),l=1-l;r.animate({opacity:l},f,t.easing),r.queue(function(){o&&r.hide(),n()}),h>1&&c.splice.apply(c,[1,0].concat(c.splice(h,a+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.puff=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"hide"),s=i==="hide",o=parseInt(t.percent,10)||150,u=o/100,a={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()};e.extend(t,{effect:"scale",queue:!1,fade:!0,mode:i,complete:n,percent:s?o:100,from:s?a:{height:a.height*u,width:a.width*u,outerHeight:a.outerHeight*u,outerWidth:a.outerWidth*u}}),r.effect(t)},e.effects.effect.scale=function(t,n){var r=e(this),i=e.extend(!0,{},t),s=e.effects.setMode(r,t.mode||"effect"),o=parseInt(t.percent,10)||(parseInt(t.percent,10)===0?0:s==="hide"?0:100),u=t.direction||"both",a=t.origin,f={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()},l={y:u!=="horizontal"?o/100:1,x:u!=="vertical"?o/100:1};i.effect="size",i.queue=!1,i.complete=n,s!=="effect"&&(i.origin=a||["middle","center"],i.restore=!0),i.from=t.from||(s==="show"?{height:0,width:0,outerHeight:0,outerWidth:0}:f),i.to={height:f.height*l.y,width:f.width*l.x,outerHeight:f.outerHeight*l.y,outerWidth:f.outerWidth*l.x},i.fade&&(s==="show"&&(i.from.opacity=0,i.to.opacity=1),s==="hide"&&(i.from.opacity=1,i.to.opacity=0)),r.effect(i)},e.effects.effect.size=function(t,n){var r,i,s,o=e(this),u=["position","top","bottom","left","right","width","height","overflow","opacity"],a=["position","top","bottom","left","right","overflow","opacity"],f=["width","height","overflow"],l=["fontSize"],c=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],h=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=e.effects.setMode(o,t.mode||"effect"),d=t.restore||p!=="effect",v=t.scale||"both",m=t.origin||["middle","center"],g=o.css("position"),y=d?u:a,b={height:0,width:0,outerHeight:0,outerWidth:0};p==="show"&&o.show(),r={height:o.height(),width:o.width(),outerHeight:o.outerHeight(),outerWidth:o.outerWidth()},t.mode==="toggle"&&p==="show"?(o.from=t.to||b,o.to=t.from||r):(o.from=t.from||(p==="show"?b:r),o.to=t.to||(p==="hide"?b:r)),s={from:{y:o.from.height/r.height,x:o.from.width/r.width},to:{y:o.to.height/r.height,x:o.to.width/r.width}};if(v==="box"||v==="both")s.from.y!==s.to.y&&(y=y.concat(c),o.from=e.effects.setTransition(o,c,s.from.y,o.from),o.to=e.effects.setTransition(o,c,s.to.y,o.to)),s.from.x!==s.to.x&&(y=y.concat(h),o.from=e.effects.setTransition(o,h,s.from.x,o.from),o.to=e.effects.setTransition(o,h,s.to.x,o.to));(v==="content"||v==="both")&&s.from.y!==s.to.y&&(y=y.concat(l).concat(f),o.from=e.effects.setTransition(o,l,s.from.y,o.from),o.to=e.effects.setTransition(o,l,s.to.y,o.to)),e.effects.save(o,y),o.show(),e.effects.createWrapper(o),o.css("overflow","hidden").css(o.from),m&&(i=e.effects.getBaseline(m,r),o.from.top=(r.outerHeight-o.outerHeight())*i.y,o.from.left=(r.outerWidth-o.outerWidth())*i.x,o.to.top=(r.outerHeight-o.to.outerHeight)*i.y,o.to.left=(r.outerWidth-o.to.outerWidth)*i.x),o.css(o.from);if(v==="content"||v==="both")c=c.concat(["marginTop","marginBottom"]).concat(l),h=h.concat(["marginLeft","marginRight"]),f=u.concat(c).concat(h),o.find("*[width]").each(function(){var n=e(this),r={height:n.height(),width:n.width(),outerHeight:n.outerHeight(),outerWidth:n.outerWidth()};d&&e.effects.save(n,f),n.from={height:r.height*s.from.y,width:r.width*s.from.x,outerHeight:r.outerHeight*s.from.y,outerWidth:r.outerWidth*s.from.x},n.to={height:r.height*s.to.y,width:r.width*s.to.x,outerHeight:r.height*s.to.y,outerWidth:r.width*s.to.x},s.from.y!==s.to.y&&(n.from=e.effects.setTransition(n,c,s.from.y,n.from),n.to=e.effects.setTransition(n,c,s.to.y,n.to)),s.from.x!==s.to.x&&(n.from=e.effects.setTransition(n,h,s.from.x,n.from),n.to=e.effects.setTransition(n,h,s.to.x,n.to)),n.css(n.from),n.animate(n.to,t.duration,t.easing,function(){d&&e.effects.restore(n,f)})});o.animate(o.to,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){o.to.opacity===0&&o.css("opacity",o.from.opacity),p==="hide"&&o.hide(),e.effects.restore(o,y),d||(g==="static"?o.css({position:"relative",top:o.to.top,left:o.to.left}):e.each(["top","left"],function(e,t){o.css(t,function(t,n){var r=parseInt(n,10),i=e?o.to.left:o.to.top;return n==="auto"?i+"px":r+i+"px"})})),e.effects.removeWrapper(o),n()}})}})(jQuery);(function(e,t){e.effects.effect.shake=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=t.direction||"left",u=t.distance||20,a=t.times||3,f=a*2+1,l=Math.round(t.duration/f),c=o==="up"||o==="down"?"top":"left",h=o==="up"||o==="left",p={},d={},v={},m,g=r.queue(),y=g.length;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),p[c]=(h?"-=":"+=")+u,d[c]=(h?"+=":"-=")+u*2,v[c]=(h?"-=":"+=")+u*2,r.animate(p,l,t.easing);for(m=1;m<a;m++)r.animate(d,l,t.easing).animate(v,l,t.easing);r.animate(d,l,t.easing).animate(p,l/2,t.easing).queue(function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),y>1&&g.splice.apply(g,[1,0].concat(g.splice(y,f+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.slide=function(t,n){var r=e(this),i=["position","top","bottom","left","right","width","height"],s=e.effects.setMode(r,t.mode||"show"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left",l,c={};e.effects.save(r,i),r.show(),l=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0),e.effects.createWrapper(r).css({overflow:"hidden"}),o&&r.css(a,f?isNaN(l)?"-"+l:-l:l),c[a]=(o?f?"+=":"-=":f?"-=":"+=")+l,r.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.transfer=function(t,n){var r=e(this),i=e(t.to),s=i.css("position")==="fixed",o=e("body"),u=s?o.scrollTop():0,a=s?o.scrollLeft():0,f=i.offset(),l={top:f.top-u,left:f.left-a,height:i.innerHeight(),width:i.innerWidth()},c=r.offset(),h=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(t.className).css({top:c.top-u,left:c.left-a,height:r.innerHeight(),width:r.innerWidth(),position:s?"fixed":"absolute"}).animate(l,t.duration,t.easing,function(){h.remove(),n()})}})(jQuery);;

/** Polyfill **/
(window.defineModule = (window.defineModule || {})).name = 'Polyfill';
/* jshint proto: true, unused: true */

if (!('console' in window)) { window.console = {}; }
if (!('log' in window.console) || (typeof window.console.log !== 'function')) {
	window.console = {log: function() {}};
}

if (typeof Object.create !== 'function') {
	Object.create = (function () {
		var Temp = function () {};
		return function (prototype) {
			if (arguments.length > 1) {
				throw Error('Second argument not supported');
			}
			if (typeof prototype !== 'object') {
				throw TypeError('Argument must be an object');
			}
			Temp.prototype = prototype;
			var result = new Temp();
			Temp.prototype = null;
			return result;
		};
	})();
}

if (typeof Object.getPrototypeOf !== 'function') {
	if (({}).__proto__ === Object.prototype && ([]).__proto__ === Array.prototype) {
		Object.getPrototypeOf = function getPrototypeOf(object) {
			return object.__proto__;
		};
	} else {
		Object.getPrototypeOf = function getPrototypeOf(object) {
			return object.constructor ? object.constructor.prototype : void 0;
		};
	}
}

if (typeof Object.assign !== 'function') {
	Object.assign = function(target, varArgs) {
		if (target == null) { // TypeError if undefined or null
			throw new TypeError('Cannot convert undefined or null to object');
		}
		var to = Object(target);
		for (var index = 1; index < arguments.length; index++) {
			var nextSource = arguments[index];
			
			if (nextSource != null) { // Skip over if undefined or null
				for (var nextKey in nextSource) {
					if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
						to[nextKey] = nextSource[nextKey];
					}
				}
			}
		}
		return to;
	};
}

if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function (searchElement, fromIndex) {
		var k;
		if (this === null) { throw new TypeError('"this" is null or not defined'); }
		var O = Object(this);
		var len = O.length >>> 0;
		if (len === 0) { return -1; }
		var n = +fromIndex || 0;
		if (Math.abs(n) === Infinity) { n = 0; }
		if (n >= len) { return -1; }
		k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
		while (k < len) {
			if (k in O && O[k] === searchElement) { return k; }
			k++;
		}
		return -1;
	};
}

if (!Array.prototype.filter) {
	Array.prototype.filter = function(fun/*, thisArg*/) {
		'use strict';
		if (this === void 0 || this === null) throw new TypeError();
		var t = Object(this);
		var len = t.length >>> 0;
		if (typeof fun !== 'function') throw new TypeError();
		var res = [];
		var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
		for (var i = 0; i < len; i++) {
			if (i in t) {
				var val = t[i];
				if (fun.call(thisArg, val, i, t)) {
					res.push(val);
				}
			}
		}
		return res;
	};
}

if (!Array.prototype.map) {
	Array.prototype.map = function(callback/*, thisArg*/) {
		var T, A, k;
		if (this == null) throw new TypeError('this is null or not defined');
		var O = Object(this);
		var len = O.length >>> 0;
		if (typeof callback !== 'function') {
			throw new TypeError(callback + ' is not a function');
		}
		if (arguments.length > 1) { T = arguments[1]; }
		A = new Array(len);
		k = 0;
		while (k < len) {
			var kValue, mappedValue;
			if (k in O) {
				kValue = O[k];
				mappedValue = callback.call(T, kValue, k, O);
				A[k] = mappedValue;
			}
			k++;
		}
		return A;
	};
}

if (!('define' in window) || (typeof window.define !== 'function')) {
	(function() {
		'use strict';
		var modules = {}, lazyModules = {};
		var resolveDep = function(relModule, module) {
			if (module.length === 0 || module.indexOf('/') < 0) return module;
			var i, res = [], part, parts = ((module.charAt(0) === '/')
					? module.substring(1)
					: (((relModule.length > 0 && module.charAt(0) === '.') ? (relModule + '/../') : '') + module)
				).split('/');
			for (i = 0; i < parts.length; i++) {
				part = parts[i];
				if ('.' === part) continue;
				if ('..' === part && res.length > 0) res.pop(); else res.push(part);
			}
			return res.join('/');
		};
		var requireToModules = function(module, deps, exports, lvl) {
			if (lvl > 1000) throw 'Recursion in define dependencies?';
			//var pref = '', prefLvl = lvl + 1;  while (prefLvl-- > 0) pref += '  ';
			var mods = [], mod, lmod, i, depName;
			for (i = 0; i < deps.length; i++) {
				//console.log(pref + 'Require: ' + deps[i]);
				mod = null; depName = resolveDep(module, deps[i]);
				if (depName in modules) {
					mod = modules[depName];
				} else if (depName in lazyModules) {
					lmod = lazyModules[depName];
					if (typeof lmod.module === 'function') {
						lmod.exports = {};
						mod = lmod.module.apply(this, requireToModules(depName, lmod.deps, lmod.exports, lvl + 1));
						if (!mod) mod = lmod.exports;
					} else {
						mod = lmod.module;
					};
					if (mod && !('__esModule' in mod)) mod.default = mod;
					modules[lmod.name] = mod;
				} else if (depName === 'exports') {
					mod = exports;
				}
				//if (!mod && deps[i] !== 'require') console.log('Dep', deps[i], 'not found for module', module);
				mods.push(mod);
			}
			if (mods.length < 2 || mods[1] !== exports) {
				// fallback to old module system
				for (i = 0; i < mods.length; i++) {
					if (mods[i] && (typeof mods[i] === 'object') && ('__esModule' in mods[i]) && ('default' in mods[i])) {
						mods[i] = mods[i].default;
					}
				}
			}
			return mods;
		};
		(window.defineModule = (window.defineModule || {name: null}));
		window.define = function(name, deps, module) {
			if (typeof name !== 'string') {
				module = deps;
				deps = name;
				name = window.defineModule.name;
			}
			var fixNames = function(name) {
				if (typeof name === 'object') {
					for (var i = 0; i < name.length; i++) { name[i] = fixNames(name[i]); }
					return name;
				}
				return ((typeof name === 'string') && name.substring(0, 2) === './') ? name.substring(2) : name;
			};
			//console.log('Define: ' + name);
			lazyModules[name] = {name: fixNames(name), deps: fixNames(deps), module: module};
		};
		window.require = function(deps, func) {
			//console.log('Require Root');
			if (typeof func === 'function') func.apply(this, requireToModules('', deps, {}, 0));
		};
	})();
}
;

/** HasherUtil **/
(window.defineModule = (window.defineModule || {})).name = 'HasherUtil';

window.HasherUtil = (function() {
	var _crcTable = null,
		makeCRCTable = function() {
			var c, n, k, crcTable = [];
			for (n = 0; n < 256; n++) {
				c = n;
				for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); }
				crcTable[n] = c;
			}
			return crcTable;
		},
		/**
		 * Get crc32
		 * @param {String} str value to hash
		 * @return {Number}
		 */
		crc32 = function(str) {
			var i, crc = (0 ^ (-1)), crcTable = _crcTable || (_crcTable = makeCRCTable());
			for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; }
			return (crc ^ (-1)) >>> 0;
		};

	return {
		crc32: crc32,
		/**
		 * Get crc32 hex version
		 * @param {String} str value to hash
		 * @return {String}
		 */
		crc32Hex: function(str) {
			var hexval = crc32(str).toString(16);
			while (hexval.length < 8) { hexval = '0' + hexval; }
			return hexval;
		}
	};
})();
;

/** Rectangle **/
(window.defineModule = (window.defineModule || {})).name = 'Rectangle';

define('Rectangle', [], function() {
	
	/**
	 * Create rectangle
	 * @param {Number} x
	 * @param {Number} y
	 * @param {Number} width
	 * @param {Number} height
	 * @class Rectangle
	 */
	var self = function(x, y, width, height) {
		if (x !== '%inherit%') {
			if (x) this.x = x;
			if (y) this.y = y;
			if (width) this.width = width;
			if (height) this.height = height;
		}
	};
	
	/** @type Number */
	self.prototype.x = 0;
	/** @type Number */
	self.prototype.y = 0;
	/** @type Number */
	self.prototype.width = 0;
	/** @type Number */
	self.prototype.height = 0;
	
	/**
	 * Create rectangle from object
	 * @param {Object} obj
	 * @return {Rectangle}
	 */
	self.fromObject = function(obj) {
		var r = new self();
		if (obj && typeof obj === 'object') {
			if (obj.x) r.x = obj.x;
			if (obj.y) r.y = obj.y;
			if (obj.width) r.width = obj.width;
			if (obj.height) r.height = obj.height;
			if (obj.position && !obj.x && !obj.y) {
				if (obj.position.x) r.x = obj.position.x;
				if (obj.position.y) r.y = obj.position.y;
			}
			if (obj.size && !obj.width && !obj.height) {
				if (obj.size.width) r.width = obj.size.width;
				if (obj.size.height) r.height = obj.size.height;
			}
		}
		
		return r;
	};
	
	/** @return {Object} */
	self.prototype.serialize = function() {
		return {x: this.x, y: this.y, width: this.width, height: this.height};
	};
	
	/**
	 * Set rectangle position
	 * @param {Number} x
	 * @param {Number} y
	 */
	self.prototype.setPosition = function(x, y) {
		if (x) this.x = x;
		if (y) this.y = y;
	};
	
	/**
	 * Set rectangle size
	 * @param {Number} width
	 * @param {Number} height
	 */
	self.prototype.setSize = function(width, height) {
		if (width) this.width = width;
		if (height) this.height = height;
	};
	
	return self;
});
;

/** IdIndexedList **/
(window.defineModule = (window.defineModule || {})).name = 'IdIndexedList';

define('IdIndexedList', [], function() {
	
	var self = function() { this.__construct.apply(this, arguments); };
	$.extend(self.prototype, {
		
		_items: null,
		_itemsIndex: null,
		
		/**
		 * Create list
		 * @param {Array|Object=} data
		 * @param {Boolean=} clone
		 * @param {Boolean=} serialize
		 */
		__construct: function(data, clone, serialize) {
			this._items = [];
			this._itemsIndex = {};
			if (typeof data === 'object') this.addItems(data, clone, serialize);
		},
		
		toArray: function() {
			var arr = [];
			for (var i = 0; i < this._item.length; i++) { arr.push(this._item[i]); }
			return arr;
		},
		
		toIdObject: function() {
			var obj = {};
			for (var i = 0; i < this._item.length; i++) { obj['#' + this._item[i].id] = this._item[i]; }
			return obj;
		},
		
		getItemCount: function() {
			return this._items.length;
		},
		
		getItem: function(index) {
			return ((index >= 0 && index < this._items.length) ? this._items[index] : null);
		},
		
		getItemById: function(id) {
			var idIdx = '#' + id;
			return ((idIdx in this._itemsIndex) ? this._itemsIndex[idIdx] : null);
		},
		
		addItems: function(data, clone, serialize) {
			if (data instanceof self) {
				for (var n = 0, c = data.getItemCount(); n < c; n++) {
					this.addItem(data.getItem(n));
				}
			} else {
				if ('length' in data) {
					for (var i = 0; i < data.length; i++) { this.addItem(clone ? $.extend({}, data[i]) : (serialize ? data[i].serialize() : data[i])); }
				} else {
					for (var k in data) { this.addItem(clone ? $.extend({}, data[k]) : (serialize ? data[k].serialize() : data[k])); }
				}
			}
		},
		
		addItem: function(item) {
			var idx = this._items.indexOf(item);
			if (idx < 0) {
				this._items.push(item);
				this._itemsIndex['#' + item.id] = item;
			}
		},
		
		removeItem: function(item) {
			var idx = this._items.indexOf(item);
			if (idx >= 0) {
				this._items.splice(idx, 1);
				this._itemsIndex['#' + item.id] = null;
				delete this._itemsIndex['#' + item.id];
			}
		},
		
		removeAllItems: function() {
			this._items.splice(0, this._items.length);
			this._itemsIndex = {};
		},
		
		/**
		 * Add new item to list
		 * @param {Object} baseItem item to base new item on
		 * @param {Boolean} noClone
		 * @returns {Object}
		 */
		newItem: function(baseItem, noClone) {
			var item = (baseItem ? (noClone ? baseItem : $.extend(true, {}, baseItem)) : {});
			item.id = this._findFreeId();
			this.addItem(item);
			return item;
		},
		
		sortItems: function(callback) {
			if (typeof(callback) !== 'function') return;
			this._items.sort(callback);
		},
		
		_findFreeId: function() {
			for (var i = 1; i < 5000; i++) {
				if (!this._itemsIndex['#' + i]) {
					return i;
				}
			}
			return 1;
		}
		
	});
	
	return self;
});
;

/** WidgetToolbar **/
(window.defineModule = (window.defineModule || {})).name = 'WidgetToolbar';

define('WidgetToolbar', ['ElementRegister', 'Service'], function(ElementRegister, Service) {
	'use strict';
	
	var collapsableGroups = [];
	
	var self = {
		
		/** @type jQuery */
		elem: null,
		/** @type Array */
		items: null,
		/** @type ToolbarItem[] */
		tbItems: null,
		/** @type ToolbarItemGroup[] */
		collapsableGroups: null,
		/** @type Boolean */
		enabled: true,
		/** @type String */
		id: null,
		/** @type Number */
		lastOrder: 0,
		/** @type Boolean */
		_resizeFuncApplied: false,
		
		/**
		 * @param {Array} data table descriptor
		 * @param {String} styleClass
		 * @param {Boolean} disableEmptyLikeGroups
		 * @return WidgetToolbar
		 */
		init: function(data, styleClass, disableEmptyLikeGroups) {
			this.elem = $('<div>').addClass('wb_toolbar');
			if (styleClass) this.elem.addClass(styleClass);
			this.items = [];
			this.tbItems = [];
			this.collapsableGroups = [];
			this.parseData(data, this, disableEmptyLikeGroups);
			return this;
		},

		/** @param {Boolean} enabled */
		setEnabled: function(enabled) {
			if (this.enabled === enabled) return;
			this.enabled = enabled;
			var i, li;
			if (enabled) {
				for (i = 0; i < this.tbItems.length; i++) {
					li = this.tbItems[i];
					if (li.oriEnabled && !li.enabled) li.setEnabled(true);
				}
			} else {
				for (i = 0; i < this.tbItems.length; i++) {
					li = this.tbItems[i];
					li.oriEnabled = li.enabled;
					if (li.oriEnabled) li.setEnabled(false);
				}
			}
		},
		
		/** Call after adding to DOM to update size */
		ajustSize: function() {
			var thisSelf = this;
			//this.elem.css({width: 1024});
			var initialCalcDone = false;
			var initialCalc = function() {
				var i, li;
				for (i = 0; i < thisSelf.items.length; i++) {
					li = thisSelf.items[i];
					if (Object.getPrototypeOf(li) === thisSelf.ToolbarItemGroup) {
						li.ajustSize();
					}
				}
			};
			/*if (this.collapsableGroups.length > 0) {
				this.collapsableGroups[0].setCollapsed(false);
			}*/
			if (!thisSelf._resizeFuncApplied) {
				thisSelf._resizeFuncApplied = true;
				var resizeFunc = function() {
					if (!initialCalcDone && thisSelf.elem.width() > 0) {
						initialCalcDone = true;
						initialCalc();
					}
					var i, w, uw = 0, tw = thisSelf.elem.width();
					for (i = 0; i < thisSelf.items.length; i++) {
						uw += (('blockWidth' in thisSelf.items[i]) && thisSelf.items[i].blockWidth) ? thisSelf.items[i].blockWidth : thisSelf.items[i].elem.outerWidth(true);
					}
					for (i = (thisSelf.items.length - 1); i >= 0; i--) {
						w = (('blockWidth' in thisSelf.items[i]) && thisSelf.items[i].blockWidth) ? thisSelf.items[i].blockWidth : thisSelf.items[i].elem.outerWidth(true);
						if (uw > tw && ('expanderWidth' in thisSelf.items[i])) {
							uw -= w - thisSelf.items[i].expanderWidth;
							thisSelf.items[i].setCollapsed(true, true);
						} else if (('expanderWidth' in thisSelf.items[i])) {
							thisSelf.items[i].setCollapsed(false, true);
						}
					}
				};
				$(window).on('resize', resizeFunc);
			}
			$(window).trigger('resize');
		},

		/**
		 * @param {Number} index
		 * @returns ToolbarItem
		 */
		getToolbarItem: function(index) {
			return (this.tbItems.length > index && index >= 0) ? this.tbItems[index] : null;
		},

		/**
		 * @param {Array} data table descriptor
		 * @param {WidgetToolbar|ToolbarItemGroup} parent
		 * @param {Boolean} disableEmptyLikeGroups
		 */
		parseData: function(data, parent, disableEmptyLikeGroups) {
			var i, o, li, btn, thisSelf = this;
			for (i = 0; i < data.length; i++) {
				o = data[i];
				if (!('type' in o) || !o.type || o.type === 'item' || o.type === 'widget') {
					li = Object.create(this.ToolbarItem).init(o.icon, o.name, (o.iconImage ? true : false));
					if (('beta' in o) && o.beta) li.setBeta(true);
					if ('id' in o) {
						li.id = o.id;
						li.setId((o.type === 'widget') ? ('wb__' + o.id) : o.id);
					}
					if (('borderless' in o) && o.borderless) li.setBorderless(true);
					if ('active' in o) {
						li.setEnabled((typeof o.active === 'function') ? o.active(o.id) : (o.active ? true : false));
					}
					if (o.type === 'widget') {
						if (window.wb_builder.isTouchDevice) {
							li.setTitle(__('Tap to add'));
						} else {
							li.setTitle(__('Drag and drop to add'));
						}
						if (li.enabled) li.setDraggable(true, function() {
							for (var i = 0; i < thisSelf.collapsableGroups.length; i++) {
								thisSelf.collapsableGroups[i].setOpen(false, true);
							}
						});
					} else {
						if (('title' in o) && o.title) li.setTitle(o.title); else if (!('submenu' in o)) li.setTitle(o.name);
						if ('submenu' in o) li.setSubmenu(o.submenu);
						if (('click' in o) && (typeof o.click === 'function')) {
							li.elem.on('click touchend', (function(func, li) { return function(e) { func.call(li, e, li); }; })(o.click, li));
						}
					}
					if (('featureMessage' in o) && o.featureMessage) li.setFeatureMessage(o.featureMessage);
					if ('init' in o && typeof o.init === 'function') o.init.call(li);
					parent.addItem(li, this.getNextOrder());
					this.tbItems.push(li);
				} else if (o.type === 'group') {
					li = Object.create(this.ToolbarItemGroup).init();
					if ('id' in o) li.setId(o.id);
					if (('collapsable' in o) && o.collapsable) {
						btn = Object.create(this.ToolbarItem).init(o.icon, o.name);
						if ('borderless' in o) btn.setBorderless(o.borderless ? true : false); else btn.setBorderless(true);
						this.registerCollapsableGroup(li, btn);
						if (('collapseCallback' in o) && o.collapseCallback) {
							li.collapseCallback = o.collapseCallback;
						}
						
					} else {
						btn = null;
					}
					this.parseData(o.items, li, disableEmptyLikeGroups);
					if (disableEmptyLikeGroups) {
						var hasActive = false;
						for (var n = 0, nc = li.items.length; n < nc; n++) {
							if (!li.items[n].enabled) continue;
							hasActive = true;
							break;
						}
						if (!hasActive && li.expander) {
							li.expander.setEnabled(false);
						}
					}
					parent.addItem(li);
				} else if (o.type === '-') {
					li = Object.create(this.ToolbarItemSeparator).init();
					if (o.styleClass) li.elem.addClass(o.styleClass);
					parent.addItem(li, this.getNextOrder());
				}
			}
		},
		
		/**
		 * Setup group as collapsable
		 * @param {ToolbarItemGroup} group
		 * @param {ToolbarItem} expander
		 */
		registerCollapsableGroup: function(group, expander) {
			if (expander) {
				expander.setExpander(true);
				group.addItem(expander);
			}
			(function(li, expander) {
				(expander ? expander.elem : li.elem).on('mouseover', function() {
					if (expander && !expander.enabled) return;
					if (!li.isOpen) {
						for (var i = 0; i < collapsableGroups.length; i++) {
							if (collapsableGroups[i] === li) continue;
							collapsableGroups[i].setOpen(false, true);
						}
					}
					li.setOpen(true);
					if (li.isOutTimeout) { clearTimeout(li.isOutTimeout); li.isOutTimeout = null; }
				}).on('touchstart', function() {
					if (expander && !expander.enabled) return;
					if (!li.isOpen) {
						for (var i = 0; i < collapsableGroups.length; i++) {
							if (collapsableGroups[i] === li) continue;
							collapsableGroups[i].setOpen(false, true);
						}
						li.setOpen(true);
					} else {
						li.setOpen(false);
					}
				}).on('mouseout', function() {
					if (expander && !expander.enabled) return;
					if (!li.isOutTimeout) {
						li.isOutTimeout = setTimeout(function() { li.isOutTimeout = null; li.setOpen(false); }, 40);
					}
				});
				(expander ? li.container : li.elem).on('mouseover', function() {
					if (li.isOutTimeout) { clearTimeout(li.isOutTimeout); li.isOutTimeout = null; }
				}).on('mouseout', function() {
					if (!li.isOutTimeout) {
						li.isOutTimeout = setTimeout(function() { li.isOutTimeout = null; li.setOpen(false); }, 40);
					}
				});
			})(group, expander);
			this.collapsableGroups.push(group);
			collapsableGroups.push(group);
		},

		/**
		 * @param {ToolbarItemGroup|ToolbarItem|ToolbarItemSeparator} item
		 * @param {Number} order
		 */
		addItem: function(item, order) {
			var appended = false;
			if (order && this.items.length > 0) {
				order = ((order = parseInt(order)) && !isNaN(order)) ? order : 0;
				item.order = order;
				for (var i in this.items) {
					if (this.items[i].order && item.order < this.items[i].order) {
						item.elem.insertBefore(this.items[i].elem);
						appended = true;
						break;
					}
				}
			}
			if (!appended) {
				this.elem.append(item.elem);
			}
			this.items.push(item);
		},
		
		getNextOrder: function() {
			this.lastOrder += 20;
			return this.lastOrder;
		},

		/**
		 * Set toolbar ID
		 * @param {String} id
		 */
		setId: function(id) {
			this.elem.attr('id', id);
		},

		/**
		 * Get toolbar ID
		 * @returns {String}
		 */
		getId: function() {
			return this.elem.attr('id');
		},
		
		/**
		 * Get toolbar item by ID
		 * @param {string} id
		 * @returns {ToolbarItemGroup|ToolbarItem}
		 */
		getItemById: function(id) {
			if (!id) return null;
			var i, item;
			for (i = 0; i < this.items.length; i++) {
				item = this.items[i];
				if (item.getId && id === item.getId()) {
					return item;
				}
			}
			return null;
		},
		
		/**
		 * Get toolbar item by ID (search sub-items)
		 * @param {string} id
		 * @returns {ToolbarItemGroup|ToolbarItem}
		 */
		getItemByIdRe: function(id) {
			if (!id) return null;
			var i, item;
			for (i = 0; i < this.tbItems.length; i++) {
				item = this.tbItems[i];
				if (item.getId && id === item.getId()) {
					return item;
				}
			}
			return null;
		},
		
		closeAllGroups: function() {
			for (var i = 0; i < collapsableGroups.length; i++) {
				collapsableGroups[i].setOpen(false, true);
			}
		}
	};
	
	
	self.ToolbarItemGroup = {
		
		/** @type {jQuery} */
		elem: null,
		/** @type {jQuery} */
		container: null,
		/** @type {ToolbarItem} */
		expander: null,
		/** @type {Array} */
		items: null,
		/** @type {Number} */
		expanderWidth: 0,
		/** @type {Number} */
		blockWidth: 0,
		/** @type {Number} */
		blockDWidth: 0,
		/** @type {Number} */
		blockHeight: 0,
		/** @type {Boolean} */
		isOpen: false,
		/** @type {Boolean} */
		isCollapsed: false,
		/** @type {String} */
		_id: null,
		
		collapseCallback: null,
		
		/** @return {ToolbarItemGroup} */
		init: function() {
			this.container = $('<div>').addClass('wb_item_group_container');
			this.elem = $('<div>').addClass('wb_item_group').append(this.container);
			$('<div>').addClass('arrow').appendTo(this.container);
			this.items = [];
			return this;
		},
		
		/** @param {ToolbarItem|ToolbarItemSeparator} item */
		addItem: function(item) {
			if (item.expander) {
				this.expander = item;
				this.elem.prepend(item.elem);
			} else {
				this.items.push(item);
				this.container.append(item.elem);
			}
		},
		
		ajustSize: function() {
			this.expanderWidth = (this.expander) ? this.expander.getWidth() : 0;
			this.blockWidth = this.getWidth(true);
			this.blockDWidth = this.getWidth(true, 3);
			this.blockHeight = this.getHeight();
			this.elem.width(this.blockWidth);
			this.container.width(this.blockWidth + 100);
			this.setCollapsed(true);
		},
		
		/**
		 * @param {Boolean} collapse
		 * @param {Boolean} instant
		 */
		setCollapsed: function(collapse, instant) {
			var thisSelf = this;
			if (!this.expander) return;
			if (collapse) {
				this.expander.setVisible(true);
				this.elem.css({overflow: 'hidden'});
				if (instant) {
					this.elem.stop(true, false).css({ width: this.expanderWidth });
					if (typeof this.collapseCallback === 'function') this.collapseCallback(true, this.elem);
				} else {
					this.elem.stop(true, false).animate({ width: this.expanderWidth }, 200, function() {
						if (typeof thisSelf.collapseCallback === 'function') thisSelf.collapseCallback(true, thisSelf.elem);
					});
				}
				this.isCollapsed = true;
			} else {
				if (this.isOpen) this.setOpen(false, true);
				if (typeof this.collapseCallback === 'function') this.collapseCallback(false, thisSelf.elem);
				this.expander.setVisible(false);
				if (instant) {
					this.elem.stop(true, false).css({ width: thisSelf.blockWidth });
					this.elem.css({overflow: 'visible'});
				} else {
					this.elem.stop(true, false).animate({ width: thisSelf.blockWidth }, 200, function() {
						thisSelf.elem.css({overflow: 'visible'});
					});
				}
				this.isCollapsed = false;
			}
		},
		
		setOpen: function(open, internal) {
			if (!this.expander || !this.isCollapsed) return;
			var idShort = this._id;
			if (idShort) idShort = idShort.replace(/^wb-group-/i, '');
			if (open) {
				this.elem.stop(true, false).css({width: '', height: '', overflow: 'visible'});
				this.elem.addClass('vertical');
				this.container.css({width: (this.blockDWidth + 21)});
				if ($(window).width() < (this.container.offset().left + this.container.outerWidth(true))) this.elem.addClass('vertical-right');
				this.isOpen = true;
				if (idShort && !internal) Service.HelpSystemPlayer.notify('toolbar-plugin-' + idShort + '-open', this);
			} else {
				this.elem.stop(true, false).css({width: this.expanderWidth, height: this.blockHeight, overflow: 'hidden'});
				this.elem.removeClass('vertical').removeClass('vertical-right');
				this.container.width(this.blockWidth + 100);
				this.isOpen = false;
				if (idShort && !internal) Service.HelpSystemPlayer.notify('toolbar-plugin-' + idShort + '-close', this);
			}
		},
		
		/**
		 * Get width
		 * @param {Boolean} deep calc width from sub-elements
		 * @param {Number} num number of deep icons to count
		 * @returns {Number}
		 */
		getWidth: function(deep, num) {
			if (deep) {
				var i, w = 0, ii = 0, iw = 0;
				if (num) {
					for (i = 0; i < this.items.length; i++) {
						if (this.items[i].expander) continue;
						w += this.items[i].elem.outerWidth(true);
						ii++;
						if (ii >= num || i === (this.items.length - 1)) {
							if (w > iw) iw = w;
							ii = 0; w = 0;
						}
					}
					return iw;
				} else {
					for (i = 0; i < this.items.length; i++) {
						if (this.items[i].expander) continue;
						w += this.items[i].elem.outerWidth(true);
						if (num && (i >= (num - 1))) break;
					}
				}
				return w;
			} else {
				return this.elem.outerWidth(true);
			}
		},
		
		/**
		 * Get height
		 * @param {Boolean} vertical calc height from sub-elements
		 * @returns {Number}
		 */
		getHeight: function(vertical) {
			if (vertical) {
				var i, h = 0;
				for (i = 0; i < this.items.length; i++) {
					h += this.items[i].elem.outerHeight(true) + 6;
				}
				return h;
			} else {
				return this.elem.outerHeight(true);
			}
		},
		
		/**
		 * Set item group ID
		 * @param {String} id
		 */
		setId: function(id) {
			this._id = id;
		},
		
		/**
		 * Get item group ID
		 * @returns {String}
		 */
		getId: function() {
			return this._id;
		},
		
		/**
		 * Get toolbar group item by ID
		 * @param {string} id
		 * @returns {ToolbarItem|ToolbarItemSeparator}
		 */
		getItemById: function(id) {
			if (!id) return null;
			var i, item;
			for (i = 0; i < this.items.length; i++) {
				item = this.items[i];
				if (id === item.getId()) {
					return item;
				}
			}
			return null;
		}
	};
	
	self.ToolbarItem = {
		
		/** @type jQuery */
		elem: null,
		/** @type jQuery */
		cover: null,
		/** @type jQuery */
		button: null,
		/** @type jQuery */
		icon: null,
		/** @type string|null */
		iconVal: null,
		/** @type jQuery */
		_caretElem: null,
		/** @type jQuery */
		_nameElem: null,
		/** @type jQuery */
		_betaElem: null,
		/** @type jQuery */
		_submenuElem: null,
		_submenuFunc: null,
		/** @type ToolbarItemSubmenuItem[] */
		submenuItems: null,
		/** @type Boolean */
		expander: false,
		/** @type Boolean */
		draggable: false,
		/** @type Boolean */
		enabled: true,
		/** @type String */
		oriTitle: null,
		/** @type Boolean */
		oriEnabled: true,
		/** @type Boolean */
		external: false,
		/** @type Boolean */
		_tooltipActive: false,
		/** @type null|String */
		_featureMessage: null,

		/**
		 * @param {String} icon
		 * @param {String} name
		 * @param {Boolean} external
		 * @return {ToolbarItem}
		 */
		init: function(icon, name, external) {
			this.iconVal = icon;
			this.elem = $('<div>').addClass('wb_item');
			this.cover = $('<div>').addClass('wb_cover');
			this.elem.append(this.cover);
			this.button = $('<button>').addClass('btn btn-wb-item');
			this.button.attr('type', 'button');
			this.external = external ? true : false;
			if (!this.external) {
				this.icon = $('<i>').addClass(icon);
			} else {
				this.icon = $('<i>').addClass('ico-tb ico-tb-no-bg');
				if (icon) {
					var iconParts = ('' + icon).split(' #');
					if (iconParts.length > 1 && iconParts[1]) {
						this.icon.addClass(iconParts[1]);
					}
					this.icon.append('<img src="' + iconParts[0] + '" alt="' + ((name !== null) ? name : '') + '" />');
				}
			}
			this.button.append(this.icon);
			this.elem.append(this.button);
			if( name !== null ) {
				this._nameElem = $('<span>').text(name);
				this.elem.append(this._nameElem);
			}
			this.submenuItems = [];
			return this;
		},
		
		/**
		 * Set beta state.
		 * @param {Boolean} beta if true then beta label will be shown else not.
		 */
		setBeta: function(beta) {
			if (beta) {
				if (this._betaElem) {
					this._betaElem.show();
				} else {
					this._betaElem = $('<span>').addClass('beta').text('beta');
					this.elem.prepend(this._betaElem);
				}
			} else {
				if (this._betaElem) this._betaElem.hide();
			}
		},
		
		setLink: function(link) {
			this.cover.append('<a href="' + link + '" target="_blank"></a>');
			return this;
		},
		
		/** @param {Object[]} data */
		setSubmenu: function(data) {
			var i, li, d = ((typeof data === 'object') && ('length' in data) && data.length > 0) ? data : null;
			if (d) {
				this.elem.addClass('wb-dropdown');
				this.button.attr('data-toggle', 'dropdown');
				if (!this._caretElem) this._caretElem = $('<span>').addClass('caret');
				this.button.append(this._caretElem);
				if (!this._submenuElem) this._submenuElem = $('<ul>').addClass('dropdown-menu');
				this.elem.append(this._submenuElem);
				if (!this._submenuFunc) {
					var thisSelf = this;
					this._submenuFunc = {
						over: function() {
							if (thisSelf.submenuItems.length > 0) thisSelf.elem.addClass('open');
						},
						out: function() {
							if (thisSelf.submenuItems.length > 0) thisSelf.elem.removeClass('open');
						}
					};
					if (window.wb_builder.isTouchDevice) {
						this.elem.on('click touchend', function(e) {
							e.stopPropagation();
							thisSelf._submenuFunc.over();
						});
					} else {
						this.elem.hover(this._submenuFunc.over, this._submenuFunc.out);
					}
				}
				for (i = 0; i < d.length; i++) {
					if (('type' in d[i]) && d[i].type === '-') {
						li = Object.create(self.ToolbarItemSubmenuSeparator).init();
					} else {
						li = Object.create(self.ToolbarItemSubmenuItem).init(d[i].name, (('help' in d[i]) ? d[i].help : null), (('helpPlacement' in d[i]) ? d[i].helpPlacement : null));
						if (("beta" in d[i]) && d[i].beta) li.setBeta(true);
						if (("featureMessage" in d[i]) && d[i].featureMessage) li.setFeatureMessage(d[i].featureMessage);
						if (('id' in d[i]) && d[i].id) li.setId(d[i].id);
						if (('active' in d[i]) && !d[i].active) {
							li.setInactive();
						} else {
							if (('click' in d[i]) && (typeof d[i].click === 'function')) li._aElem.on('click touchend', d[i].click);
						}
					}
					if(!(("hidden" in d[i]) && d[i].hidden))
						this.addSubmenuItem(li);
				}
			} else {
				this.elem.removeClass('wb-dropdown');
				this.elem.removeClass('open');
				this.button.removeAttr('data-toggle');
				if (this._caretElem) this._caretElem.detach();
				if (this._submenuElem) {
					this._submenuElem.empty();
					this._submenuElem.detach();
				}
				this.submenuItems.splice(0, this.submenuItems.length);
			}
		},
		
		/** @param {ToolbarItemSubmenuItem} item */
		addSubmenuItem: function(item) {
			this.submenuItems.push(item);
			if (this._submenuElem) this._submenuElem.append(item.elem);
		},
		
		/** @param {String} title */
		setTitle: function(title) {
			this.oriTitle = title;
			this.updateTooltip();
		},

		setFeatureMessage: function(message) {
			this._featureMessage = message;
			this.updateTooltip();
		},

		/** @param {Boolean} borderless */
		setBorderless: function(borderless) {
			if (borderless) {
				this.button.addClass('btn-wb-noborder');
			} else {
				this.button.removeClass('btn-wb-noborder');
			}
		},
		
		/** @param {Boolean} expander */
		setExpander: function(expander) {
			this.expander = expander;
			if (expander) {
				this.elem.addClass('wb_item_grouper');
				if (!this._caretElem) this._caretElem = $('<span>').addClass('caret');
				this.button.append(this._caretElem);
			} else {
				this.elem.removeClass('wb_item_grouper');
				if (this._caretElem && this.submenuItems.length === 0) {
					this._caretElem.remove();
					this._caretElem = null;
				}
			}
		},
		
		/**
		 * @param {Boolean} draggable
		 * @param {Function} startEventHandler
		 */
		setDraggable: function(draggable, startEventHandler) {
			this.draggable = draggable;
			if (draggable) {
				this.elem.draggable({
					revert: 'invalid',
					revertDuration: 300,
					helper: 'clone',
					appendTo: $(document.body),
					start: (typeof startEventHandler === 'function') ? startEventHandler : (function(event, ui) {}),
					drag: function(event, ui) {}
				});
				this.elem.css('cursor', 'move');
				(function(elem, thisSelf, func) {
					elem.on('touchend', function() {
						if (!this.id) return;

						var id, bounds, container = null,
							cx = ($(window).width() / 2) + $(window).scrollLeft(),
							cy = ($(window).height() / 2) + $(window).scrollTop();

						for (id in thisSelf.bodyInstance.blocks) {
							bounds = thisSelf.bodyInstance.blocks[id].getBounds();
							if (bounds.left <= cx && (bounds.left + bounds.width) >= cx && bounds.top <= cy && (bounds.top + bounds.height) >= cy) {
								container = thisSelf.bodyInstance.blocks[id];
								break;
							}
						}
						if (container) {
							var thisNode = this;
							ElementRegister.createElement(this.id.split('__')[1], function(item) {
								WB_Element.unselectAll();
								item.setLocation(
									wb_builder.autoSnapX(cx - bounds.left - item.getWidth() / 2),
									wb_builder.autoSnapY(cy - bounds.top - item.getHeight() / 2, container.id)
								);
								container.addElement(item);
								item.setSelected(true);
								item.setControlsVisible(true);
								thisSelf.setPageModified(true);
								if (typeof func === 'function') func.call(thisNode);
							}, function() {
								if (typeof func === 'function') func.call(thisNode);
							});
						}
						else
							if (typeof func === 'function') func.call(this);
						return false;
					});
				})(this.elem, wb_builder, startEventHandler);
			} else {
				this.elem.draggable('destroy');
				this.elem.css('cursor', 'pointer');
			}
			this.updateTooltip();
		},
		
		/** @param {Boolean} enabled */
		setEnabled: function(enabled) {
			this.enabled = enabled;
			if (enabled) {
				this.elem.removeClass('wb_inactive');
				this.elem.css({ opacity: 1, cursor: (this.draggable ? 'move' : 'pointer') });
				this.elem.attr('title', this.oriTitle);
				if (this.draggable)
					this.elem.draggable('enable');
			}
			else {
				this.elem.addClass('wb_inactive');
				this.elem.css({ opacity: 0.3, cursor: 'default' });
				if (this.draggable)
					this.elem.draggable('disable');
			}
			this.updateTooltip();
		},

		/** @param {Boolean} visible */
		setVisible: function(visible) {
			if (visible) {
				this.elem.show();
			} else {
				this.elem.hide();
			}
		},

		/** @param {Boolean} active */
		setActive: function(active) {
			if( active )
				this.elem.addClass('active');
			else
				this.elem.removeClass('active');
		},

		/** @returns {Number} */
		getWidth: function() {
			return this.elem.outerWidth(true);
		},
		
		/**
		 * Set item ID
		 * @param {String} id
		 */
		setId: function(id) {
			this.elem.attr('id', id);
		},
		
		/**
		 * Get item ID
		 * @returns {String}
		 */
		getId: function() {
			return this.elem.attr('id');
		},

		updateTooltip: function() {
			var tooltipEnabled = false;
			if( !this.enabled && this._featureMessage ) {
				this.elem.attr('title', this._featureMessage);
				tooltipEnabled = true;
			}
			else if( this.oriTitle ) {
				this.elem.attr('title', this.oriTitle);
				tooltipEnabled = this.draggable;
			}
			else
				this.elem.removeAttr('title');

			if (tooltipEnabled && !this._tooltipActive) {
				// Note: Container value is total hack. We need it to be '#head' to get proper width,
				// but when used in dropdown menu it creates issue of dropdown menu auto closing.
				this.elem.tooltip({placement: 'bottom', container: 'body', template: '<div class="tooltip no-interaction" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'});
			} else if (!tooltipEnabled && this._tooltipActive) {
				this.elem.tooltip("destroy");
			}
			this._tooltipActive = tooltipEnabled;
		}
	};
	
	self.ToolbarItemSeparator = {
		
		/** @type jQuery */
		elem: null,
		
		/** @return {ToolbarItemSeparator} */
		init: function() {
			this.elem = $('<div>').addClass('wb_item_sep');
			return this;
		}
	};
	
	self.ToolbarItemSubmenuItem = {
		
		/** @type jQuery */
		elem: null,
		/** @type jQuery */
		_aElem: null,
		/** @type jQuery */
		_helpElem: null,
		/** @type jQuery */
		_betaElem: null,
		/** @type Boolean **/
		_inactive: false,
		/** @type Boolean **/
		_helpMessage: null,
		/** @type Boolean **/
		_featureMessage: null,
		/** @type String **/
		_helpPlacement: "top",

		/**
		 * @param {String} name
		 * @param {String} help
		 * @return {ToolbarItemSubmenuItem}
		 */
		init: function(name, help, helpPlacement) {
			this.elem = $('<li>');
			this._aElem = $('<a>').attr('href', 'javascript:void(0)').appendTo(this.elem);
			this._aElem.text(name);
			if( helpPlacement )
				this._helpPlacement = helpPlacement;
			if (help) {
				this._helpMessage = help;
				this.updateTooltip();
			}
			return this;
		},
		
		/**
		 * Set item ID
		 * @param {String} id
		 */
		setId: function(id) {
			this._aElem.attr('id', id);
		},
		
		/**
		 * Get item ID
		 * @returns {String}
		 */
		getId: function() {
			return this._aElem.attr('id');
		},
		
		setInactive: function() {
			var inaColor = 'rgba(51, 51, 51, 0.3)';
			this._aElem.css({ cursor: 'default', color: inaColor });
			this._aElem.off("click touchend").on('click touchend', function(e) {
				e.stopImmediatePropagation();
				e.preventDefault();
			});
			this._inactive = true;
			this.updateTooltip();
		},

		/**
		 * Set beta state.
		 * @param {Boolean} beta if true then beta label will be shown else not.
		 */
		setBeta: function(beta) {
			if (beta) {
				if (this._betaElem) {
					this._betaElem.show();
				} else {
					this._betaElem = $('<sup>').addClass('submenu-beta').text(' beta');
					this._aElem.append(this._betaElem);
				}
			} else {
				if (this._betaElem) this._betaElem.hide();
			}
		},

		/**
		 * Sets the message to show on touch/click/hover if element is disabled
		 * @param message
		 */
		setFeatureMessage: function(message) {
			this._featureMessage = message;
			if( this._inactive )
				this.updateTooltip();
		},

		updateTooltip: function() {
			var message = this._inactive ? this._featureMessage : this._helpMessage;
			if( !this._helpElem ) {
				this._helpElem = $('<span>').addClass('badge wb_badge_help').attr('title', message).text('?').appendTo(this._aElem);
				this._helpElem.tooltip({placement: this._helpPlacement, container: 'body', template: '<div class="tooltip no-interaction" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'});
			}
			else {
				this._helpElem.attr("title", message);
			}
			if( this._inactive ) {
				var inaColor = 'rgba(51, 51, 51, 0.3)';
				this._helpElem.css({ color: inaColor, borderColor: inaColor });
			}
		}

	};
	
	self.ToolbarItemSubmenuSeparator = {
		
		/** @type jQuery */
		elem: null,
		
		/** @return {ToolbarItemSeparator} */
		init: function() {
			this.elem = $('<li>').addClass('divider')
					.on('click', function(e) {
						e.stopPropagation();
						e.preventDefault();
						return false;
					}).css('cursor', 'default');
			return this;
		}
	};
	
	return self;
});
;

/** MobileToolbar **/
(window.defineModule = (window.defineModule || {})).name = 'MobileToolbar';

define('MobileToolbar', ['UIComponent'], function(UIComponent) {
	'use strict';
	
	/**
	 * Toolbar component.
	 * @param {Object} definition
	 * @constructor
	 * @extends {UIComponent.UIComponent}
	 */
	var Toolbar = function(definition) {
		if (definition !== '%inherit%') {
			UIComponent.UIComponent.prototype.constructor.call(this);
			this.addClass('mobile-toolbar');
			this._items = [];
			if (typeof definition === 'object') this.buildFromDefinition(definition);
		}
	};
	
	/**
	 * Build toolbar item from definition object.
	 * @param {Object} definition
	 * @return {ToolbarItem}
	 */
	Toolbar.buildItem = function(definition) {
		var drawer,
			item = new ToolbarItem(definition.name, definition.icon);
		if ('drawer' in definition && definition.drawer) {
			drawer = Toolbar.buildDrawer(definition.drawer);
			$(document.body).append(drawer.getElem());
			(function(drawer) {
				item.on('click touchstart', function(e) {
					e.stopPropagation();
					e.preventDefault();
					Drawer.open(drawer);
					return false;
				});
			})(drawer);
		} else if ('click' in definition && (typeof definition.click === 'function')) {
			(function(item, clickFunc) {
				item.on('click', function(e) { clickFunc.call(item, e); return false; });
			})(item, definition.click);
		}
		return item;
	};
	/**
	 * Build drawer from definition object.
	 * @param {Object} definition
	 * @return {Drawer}
	 */
	Toolbar.buildDrawer = function(definition) {
		var i, item, element = new Drawer(definition.type);
		if ('id' in definition && definition.id) element.id = definition.id;
		if ('items' in definition) {
			for (i = 0; i < definition.items.length; i++) {
				item = Toolbar.buildDrawerItem(definition.items[i], element);
				if (!item) continue;
				element.addItem(item);
			}
		}
		return element;
	};
	/**
	 * Build drawer item from definition object.
	 * @param {Object} definition
	 * @param {Drawer} parentDrawer
	 * @return {DrawerItem}
	 */
	Toolbar.buildDrawerItem = function(definition, parentDrawer) {
		var item, iconDef, iconImageDef, drawer, drawerDef, itemType;
		if (typeof definition !== 'object' || definition === null) return null;
		itemType = ('type' in definition) ? definition.type : null;
		if (itemType && itemType !== 'group' && itemType !== 'widget') return null;
		iconDef = definition.iconImage ? ('ico-pl-' + definition.id) : definition.icon;
		iconImageDef = definition.iconImage ? definition.icon : null;
		drawerDef = ('drawer' in definition && definition.drawer) ? definition.drawer : null;
		if (!drawerDef && ('items' in definition)) drawerDef = {type: 'grid', items: definition.items};
		item = new DrawerItem(definition.name, iconDef, iconImageDef, (drawerDef ? true : false));
		item.id = ('id' in definition && definition.id) ? definition.id : null;
		if ('checked' in definition) item.setChecked(definition.checked ? true : false);
		if ('click' in definition && (typeof definition.click === 'function')) {
			if (!('active' in definition) || ((typeof definition.active === 'function') ? definition.active(item.id) : definition.active)) {
				(function(item, clickFunc) {
					item.on('click', function(e) {
						clickFunc.call(item, e);
						Drawer.open(null, null, true);
						return false;
					});
				})(item, definition.click);
			} else {
				item.getElem(); // Note: pull element into existence
				item.setEnabled(false);
			}
		}
		if (drawerDef) {
			drawer = Toolbar.buildDrawer(drawerDef);
			if (item.id) drawer.id = item.id + '-drawer';
			$(document.body).append(drawer.getElem());
			(function(drawer, parentDrawer) {
				item.on('click touchstart', function(e) {
					e.stopPropagation();
					e.preventDefault();
					Drawer.open(drawer, parentDrawer);
					return false;
				});
			})(drawer, parentDrawer);
		}
		return item;
	};
	
	Toolbar.prototype = new UIComponent.UIComponent('%inherit%');
	Toolbar.prototype.constructor = Toolbar;
	/**
	 * Toolbar item list.
	 * @type {ToolbarItem[]}
	 * @private
	 */
	Toolbar.prototype._items = null;
	
	/**
	 * Add item to this toolbar.
	 * @param {ToolbarItem} item
	 * @param {number} index index to add at (if not specified added at the end)
	 * @param {ToolbarItem}
	 */
	Toolbar.prototype.addItem = function(item, index) {
		if (!(item instanceof ToolbarItem)) return;
		if (index === null || index === undefined || index < 0 || index >= this._items.length || isNaN(index)) {
			this._elem.append(item.getElem());
			this._items.push(item);
		} else {
			this._elem.children().eq(index).before(item.getElem());
			this._items.splice(index, 0, item);
		}
		return item;
	};
	
	/**
	 * Build toolbar item structure from definition object.
	 * @param {Object} definition
	 */
	Toolbar.prototype.buildFromDefinition = function(definition) {
		var i;
		if ('items' in definition) {
			for (i = 0; i < definition.items.length; i++) {
				this.addItem(Toolbar.buildItem(definition.items[i]));
			}
		}
	};
	
	/**
	 * @param {string} title
	 * @param {string} icon
	 * @constructor
	 */
	var ToolbarItem = function(title, icon) {
		if (title !== '%inherit%') {
			if (title) this._title = title;
			if (icon) this._icon = icon;
		}
	};
	/**
	 * @type {jQuery}
	 * @private
	 */
	ToolbarItem.prototype._elem = null;
	/**
	 * @type {jQuery}
	 * @private
	 */
	ToolbarItem.prototype._iconElem = null;
	/**
	 * @type {string}
	 * @private
	 */
	ToolbarItem.prototype._title = '';
	/**
	 * @type {string}
	 * @private
	 */
	ToolbarItem.prototype._icon = '';
	/**
	 * @type {boolean}
	 * @private
	 */
	ToolbarItem.prototype._enabled = true;
	
	/** @returns {jQuery} */
	ToolbarItem.prototype.getElem = function() {
		if (!this._elem) {
			this._elem = $('<div>');
			this._iconElem = $('<span>').appendTo(this._elem);
			if (this._title) this._elem.attr({title: this._title});
			if (this._icon) this._iconElem.addClass(this._icon);
		}
		return this._elem;
	};
	
	/**
	 * Attach event to this element.
	 * @param {string} event
	 * @param {function} func
	 * @returns {MobileToolbar}
	 */
	ToolbarItem.prototype.on = function(event, func) {
		var thisSelf = this;
		var thisFunc = func;
		func._wrapCallback = function(e) { if (thisSelf._enabled) thisFunc(e); };
		if (!this._elem) this.getElem();
		if (this._elem) this._elem.on(event, func._wrapCallback);
		return this;
	};
	/**
	 * Detach event from this element.
	 * @param {string} event
	 * @param {function} func
	 * @returns {ToolbarItem}
	 */
	ToolbarItem.prototype.off = function(event, func) {
		if (this._elem) this._elem.off(event, (func._wrapCallback ? func._wrapCallback : func));
		return this;
	};
	/**
	 * Trigger event attached to this element.
	 * @param {string} event
	 * @param {any} extraParameters
	 * @returns {ToolbarItem}
	 */
	ToolbarItem.prototype.trigger = function(event, extraParameters) {
		if (this._elem) this._elem.trigger(event, extraParameters);
		return this;
	};
	
	/**
	 * Drawer that opens at the bottom of the screen.
	 * @param {string} type
	 * @constructor
	 * @extends {UIComponent.UIComponent}
	 */
	var Drawer = function(type) {
		if (type !== '%inherit%') {
			UIComponent.UIComponent.prototype.constructor.call(this);
			this.addClass('mobile-drawer');
			if (type) this.addClass('type-' + type);
			var closeBackFunc = function(e) {
				e.stopPropagation();
				e.preventDefault();
				Drawer.open(null);
				return false;
			};
			this._navElem = $('<div>').addClass('drawer-nav')
				.append($('<div>').addClass('back')
					.append($('<span>').addClass('chevron icon-wb-chevron-left'))
					.append($('<span>').addClass('title').text(__('Back')))
					.on('click touchstart', closeBackFunc))
				/*.append($('<span>').addClass('close').html('&times;')
					.on('click touchstart', closeBackFunc))*/
				.appendTo(this._elem);
			this._bodyElem = $('<div>').addClass('drawer-body').appendTo(this._elem);
			this._items = [];
			this.setVisible(false);
			Drawer.list.push(this);
		}
	};
	/**
	 * Open drawer stack.
	 * @type {ToolbarDrawer[]}
	 */
	Drawer.stack = [];
	/**
	 * List of all created drawers.
	 * @type {ToolbarDrawer[]}
	 */
	Drawer.list = [];
	Drawer._lastOpen = null;
	/**
	 * Open specified drawer. Closes other open drawers.
	 * @param {Drawer} drawer drawer to open (can be null)
	 * @param {Drawer=} parent drawer to open when this drawer is closed
	 * @param {boolean=} clearStack clear open drawer stack
	 */
	Drawer.open = function(drawer, parent, clearStack) {
		if (clearStack) Drawer.stack.splice(0, Drawer.stack.length);
		if (!drawer && Drawer.stack.length > 0) drawer = Drawer.stack.pop();
		
		for (var i = 0; i < Drawer.list.length; i++) {
			if (drawer !== Drawer.list[i]) {
				(function(item) {
					item.removeClass('open');
					Drawer._lastOpen = null;
					setTimeout(function() { if (Drawer._lastOpen !== item) item.setVisible(false); }, 100);
				})(Drawer.list[i]);
			}
		}
		
		if (drawer) {
			if (parent) Drawer.stack.push(parent);
			drawer.setVisible(true);
			drawer.addClass('open');
			Drawer._lastOpen = drawer;
		}
	};
	/**
	 * Get drawer by id
	 * @param {string} id
	 * @returns {Drawer}
	 */
	Drawer.get = function(id) {
		for (var i = 0; i < Drawer.list.length; i++) {
			if (Drawer.list[i].id === id) return Drawer.list[i];
		}
		return null;
	};
	Drawer.prototype = new UIComponent.UIComponent('%inherit%');
	Drawer.prototype.constructor = Drawer;
	
	/**
	 * Item identifier
	 * @type {string}
	 */
	Drawer.prototype.id = null;
	
	/** @type {jQuery} */
	Drawer.prototype._navElem = null;
	/** @type {jQuery} */
	Drawer.prototype._bodyElem = null;
	
	/**
	 * Drawer item list.
	 * @type {ToolbarDrawerItem[]}
	 * @private
	 */
	Drawer.prototype._items = null;
	
	/** @return {JQuery} */
	Drawer.prototype.getBodyElem = function() {
		return this._bodyElem;
	};
	
	/** @return {number} */
	Drawer.prototype.getItemCount = function() {
		return this._items.length;
	};
	
	/**
	 * @param {number} idx
	 * @return {DrawerItem}
	 */
	Drawer.prototype.getItem = function(idx) {
		return this._items[idx];
	};
	
	/**
	 * Add item to this drawer.
	 * @param {DrawerItem} item
	 * @return {DrawerItem}
	 */
	Drawer.prototype.addItem = function(item) {
		if (!(item instanceof DrawerItem)) return;
		this._bodyElem.append(item.getElem());
		this._items.push(item);
		return item;
	};
	
	/**
	 * Remove all items
	 */
	Drawer.prototype.removeAllItems = function() {
		this._bodyElem.empty();
		this._items.splice(0, this._items.length);
	};
	
	/**
	 * Drawer item.
	 * @param {string} title
	 * @param {string} icon
	 * @param {string} iconImage
	 * @param {boolean} isGroup
	 * @constructor
	 */
	var DrawerItem = function(title, icon, iconImage, isGroup) {
		if (title !== '%inherit%') {
			if (title) this._title = title;
			if (icon) this._icon = icon;
			if (iconImage) this._iconImage = iconImage;
			this._isGroup = isGroup ? true : false;
		}
	};
	/**
	 * @type {jQuery}
	 * @private
	 */
	DrawerItem.prototype._elem = null;
	/**
	 * @type {jQuery}
	 * @private
	 */
	DrawerItem.prototype._iconElem = null;
	/**
	 * @type {jQuery}
	 * @private
	 */
	DrawerItem.prototype._titleElem = null;
	/**
	 * @type {jQuery}
	 * @private
	 */
	DrawerItem.prototype._chevronElem = null;
	/**
	 * @type {string}
	 * @private
	 */
	DrawerItem.prototype._title = '';
	/**
	 * @type {string}
	 * @private
	 */
	DrawerItem.prototype._icon = '';
	/**
	 * @type {string}
	 * @private
	 */
	DrawerItem.prototype._iconImage = null;
	/**
	 * @type {string}
	 * @private
	 */
	DrawerItem.prototype._isGroup = '';
	/**
	 * @type {boolean}
	 * @private
	 */
	DrawerItem.prototype._enabled = true;
	/**
	 * @type {boolean}
	 * @private
	 */
	DrawerItem.prototype._isChecked = false;
	
	/** @return {boolean} */
	DrawerItem.prototype.isEnabled = function() {
		return this._enabled;
	};
	
	/** @param {boolean} enabled */
	DrawerItem.prototype.setEnabled = function(enabled) {
		this._enabled = enabled ? true : false;
		if (this._elem) {
			if (this._enabled) {
				this._elem.css({opacity: '', cursor: ''});
			} else {
				this._elem.css({opacity: 0.5, cursor: 'default'});
			}
		}
	};
	
	/**
	 * Get if item is checked
	 * @returns {boolean}
	 */
	DrawerItem.prototype.isChecked = function() {
		return this._isChecked;
	};
	
	/**
	 * Set if item is checked
	 * @param {boolean} checked
	 */
	DrawerItem.prototype.setChecked = function(checked) {
		this._isChecked = checked ? true : false;
		if (this._elem) {
			if (this._isChecked) {
				this._elem.addClass('checked');
			} else {
				this._elem.removeClass('checked');
			}
		}
	};
	
	/** @return {jQuery} */
	DrawerItem.prototype.getElem = function() {
		if (!this._elem) {
			this._elem = $('<div>').addClass('item');
			this._iconElem = $('<span>').addClass('icon').appendTo(this._elem);
			if (this._iconImage) {
				var iconParts = ('' + this._iconImage).split(' #');
				if (iconParts.length > 1 && iconParts[1]) {
					this._iconElem.addClass(iconParts[1]);
				}
				$('<img>').attr({src: iconParts[0]}).appendTo(this._iconElem);
			}
			this._titleElem = $('<span>').addClass('title').appendTo(this._elem);
			if (this._isGroup) this._chevronElem = $('<span>').addClass('chevron icon-wb-chevron-right').appendTo(this._elem);
			if (this._title) this._titleElem.html(this._title);
			if (this._icon) this._iconElem.addClass(this._icon);
			if (this._isChecked) this._elem.addClass('checked');
		}
		return this._elem;
	};
	/**
	 * Attach event to this element.
	 * @param {string} event
	 * @param {function} func
	 * @returns {DrawerItem}
	 */
	DrawerItem.prototype.on = function(event, func) {
		var thisSelf = this;
		var thisFunc = func;
		func._wrapCallback = function(e) { if (thisSelf._enabled) thisFunc(e); };
		if (!this._elem) this.getElem();
		if (this._elem) this._elem.on(event, func._wrapCallback);
		return this;
	};
	/**
	 * Detach event from this element.
	 * @param {string} event
	 * @param {function} func
	 * @returns {DrawerItem}
	 */
	DrawerItem.prototype.off = function(event, func) {
		if (this._elem) this._elem.off(event, (func._wrapCallback ? func._wrapCallback : func));
		return this;
	};
	/**
	 * Trigger event attached to this element.
	 * @param {string} event
	 * @param {any} extraParameters
	 * @returns {DrawerItem}
	 */
	DrawerItem.prototype.trigger = function(event, extraParameters) {
		if (this._elem) this._elem.trigger(event, extraParameters);
		return this;
	};
	
	return {
		Toolbar: Toolbar,
		ToolbarItem: ToolbarItem,
		Drawer: Drawer,
		DrawerItem: DrawerItem
	};
});
;

/** DragNDropZone **/
(window.defineModule = (window.defineModule || {})).name = 'DragNDropZone';

define('DragNDropZone', ['ElementRegister', 'Service', 'Preloader', 'MsgDialog'], function(ElementRegister, Service, Preloader, MsgDialog) {
	'use strict';
	
	var builder;
	
	/**
	 * @param {jQuery} elem
	 */
	function DragNDropZone(elem) {
		var thisSelf = this;
		this.elem = elem;
		this.hover = false;
		this.hoverTimeout = null;
		this.cover = $('<div>').addClass('wb-builder-dnd-cover')
			.append($('<div>').addClass('txt').text(__('Drop to add files')))
			.on('mouseover', function() { thisSelf.hover = true; })
			.appendTo(this.elem);
		this.cover.hide();
		this.elem.on('drop', function(e) { thisSelf.drop(e); });
		this.elem.on('dragover dragenter', function(e) { thisSelf.dragOver(e); });
		this.elem.on('dragend dragleave', function(e) { thisSelf.dragEnd(e); });
		this.form = $('<form>')
			.attr({action: builder.getUrl('upload') + '?mode=all&return=1', method: 'post', enctype: 'multipart/form-data'})
			.hide()
			.appendTo(this.elem);
		this.cleaned = true;
		this.preloader = null;
		this.alertDlg = null;
		this.uploadingBackup = false;
		this.uploadFileCount = 0;
		this.uploadedFiles = 0;
		this.rFiles = [];
		this.errors = [];
		this.dropPosition = null;

		this.form
			.fileupload({
				dataType: 'json',
				fileInput: null,
				dropZone: null,
				pasteZone: null,
				sequentialUploads: true,
				autoUpload: true,
				disableImagePreview: true,
				disableImageResize: false,
				imageMaxWidth: 1920,
				imageMaxHeight: 1080,
				imageOrientation: true,
				loadImageMaxFileSize: 50000000, // max size in memory, not for upload
				maxFileSize: builder.maxUploadFileSize
			})
			.on('fileuploadprocess', window.prepareAutoScaleOptions)
			.on('fileuploadprocessfail fileuploadfail', function(e, data) {
				thisSelf.uploadedFiles++;
				thisSelf.preloader.setProgress(100 * thisSelf.uploadedFiles / thisSelf.uploadFileCount);
				if (!thisSelf.uploadingBackup) thisSelf.errors.push(__('Unknown error'));
				if (thisSelf.uploadedFiles >=  thisSelf.uploadFileCount) {
					thisSelf.preloader.setVisible(false);
					if (!thisSelf.uploadingBackup && thisSelf.rFiles.length) {
						thisSelf.createElements(e, thisSelf.rFiles);
					}
					if (thisSelf.errors.length > 0) {
						thisSelf.showError(thisSelf.errors);
					}
					thisSelf.dropPosition = null;
				}
			})
			.on('fileuploadalways fileuploadprocessfail', function(e, data) {
				if (thisSelf.uploadingBackup) location.href = '' + location.href;
			})
			.on('fileuploadprogressall', function(e, data) {
				thisSelf.preloader.setProgress(100 * (thisSelf.uploadedFiles + (data.total ? (data.loaded / data.total) : 0)) / thisSelf.uploadFileCount);
			})
			.on('fileuploaddone', function(e, data) {
				thisSelf.uploadedFiles++;
				var r = data.result;
				if (r.error) {
					thisSelf.errors.push((r.error.message ? r.error.message : r.error));
				} else {
					thisSelf.rFiles.push(r);
				}
				thisSelf.preloader.setProgress(100 * thisSelf.uploadedFiles / thisSelf.uploadFileCount);
				if (thisSelf.uploadedFiles >=  thisSelf.uploadFileCount) {
					thisSelf.preloader.setVisible(false);
					if (!thisSelf.uploadingBackup && thisSelf.rFiles.length) {
						thisSelf.createElements(e, thisSelf.rFiles);
					}
					if (thisSelf.errors.length > 0) {
						thisSelf.showError(thisSelf.errors);
					}
					thisSelf.dropPosition = null;
				}
			})
		;
	}
	
	DragNDropZone.getDialogTitle = function() {
//		return __('Uploading');
		var msg = __('uploading...');
		msg = msg.replace('...', '').replace('…', '');
		msg = msg.substring(0,1).toUpperCase() + msg.substring(1);
		return msg;
	};

	/**
	 * Create element by type.
	 * @param {Content} parent block to add created element to.
	 * @param {number} x elements location X coordinate.
	 * @param {number} y elements location Y coordinate.
	 * @param {any} data to use for element creation.
	 * @param {string} type element type to create.
	 * @param {string|boolean|null} styleId
	 */
	DragNDropZone.prototype.createElement = function(parent, x, y, data, type, styleId) {
		var elemData = {content:{}};
		if (type === 'Picture') {
			elemData.content.src = data;
		}
		else if (type === 'Gallery') {
			elemData.content.images = data.slice();
		}
		else if( type === 'TextArea' ) {
			elemData.content.text = data;
		}
		ElementRegister.createElement(type, function(item) {
			item.setLocation(
				wb_builder.autoSnapX(x - item.getWidth() / 2.0),
				wb_builder.autoSnapY(y - item.getHeight() / 2.0, parent.id)
			);
			parent.addElement(item);

			Service.HelpSystemPlayer.notify('item-plugin-' + item.getClassType() + '-edit-start', item);
			if (type === 'Picture') {
				item.setSrc(data, function() {
					item.resetImageSize();
					if (item.getWidth() > 400) {
						item.setSize(400, 400 * item.getHeight() / item.getWidth());
						item.crop.width = item.getWidth();
						item.crop.height = item.getHeight();
						item.crop.x = 0;
						item.crop.y = 0;
						item.updateImageSize();
					}
				});
			} else if (type === 'Gallery') {
				// item.render();
				// item.updateMinSize(true);
			} else if (type === 'TextArea') {
				item.setValue(data);
				item.setHtml(data);
				item.onResize();
			}
			Service.HelpSystemPlayer.notify('item-plugin-' + item.getClassType() + '-edit-end', item);

			builder.setPageModified(true);
		}, null, elemData, true, false, styleId);
	};

	/**
	 * Create elements from uploaded file list.
	 * @param {Event} e event descriptor object.
	 * @param {Object[]} files file descriptor list.
	 * @return {boolean}
	 */
	DragNDropZone.prototype.createElements = function(e, files) {
		if (!files || files.length <= 0) return false;

		var i, id, bounds, container = null, data,
			images = [], others = [], url, m,
			win = $(window),
			cx = this.dropPosition ? this.dropPosition.left : (win.width() / 2),
			cy = this.dropPosition ? this.dropPosition.top : (win.height() / 2);

		for (id in builder.bodyInstance.blocks) {
			bounds = builder.bodyInstance.blocks[id].getBoundingClientRect();
			if (bounds.left <= cx && (bounds.left + bounds.width) >= cx && bounds.top <= cy && (bounds.top + bounds.height) >= cy) {
				container = builder.bodyInstance.blocks[id];
				break;
			}
		}
		if (!container) return false;
		
		Service.element.unselectAll();
		
		// split files by type
		for (i = 0; i < files.length; i++) {
			if (files[i].dataType === 'image') {
				images.push(builder.makeRelUrl(files[i].data));
			} else if (files[i].dataType === 'text') {
				this.createElement(container, cx - bounds.left, cy - bounds.top, files[i].data.replace(/[\n\r]+/ig, '<br/>'), 'TextArea');
			} else {
				others.push(files[i].data);
			}
		}
		
		if (images.length > 3) {
			// build gallery
			this.createElement(container, cx - bounds.left, cy - bounds.top, images, 'Gallery');
		} else if (images.length > 0) {
			// build separate pictures
			for (i = 0; i < images.length; i++) {
				this.createElement(container, cx - bounds.left, cy - bounds.top, images[i], 'Picture', (images.length > 1) ? false : null);
			}
		}
		
		if (others.length > 0) {
			// build text element with links
			data = '';
			for (i = 0; i < others.length; i++) {
				url = builder.makeRelUrl(others[i]);
				data += '<p><a data-type="file" data-url="' + url + '" href="' + url + '">' + ((m = url.match(/^.*\/([^\/]+)$/)) ? m[1] : url) + '</a></p>';
			}
			this.createElement(container, cx - bounds.left, cy - bounds.top, data, 'TextArea');
		}
		return true;
	};

	/**
	 * Display error message in a dialog.
	 * @param {string|string[]} error error message to display.
	 */
	DragNDropZone.prototype.showError = function(error) {
		//var thisSelf = this;
		if (!this.alertDlg) {
			this.alertDlg = new MsgDialog(null, null, null, null, true);
			this.alertDlg.setTitle(DragNDropZone.getDialogTitle());
		}
		var i, errorStr = '';
		if (error instanceof Array) {
			for (i = 0; i < error.length; i++) { errorStr += __pr(error[i]); }
		} else {
			errorStr = __pr(error);
		}
		this.alertDlg.setMessage(errorStr);
		this.alertDlg.setVisible(true);
	};

	/**
	 * Handle file file upload.
	 * @param {File[]} files list of files to upload.
	 * @param {Event} e event descriptor object.
	 * @return {boolean}
	 */
	DragNDropZone.prototype.handleUpload = function(files, e) {
		if (this.uploadingBackup || !files || files.length <= 0) return false;
		var i;
		
		if (!this.preloader) this.preloader = new Preloader(DragNDropZone.getDialogTitle());
		if (this.uploadedFiles === this.uploadFileCount) {
			this.preloader.reset();
			this.preloader.setVisible(true);
			this.preloader.setProgress(100);
			this.uploadFileCount = 0;
			this.uploadedFiles = 0;
			this.rFiles = [];
			this.errors = [];
		}

		for (i = 0; i < files.length; i++) {
			if ((files[i].name + '').match(/^.+\.sitebuilder$/i)) {
				if (builder.maxUploadBackupFileSizeInt && files[i].size > builder.maxUploadBackupFileSizeInt) {
					// simulate error response
					this.form.trigger('fileuploaddone', [{result: {error: {message: __('File size is larger than allowed') + ' (' + __('max') + ': ' + builder.maxUploadBackupFileSize + ')'}}}]);
					this.uploadFileCount = this.uploadedFiles;
					return false;
				}
				this.uploadFileCount++;
				this.uploadingBackup = true;
				this.form.fileupload('add', {
					paramName: 'pro_upl',
					files: [files[i]],
					url: builder.getUrl('restore_project'),
					formData: {
						backup_type: 'file'
					}
				});
				return true;
			}
		}
		
		for (i = 0; i < files.length; i++) {
			if (builder.maxUploadBackupFileSizeInt && files[i].size > builder.maxUploadBackupFileSizeInt
					&& (files[i].type != 'image/jpeg' && files[i].type != 'image/jpg' && files[i].type != 'image/png' && files[i].type != 'image/gif')) {
				// simulate error response
				this.form.trigger('fileuploaddone', [{result: {error: {message: __('File size is larger than allowed') + ' (' + __('max') + ': ' + builder.maxUploadBackupFileSize + ')'}}}]);
				this.uploadFileCount = this.uploadedFiles;
				return false;
			}
			this.uploadFileCount++;
			this.form.fileupload('add', {
				paramName: 'file',
				files: [files[i]],
				url: this.form.attr('action'),
				formData: {
					backup_type: 'file'
				}
			});
		}
		return false;
	};

	/**
	 * Handle drop event.
	 * @param {Event} e event descriptor object.
	 */
	DragNDropZone.prototype.drop = function(e) {
		this.cleaned = false;
		e.preventDefault();
		e.stopPropagation();
		var win = $(window);
		this.dropPosition = {
			left: e.originalEvent.clientX,
			top: e.originalEvent.clientY
		};
		var i, files = [], dt = e.originalEvent.dataTransfer;
		if (dt && dt.items) {
			// Use DataTransferItemList interface to access the file(s)
			for (i = 0; i < dt.items.length; i++) {
				if (dt.items[i].kind === 'file') {
					files.push(dt.items[i].getAsFile());
				}
			}
			this.handleUpload(files, e);
		} else if (dt) {
			// Use DataTransfer interface to access the file(s)
			for (i = 0; i < dt.files.length; i++) {
				files.push(dt.files[i]);
			}
			this.handleUpload(files, e);
		}
		this.dragEnd(e);
	};

	/**
	 * Handle drag over event.
	 * @param {Event} e event descriptor object.
	 */
	DragNDropZone.prototype.dragOver = function(e) {
		if (Service.textArea.isMousedowned()) return;
		this.hover = true;
		e.preventDefault();
		e.stopPropagation();
		this.cover.show();
	};

	/**
	 * Handle drag end/out event. Cleanup the drag data.
	 * @param {Event} e event descriptor object.
	 */
	DragNDropZone.prototype.dragEnd = function(e) {
		var thisSelf = this;
		e.preventDefault();
		e.stopPropagation();
		if (this.hover) {
			this.hover = false;
			if (!this.hoverTimeout) {
				this.hoverTimeout = setTimeout(function() {
					thisSelf.hoverTimeout = null;
					if (!thisSelf.hover) thisSelf.cover.hide();
				}, 100);
			}
		}
		/*var i, dt = e.originalEvent.dataTransfer;
		if (dt && dt.items) {
			// Use DataTransferItemList interface to remove the drag data
			for (i = 0; i < dt.items.length; i++) { dt.items.remove(i); }
		} else if (dt) {
			// Use DataTransfer interface to remove the drag data
			e.originalEvent.dataTransfer.clearData();
		}*/
	};
	
	/**
	 * Initialise drag and drop handler.
	 * @param {Builder} builderInstance
	 */
	DragNDropZone.init = function(builderInstance) {
		builder = builderInstance;
		// Enable only if supported.
		if ((('DataTransfer' in window) || ('DataTransferItemList' in window)) && ('FormData' in window)) {
			new DragNDropZone(builder.body);
		}
	};
	
	return DragNDropZone;
});
;

/** __bundle__ **/
(window.defineModule = (window.defineModule || {})).name = '__bundle__';
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
define("CommonTypes", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var ContentBlockId;
    (function (ContentBlockId) {
        ContentBlockId["Header"] = "wb_header";
        ContentBlockId["Main"] = "wb_main";
        ContentBlockId["Footer"] = "wb_footer";
    })(ContentBlockId = exports.ContentBlockId || (exports.ContentBlockId = {}));
});
define("UIComponent", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var UIComponent = (function () {
        function UIComponent(tagType) {
            this._enabled = true;
            this._control = null;
            this._tooltipIsSet = false;
            if (tagType === '%inherit%')
                return;
            if (tagType)
                this.tagType = tagType;
            this._elem = this._createElem();
        }
        UIComponent.prototype._createElem = function () { return $('<' + (this.tagType ? this.tagType : 'div') + '>'); };
        UIComponent.prototype.getElem = function () { return this._elem; };
        ;
        UIComponent.prototype.css = function (css) {
            if (this._elem)
                this._elem.css(css);
            return this;
        };
        UIComponent.prototype.addClass = function (cls) {
            if (this._elem)
                this._elem.addClass(cls);
            return this;
        };
        UIComponent.prototype.removeClass = function (cls) {
            if (this._elem)
                this._elem.removeClass(cls);
            return this;
        };
        UIComponent.prototype.setVisible = function (visible) {
            if (this._elem) {
                if (visible) {
                    this._elem.show();
                }
                else {
                    this._elem.hide();
                }
            }
            return this;
        };
        UIComponent.prototype.setEnabled = function (enabled) {
            this._enabled = enabled ? true : false;
        };
        UIComponent.prototype.setTitle = function (title) {
            if (title) {
                this._elem.attr('title', title);
            }
            else {
                this._elem.removeAttr('title');
            }
            return this;
        };
        UIComponent.prototype.on = function (event, callback) {
            var _this = this;
            var thisFunc = callback;
            thisFunc._wrapCallback = function (e) { if (_this._enabled)
                thisFunc(e); };
            if (this._elem)
                this._elem.on(event, thisFunc._wrapCallback);
            return this;
        };
        UIComponent.prototype.off = function (event, callback) {
            if (this._elem)
                this._elem.off(event, (callback._wrapCallback ? callback._wrapCallback : callback));
            return this;
        };
        UIComponent.prototype.setTooltip = function (text, placement, trigger) {
            if (this._tooltipIsSet) {
                this._elem.tooltip('destroy');
                this._tooltipIsSet = false;
            }
            if (text) {
                if (!placement)
                    placement = 'top';
                if (!trigger)
                    trigger = 'hover';
                this._elem.tooltip({ title: text, placement: placement, trigger: trigger });
                this._tooltipIsSet = true;
            }
        };
        UIComponent.prototype.trigger = function (event, extraParameters) {
            if (this._elem)
                this._elem.trigger(event, extraParameters);
            return this;
        };
        UIComponent.prototype.getWrappedControl = function () {
            return this._control;
        };
        UIComponent.wrapControl = function (control) {
            var el = new UIComponent();
            el._control = control;
            el._elem = control.elem;
            el.getValue = function () { return this._control.getValue(); };
            el.setValue = function (value) { this._control.setValue(value); };
            el.setEnabled = function (enabled) {
                UIComponent.prototype.setEnabled.call(this, enabled);
                if (this._control && typeof this._control.setEnabled === "function") {
                    this._control.setEnabled(enabled);
                }
            };
            return el;
        };
        return UIComponent;
    }());
    exports.UIComponent = UIComponent;
});
define("UIContainer", ["require", "exports", "UIComponent"], function (require, exports, UIComponent_1) {
    "use strict";
    exports.__esModule = true;
    var UIContainer = (function (_super) {
        __extends(UIContainer, _super);
        function UIContainer(tagType) {
            var _this = _super.call(this, tagType) || this;
            _this._children = [];
            _this._container = null;
            if (tagType === '%inherit%')
                return _this;
            _this._children = [];
            return _this;
        }
        UIContainer.prototype._appendChild = function (child) {
            this._elem.append(child.getElem());
        };
        UIContainer.prototype._detachChild = function (child) {
            child.getElem().detach();
        };
        UIContainer.prototype.addChild = function (child) {
            var idx = this._children.indexOf(child);
            if (idx < 0) {
                this._children.push(child);
                this._appendChild(child);
            }
            return this;
        };
        UIContainer.prototype.removeChild = function (child) {
            var idx = this._children.indexOf(child);
            if (idx >= 0) {
                this._children.splice(idx, 1);
                this._detachChild(child);
            }
            return this;
        };
        UIContainer.prototype.removeAllChildren = function () {
            for (var i = 0; i < this._children.length; i++) {
                this._detachChild(this._children[i]);
            }
            this._children.splice(0, this._children.length);
            return this;
        };
        UIContainer.prototype.setEnabled = function (enabled) {
            _super.prototype.setEnabled.call(this, enabled);
            for (var i = 0; i < this._children.length; i++) {
                this._children[i].setEnabled(enabled);
            }
        };
        return UIContainer;
    }(UIComponent_1.UIComponent));
    exports.UIContainer = UIContainer;
});
define("BuilderEvent", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var GlobalEvents;
    (function (GlobalEvents) {
        var eventListeners = {};
        function triggerEvent(eventType, event) {
            event.eventType = eventType.toLowerCase();
            event.defaultPrevented = false;
            event.propagationStopped = false;
            if (eventType in eventListeners) {
                var listeners = eventListeners[eventType].slice();
                for (var i = listeners.length - 1; i >= 0 && !event.propagationStopped; i--)
                    listeners[i](event);
            }
        }
        GlobalEvents.triggerEvent = triggerEvent;
        function on(eventType, handler) {
            var types = eventType.toLowerCase().split(" ");
            for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
                var type = types_1[_i];
                if (type === "")
                    continue;
                if (!(type in eventListeners))
                    eventListeners[type] = [];
                eventListeners[type].unshift(handler);
            }
        }
        GlobalEvents.on = on;
        function off(eventType, handler) {
            var types = eventType.toLowerCase().split(" ");
            for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
                var type = types_2[_i];
                if (type === "")
                    continue;
                if (type in eventListeners) {
                    if (handler) {
                        var listeners = eventListeners[type];
                        for (var i = listeners.length - 1; i >= 0; i--)
                            if (listeners[i] === handler)
                                listeners.splice(i, 1);
                    }
                    else {
                        delete eventListeners[type];
                    }
                }
            }
        }
        GlobalEvents.off = off;
    })(GlobalEvents = exports.GlobalEvents || (exports.GlobalEvents = {}));
    var BuilderEvent = (function () {
        function BuilderEvent() {
            this.defaultPrevented = false;
            this.propagationStopped = false;
        }
        BuilderEvent.prototype.preventDefault = function () {
            this.defaultPrevented = true;
            return this;
        };
        BuilderEvent.prototype.stopPropagation = function () {
            this.propagationStopped = true;
            return this;
        };
        BuilderEvent.prototype.stopImmediatePropagation = function () {
            this.propagationStopped = true;
            return this;
        };
        return BuilderEvent;
    }());
    exports.BuilderEvent = BuilderEvent;
    var BooleanValueChangedBuilderEvent = (function (_super) {
        __extends(BooleanValueChangedBuilderEvent, _super);
        function BooleanValueChangedBuilderEvent(value) {
            var _this = _super.call(this) || this;
            _this.value = value;
            return _this;
        }
        return BooleanValueChangedBuilderEvent;
    }(BuilderEvent));
    exports.BooleanValueChangedBuilderEvent = BooleanValueChangedBuilderEvent;
    var PreviewSizeChangedEvent = (function (_super) {
        __extends(PreviewSizeChangedEvent, _super);
        function PreviewSizeChangedEvent(width) {
            var _this = _super.call(this) || this;
            _this.width = width;
            return _this;
        }
        return PreviewSizeChangedEvent;
    }(BuilderEvent));
    exports.PreviewSizeChangedEvent = PreviewSizeChangedEvent;
    var NotificationEvent = (function (_super) {
        __extends(NotificationEvent, _super);
        function NotificationEvent(message, isHtml) {
            if (message === void 0) { message = ''; }
            if (isHtml === void 0) { isHtml = false; }
            var _this = _super.call(this) || this;
            _this.message = message;
            _this.isHtml = isHtml;
            return _this;
        }
        return NotificationEvent;
    }(BuilderEvent));
    exports.NotificationEvent = NotificationEvent;
    var SaveEvent = (function (_super) {
        __extends(SaveEvent, _super);
        function SaveEvent() {
            return _super.call(this) || this;
        }
        return SaveEvent;
    }(BuilderEvent));
    exports.SaveEvent = SaveEvent;
    var ContextMenuEvent = (function (_super) {
        __extends(ContextMenuEvent, _super);
        function ContextMenuEvent(menu, x, y, target) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (target === void 0) { target = null; }
            var _this = _super.call(this) || this;
            _this.menu = menu;
            _this.x = x;
            _this.y = y;
            _this.target = target;
            return _this;
        }
        return ContextMenuEvent;
    }(BuilderEvent));
    exports.ContextMenuEvent = ContextMenuEvent;
    var PagesChangedEvent = (function (_super) {
        __extends(PagesChangedEvent, _super);
        function PagesChangedEvent() {
            return _super.call(this) || this;
        }
        return PagesChangedEvent;
    }(BuilderEvent));
    exports.PagesChangedEvent = PagesChangedEvent;
    var LanguagesUpdateBuilderEvent = (function (_super) {
        __extends(LanguagesUpdateBuilderEvent, _super);
        function LanguagesUpdateBuilderEvent(initial) {
            var _this = _super.call(this) || this;
            _this.initial = initial;
            return _this;
        }
        return LanguagesUpdateBuilderEvent;
    }(BuilderEvent));
    exports.LanguagesUpdateBuilderEvent = LanguagesUpdateBuilderEvent;
    var ModesChangeBuilderEvent = (function (_super) {
        __extends(ModesChangeBuilderEvent, _super);
        function ModesChangeBuilderEvent(previousMode, mode, manual) {
            var _this = _super.call(this) || this;
            _this.previousMode = previousMode;
            _this.mode = mode;
            _this.manual = manual;
            return _this;
        }
        return ModesChangeBuilderEvent;
    }(BuilderEvent));
    exports.ModesChangeBuilderEvent = ModesChangeBuilderEvent;
    var ModesEnabledChangeBuilderEvent = (function (_super) {
        __extends(ModesEnabledChangeBuilderEvent, _super);
        function ModesEnabledChangeBuilderEvent(mode, value) {
            var _this = _super.call(this) || this;
            _this.mode = mode;
            _this.value = value;
            return _this;
        }
        return ModesEnabledChangeBuilderEvent;
    }(BuilderEvent));
    exports.ModesEnabledChangeBuilderEvent = ModesEnabledChangeBuilderEvent;
    var BlocksResizeBuilderEvent = (function (_super) {
        __extends(BlocksResizeBuilderEvent, _super);
        function BlocksResizeBuilderEvent(contentBlock, width, height) {
            var _this = _super.call(this) || this;
            _this.contentBlock = contentBlock;
            _this.width = width;
            _this.height = height;
            return _this;
        }
        return BlocksResizeBuilderEvent;
    }(BuilderEvent));
    exports.BlocksResizeBuilderEvent = BlocksResizeBuilderEvent;
    var BuilderInitBuilderEvent = (function (_super) {
        __extends(BuilderInitBuilderEvent, _super);
        function BuilderInitBuilderEvent() {
            return _super.call(this) || this;
        }
        return BuilderInitBuilderEvent;
    }(BuilderEvent));
    exports.BuilderInitBuilderEvent = BuilderInitBuilderEvent;
    var PageLoadBuilderEvent = (function (_super) {
        __extends(PageLoadBuilderEvent, _super);
        function PageLoadBuilderEvent(pageId, pageData) {
            var _this = _super.call(this) || this;
            _this.pageId = pageId;
            _this.pageData = pageData;
            return _this;
        }
        return PageLoadBuilderEvent;
    }(BuilderEvent));
    exports.PageLoadBuilderEvent = PageLoadBuilderEvent;
    var PagesChangedBuilderEvent = (function (_super) {
        __extends(PagesChangedBuilderEvent, _super);
        function PagesChangedBuilderEvent() {
            return _super.call(this) || this;
        }
        return PagesChangedBuilderEvent;
    }(BuilderEvent));
    exports.PagesChangedBuilderEvent = PagesChangedBuilderEvent;
    var VisibilityChangedBuilderEvent = (function (_super) {
        __extends(VisibilityChangedBuilderEvent, _super);
        function VisibilityChangedBuilderEvent(visible) {
            var _this = _super.call(this) || this;
            _this.visible = visible;
            return _this;
        }
        return VisibilityChangedBuilderEvent;
    }(BuilderEvent));
    exports.VisibilityChangedBuilderEvent = VisibilityChangedBuilderEvent;
    var StoreCategoriesChangedBuilderEvent = (function (_super) {
        __extends(StoreCategoriesChangedBuilderEvent, _super);
        function StoreCategoriesChangedBuilderEvent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return StoreCategoriesChangedBuilderEvent;
    }(BuilderEvent));
    exports.StoreCategoriesChangedBuilderEvent = StoreCategoriesChangedBuilderEvent;
    var MediaLibraryMetaChangedBuilderEvent = (function (_super) {
        __extends(MediaLibraryMetaChangedBuilderEvent, _super);
        function MediaLibraryMetaChangedBuilderEvent(path, meta) {
            var _this = _super.call(this) || this;
            _this.path = path;
            _this.meta = meta;
            return _this;
        }
        return MediaLibraryMetaChangedBuilderEvent;
    }(BuilderEvent));
    exports.MediaLibraryMetaChangedBuilderEvent = MediaLibraryMetaChangedBuilderEvent;
    var FontsChangedBuilderEvent = (function (_super) {
        __extends(FontsChangedBuilderEvent, _super);
        function FontsChangedBuilderEvent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return FontsChangedBuilderEvent;
    }(BuilderEvent));
    exports.FontsChangedBuilderEvent = FontsChangedBuilderEvent;
    var HistoryChangedBuilderEvent = (function (_super) {
        __extends(HistoryChangedBuilderEvent, _super);
        function HistoryChangedBuilderEvent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return HistoryChangedBuilderEvent;
    }(BuilderEvent));
    exports.HistoryChangedBuilderEvent = HistoryChangedBuilderEvent;
    var LandingChangedBuilderEvent = (function (_super) {
        __extends(LandingChangedBuilderEvent, _super);
        function LandingChangedBuilderEvent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LandingChangedBuilderEvent;
    }(BooleanValueChangedBuilderEvent));
    exports.LandingChangedBuilderEvent = LandingChangedBuilderEvent;
    var AutoLayoutChangedBuilderEvent = (function (_super) {
        __extends(AutoLayoutChangedBuilderEvent, _super);
        function AutoLayoutChangedBuilderEvent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return AutoLayoutChangedBuilderEvent;
    }(BooleanValueChangedBuilderEvent));
    exports.AutoLayoutChangedBuilderEvent = AutoLayoutChangedBuilderEvent;
});
define("FontManager", ["require", "exports", "BuilderEvent"], function (require, exports, BuilderEvent_1) {
    "use strict";
    exports.__esModule = true;
    var GoogleFontVariantData = (function () {
        function GoogleFontVariantData(weight, italic) {
            this.weight = weight;
            this.italic = italic;
        }
        return GoogleFontVariantData;
    }());
    exports.GoogleFontVariantData = GoogleFontVariantData;
    var GoogleFont = (function () {
        function GoogleFont(data) {
            this.earlyAccessUrl = null;
            if (data) {
                this.family = data.family;
                this.category = data.category;
                this.variants = [];
                for (var i = 0; i < data.variants.length; i++)
                    this.variants.push(GoogleFont.getVariantUrlValue(data.variants[i]));
                this.variants.sort();
                this.subsets = data.subsets.slice();
                this.subsets.sort();
                this.earlyAccessUrl = data.hasOwnProperty("earlyAccessUrl") ? data.earlyAccessUrl : null;
            }
        }
        GoogleFont.getVariantUrlValue = function (variant) {
            if (variant === "regular")
                return "400";
            if (variant === "italic")
                return "400i";
            if (/^[0-9]{3}italic$/.test(variant))
                return variant.substr(0, 3) + "i";
            return variant;
        };
        GoogleFont.parseVariantCode = function (variant) {
            if (/^[0-9]+i$/.test(variant))
                return new GoogleFontVariantData(variant.substr(0, variant.length - 1), true);
            return new GoogleFontVariantData(variant, false);
        };
        GoogleFont.getVariantName = function (variant) {
            var vd = GoogleFont.parseVariantCode(variant);
            switch (vd.weight) {
                case "100": {
                    vd.weight = __("Thin") + " " + vd.weight;
                    break;
                }
                case "200": {
                    vd.weight = __("Extra-Light") + " " + vd.weight;
                    break;
                }
                case "300": {
                    vd.weight = __("Light") + " " + vd.weight;
                    break;
                }
                case "400": {
                    vd.weight = __("Regular") + " " + vd.weight;
                    break;
                }
                case "500": {
                    vd.weight = __("Medium") + " " + vd.weight;
                    break;
                }
                case "600": {
                    vd.weight = __("Semi-Bold") + " " + vd.weight;
                    break;
                }
                case "700": {
                    vd.weight = __("Bold") + " " + vd.weight;
                    break;
                }
                case "800": {
                    vd.weight = __("Extra-Bold") + " " + vd.weight;
                    break;
                }
                case "900": {
                    vd.weight = __("Black") + " " + vd.weight;
                    break;
                }
            }
            return vd.weight + (vd.italic ? " " + __("Italic") : "");
        };
        GoogleFont.getSubsetName = function (subset) {
            switch (subset) {
                case "arabic": return __("Arabic");
                case "bengali": return __("Bengali");
                case "cyrillic": return __("Cyrillic");
                case "cyrillic-ext": return __("Cyrillic Extended");
                case "devanagari": return __("Devanagari");
                case "greek": return __("Greek");
                case "greek-ext": return __("Greek Extended");
                case "gujarati": return __("Gujarati");
                case "gurmukhi": return __("Gurmukhi");
                case "hebrew": return __("Hebrew");
                case "kannada": return __("Kannada");
                case "khmer": return __("Khmer");
                case "latin": return __("Latin");
                case "latin-ext": return __("Latin Extended");
                case "malayalam": return __("Malayalam");
                case "myanmar": return __("Myanmar");
                case "oriya": return __("Oriya");
                case "sinhala": return __("Sinhala");
                case "tamil": return __("Tamil");
                case "telugu": return __("Telugu");
                case "thai": return __("Thai");
                case "vietnamese": return __("Vietnamese");
            }
            return subset;
        };
        GoogleFont.prototype.getUrl = function (variants, subsets) {
            if (this.earlyAccessUrl)
                return "https://" + this.earlyAccessUrl;
            return "https://fonts.googleapis.com/css?family=" + this.family + ":" + variants.join(",") + (subsets.length ? ("&subset=" + subsets.join(",")) : "");
        };
        GoogleFont.prototype.getCssFontFamily = function () {
            var fontFamily = "'" + this.family + "'";
            switch (this.category) {
                case "sans-serif":
                    fontFamily += ",Arial,sans-serif";
                    break;
                case "serif":
                    fontFamily += ",Arial,serif";
                    break;
                case "monospace":
                    fontFamily += ",Arial,monospace";
                    break;
                case "handwriting":
                    fontFamily += ",Arial,cursive";
                    break;
                default:
                    fontFamily += ",Arial," + this.category;
                    break;
            }
            return fontFamily;
        };
        GoogleFont.prototype.clone = function () {
            var obj = new GoogleFont();
            obj.family = this.family;
            obj.category = this.category;
            obj.earlyAccessUrl = this.earlyAccessUrl;
            obj.variants = this.variants.slice();
            obj.subsets = this.subsets.slice();
            return obj;
        };
        GoogleFont.fromJson = function (data) {
            var obj = new GoogleFont();
            obj.family = data.family;
            obj.category = data.category;
            obj.earlyAccessUrl = data.hasOwnProperty("earlyAccessUrl") ? data.earlyAccessUrl : null;
            obj.variants = data.variants;
            obj.subsets = data.subsets;
            return obj;
        };
        GoogleFont.prototype.serialize = function () {
            return {
                family: this.family,
                category: this.category,
                earlyAccessUrl: this.earlyAccessUrl,
                variants: this.variants,
                subsets: this.subsets
            };
        };
        return GoogleFont;
    }());
    exports.GoogleFont = GoogleFont;
    var GoogleFontUsage = (function () {
        function GoogleFontUsage() {
            this.variants = [];
            this.subsets = [];
        }
        GoogleFontUsage.fromJson = function (data) {
            var obj = new GoogleFontUsage();
            obj.font = GoogleFont.fromJson(data.font);
            obj.variants = data.variants;
            obj.subsets = data.subsets;
            return obj;
        };
        GoogleFontUsage.prototype.serialize = function () {
            return {
                font: this.font.serialize(),
                variants: this.variants,
                subsets: this.subsets
            };
        };
        GoogleFontUsage.prototype.clone = function () {
            var obj = new GoogleFontUsage();
            obj.font = this.font.clone();
            obj.variants = this.variants.slice();
            obj.subsets = this.subsets.slice();
            return obj;
        };
        return GoogleFontUsage;
    }());
    exports.GoogleFontUsage = GoogleFontUsage;
    var FontManagerModule = (function () {
        function FontManagerModule() {
            this.state = "none";
            this.fontElements = {};
            this.ready = false;
            this.error = null;
            this.fontThumbs = null;
        }
        FontManagerModule.getHardcodedFontList = function () {
            return [
                "Arial", "Batang", "Capture it", "Comic Sans MS", "Courier New", "Dotum", "Georgia", "Gulim",
                "Helvetica", "Microsoft JhengHei", "Malgun Gothic", "MingLiU", "Myriad Set Pro", "Nanum Gothic",
                "Lucida Grande", "PMingLiU", "Tahoma", "Times New Roman", "Trebuchet MS", "Sylfaen"
            ];
        };
        ;
        FontManagerModule.getForcedCustomFonts = function () {
            return [
                "Exo 2", "Open Sans", "Open Sans Condensed", "PT Sans", "PT Sans Caption", "PT Sans Narrow", "Roboto",
                "Roboto Condensed", "Roboto Slab"
            ];
        };
        ;
        FontManagerModule.prototype.forceCustomFontsUsage = function () {
            if (!this.ready)
                return;
            var i, forcedFonts = {};
            for (var _i = 0, _a = FontManagerModule.getForcedCustomFonts(); _i < _a.length; _i++) {
                i = _a[_i];
                forcedFonts[i] = true;
            }
            for (i in this.availableFonts) {
                var font = this.availableFonts[i];
                if (!forcedFonts.hasOwnProperty(font.family))
                    continue;
                var usage = new GoogleFontUsage();
                usage.font = font;
                usage.subsets = font.subsets.slice();
                usage.variants = font.variants.slice();
                wb_builder.site.usedCustomFonts[i] = usage;
                this.createFontLinkElementForFont(font);
            }
        };
        FontManagerModule.prototype.init = function () {
            if (this.state != "none")
                return;
            var thisClass = this;
            this.availableFonts = {};
            this.state = "loading";
            $.ajax({
                url: wb_builder.availableFontsUrl,
                type: "GET",
                dataType: "json",
                async: true,
                success: function (resp) {
                    if (resp.error) {
                        thisClass.state = "error";
                        thisClass.error = resp.error;
                    }
                    else {
                        for (var i = 0; i < resp.items.length; i++)
                            thisClass.availableFonts[resp.items[i].family] = new GoogleFont(resp.items[i]);
                        thisClass.state = "done";
                        thisClass.ready = true;
                        thisClass.forceCustomFontsUsage();
                    }
                },
                error: function () {
                    thisClass.state = "error";
                    thisClass.error = __("Failed to load list of available fonts") + " (1)";
                }
            });
        };
        FontManagerModule.prototype.loadFontThumbs = function (callback) {
            var _this = this;
            if (this.fontThumbs)
                callback();
            else {
                var cb_1 = callback;
                $.ajax({
                    url: wb_builder.fontThumbsUrl,
                    type: "GET",
                    dataType: "json",
                    async: true,
                    success: function (resp) {
                        _this.fontThumbs = resp;
                        cb_1();
                    },
                    error: function () {
                        _this.state = "error";
                        _this.error = __("Failed to load list of available fonts") + " (2)";
                        cb_1();
                    }
                });
            }
        };
        FontManagerModule.prototype.createFontLinkElementForFont = function (font, doc) {
            var fontId = font.family;
            var elem = $('<link/>').attr({
                rel: "stylesheet",
                type: "text/css",
                href: font.getUrl(font.variants, font.subsets)
            });
            if (!doc)
                doc = document;
            doc.getElementsByTagName('head')[0].appendChild(elem.get(0));
            return this.fontElements[fontId] = elem;
        };
        FontManagerModule.prototype.getFontThumbnail = function (font) {
            var $item;
            if (this.fontThumbs && this.fontThumbs.hasOwnProperty(font.family)) {
                $item = $('<img>')
                    .attr("src", this.fontThumbs[font.family])
                    .attr("alt", font.family)
                    .attr("title", font.family);
            }
            else {
                this.createFontLinkElement(font.family);
                $item = $('<span>').css({
                    fontSize: "20px",
                    fontFamily: font.family,
                    padding: "0 10px"
                }).attr("title", font.family);
                $item.text(font.family);
            }
            return $item;
        };
        FontManagerModule.prototype.createFontLinkElement = function (fontId) {
            if (fontId in this.fontElements)
                return this.fontElements[fontId];
            if (!(fontId in this.availableFonts))
                return null;
            return this.createFontLinkElementForFont(this.availableFonts[fontId]);
        };
        FontManagerModule.prototype.removeFontLinkElement = function (fontId) {
            if (fontId in this.fontElements)
                this.fontElements[fontId].remove();
        };
        FontManagerModule.prototype.addCustomFontUsage = function (font, forPreview) {
            if (forPreview === void 0) { forPreview = false; }
            var fontFamily = font.split(',')[0].replace(/^["']/, '').replace(/["']$/, '');
            for (var i in this.availableFonts) {
                var font_1 = this.availableFonts[i];
                if (font_1.family != fontFamily)
                    continue;
                if (wb_builder.site.usedCustomFonts.hasOwnProperty(i))
                    break;
                if (!forPreview) {
                    var usage = new GoogleFontUsage();
                    usage.font = font_1;
                    usage.subsets = font_1.subsets.slice();
                    usage.variants = font_1.variants.slice();
                    wb_builder.site.usedCustomFonts[i] = usage;
                    var e = new BuilderEvent_1.FontsChangedBuilderEvent();
                    BuilderEvent_1.GlobalEvents.triggerEvent("fonts.changed", e);
                }
                this.createFontLinkElement(i);
            }
        };
        return FontManagerModule;
    }());
    exports.FontManagerModule = FontManagerModule;
    exports.FontManager = new FontManagerModule();
});
define("ElementRegister", ["require", "exports", "Service", "FontManager"], function (require, exports, Service_1, FontManager_1) {
    "use strict";
    exports.__esModule = true;
    var ElementRegisterType = (function () {
        function ElementRegisterType() {
            this.classList = {};
            this.pluginRegistry = {};
            this.paymentGateways = [];
        }
        ElementRegisterType.prototype.registerClass = function (className, cls, plugin, active) {
            if (plugin === void 0) { plugin = false; }
            if (active === void 0) { active = false; }
            cls.prototype.className = className;
            this.classList[className] = cls;
            window['WB_' + className] = cls;
            if (plugin) {
                var meta = cls._metaData_;
                var item = {
                    id: className,
                    textId: (meta.id ? meta.id : null),
                    icon: (meta.icon ? meta.icon : 'ico-tb ico-tb-no-bg') + ' #ico-pl-' + className,
                    iconImage: (!!meta.icon),
                    name: (meta.name ? meta.name : className),
                    borderless: (!!meta.isBorderless),
                    active: (!!active)
                };
                this.pluginRegistry[className] = item;
                if (item.textId) {
                    this.classList[item.textId] = cls;
                }
            }
        };
        ElementRegisterType.prototype.getClassByName = function (className) {
            return this.classList[className];
        };
        ElementRegisterType.prototype.isClassEnabled = function (className) {
            var item = this.pluginRegistry[className];
            return ((!!item) && item.active);
        };
        ElementRegisterType.prototype.registerPaymentGateway = function (gateway) {
            if (gateway && typeof gateway === 'object' && ('id' in gateway))
                this.paymentGateways.push(gateway);
        };
        ElementRegisterType.prototype.getPaymentGateways = function () {
            var i, gateway, list = [];
            for (i = 0; i < this.paymentGateways.length; i++) {
                gateway = this.paymentGateways[i];
                var id = (('className' in gateway) && gateway.className) ? gateway.className : gateway.id;
                if ((('forceActive' in gateway) && gateway.forceActive) || ((typeof this.pluginRegistry[id] === 'object') && this.pluginRegistry[id].active)) {
                    list.push(gateway);
                }
            }
            list.sort(function (a, b) {
                var ap = ("priority" in a) ? a.priority : 0;
                var bp = ("priority" in b) ? b.priority : 0;
                if (ap == bp) {
                    var an = a.name.toLowerCase(), bn = b.name.toLowerCase();
                    if (an == bn)
                        return 0;
                    return (an > bn) ? 1 : -1;
                }
                return (ap > bp) ? -1 : 1;
            });
            return list;
        };
        ElementRegisterType.prototype.registerClassAll = function (items) {
            for (var i in items) {
                this.pluginRegistry[i] = items[i];
            }
        };
        ElementRegisterType.prototype.getPluginRegistry = function () {
            return this.pluginRegistry;
        };
        ElementRegisterType.prototype.getPluginNameById = function (id) {
            return ((id in this.pluginRegistry) && this.pluginRegistry[id]) ? this.pluginRegistry[id].name : id;
        };
        ElementRegisterType.prototype.createElement = function (className, successCallback, cancelCallback, defaultData, initial, virtual, styleId) {
            if (cancelCallback === void 0) { cancelCallback = null; }
            if (defaultData === void 0) { defaultData = null; }
            if (initial === void 0) { initial = false; }
            if (virtual === void 0) { virtual = false; }
            if (styleId === void 0) { styleId = null; }
            var cls = this.getClassByName(className);
            if (!cls) {
                if (typeof cancelCallback === "function")
                    cancelCallback();
                return;
            }
            var createClassName = className;
            var createSuccessCallback = successCallback;
            var createCancelCallback = cancelCallback;
            var createInitial = initial;
            var createVirtual = virtual;
            var createDefaults = defaultData;
            var create = function (styleId) {
                var element;
                try {
                    var hasDefaults = createDefaults && typeof createDefaults === "object";
                    var isPreview = (hasDefaults && createDefaults.isElementPreview);
                    var data_1 = { content: {} };
                    var styleInfo_1 = Service_1["default"].ElementStyles.getStyleInfo(createClassName, styleId);
                    if (styleInfo_1) {
                        data_1 = $.extend(true, data_1, isPreview ? styleInfo_1.previewData : styleInfo_1.data);
                        if (!isPreview && data_1.content) {
                            if (createClassName === "Picture")
                                data_1.content.src = null;
                            if (createClassName === "Gallery")
                                data_1.content.images = null;
                        }
                        if (styleInfo_1.fonts.length) {
                            for (var _i = 0, _a = styleInfo_1.fonts; _i < _a.length; _i++) {
                                var fontName = _a[_i];
                                FontManager_1.FontManager.addCustomFontUsage(fontName, isPreview);
                            }
                        }
                    }
                    if (hasDefaults)
                        data_1 = $.extend(true, data_1, createDefaults);
                    var createInternal = function () {
                        element = new cls(data_1, createInitial, createVirtual);
                        if (typeof createSuccessCallback === "function")
                            createSuccessCallback(element, styleInfo_1);
                    };
                    if (isPreview)
                        createInternal();
                    else
                        Service_1["default"].ElementStyles.mergeGallery(createClassName, styleId, createInternal);
                }
                catch (err) {
                    console.error(err);
                    if (typeof createCancelCallback === "function")
                        createCancelCallback();
                    return;
                }
            };
            if (styleId === null) {
                var styleIds = Service_1["default"].ElementStyles.getAvailableStyles(createClassName);
                if (!styleIds.length)
                    create(false);
                else if (styleIds.length === 1 && !wb_builder.adminMode)
                    create(styleIds[0]);
                else
                    Service_1["default"].ElementStyles.open(createClassName, createDefaults, create, createCancelCallback);
            }
            else
                create(styleId);
        };
        return ElementRegisterType;
    }());
    var ElementRegister = new ElementRegisterType();
    exports["default"] = ElementRegister;
});
define("UserInput", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var UserInputType = (function () {
        function UserInputType() {
            this.hotKeysMap = {
                27: 'esc', 9: 'tab', 32: 'space', 13: 'return', 8: 'backspace', 145: 'scroll',
                20: 'capslock', 144: 'numlock', 19: 'pause', 45: 'insert', 36: 'home', 46: 'del',
                35: 'end', 33: 'pageup', 34: 'pagedown', 37: 'left', 38: 'up', 39: 'right', 40: 'down',
                109: '-',
                112: 'f1', 113: 'f2', 114: 'f3', 115: 'f4', 116: 'f5', 117: 'f6', 118: 'f7', 119: 'f8',
                120: 'f9', 121: 'f10', 122: 'f11', 123: 'f12', 191: '/'
            };
            this.hotKeysMod = { shift: false, ctrl: false, alt: false, win: false };
            this.hotKeysListeners = {};
            this.initialized = false;
            for (var i = 65; i <= 90; i++) {
                this.hotKeysMap[i] = String.fromCharCode(i).toLowerCase();
            }
            for (var i = 96; i <= 105; i++) {
                this.hotKeysMap[i] = String.fromCharCode(i - 48).toLowerCase();
            }
        }
        UserInputType.prototype.init = function (doc) {
            var _this = this;
            if (this.initialized)
                return;
            this.initialized = true;
            $(doc).on('keydown', function (e) {
                if ($(e.target).is('body') && e.which === 8) {
                    e.preventDefault();
                    return false;
                }
                if (e.keyCode === 16) {
                    _this.hotKeysMod.shift = true;
                }
                else if (e.keyCode === 17) {
                    _this.hotKeysMod.ctrl = true;
                }
                else if (e.keyCode === 18) {
                    _this.hotKeysMod.alt = true;
                }
                var key = _this.hotKeysMap[e.keyCode], _key = key, listeners = _this.hotKeysListeners[_key];
                if (_this.hotKeysMod.shift && key !== 'shift') {
                    _key = 'shift+' + key;
                    listeners = _this.hotKeysListeners[_key];
                }
                if (_this.hotKeysMod.ctrl && key !== 'ctrl') {
                    _key = 'ctrl+' + key;
                    listeners = _this.hotKeysListeners[_key];
                }
                if (_this.hotKeysMod.alt && key !== 'alt') {
                    _key = 'alt+' + key;
                    listeners = _this.hotKeysListeners[_key];
                }
                if (listeners && listeners.length > 0) {
                    if (!e.data)
                        e.data = {};
                    e.data.hotKey = _key;
                    for (var _i = 0, listeners_1 = listeners; _i < listeners_1.length; _i++) {
                        var listener = listeners_1[_i];
                        listener(e);
                    }
                }
                return true;
            }).on('keyup', function (e) {
                if (e.keyCode === 16) {
                    _this.hotKeysMod.shift = false;
                }
                else if (e.keyCode === 17) {
                    _this.hotKeysMod.ctrl = false;
                }
                else if (e.keyCode === 18) {
                    _this.hotKeysMod.alt = false;
                }
            });
        };
        UserInputType.prototype.addHotKey = function (comb, func) {
            var lComb = comb.toLowerCase();
            var funcs = this.hotKeysListeners[lComb];
            if (!funcs) {
                funcs = [];
                this.hotKeysListeners[lComb] = funcs;
            }
            funcs.push(func);
        };
        return UserInputType;
    }());
    exports.UserInput = new UserInputType();
});
define("UIBuildable", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
});
define("HorizontalLayout", ["require", "exports", "UIContainer"], function (require, exports, UIContainer_1) {
    "use strict";
    exports.__esModule = true;
    var HorizontalLayout = (function (_super) {
        __extends(HorizontalLayout, _super);
        function HorizontalLayout(tagType) {
            var _this = _super.call(this, (tagType === '%inherit%') ? tagType : 'div') || this;
            _this.columnWeights = {};
            _this.columnWeightsSmall = {};
            if (tagType === '%inherit%')
                return _this;
            _this._elem.addClass('row');
            return _this;
        }
        HorizontalLayout.prototype.buildInit = function (data, fields) {
            if (data.columnWeights && typeof data.columnWeights === 'object' && data.columnWeights.length) {
                if (wb_builder.rtl)
                    data.columnWeights.reverse();
                for (var n = 0; n < data.columnWeights.length; n++) {
                    this.setColWeight(n, data.columnWeights[n]);
                }
            }
            if (data.columnWeightsSmall && typeof data.columnWeightsSmall === 'object' && data.columnWeightsSmall.length) {
                if (wb_builder.rtl)
                    data.columnWeightsSmall.reverse();
                for (var n = 0; n < data.columnWeightsSmall.length; n++) {
                    this.setColWeight(n, data.columnWeightsSmall[n], 1);
                }
            }
            if (('noPadding' in data) && data.noPadding) {
                this.setNoPadding(true);
            }
            if (wb_builder.rtl && data.children && (typeof data.children.length === 'number')) {
                data.children.reverse();
            }
        };
        HorizontalLayout.prototype._appendChild = function (child) {
            var div = $('<div>').append(child.getElem());
            this._elem.append(div);
            var c = Math.floor(12 / this._elem.children().length);
            if (c < 1)
                c = 1;
            var idx = (this._elem.children().length - 1);
            if (('#' + idx) in this.columnWeights) {
                this._elem.children().eq(idx).attr('class', 'wb-horiz-lay-item col-md-' + this.columnWeights['#' + idx]);
            }
            else {
                this._elem.children().attr('class', 'wb-horiz-lay-item col-md-' + c);
            }
            if (('#' + idx) in this.columnWeightsSmall) {
                this._elem.children().eq(idx).addClass('col-sm-' + this.columnWeightsSmall['#' + idx]);
            }
        };
        HorizontalLayout.prototype._detachChild = function (child) {
            var childElem = child.getElem(), div = childElem.parent();
            childElem.detach();
            div.remove();
            var c = Math.floor(12 / this._elem.children().length);
            if (c < 1)
                c = 1;
            this._elem.children().attr('class', 'wb-horiz-lay-item col-md-' + c);
        };
        HorizontalLayout.prototype.applyLayoutCellCss = function (idx, css) {
            this._elem.children().eq(idx).css(css);
            return this;
        };
        HorizontalLayout.prototype.setColWeight = function (idx, weight, size) {
            if (size === void 0) { size = 0; }
            var oldWeight = Math.floor(12 / this._elem.children().length);
            if (size === 1) {
                if (('#' + idx) in this.columnWeightsSmall) {
                    oldWeight = this.columnWeightsSmall['#' + idx];
                }
                this.columnWeightsSmall['#' + idx] = weight;
                this._elem.children().eq(idx).removeClass('col-sm-' + oldWeight).addClass('col-sm-' + weight);
            }
            else {
                if (('#' + idx) in this.columnWeights) {
                    oldWeight = this.columnWeights['#' + idx];
                }
                this.columnWeights['#' + idx] = weight;
                this._elem.children().eq(idx).removeClass('col-md-' + oldWeight).addClass('col-md-' + weight);
            }
            return this;
        };
        HorizontalLayout.prototype.setNoPadding = function (noPadding) {
            if (noPadding) {
                this._elem.addClass('wb-horiz-lay-no-padding');
            }
            else {
                this._elem.removeClass('wb-horiz-lay-no-padding');
            }
        };
        return HorizontalLayout;
    }(UIContainer_1.UIContainer));
    exports.HorizontalLayout = HorizontalLayout;
});
define("TextField", ["require", "exports", "UIComponent"], function (require, exports, UIComponent_2) {
    "use strict";
    exports.__esModule = true;
    var TextField = (function (_super) {
        __extends(TextField, _super);
        function TextField(text, placeholder, textArea, resizable, prepend, append) {
            if (textArea === void 0) { textArea = false; }
            if (resizable === void 0) { resizable = false; }
            var _this = _super.call(this) || this;
            _this.textArea = false;
            _this.setTextArea(textArea, true);
            if (text)
                _this.setText(text);
            if (placeholder)
                _this.setPlaceholder(placeholder);
            _this.setResizable(resizable);
            _this.input = _this._elem;
            if (prepend || append) {
                _this.elem = $('<div>');
                _this.elem.append(_this.input);
                if (prepend) {
                    _this.elem.addClass("input-prepend");
                    _this.elem.prepend(_this.prepareAdOn(prepend));
                }
                if (append) {
                    _this.elem.addClass("input-append");
                    _this.elem.append(_this.prepareAdOn(append));
                }
            }
            else {
                _this.elem = _this.input;
            }
            return _this;
        }
        TextField.prototype.buildInit = function (data, fields) {
            var _this = this;
            this.setTextArea(data.textArea ? true : false);
            if (data.placeholder)
                this.setPlaceholder(data.placeholder);
            this.setResizable(data.resizable ? data.resizable : false);
            if (data.value)
                this.setText(data.value);
            else if (data.text)
                this.setText(data.text);
            if (data.password)
                this.setAsPassword(data.password ? true : false);
            if (data.title)
                this.setTitle(data.title);
            if (('change' in data) && (typeof data.change === 'function')) {
                (function (el, func) { _this.on('change', function () { func.call(el, fields); }); })(this, data.change);
            }
        };
        TextField.prototype.setTextArea = function (textArea, force) {
            if (force === void 0) { force = false; }
            if (textArea && (!this.textArea || force)) {
                this._elem = $('<textarea>').addClass('form-control');
            }
            else if (!textArea && (this.textArea || force)) {
                this._elem = $('<input>').addClass('form-control').attr('type', 'text');
            }
            this.input = this._elem;
            this.textArea = textArea ? true : false;
        };
        TextField.prototype.setResizable = function (resizable) {
            if (this.textArea) {
                if (!resizable) {
                    this._elem.css({ resize: 'none' });
                }
                else if (resizable === 'vertical' || resizable === 'horizontal' || resizable === 'both') {
                    this._elem.css({ resize: resizable });
                }
                else if (resizable === true) {
                    this._elem.css({ resize: 'both' });
                }
            }
        };
        TextField.prototype.setName = function (name) {
            this.input.attr('name', name);
        };
        TextField.prototype.setText = function (text) {
            return this.setValue(text);
        };
        TextField.prototype.getText = function () {
            return this.getValue();
        };
        TextField.prototype.setValue = function (text) {
            this._elem.val(text);
            return this;
        };
        TextField.prototype.getValue = function () {
            return this._elem.val();
        };
        TextField.prototype.setPlaceholder = function (text) {
            this._elem.attr('placeholder', text);
            return this;
        };
        ;
        TextField.prototype.getPlaceholder = function () {
            return this._elem.attr('placeholder');
        };
        ;
        TextField.prototype.setAsPassword = function (asPassword) {
            if (!this.textArea) {
                this._elem.attr('type', (asPassword ? 'password' : 'text'));
            }
            return this;
        };
        ;
        TextField.prototype.setEnabled = function (enabled) {
            _super.prototype.setEnabled.call(this, enabled);
            if (enabled) {
                this._elem.removeClass('disabled');
                this._elem.removeAttr('disabled');
            }
            else {
                this._elem.addClass('disabled');
                this._elem.attr('disabled', 'disabled');
            }
            return this;
        };
        ;
        TextField.prototype.focus = function () {
            this._elem.focus();
        };
        TextField.prototype.insertAtCursor = function (text) {
            var el = this._elem.get(0), val = el.value;
            el.focus();
            if (el.selectionStart !== undefined && el.selectionStart !== null && el.selectionEnd !== null) {
                el.value = val.substring(0, el.selectionStart) + text + val.substring(el.selectionEnd);
            }
            else if (typeof el.createTextRange) {
                var rng = el.createTextRange();
                if (rng)
                    rng.text = text;
            }
            else {
                el.value = val + text;
            }
        };
        TextField.prototype.prepareAdOn = function (el) {
            var wrp = null;
            if (typeof (el) !== "object" || typeof (el.hasClass) !== "function" || !el.className) {
                wrp = $('<span class="add-on"></span>');
                wrp.append(el);
            }
            else {
                wrp = $(el);
                if (!el.hasClass("add-on") && !el.hasClass("btn")) {
                    wrp.addClass("add-on");
                }
            }
            return wrp;
        };
        return TextField;
    }(UIComponent_2.UIComponent));
    exports["default"] = TextField;
});
define("UIButton", ["require", "exports", "UIComponent"], function (require, exports, UIComponent_3) {
    "use strict";
    exports.__esModule = true;
    var UIButton = (function (_super) {
        __extends(UIButton, _super);
        function UIButton(text, style, icon, type) {
            var _this = _super.call(this, ((text === '%inherit%') ? text : undefined)) || this;
            _this._icon = null;
            _this._iconElem = null;
            _this._preloader = null;
            _this.caretElem = null;
            _this.menuElem = null;
            if (text !== '%inherit%') {
                _this.btnElem = _this._elem;
                _this._iconElem = $('<i>');
                _this.setText(text);
                if (style)
                    _this.setButtonStyle(style);
                if (icon)
                    _this.setIcon(icon);
                if (type)
                    _this.setType(type);
            }
            return _this;
        }
        UIButton.prototype.buildInit = function (data, fields) {
            var _this = this;
            var dataMenu = data.menuUp ? data.menuUp : data.menu;
            if (dataMenu && dataMenu.length > 0) {
                this._elem = $('<div>')
                    .addClass('btn-group')
                    .append(this.btnElem);
                if (data.menuUp)
                    this._elem.addClass('dropup');
                this.caretElem = $('<span>').addClass('caret').css({ marginLeft: '4px' });
                this.menuElem = $('<ul>').addClass('dropdown-menu');
                if (data.menuWidth)
                    this.menuElem.css({ width: data.menuWidth + 'px', minWidth: data.menuWidth + 'px' });
                var _loop_1 = function (mi) {
                    var miElem = $('<li>'), miAElem = $('<a>')
                        .attr({ href: 'javascript:void(0)' })
                        .text(mi.name)
                        .appendTo(miElem);
                    if (typeof mi.click === 'function') {
                        (function (btn, func) {
                            miAElem.on('click', function () {
                                func.call(btn);
                                btn._elem.removeClass('open');
                                return false;
                            });
                        })(this_1, mi.click);
                    }
                    this_1.menuElem.append(miElem);
                };
                var this_1 = this;
                for (var _i = 0, dataMenu_1 = dataMenu; _i < dataMenu_1.length; _i++) {
                    var mi = dataMenu_1[_i];
                    _loop_1(mi);
                }
                this.btnElem.on('click', function () { _this._elem.toggleClass('open'); });
                this.menuElem.appendTo(this._elem);
            }
            if (data.value)
                this.setText(data.value);
            else if (data.text)
                this.setText(data.text);
            if (data.icon)
                this.setIcon(data.icon);
            if (data.buttonStyle)
                this.setButtonStyle(data.buttonStyle);
            if (data.buttonSize)
                this.setButtonSize(data.buttonSize);
            if (data.buttonType)
                this.setType(data.buttonType);
            if (data.borderless)
                this.btnElem.css({ border: 'none' });
        };
        UIButton.prototype.setType = function (type) {
            if (type)
                this.btnElem.attr({ type: type });
        };
        UIButton.prototype.setIcon = function (icon) {
            var prevIcon = this._icon;
            this._icon = icon ? icon : null;
            if (!this._iconElem)
                return;
            if (prevIcon)
                this._iconElem.removeClass(prevIcon);
            if (this._icon) {
                this._iconElem.addClass(this._icon).prependTo(this.btnElem);
            }
            else {
                this._iconElem.detach();
            }
        };
        UIButton.prototype._createElem = function () { return $('<button>').attr('type', 'button').addClass('btn btn-default'); };
        UIButton.prototype.setText = function (text) {
            this.btnElem.text((text === null) ? '' : text);
            if (this._iconElem) {
                if (text) {
                    this._iconElem.css((wb_builder.rtl ? { marginLeft: '4px' } : { marginRight: '4px' }));
                }
                else {
                    this._iconElem.css({ marginLeft: 0, marginRight: 0 });
                }
            }
            if (this.caretElem) {
                this.caretElem.appendTo(this.btnElem);
            }
            return this;
        };
        UIButton.prototype.getText = function () {
            return this.btnElem.text();
        };
        UIButton.prototype.setButtonSize = function (size) {
            this.btnElem.removeClass('btn-lg btn-sm btn-xs');
            if (size === UIButton.SIZE_LARGE) {
                this.btnElem.addClass('btn-lg');
            }
            else if (size === UIButton.SIZE_SMALL) {
                this.btnElem.addClass('btn-sm');
            }
            else if (size === UIButton.SIZE_TINY) {
                this.btnElem.addClass('btn-xs');
            }
            return this;
        };
        UIButton.prototype.setButtonStyle = function (style) {
            this.btnElem.removeClass('btn-success btn-danger btn-info btn-warning btn-primary btn-link btn-default');
            if (style === UIButton.STYLE_DANGER) {
                this.btnElem.addClass('btn-danger');
            }
            else if (style === UIButton.STYLE_SUCCESS) {
                this.btnElem.addClass('btn-success');
            }
            else if (style === UIButton.STYLE_INFO) {
                this.btnElem.addClass('btn-info');
            }
            else if (style === UIButton.STYLE_WARNING) {
                this.btnElem.addClass('btn-warning');
            }
            else if (style === UIButton.STYLE_PRIMARY) {
                this.btnElem.addClass('btn-primary');
            }
            else if (style === UIButton.STYLE_LINK) {
                this.btnElem.addClass('btn-link');
            }
            else if (style === UIButton.STYLE_DEFAULT) {
                this.btnElem.addClass('btn-default');
            }
            return this;
        };
        UIButton.prototype.setEnabled = function (enabled) {
            _super.prototype.setEnabled.call(this, enabled);
            if (enabled) {
                this._elem.removeClass('disabled');
            }
            else {
                this._elem.addClass('disabled');
            }
        };
        UIButton.prototype.setLoading = function (enabled) {
            if (enabled) {
                if (!this._preloader) {
                    this._preloader = $('<span class="icon-wb-spinner ico-spin"></span>');
                    this.btnElem.prepend(this._preloader);
                }
                this._preloader.show();
                this.setEnabled(false);
            }
            else {
                if (this._preloader) {
                    this._preloader.hide();
                }
                this.setEnabled(true);
            }
        };
        UIButton.STYLE_SUCCESS = 'success';
        UIButton.STYLE_INFO = 'info';
        UIButton.STYLE_DANGER = 'danger';
        UIButton.STYLE_WARNING = 'warning';
        UIButton.STYLE_PRIMARY = 'primary';
        UIButton.STYLE_DEFAULT = 'default';
        UIButton.STYLE_LINK = 'link';
        UIButton.SIZE_NORMAL = 'normal';
        UIButton.SIZE_LARGE = 'btn-lg';
        UIButton.SIZE_SMALL = 'btn-sm';
        UIButton.SIZE_TINY = 'btn-xs';
        UIButton.TYPE_BUTTON = 'button';
        UIButton.TYPE_SUBMIT = 'submit';
        return UIButton;
    }(UIComponent_3.UIComponent));
    exports.UIButton = UIButton;
});
define("VerticalLayout", ["require", "exports", "UIContainer"], function (require, exports, UIContainer_2) {
    "use strict";
    exports.__esModule = true;
    var VerticalLayout = (function (_super) {
        __extends(VerticalLayout, _super);
        function VerticalLayout(fluid, rowStyleClass) {
            if (fluid === void 0) { fluid = false; }
            if (rowStyleClass === void 0) { rowStyleClass = []; }
            var _this = _super.call(this, (fluid === '%inherit%') ? fluid : 'div') || this;
            _this._spacing = 0;
            _this._childCount = 0;
            if (fluid === '%inherit%')
                return _this;
            _this.addClass('wb-vertical-layout');
            if (fluid)
                _this.addClass('row-fluid');
            _this._rowStyleClass = (rowStyleClass && (typeof rowStyleClass === 'object') && ('length' in rowStyleClass)) ? rowStyleClass : [];
            return _this;
        }
        VerticalLayout.prototype.buildInit = function (data, fields) {
            if (data.fluid)
                this.addClass('row-fluid');
            if (data.rowStyleClass && data.rowStyleClass instanceof Array)
                this._rowStyleClass = data.rowStyleClass;
            if (data.spacing || data.spacing === 0)
                this.setSpacing(data.spacing);
        };
        VerticalLayout.prototype._appendChild = function (child) {
            var div = $('<div>').append(child.getElem());
            if (this._childCount > 0)
                div.css({ marginTop: this._spacing + 'px' });
            this._elem.append(div);
            if (this._childCount >= 0 && this._childCount < this._rowStyleClass.length && this._rowStyleClass[this._childCount]) {
                div.addClass(this._rowStyleClass[this._childCount]);
            }
            this._childCount++;
        };
        VerticalLayout.prototype._detachChild = function (child) {
            var childElem = child.getElem();
            var div = childElem.parent();
            childElem.detach();
            div.remove();
            this._childCount--;
        };
        VerticalLayout.prototype.applyLayoutCellCss = function (idx, css) {
            this._elem.children().eq(idx).css(css);
            return this;
        };
        VerticalLayout.prototype.setSpacing = function (spacing) {
            this._spacing = spacing;
            return this;
        };
        return VerticalLayout;
    }(UIContainer_2.UIContainer));
    exports.VerticalLayout = VerticalLayout;
});
define("Label", ["require", "exports", "UIComponent", "ToolTipControl"], function (require, exports, UIComponent_4, ToolTipControl_1) {
    "use strict";
    exports.__esModule = true;
    var Label = (function (_super) {
        __extends(Label, _super);
        function Label(text) {
            var _this = _super.call(this, (text === '%inherit%') ? text : undefined) || this;
            if (text !== '%inherit%')
                _this.setText(text);
            return _this;
        }
        Label.prototype.buildInit = function (data, fields) {
            if (data.value)
                this.setText(data.value);
            else if (data.text)
                this.setText(data.text);
            else if (data.html)
                this.setHtml(data.html);
            if (data.helpText) {
                this._elem.append((new ToolTipControl_1["default"]('?', data.helpText, (data.helpPlacement ? data.helpPlacement : 'right'))).elem);
            }
        };
        Label.prototype._createElem = function () { return $('<label>'); };
        Label.prototype.setText = function (text) {
            this._elem.text(text);
            return this;
        };
        Label.prototype.getText = function () {
            return this._elem.text();
        };
        Label.prototype.setHtml = function (html) {
            if (typeof html === 'string') {
                this._elem.html(html);
            }
            else {
                this._elem.empty().append(html);
            }
            return this;
        };
        Label.prototype.getHtml = function () {
            return this._elem.html();
        };
        return Label;
    }(UIComponent_4.UIComponent));
    exports.Label = Label;
});
define("CongratsDialog", ["require", "exports", "Dialog", "VerticalLayout", "Label", "UIButton", "Service"], function (require, exports, Dialog_1, VerticalLayout_1, Label_1, UIButton_1, Service_2) {
    "use strict";
    exports.__esModule = true;
    var CongratsDialog = (function (_super) {
        __extends(CongratsDialog, _super);
        function CongratsDialog() {
            var _this = _super.call(this, '', false) || this;
            _this.content.css({ padding: '20px' });
            _this.setTitleVisible(false);
            _this.setFooterVisible(false);
            _this.setSize(500, null);
            _this.setTitle("Congrats Stuff");
            _this.setContent(new Service_2["default"].UIBuilder({
                type: VerticalLayout_1.VerticalLayout,
                css: { textAlign: 'center', marginBottom: '10px' },
                children: [
                    { type: Label_1.Label, text: __('Congratulations, your website is live!'),
                        css: { fontSize: '25px', margin: '20px 0px 30px 0px', textAlign: 'center', cursor: 'default' }
                    },
                    { type: Label_1.Label, text: '', id: 'msgLabel',
                        css: { textAlign: 'center', marginBottom: '30px', color: '#666666', cursor: 'default' }
                    },
                    { type: UIButton_1.UIButton, text: __('View Site'), buttonStyle: UIButton_1.UIButton.STYLE_SUCCESS, click: function () {
                            window.open('http://' + wb_builder.siteDomain, 'wb_builder_prewiew_published');
                        } }
                ]
            }, _this.fields), true);
            _this.content.prepend($('<button>').attr('type', 'button').css({
                position: 'absolute',
                zIndex: 999,
                top: '12px',
                right: '20px'
            }).addClass('close').html('&times;').on('click', function () {
                _this.setVisible(false);
            }));
            return _this;
        }
        CongratsDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (visible) {
                var url = 'http://' + wb_builder.siteDomain, link = '<a href="' + url + '" target="_blank">' + url + '</a>';
                this.fields.msgLabel.setHtml(String(__('Here is your website address: %s')).replace('%s', link));
            }
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        return CongratsDialog;
    }(Dialog_1["default"]));
    exports.CongratsDialog = CongratsDialog;
});
define("PreloaderOverlay", ["require", "exports", "UIComponent"], function (require, exports, UIComponent_5) {
    "use strict";
    exports.__esModule = true;
    var PreloaderOverlay = (function (_super) {
        __extends(PreloaderOverlay, _super);
        function PreloaderOverlay(value, noParentLimit) {
            if (value === void 0) { value = 100; }
            if (noParentLimit === void 0) { noParentLimit = false; }
            var _this = _super.call(this, 'div') || this;
            _this.value = value;
            _this.noParentLimit = noParentLimit;
            _this.parentLimitsRemoved = false;
            _this._elem.addClass('wb-preloader-overlay');
            _this.progressElem = $('<div>')
                .addClass('progress-bar progress-bar-striped active')
                .css({ width: '100%' });
            _this.progressBarElem = $('<div>').addClass('progress')
                .append(_this.progressElem)
                .appendTo(_this._elem);
            return _this;
        }
        PreloaderOverlay.prototype.buildInit = function (data, fields) {
            if (data.value)
                this.setValue(data.value);
            this.noParentLimit = !!data.noParentLimit;
        };
        PreloaderOverlay.prototype.setVisible = function (visible) {
            if (visible && this.noParentLimit && !this.parentLimitsRemoved) {
                this._elem.parent().css({ position: 'static' });
                this.parentLimitsRemoved = true;
            }
            _super.prototype.setVisible.call(this, visible);
            if (visible) {
                var top_1 = Math.round((this._elem.outerHeight(false) - this.progressBarElem.outerHeight(false)) / 2.0);
                if (top_1 > 0) {
                    this.progressBarElem.css({ marginTop: '' + top_1 + 'px' });
                }
            }
            return this;
        };
        PreloaderOverlay.prototype.setValue = function (value) {
            this.value = Math.max(Math.min(value, 100), 0);
            this.progressElem.css({ width: (this.value + '%') });
        };
        PreloaderOverlay.prototype.getValue = function () {
            return this.value;
        };
        return PreloaderOverlay;
    }(UIComponent_5.UIComponent));
    exports.PreloaderOverlay = PreloaderOverlay;
});
define("IFrameControl", ["require", "exports", "UIComponent"], function (require, exports, UIComponent_6) {
    "use strict";
    exports.__esModule = true;
    var IFrameControl = (function (_super) {
        __extends(IFrameControl, _super);
        function IFrameControl(url, params) {
            var _this = _super.call(this, 'iframe') || this;
            _this.parseUrl(url ? url : 'about:blank');
            _this.params = (typeof params === "object") ? params : {};
            _this._elem
                .attr({ 'frameborder': '0', 'src': _this.buildUrl() })
                .css({ width: '200px', height: '200px' });
            return _this;
        }
        IFrameControl.prototype.buildInit = function (data, fields) {
            this.parseUrl(data.url ? data.url : 'about:blank');
            if (data.params && (typeof data.params === 'object'))
                this.params = data.params;
            this._elem.attr('src', this.buildUrl());
        };
        IFrameControl.prototype.parseUrl = function (url) {
            var _url = (url ? (url + "") : "").split("?");
            this.url = _url[0];
            var params = (_url.length > 1) ? _url[1].split("&") : [];
            for (var i = 0; i < params.length; i++) {
                var param = params[i].split("=");
                this.params[param[0]] = (param.length > 1) ? param[1] : "";
            }
        };
        IFrameControl.prototype.buildUrl = function () {
            var url = this.url, params = "";
            for (var k in this.params) {
                params += ((params.length > 0) ? "&" : "") + k + "=" + encodeURIComponent(this.params[k]);
            }
            return url + ((params.length > 0) ? ("?" + params) : "");
        };
        IFrameControl.prototype.setParam = function (name, value) {
            this.params[name] = value;
            this._elem.attr("src", this.buildUrl());
        };
        IFrameControl.prototype.setParams = function (params) {
            this.params = (typeof params === "object") ? params : {};
            this._elem.attr("src", this.buildUrl());
        };
        IFrameControl.prototype.getValue = function () {
            return this.buildUrl();
        };
        IFrameControl.prototype.setValue = function (value, params) {
            if (params === void 0) { params = null; }
            this.url = "";
            this.params = ((typeof params === 'object') && params) ? params : {};
            this.parseUrl(value);
            this._elem.attr("src", this.buildUrl());
        };
        return IFrameControl;
    }(UIComponent_6.UIComponent));
    exports.IFrameControl = IFrameControl;
});
define("RemoteLoginDialog", ["require", "exports", "HorizontalLayout", "UIButton", "AlertBox", "NotificationRibbon", "CongratsDialog", "PreloaderOverlay", "Dialog", "Service", "jquery", "VerticalLayout", "IFrameControl", "Label"], function (require, exports, HorizontalLayout_1, UIButton_2, AlertBox_1, NotificationRibbon_1, CongratsDialog_1, PreloaderOverlay_1, Dialog_2, Service_3, $, VerticalLayout_2, IFrameControl_1, Label_2) {
    "use strict";
    exports.__esModule = true;
    var RemoteLoginDialogType = (function (_super) {
        __extends(RemoteLoginDialogType, _super);
        function RemoteLoginDialogType() {
            var _this = _super.call(this, '%inherit%') || this;
            _this.waitTimer = null;
            _this.onLoadCallback = null;
            return _this;
        }
        RemoteLoginDialogType.prototype.available = function () {
            if (wb_builder.testMode) {
                if (wb_builder.isReseller)
                    return true;
                if (wb_builder.demoConfig && wb_builder.demoConfig.loginRegApiUrl
                    && (wb_builder.demoConfig.useRegForm
                        || wb_builder.demoConfig.useRemoteRegForm
                        || wb_builder.demoConfig.useLoginForm))
                    return true;
            }
            return false;
        };
        RemoteLoginDialogType.prototype.isRegistrationAvailable = function () {
            return (wb_builder.testMode && wb_builder.demoConfig && wb_builder.demoConfig.loginRegApiUrl
                && (wb_builder.demoConfig.useRegForm || wb_builder.demoConfig.useRemoteRegForm));
        };
        RemoteLoginDialogType.prototype.isPlainPublish = function () {
            return (wb_builder.testMode && wb_builder.demoConfig && wb_builder.demoConfig.hidePublishSubMenu);
        };
        RemoteLoginDialogType.prototype.handlePublish = function () {
            var _this = this;
            if (!wb_builder.publishOnLoad)
                return;
            wb_builder.publish(function () { _this.congratsDialog.setVisible(true); });
        };
        RemoteLoginDialogType.prototype.buildBanner = function (bannerImageUrl) {
            var _this = this;
            var image = new Image();
            image.onload = function () {
                var imgElem = $('<div>').append(image)
                    .css({
                    position: 'fixed',
                    zIndex: 9990,
                    cursor: 'pointer',
                    width: image.width + 'px',
                    height: image.height + 'px',
                    marginLeft: (image.width / -2.0) + 'px',
                    bottom: 10,
                    left: '50%'
                })
                    .appendTo(document.body);
                $(image).on('click', function () { if (_this.available())
                    _this.setVisible(true); });
                $('<button>').attr({ type: 'button' })
                    .css({
                    position: 'absolute',
                    zIndex: 9991,
                    color: '#333',
                    opacity: 1,
                    top: 0,
                    right: '4px'
                })
                    .addClass('close')
                    .html('&times;')
                    .on('click', function () { imgElem.remove(); })
                    .appendTo(imgElem);
            };
            image.onerror = function () { console.log("Error loading banner image '" + bannerImageUrl + "'."); };
            image.src = bannerImageUrl;
        };
        RemoteLoginDialogType.prototype.enableWaitTimer = function (enable) {
            var _this = this;
            if (this.waitTimer)
                clearTimeout(this.waitTimer);
            this.fields.iframeAlert.setText('').setVisible(false);
            if (!enable)
                return;
            this.waitTimer = setTimeout(function () {
                $.getJSON(wb_builder.lnBaseUrl + 'create-website/notify-wait', function (data) {
                    if (data.error) {
                        _this.fields.iframeAlert.setText((data.error.message ? data.error.message : data.error)).setVisible(true);
                    }
                    else if (!data.result) {
                        _this.enableWaitTimer(true);
                    }
                    else {
                        wb_builder.testMode = false;
                        if (data.reloadData && data.reloadData.sessUniqKey) {
                            wb_builder.sessUniqKey = data.reloadData.sessUniqKey;
                            wb_builder.siteDomain = data.reloadData.domain;
                            wb_builder.upgradeUrl = data.reloadData.upgradeUrl;
                            wb_builder.formsAllowed = data.reloadData.formsAllowed;
                        }
                        NotificationRibbon_1["default"].setVisible(false);
                        _this.hide();
                        wb_builder.publish(function () { _this.congratsDialog.setVisible(true); });
                    }
                }).fail(function () {
                    _this.fields.iframeAlert.setText(__('Action failed')).setVisible(true);
                });
            }, 5000);
        };
        RemoteLoginDialogType.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            var _this = this;
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
            if (this.fields.iframe && wb_builder.demoConfig) {
                if (visible) {
                    this.fields.preloader.setVisible(true);
                    if (!this.onLoadCallback) {
                        this.fields.iframe.on('load', this.onLoadCallback = function () {
                            _this.fields.preloader.setVisible(false);
                        });
                    }
                    this.fields.iframe.setValue(wb_builder.demoConfig.loginRegApiUrl, {
                        builderApiUrl: wb_builder.lnBaseUrl + 'api/create-website/',
                        loginHash: (wb_builder.demoConfig.loginHash ? wb_builder.demoConfig.loginHash : '')
                    });
                    this.enableWaitTimer(true);
                }
                else {
                    this.enableWaitTimer(false);
                }
            }
        };
        RemoteLoginDialogType.prototype.init = function () {
            var _this = this;
            _super.prototype.__construct.call(this, '', false);
            this.dialog.addClass('wb-remote-login-dialog');
            this.content.css({ padding: '20px' });
            this.setTitleVisible(false);
            this.setFooterVisible(false);
            this.setSize(600, null);
            this.setTitle('Login Stuff');
            var showLoginMode;
            var useRemoteRegForm = wb_builder.demoConfig ? wb_builder.demoConfig.useRemoteRegForm : false;
            var useRegForm = !useRemoteRegForm && (wb_builder.demoConfig ? wb_builder.demoConfig.useRegForm : true);
            var useInline = useRemoteRegForm && (wb_builder.demoConfig ? wb_builder.demoConfig.inlineRemoteForm : false);
            if (useInline)
                useRemoteRegForm = false;
            var useLoginForm = wb_builder.demoConfig ? wb_builder.demoConfig.useLoginForm : true;
            if (wb_builder.demoConfig && !wb_builder.demoConfig.loginRegApiUrl) {
                useRegForm = false;
                useRemoteRegForm = false;
                useInline = false;
                useLoginForm = false;
            }
            var loginRegMsg = wb_builder.demoConfig ? wb_builder.demoConfig.loginRegMsg : null;
            this.setContent(new Service_3["default"].UIBuilder({
                type: VerticalLayout_2.VerticalLayout,
                children: [
                    { type: 'AlertBox', style: AlertBox_1["default"].STYLE_WARNING, html: loginRegMsg,
                        css: { marginTop: 15 },
                        ignore: (loginRegMsg ? false : true)
                    },
                    { type: PreloaderOverlay_1.PreloaderOverlay, id: 'preloader', value: 100, visible: false, noParentLimit: true },
                    { type: HorizontalLayout_1.HorizontalLayout, id: 'hl',
                        children: [
                            { type: VerticalLayout_2.VerticalLayout, spacing: 0, ignore: !useInline, children: [
                                    { type: 'AlertBox', id: 'iframeAlert', style: AlertBox_1["default"].STYLE_DANGER, visible: false, css: { marginBottom: 10 } },
                                    { type: IFrameControl_1.IFrameControl, id: 'iframe', css: { width: '100%', minHeight: '420px', marginTop: '10px' } }
                                ] },
                            { type: VerticalLayout_2.VerticalLayout, spacing: 15, ignore: !useRemoteRegForm, children: [
                                    { type: Label_2.Label, text: __('RemoteRegistrationMessage'),
                                        css: { fontWeight: 'bold', whiteSpace: 'pre-wrap' }
                                    },
                                    { type: UIButton_2.UIButton, id: 'remoteRegisterBtn', text: __('Go to registration'), buttonStyle: UIButton_2.UIButton.STYLE_SUCCESS,
                                        click: function (e, fields) {
                                            fields.remoteRegisterBtn.setEnabled(false);
                                            wb_builder.save(true, function () {
                                                setTimeout(function () {
                                                    wb_builder.goToPage(null, wb_builder.lnBaseUrl + 'create-website/remote-register');
                                                }, 100);
                                            });
                                        }
                                    }
                                ] },
                            { type: VerticalLayout_2.VerticalLayout, id: 'registerForm', spacing: 15, ignore: !useRegForm, children: [
                                    { type: Label_2.Label, text: __('Sign Up'), css: { fontWeight: 'bold' } },
                                    { type: 'AlertBox', id: 'registerAlert', style: AlertBox_1["default"].STYLE_DANGER, visible: false, css: { marginBottom: 10 } },
                                    { type: 'TextField', id: 'rEmail', placeholder: __('E-mail') },
                                    { type: 'TextField', id: 'rName', placeholder: __('Name') },
                                    { type: 'TextField', id: 'rPassword', placeholder: __('Password'), password: true },
                                    { type: 'TextField', id: 'rPassword2', placeholder: __('Confirm password'), password: true },
                                    { type: UIButton_2.UIButton, id: 'registerBtn', text: __('Register'), buttonStyle: UIButton_2.UIButton.STYLE_SUCCESS,
                                        click: function (e, fields) {
                                            fields.registerForm.setEnabled(false);
                                            fields.registerAlert.setText('').setVisible(false);
                                            fields.preloader.setVisible(true);
                                            $.post(wb_builder.lnBaseUrl + 'create-website/', {
                                                register: 1,
                                                email: fields.rEmail.getText(),
                                                name: fields.rName.getText(),
                                                password: fields.rPassword.getText(),
                                                password2: fields.rPassword2.getText()
                                            }, undefined, 'json').done(function (data) {
                                                if (data.error) {
                                                    fields.registerAlert.setText((data.error.message ? data.error.message : data.error)).setVisible(true);
                                                }
                                                else {
                                                    wb_builder.testMode = false;
                                                    if (data.reloadData && data.reloadData.sessUniqKey) {
                                                        wb_builder.sessUniqKey = data.reloadData.sessUniqKey;
                                                        wb_builder.siteDomain = data.reloadData.domain;
                                                        wb_builder.upgradeUrl = data.reloadData.upgradeUrl;
                                                    }
                                                    NotificationRibbon_1["default"].setVisible(false);
                                                    _this.hide();
                                                    wb_builder.publish(function () { _this.congratsDialog.setVisible(true); });
                                                }
                                                fields.registerForm.setEnabled(true);
                                                fields.preloader.setVisible(false);
                                            }).fail(function () {
                                                fields.registerAlert.setText(__('Action failed')).setVisible(true);
                                                fields.registerForm.setEnabled(true);
                                                fields.preloader.setVisible(false);
                                            });
                                        }
                                    }
                                ] },
                            { type: VerticalLayout_2.VerticalLayout, id: 'loginForm', spacing: 15, ignore: !useLoginForm, children: [
                                    { type: Label_2.Label, text: __('Login'), css: { fontWeight: 'bold' } },
                                    { type: 'AlertBox', id: 'loginAlert', style: AlertBox_1["default"].STYLE_DANGER, visible: false, css: { marginBottom: 10 } },
                                    { type: 'AlertBox', id: 'remindAlert', style: AlertBox_1["default"].STYLE_INFO, visible: false, css: { marginBottom: 10 },
                                        text: __('A new password will be sent to the specified e-mail address.')
                                    },
                                    { type: 'TextField', id: 'lEmail', placeholder: __('E-mail') },
                                    { type: 'TextField', id: 'lPassword', placeholder: __('Password'), password: true },
                                    { type: UIButton_2.UIButton, id: 'lRemind', text: __('Remind password'), buttonStyle: UIButton_2.UIButton.STYLE_LINK,
                                        css: { padding: 0 },
                                        click: function (e, fields) {
                                            fields.loginAlert.setVisible(false);
                                            fields.remindAlert.setVisible(true);
                                            fields.lPassword.setVisible(false);
                                            fields.lRemind.setVisible(false);
                                            fields.lLogin.setVisible(true);
                                            fields.loginBtn.setVisible(false);
                                            fields.remindBtn.setVisible(true);
                                        }
                                    },
                                    { type: UIButton_2.UIButton, id: 'lLogin', text: __('Return to login form'), buttonStyle: UIButton_2.UIButton.STYLE_LINK,
                                        css: { padding: 0 },
                                        visible: false,
                                        click: (showLoginMode = function (e, fields) {
                                            fields.loginAlert.setVisible(false);
                                            fields.remindAlert.setVisible(false);
                                            fields.lPassword.setVisible(true);
                                            fields.lRemind.setVisible(true);
                                            fields.lLogin.setVisible(false);
                                            fields.loginBtn.setVisible(true);
                                            fields.remindBtn.setVisible(false);
                                        })
                                    },
                                    { type: UIButton_2.UIButton, id: 'loginBtn', text: __('Login'), buttonStyle: UIButton_2.UIButton.STYLE_SUCCESS,
                                        click: function (e, fields) {
                                            fields.loginForm.setEnabled(false);
                                            fields.loginAlert.setText("").setVisible(false);
                                            fields.preloader.setVisible(true);
                                            $.post(wb_builder.lnBaseUrl + 'create-website/', {
                                                login: 1,
                                                email: fields.lEmail.getText(),
                                                password: fields.lPassword.getText()
                                            }, undefined, 'json').done(function (data) {
                                                if (data.error) {
                                                    fields.loginAlert.setText((data.error.message ? data.error.message : data.error)).setBoxStyle(AlertBox_1["default"].STYLE_DANGER).setVisible(true);
                                                }
                                                else {
                                                    wb_builder.testMode = false;
                                                    if (data.reloadData && data.reloadData.sessUniqKey) {
                                                        wb_builder.sessUniqKey = data.reloadData.sessUniqKey;
                                                        wb_builder.siteDomain = data.reloadData.domain;
                                                        wb_builder.upgradeUrl = data.reloadData.upgradeUrl;
                                                    }
                                                    NotificationRibbon_1["default"].setVisible(false);
                                                    _this.hide();
                                                    wb_builder.publish(function () { _this.congratsDialog.setVisible(true); });
                                                }
                                                fields.loginForm.setEnabled(true);
                                                fields.preloader.setVisible(false);
                                            }).fail(function () {
                                                fields.loginAlert.setText(__('Action failed')).setVisible(true);
                                                fields.loginForm.setEnabled(true);
                                                fields.preloader.setVisible(false);
                                            });
                                        }
                                    },
                                    { type: UIButton_2.UIButton, id: 'remindBtn', text: __('Send Password'), buttonStyle: UIButton_2.UIButton.STYLE_SUCCESS,
                                        visible: false,
                                        click: function (e, fields) {
                                            fields.loginForm.setEnabled(false);
                                            fields.loginAlert.setText("").setVisible(false);
                                            fields.preloader.setVisible(true);
                                            $.post(wb_builder.lnBaseUrl + 'create-website/', {
                                                remind: 1,
                                                email: fields.lEmail.getText()
                                            }, undefined, 'json').done(function (data) {
                                                if (data.error) {
                                                    fields.loginAlert.setText((data.error.message ? data.error.message : data.error)).setBoxStyle(AlertBox_1["default"].STYLE_DANGER).setVisible(true);
                                                }
                                                else {
                                                    showLoginMode(e, fields);
                                                    fields.lPassword.focus();
                                                    fields.loginAlert.setText(__('Password sent')).setBoxStyle(AlertBox_1["default"].STYLE_SUCCESS).setVisible(true);
                                                }
                                                fields.loginForm.setEnabled(true);
                                                fields.preloader.setVisible(false);
                                            }).fail(function () {
                                                fields.loginAlert.setText(__('Action failed')).setVisible(true);
                                                fields.loginForm.setEnabled(true);
                                                fields.preloader.setVisible(false);
                                            });
                                        }
                                    }
                                ] }
                        ]
                    }
                ]
            }, this.fields), true);
            if (useRegForm && useLoginForm) {
                this.fields.hl.applyLayoutCellCss(0, { borderRight: '1px solid #d5d5d5' });
                this.fields.hl.applyLayoutCellCss(1, { borderLeft: '1px solid #d5d5d5', marginLeft: -1 });
            }
            $('<button>').addClass('close').attr({ type: 'button' }).html('&times;')
                .css({ position: 'absolute', top: '12px', right: '20px', zIndex: 99 })
                .on('click', function () { return _this.hide(); })
                .prependTo(this.content);
            this.congratsDialog = new CongratsDialog_1.CongratsDialog();
            if (wb_builder.demoConfig && wb_builder.demoConfig.bannerImageUrl) {
                this.buildBanner(wb_builder.demoConfig.bannerImageUrl);
            }
        };
        return RemoteLoginDialogType;
    }(Dialog_2["default"]));
    exports.RemoteLoginDialogType = RemoteLoginDialogType;
    var RemoteLoginDialog = new RemoteLoginDialogType();
    Service_3["default"].RemoteLoginDialog = RemoteLoginDialog;
    exports["default"] = RemoteLoginDialog;
});
define("NotificationRibbon", ["require", "exports", "Service", "BuilderEvent"], function (require, exports, Service_4, BuilderEvent_2) {
    "use strict";
    exports.__esModule = true;
    var NotificationRibbonType = (function () {
        function NotificationRibbonType() {
            this.text = '';
            this.isHtml = false;
        }
        NotificationRibbonType.prototype.init = function (builder) { this.builder = builder; };
        NotificationRibbonType.prototype.defaulMessages = function () {
            if (this.builder.testMode && !this.builder.devTestMode && !this.builder.websiteImportStatus) {
                var text = __('This is Demo version. Everything created with it will be reset after 24 hours.');
                var rld_1 = Service_4["default"].RemoteLoginDialog;
                if (rld_1.isRegistrationAvailable()) {
                    text += ' <a href="javascript:void(0)" class="wb-reg-link">' + __('To save your site, use Publish button.') + '</a>';
                    var elem = $('<span>').html(text);
                    elem.find('a[class=wb-reg-link]').on('click', function () { rld_1.setVisible(true); });
                    this.setText(elem, true);
                }
                else {
                    this.setText(text);
                }
            }
        };
        NotificationRibbonType.prototype.setVisible = function (visible) {
            if (visible && this.text) {
                BuilderEvent_2.GlobalEvents.triggerEvent('notification.changed', new BuilderEvent_2.NotificationEvent(this.text, this.isHtml));
            }
            else {
                BuilderEvent_2.GlobalEvents.triggerEvent('notification.changed', new BuilderEvent_2.NotificationEvent('', false));
            }
        };
        NotificationRibbonType.prototype.setText = function (text, asHtml) {
            if (asHtml === void 0) { asHtml = false; }
            this.text = text;
            this.isHtml = asHtml;
            BuilderEvent_2.GlobalEvents.triggerEvent('notification.changed', new BuilderEvent_2.NotificationEvent(text, asHtml));
        };
        NotificationRibbonType.prototype.getText = function () {
            return this.text;
        };
        return NotificationRibbonType;
    }());
    var NotificationRibbon = new NotificationRibbonType();
    exports["default"] = NotificationRibbon;
});
define("HelpSystem/Scenario", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    function applyBounds(subject, forceBounds) {
        if (!forceBounds || typeof forceBounds !== 'object')
            return;
        if ('width' in forceBounds) {
            subject.setSize(forceBounds.width, null);
            if (subject.getClassType() == 'Picture') {
                if (subject.crop)
                    subject.crop.width = forceBounds.width;
            }
        }
        if ('height' in forceBounds) {
            subject.setSize(null, forceBounds.height);
            if (subject.getClassType() == 'Picture') {
                if (subject.crop)
                    subject.crop.height = forceBounds.height;
            }
        }
        if ('left' in forceBounds) {
            var left = 0;
            if (typeof forceBounds.left === 'string') {
                var pWidth = subject.getParent().getWidth();
                var width = forceBounds.refWidth ? forceBounds.refWidth : subject.getWidth();
                if (forceBounds.left === 'left') {
                    left = 0;
                }
                else if (forceBounds.left === 'right') {
                    left = pWidth - width;
                }
                else if (forceBounds.left === 'center' || forceBounds.left === 'middle') {
                    left = (pWidth - width) / 2;
                }
            }
            else {
                left = forceBounds.left;
            }
            subject.setLocation(left, null);
        }
        if ('top' in forceBounds) {
            var top_2 = 0;
            if (typeof forceBounds.top === 'string') {
                var pHeight = subject.getParent().getHeight();
                if (forceBounds.top === 'top') {
                    top_2 = 0;
                }
                else if (forceBounds.top === 'bottom') {
                    top_2 = pHeight - subject.getHeight();
                }
                else if (forceBounds.top === 'middle' || forceBounds.top === 'center') {
                    top_2 = (pHeight - subject.getHeight()) / 2;
                }
            }
            else {
                top_2 = forceBounds.top;
            }
            subject.setLocation(null, top_2);
        }
        subject.onResize();
    }
    exports.applyBounds = applyBounds;
    var BoundableElement = (function () {
        function BoundableElement(type, parent, position, toPageRelative) {
            if (position === void 0) { position = null; }
            if (toPageRelative === void 0) { toPageRelative = false; }
            this.type = type;
            this.parent = parent;
            this.left = 0;
            this.top = 0;
            this.width = 0;
            this.height = 0;
            if (position) {
                if (typeof position.left === 'number')
                    this.left = position.left;
                if (typeof position.top === 'number')
                    this.top = position.top;
            }
            if (toPageRelative)
                this.makePageRelative();
        }
        BoundableElement.prototype.getClassType = function () { return this.type; };
        BoundableElement.prototype.setSize = function (width, height) {
            if (width === void 0) { width = null; }
            if (height === void 0) { height = null; }
            if (width !== null)
                this.width = width;
            if (height !== null)
                this.height = height;
        };
        BoundableElement.prototype.setLocation = function (left, top) {
            if (left === void 0) { left = null; }
            if (top === void 0) { top = null; }
            if (left !== null)
                this.left = left;
            if (top !== null)
                this.top = top;
        };
        BoundableElement.prototype.onResize = function () { };
        BoundableElement.prototype.getWidth = function () { return this.width; };
        BoundableElement.prototype.getHeight = function () { return this.height; };
        BoundableElement.prototype.getParent = function () { return this.parent; };
        BoundableElement.prototype.makePageRelative = function () {
            var off = this.getParent().container.offset();
            this.left += off.left;
            this.top += off.top;
        };
        return BoundableElement;
    }());
    exports.BoundableElement = BoundableElement;
    var ForceBounds = (function () {
        function ForceBounds() {
        }
        return ForceBounds;
    }());
    exports.ForceBounds = ForceBounds;
    var ScenarioStep = (function () {
        function ScenarioStep() {
        }
        return ScenarioStep;
    }());
    exports.ScenarioStep = ScenarioStep;
    var Scenario = (function () {
        function Scenario() {
        }
        return Scenario;
    }());
    exports.Scenario = Scenario;
});
define("ButtonGroup", ["require", "exports", "UIContainer"], function (require, exports, UIContainer_3) {
    "use strict";
    exports.__esModule = true;
    var ButtonGroup = (function (_super) {
        __extends(ButtonGroup, _super);
        function ButtonGroup() {
            var _this = _super.call(this) || this;
            _this.addClass('btn-group');
            _this._elem.attr({ role: 'group' });
            return _this;
        }
        ButtonGroup.prototype.buildInit = function (data, fields) { };
        return ButtonGroup;
    }(UIContainer_3.UIContainer));
    exports.ButtonGroup = ButtonGroup;
});
define("FlowLayout", ["require", "exports", "UIContainer"], function (require, exports, UIContainer_4) {
    "use strict";
    exports.__esModule = true;
    var FlowLayout = (function (_super) {
        __extends(FlowLayout, _super);
        function FlowLayout(inh) {
            var _this = _super.call(this, (inh === '%inherit%') ? inh : 'div') || this;
            _this.spacing = 0;
            _this.horizontalAlign = 'left';
            _this.verticalAlign = 'bottom';
            if (inh === '%inherit%')
                return _this;
            return _this;
        }
        FlowLayout.prototype.buildInit = function (data, fields) {
            if (data.spacing || data.spacing === 0) {
                this.setSpacing(data.spacing);
            }
            else {
                this.setSpacing(10);
            }
            if (data.align) {
                this.setHorizontalAlign(data.align);
            }
            if (data.verticalAlign) {
                this.setVerticalAlign(data.verticalAlign);
            }
            else {
                this.setVerticalAlign('top');
            }
        };
        FlowLayout.prototype._appendChild = function (child) {
            var div = $('<div>').css({ display: 'inline-block', verticalAlign: this.verticalAlign }).append(child.getElem());
            div.addClass('wb-horiz-lay-item');
            this._elem.append(div);
            this.setSpacing(this.spacing);
        };
        FlowLayout.prototype._detachChild = function (child) {
            var childElem = child.getElem(), div = childElem.parent();
            childElem.detach();
            div.remove();
        };
        FlowLayout.prototype.applyLayoutCellCss = function (idx, css) {
            this._elem.children().eq(idx).css(css);
            return this;
        };
        FlowLayout.prototype.setSpacing = function (spacing) {
            this.spacing = spacing;
            var css = {};
            if (wb_builder.rtl) {
                css.marginLeft = (spacing + 'px');
                this._elem.children(':not(:first-child)').css(css);
            }
            else {
                css.marginRight = (spacing + 'px');
                this._elem.children(':not(:last-child)').css(css);
            }
            return this;
        };
        FlowLayout.prototype.setHorizontalAlign = function (horizontalAlign) {
            this.horizontalAlign = horizontalAlign;
            this._elem.css({ textAlign: horizontalAlign });
        };
        FlowLayout.prototype.setVerticalAlign = function (verticalAlign) {
            this.verticalAlign = verticalAlign;
            this._elem.children().css({ verticalAlign: verticalAlign });
        };
        return FlowLayout;
    }(UIContainer_4.UIContainer));
    exports.FlowLayout = FlowLayout;
});
define("HelpSystem/PlayerControls", ["require", "exports", "UIContainer", "UIButton", "Service", "ButtonGroup", "FlowLayout"], function (require, exports, UIContainer_5, UIButton_3, Service_5, ButtonGroup_1, FlowLayout_1) {
    "use strict";
    exports.__esModule = true;
    var SpeedSelectorFields = (function () {
        function SpeedSelectorFields() {
        }
        return SpeedSelectorFields;
    }());
    var SpeedSelector = (function (_super) {
        __extends(SpeedSelector, _super);
        function SpeedSelector() {
            var _this = _super.call(this) || this;
            _this.fields = new SpeedSelectorFields();
            _this.baseSpeed = 3;
            _this.onSpeedChange = null;
            Service_5["default"].UIBuilder.buildLayout([
                { type: ButtonGroup_1.ButtonGroup, children: [
                        { type: UIButton_3.UIButton, id: 'val', borderless: true, text: '1.0x',
                            buttonSize: UIButton_3.UIButton.SIZE_SMALL,
                            menuWidth: 80, menuUp: [
                                { name: '0.25x', click: function () { _this.applySpeed(0, 0.25); } },
                                { name: '0.5x', click: function () { _this.applySpeed(0, 0.50); } },
                                { name: '1.0x', click: function () { _this.applySpeed(0, 1.00); } },
                                { name: '1.5x', click: function () { _this.applySpeed(0, 1.50); } },
                                { name: '2.0x', click: function () { _this.applySpeed(0, 2.00); } }
                            ]
                        }
                    ] }
            ], _this, _this.fields);
            return _this;
        }
        SpeedSelector.prototype.buildInit = function (data, fields) {
            _super.prototype.buildInit.call(this, data, fields);
            if (('baseSpeed' in data) && data.baseSpeed) {
                var val = data.baseSpeed * 1;
                if (val > 0 && !isNaN(val))
                    this.baseSpeed = val;
            }
            if (('change' in data) && typeof data.change === 'function') {
                this.onSpeedChange = data.change;
            }
        };
        SpeedSelector.prototype.applySpeed = function (speed, pSpeed) {
            if (pSpeed === void 0) { pSpeed = 0; }
            var speedVal = Math.ceil((speed > 0) ? speed : (this.baseSpeed * pSpeed));
            var maxSpeed = Math.ceil(this.baseSpeed * 1.75);
            if (pSpeed === 0)
                pSpeed = speedVal / this.baseSpeed;
            this.fields.val.setText(pSpeed + ((pSpeed === 1 || pSpeed === 2) ? '.0' : '') + 'x');
            if (this.onSpeedChange)
                this.onSpeedChange(speedVal, maxSpeed);
        };
        return SpeedSelector;
    }(FlowLayout_1.FlowLayout));
    var PlayerControlsFields = (function () {
        function PlayerControlsFields() {
        }
        return PlayerControlsFields;
    }());
    var PlayerControls = (function (_super) {
        __extends(PlayerControls, _super);
        function PlayerControls(onClose) {
            var _this = _super.call(this) || this;
            _this.onClose = onClose;
            _this.fields = new PlayerControlsFields();
            _this.closeTimeout = 0;
            _this.addClass('wb-hlp-player-controls');
            return _this;
        }
        PlayerControls.prototype.setStep = function (pos, total) {
            this.fields.label.setText(pos + ' of ' + total);
        };
        PlayerControls.prototype.setSpeed = function (speed) {
            this.fields.speedGroup.applySpeed(speed);
        };
        PlayerControls.prototype.setEndState = function (endState, autoClose) {
            var _this = this;
            if (autoClose === void 0) { autoClose = false; }
            if (this.closeTimeout)
                clearTimeout(this.closeTimeout);
            if (endState) {
                this.fields.playBtn.setVisible(false);
                this.fields.nextBtn.setVisible(false);
                this.fields.closeBtn.setVisible(true);
                this.fields.label.setVisible(false);
                this.fields.speedLabel.setVisible(false);
                this.fields.speedGroup.setVisible(false);
                this.fields.speedGroupSep.setVisible(false);
                if (autoClose)
                    this.closeTimeout = setTimeout(function () { return _this.onClose(); }, 3000);
            }
            else {
                this.fields.playBtn.setVisible(true);
                this.fields.nextBtn.setVisible(true);
                this.fields.closeBtn.setVisible(true);
                this.fields.label.setVisible(true);
                this.fields.speedLabel.setVisible(true);
                this.fields.speedGroup.setVisible(true);
                this.fields.speedGroupSep.setVisible(true);
            }
            this.css({ marginLeft: -this.getElem().outerWidth() / 2.0 });
        };
        PlayerControls.prototype.getFields = function () {
            return this.fields;
        };
        PlayerControls.init = function (onPlay, onNext, onClose, onSpeedChange) {
            var ins = new PlayerControls(onClose);
            ins.onSpeedChange = onSpeedChange;
            Service_5["default"].UIBuilder.buildLayout({ type: 'FlowLayout',
                verticalAlign: 'middle',
                spacing: 0,
                children: [
                    { type: 'Button', text: '', attr: { title: __('Play') },
                        buttonSize: UIButton_3.UIButton.SIZE_SMALL,
                        icon: 'fa fa-pause', borderless: true, id: 'playBtn', click: onPlay
                    },
                    { type: 'Button', text: '', attr: { title: __('Next') },
                        buttonSize: UIButton_3.UIButton.SIZE_SMALL,
                        icon: 'fa fa-step-forward', borderless: true, id: 'nextBtn', click: onNext,
                        css: { marginLeft: 10, marginRight: 10 }
                    },
                    { type: 'Label', text: '0/0', id: 'label', css: {
                            paddingLeft: 15, marginBottom: 2, borderLeft: '1px solid #ccc'
                        } },
                    { type: 'Label', text: __('Speed'), id: 'speedLabel',
                        css: {
                            marginLeft: 15, marginRight: 10, marginBottom: 2, paddingLeft: '15px', fontWeight: 'normal',
                            borderLeft: '1px solid #ccc'
                        }
                    },
                    { type: SpeedSelector, id: 'speedGroup', change: onSpeedChange },
                    { type: 'Label', html: '&nbsp;', id: 'speedGroupSep', css: {
                            marginBottom: 2, paddingLeft: '6px', borderLeft: '1px solid #ccc'
                        } },
                    { type: 'Button', text: '', attr: { title: __('Close') },
                        buttonSize: UIButton_3.UIButton.SIZE_SMALL,
                        icon: 'fa fa-times', borderless: true, id: 'closeBtn', click: onClose
                    }
                ]
            }, ins, ins.fields);
            ins.css({
                position: 'fixed', zIndex: 99999, bottom: 10, left: '50%',
                background: '#fff',
                border: '1px solid #ccc',
                padding: 5
            });
            return ins;
        };
        return PlayerControls;
    }(UIContainer_5.UIContainer));
    exports.PlayerControls = PlayerControls;
});
define("HelpSystem/Tooltip", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var ScenarioStepSubject = (function () {
        function ScenarioStepSubject(elem, tipPlacement, topOffset, leftOffset, absolute, absoluteScroll) {
            if (tipPlacement === void 0) { tipPlacement = null; }
            if (topOffset === void 0) { topOffset = 0; }
            if (leftOffset === void 0) { leftOffset = 0; }
            if (absolute === void 0) { absolute = false; }
            if (absoluteScroll === void 0) { absoluteScroll = false; }
            this.elem = elem;
            this.tipPlacement = tipPlacement;
            this.topOffset = topOffset;
            this.leftOffset = leftOffset;
            this.absolute = absolute;
            this.absoluteScroll = absoluteScroll;
            var elemType = elem ? ('' + elem[0].tagName).toLowerCase() : '';
            if (elemType === 'input' || elemType === 'textarea' || elemType === 'select' || elemType === 'button' || elemType === 'table') {
                this.absolute = true;
                this.absoluteScroll = true;
            }
        }
        ScenarioStepSubject.prototype.calcSize = function () { return ScenarioStepSubject.calcActualSize(this); };
        ScenarioStepSubject.calcActualSize = function (element) {
            var elem = (element instanceof ScenarioStepSubject) ? element.elem : element;
            var width = elem.outerWidth(true);
            var height = elem.outerHeight(true);
            var chlist, cWidth = 0;
            if (elem.hasClass('wb-vertical-layout')) {
                chlist = elem.children('.wb-horiz-lay-item');
                cWidth = 0;
                for (var i = 0, c = chlist.length; i < c; i++) {
                    var w = ScenarioStepSubject.calcActualSize(chlist.eq(i)).width;
                    if (w > 0 && (cWidth == 0 || w < cWidth))
                        cWidth = w;
                }
            }
            else if ((chlist = elem.children('.wb-horiz-lay-item')).length > 0) {
                cWidth = 0;
                for (var i = 0, c = chlist.length; i < c; i++) {
                    cWidth += ScenarioStepSubject.calcActualSize(chlist.eq(i)).width;
                }
            }
            else if ((chlist = elem.eq(0).children(':not(.wb-hlp-ttip)')).length === 1) {
                var el = chlist.first();
                if (el.hasClass('wb-vertical-layout'))
                    return ScenarioStepSubject.calcActualSize(el);
                cWidth = el.outerWidth(true);
            }
            if (cWidth > 0 && cWidth < width)
                width = cWidth;
            return { width: width, height: height };
        };
        return ScenarioStepSubject;
    }());
    exports.ScenarioStepSubject = ScenarioStepSubject;
    var Tooltip = (function () {
        function Tooltip(step, subject, onClose) {
            if (onClose === void 0) { onClose = null; }
            this.subject = subject;
            this.title = step.title;
            this.text = step.text;
            this.el = $('<div class="wb-hlp-ttip"><div class="wb-hlp-ttip-tip"><div></div></div></div>');
            var o = subject.elem.offset();
            var align = step.placement ? step.placement : (subject.tipPlacement ? subject.tipPlacement : '');
            if (align)
                this.el.addClass('wb-hlp-ttip-' + align);
            this.el.css({
                whiteSpace: 'normal',
                textTransform: 'none',
                opacity: 0.9,
                position: (subject.absolute ? 'fixed' : 'absolute')
            });
            if (typeof onClose === 'function') {
                this.el.append($('<div class="close">&times;</div>').on('click', onClose));
            }
            if (step.title)
                this.el.append($('<div class="wb-hlp-ttip-title">' + step.title + '</div>').css({ whiteSpace: 'nowrap' }));
            if (step.text)
                this.el.append(this.formatText(step.text));
            var vOffset = 0;
            if (!step.text && (align === 'left' || align === 'right')) {
                this.el.find('.wb-hlp-ttip-tip').css({ top: '93%' });
                vOffset = 0;
            }
            else {
                this.el.find('.wb-hlp-ttip-tip').css({ top: '' });
                vOffset = 20;
            }
            if (subject.absolute) {
                $(document.body).append(this.el);
            }
            else {
                subject.elem.append(this.el);
                if (subject.elem.is('li')) {
                    subject.elem.css({ position: 'relative' });
                }
                var elRaw_1 = subject.elem[0];
                if ((elRaw_1.className + '').indexOf('wb_move_btn') >= 0 || (elRaw_1.className + '').indexOf('wb_edit_btn') >= 0) {
                    elRaw_1 = elRaw_1.parentNode;
                }
                if (('scrollIntoView' in elRaw_1) && typeof elRaw_1.scrollIntoView === 'function') {
                    if (!step.subject || !step.subject.match(/^toolbar\-plugin\-.+$/)) {
                        setTimeout(function () { elRaw_1.scrollIntoView(false); }, 40);
                    }
                }
            }
            var px = subject.absolute ? (o.left - (subject.absoluteScroll ? $(document).scrollLeft() : 0)) : 0;
            var py = subject.absolute ? (o.top - (subject.absoluteScroll ? $(document).scrollTop() : 0)) : 0;
            var sSize = subject.calcSize();
            if (align === 'left') {
                o.top = py + sSize.height / 2 - this.el.outerHeight(true) / 2 + vOffset;
                o.left = px - this.el.outerWidth(true) + subject.leftOffset;
            }
            else if (align === 'right') {
                o.top = py + sSize.height / 2 - this.el.outerHeight(true) / 2 + vOffset;
                o.left = px + sSize.width + 7 + subject.leftOffset;
            }
            else if (align === 'top') {
                o.top = py - this.el.outerHeight(true) + subject.topOffset;
                o.left = px + ((sSize.width - this.el.outerWidth(true)) / 2);
            }
            else {
                o.top = py + sSize.height + subject.topOffset;
                o.left = px + ((sSize.width - this.el.outerWidth(true)) / 2);
            }
            this.el.css({ left: o.left, top: o.top });
        }
        Tooltip.prototype.formatText = function (text) {
            var fText = text.replace(/\*([^\*]+)\*/g, "<b>$1</b>");
            return fText;
        };
        return Tooltip;
    }());
    exports.Tooltip = Tooltip;
});
define("HelpSystem/PlayerCanvas", ["require", "exports", "Content"], function (require, exports, Content_1) {
    "use strict";
    exports.__esModule = true;
    var PlayerCanvas = (function (_super) {
        __extends(PlayerCanvas, _super);
        function PlayerCanvas(more) {
            if (more === void 0) { more = false; }
            var _this = _super.call(this, {}, $('<div>')) || this;
            _this.id = 'canvas';
            _this.isFlexible = false;
            _this.elem.css({
                position: 'absolute',
                zIndex: 2001,
                top: 0,
                left: 0,
                width: '100%',
                height: wb_builder.bodyInstance.site.height(),
                backgroundColor: (more ? '#ffffff' : 'rgba(0, 0, 0, 0.80)')
            }).attr({ id: 'site' });
            _this.elem.appendTo(wb_builder.bodyInstance.elem);
            return _this;
        }
        PlayerCanvas.prototype.dispose = function () {
            this.elem.remove();
        };
        return PlayerCanvas;
    }(Content_1["default"]));
    exports.PlayerCanvas = PlayerCanvas;
});
define("Confirm", ["require", "exports", "Dialog", "UserInput"], function (require, exports, Dialog_3, UserInput_1) {
    "use strict";
    exports.__esModule = true;
    var Confirm = (function () {
        function Confirm() {
        }
        Confirm.showPopover = function (title, message, buttons, width, parent, placement) {
            if (placement === void 0) { placement = ''; }
            if (!Confirm.hasHotkey) {
                Confirm.hasHotkey = function () {
                    if (Confirm.popover) {
                        Confirm.popover.popover('hide');
                        Confirm.popover.popover('destroy');
                    }
                };
                UserInput_1.UserInput.addHotKey('esc', Confirm.hasHotkey);
            }
            if (Confirm.popover) {
                Confirm.popover.popover('hide');
                Confirm.popover.popover('destroy');
            }
            if (!buttons)
                buttons = [{ title: __('OK') }];
            if (!placement)
                placement = 'bottom';
            var panel = $('<div>');
            panel.css({ textAlign: 'center' });
            var msg = null;
            panel.append(msg = $('<div>').css({ textAlign: 'left', marginBottom: '20px' }));
            msg.html(message.split("\n").join('<br />'));
            var buttonPanel = $('<div>').addClass('clearfix');
            panel.append(buttonPanel);
            var _loop_2 = function (i) {
                var cfg = buttons[i];
                var btn = $('<button>').addClass('btn');
                if (cfg.cssClass)
                    btn.addClass(cfg.cssClass);
                btn.html(cfg.title ? cfg.title : __('Untitled'));
                if (i > 0)
                    btn.css({ marginLeft: '10px' });
                (function (func, validateFunc) {
                    btn.on('click', function () {
                        if ((typeof validateFunc === 'function') && !validateFunc())
                            return;
                        if (Confirm.popover)
                            Confirm.popover.popover('hide');
                        if (typeof func === 'function')
                            func();
                        panel.empty();
                        if (Confirm.popover)
                            Confirm.popover.popover('destroy');
                        Confirm.popover = null;
                    });
                })(cfg.func, cfg.validateFunc);
                buttonPanel.append(btn);
            };
            for (var i = 0; i < buttons.length; i++) {
                _loop_2(i);
            }
            Confirm.popover = parent;
            Confirm.popover.popover({
                html: true,
                title: title,
                content: function () { return panel; },
                trigger: 'manual',
                placement: placement
            });
            Confirm.popover.popover('show');
            if (width && !isNaN(width * 1))
                parent.next('.popover').width(width * 1);
        };
        ;
        Confirm.showDialog = function (title, message, buttons, width) {
            if (!Confirm.hasHotkey) {
                Confirm.hasHotkey = function () { if (Confirm.dialog)
                    Confirm.dialog.hide(); };
                UserInput_1.UserInput.addHotKey('esc', Confirm.hasHotkey);
            }
            if (Confirm.dialog) {
                Confirm.dialog.hide();
            }
            else {
                Confirm.dialog = new Dialog_3["default"]();
                Confirm.dialog.fields.panel = $('<div></div>');
                Confirm.dialog.setContent(Confirm.dialog.fields.panel);
            }
            Confirm.dialog.setCenterButtons(false);
            if (!buttons)
                buttons = [{ title: __('OK') }];
            Confirm.dialog.setTitle(title);
            Confirm.dialog.fields.panel.empty();
            var msg = (typeof message === 'string') ? message.split("\n").join('<br />') : message;
            Confirm.dialog.fields.panel.append(msg);
            Confirm.dialog.removeAllButtons();
            var _loop_3 = function (i) {
                var cfg = buttons[i];
                (function (func, validateFunc) {
                    Confirm.dialog.addButton((cfg.title ? cfg.title : __('Untitled')), function () {
                        if ((typeof validateFunc === 'function') && !validateFunc())
                            return;
                        if (Confirm.dialog)
                            Confirm.dialog.hide();
                        if (typeof func === 'function')
                            func();
                    }, undefined, cfg.cssClass);
                })(cfg.func, cfg.validateFunc);
            };
            for (var i = 0; i < buttons.length; i++) {
                _loop_3(i);
            }
            if (width && !isNaN(width * 1))
                Confirm.dialog.setSize(width * 1);
            Confirm.dialog.show();
        };
        ;
        Confirm.popover = null;
        Confirm.dialog = null;
        Confirm.hasHotkey = null;
        return Confirm;
    }());
    exports["default"] = Confirm;
});
define("MenuConfirmDialog", ["require", "exports", "Confirm"], function (require, exports, Confirm_1) {
    "use strict";
    exports.__esModule = true;
    function confirmDelete(onConfirm) {
        Confirm_1["default"].showDialog(__("Delete menu"), $('<div class="wb_change_template_dlg">' +
            '<div class="qq">' + __("Are you sure you want to delete this menu?") + '</div>' +
            '<div class="red">' + __("Once deleted all pages this menu links to will also be deleted.") + '</div>' +
            '</div>'), [
            {
                title: __("No, keep current menu")
            },
            {
                title: __("Yes, delete menu"),
                cssClass: "btn-danger",
                func: onConfirm
            }
        ], 480);
        if (Confirm_1["default"].dialog)
            Confirm_1["default"].dialog.setCenterButtons(true);
    }
    exports.confirmDelete = confirmDelete;
});
define("HelpSystem/ScenarioBuilder", ["require", "exports", "HelpSystem/Scenario"], function (require, exports, Scenario_1) {
    "use strict";
    exports.__esModule = true;
    var dict = {};
    var lastBuilder = null;
    var USE_VARIATION = false;
    function init(builder) {
        lastBuilder = builder;
        $.getJSON(builder.lnBaseUrl + 'scenario/dict').then(function (res) { if (res && (typeof res === 'object'))
            dict = res; }, function () { return console.log('Error loading scenario dictionary.'); });
    }
    exports.init = init;
    function buildFromCurrent(builder, useOverlay) {
        if (useOverlay === void 0) { useOverlay = true; }
        var scenario = new Scenario_1.Scenario();
        scenario.baseUrl = 'scenarios/';
        scenario.name = __('Current Template');
        scenario.requireSpace = 600;
        scenario.steps = [
            {
                title: "Lets create site",
                text: "Lets create site",
                subject: "toolbar-ctrl-change"
            }
        ];
        var requirement = null;
        requirement = buildBackgroundSteps(scenario, builder);
        var elements = builder.bodyInstance.getContentElements();
        elements.sort(function (e1, e2) {
            var p1 = getOffset(e1, true), p2 = getOffset(e2, true);
            var l1 = e1.getLocation(), l2 = e2.getLocation();
            if ((l1.top + p1.top) == (l2.top + p2.top)) {
                if (e1.getZIndex() == e2.getZIndex())
                    return 0;
                return ((e1.getZIndex() > e2.getZIndex()) ? 1 : -1);
            }
            return (((l1.top + p1.top) > (l2.top + p2.top)) ? 1 : -1);
        });
        for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
            var elem = elements_1[_i];
            var classType = elem.getClassType();
            if (classType === 'LinkExchangeBadge')
                continue;
            var step = buildCreateStep(scenario, classType, elem, requirement, useOverlay);
            requirement = null;
            if (classType === 'Picture') {
                requirement = buildPictureSteps(scenario, step, classType, elem);
            }
            else if (classType === 'Menu') {
                requirement = buildMenuSteps(scenario, step, classType, elem);
            }
            else if (classType === 'TextArea') {
                requirement = buildTextSteps(scenario, step, classType, elem);
            }
            else if (classType === 'Line') {
                requirement = buildLineSteps(scenario, step, classType, elem);
            }
            else if (classType === 'Shape') {
                requirement = buildShapeSteps(scenario, step, classType, elem);
            }
            else if (classType === 'Button') {
                requirement = buildButtonSteps(scenario, step, classType, elem);
            }
            else if (classType === 'GoogleMaps') {
                requirement = buildMapsSteps(scenario, step, classType, elem);
            }
            buildResizeStep(scenario, classType, elem, requirement, useOverlay);
            requirement = null;
        }
        return scenario;
    }
    exports.buildFromCurrent = buildFromCurrent;
    function buildBackgroundSteps(scenario, builder) {
        scenario.steps.push({
            title: ((dict.Click && dict.Click.title) ? dict.Click.title : __('Click')),
            text: ((dict.Click && dict.Click.text) ? dict.Click.text : ''),
            subject: 'toolbar-ctrl-config',
            objectives: ['toolbar-ctrl-config-click']
        });
        scenario.steps.push({
            title: ((dict.Click && dict.Click.title) ? dict.Click.title : __('Click')),
            text: ((dict.Click && dict.Click.text) ? dict.Click.text : ''),
            subject: 'toolbar-ctrl-config-background',
            objectives: ['config-background-open']
        });
        var bg, p = builder.site.getPage(builder.pageId);
        if (p && p.background && ((p.background.image && p.background.image !== 'none') ||
            (p.background.color && p.background.color !== 'transparent'))) {
            bg = p.background;
        }
        else {
            bg = builder.bodyInstance.bgSite;
        }
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            requirements: ['timeout:500'],
            subject: 'config-background-prop-bgPage',
            defaultContent: { value: bg },
            objectives: ['config-background-prop-bgPage-change']
        });
        scenario.steps.push({
            title: ((dict.Apply && dict.Apply.title) ? dict.Apply.title : __('Apply')),
            text: ((dict.Apply && dict.Apply.text) ? dict.Apply.text : ''),
            audio: ((dict.Apply && dict.Apply.audio) ? dict.Apply.audio : ''),
            subject: 'config-background-prop-apply',
            objectives: ['config-background-apply']
        });
        return null;
    }
    function buildMenuSteps(scenario, step, classType, elem) {
        var rawElem = elem, newMode = true;
        var editStep = {
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '-edit-btn[0]',
            objectives: ['item-plugin-' + classType + '-menu-edit']
        };
        if (!newMode)
            scenario.steps.push(editStep);
        var cc = 0, numItems = newMode ? 0 : 2;
        for (var itemKey in rawElem.items) {
            var item = rawElem.items[itemKey];
            if (cc < numItems) {
                scenario.steps.push({
                    title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
                    text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
                    audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
                    requirements: ['timeout:500'],
                    subject: 'item-plugin-' + classType + '-menu-edit-select:' + cc,
                    objectives: ['item-plugin-' + classType + '-menu-edit-select:' + cc]
                });
                scenario.steps.push({
                    title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
                    text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
                    audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
                    requirements: ['timeout:500'],
                    subject: 'item-plugin-' + classType + '-menu-edit-fldName[0]',
                    defaultContent: { 'value': item.name },
                    objectives: ['item-plugin-' + classType + '-menu-edit-fldName-change']
                });
            }
            else {
                if (cc == 1 && newMode)
                    scenario.steps.push(editStep);
                if (cc > 0 || !newMode) {
                    scenario.steps.push({
                        title: ((dict.Click && dict.Click.title) ? dict.Click.title : __('Click')),
                        text: ((dict.Click && dict.Click.text) ? dict.Click.text : ''),
                        requirements: ['timeout:500'],
                        subject: 'item-plugin-' + classType + '-menu-edit-newItemButton[0]',
                        objectives: ['item-plugin-' + classType + '-menu-edit-newItemButton-click']
                    });
                }
                scenario.steps.push({
                    title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
                    text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
                    audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
                    requirements: ['timeout:500'],
                    subject: 'item-plugin-' + classType + '-menu-new-fldName[0]',
                    defaultContent: { 'value': item.name },
                    objectives: ['item-plugin-' + classType + '-menu-new-fldName-change']
                });
                scenario.steps.push({
                    title: ((dict.Apply && dict.Apply.title) ? dict.Apply.title : __('Apply')),
                    text: ((dict.Apply && dict.Apply.text) ? dict.Apply.text : ''),
                    audio: ((dict.Apply && dict.Apply.audio) ? dict.Apply.audio : ''),
                    subject: 'item-plugin-' + classType + '-menu-new-apply[0]',
                    objectives: ['item-plugin-' + classType + '-menu-new-apply']
                });
            }
            cc++;
        }
        scenario.steps.push({
            title: ((dict.Apply && dict.Apply.title) ? dict.Apply.title : __('Apply')),
            text: ((dict.Apply && dict.Apply.text) ? dict.Apply.text : ''),
            audio: ((dict.Apply && dict.Apply.audio) ? dict.Apply.audio : ''),
            requirements: ['timeout:500'],
            subject: 'item-plugin-' + classType + '-menu-edit-apply[0]',
            objectives: ['item-plugin-' + classType + '-menu-edit-apply']
        });
        buildPropertiesOpenStep(scenario, classType, 'timeout:500');
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            requirements: ['timeout:500'],
            subject: 'item-plugin-' + classType + '-prop-menuItemAlign[0]',
            defaultContent: { value: rawElem.menuItemAlign },
            objectives: ['item-plugin-' + classType + '-prop-menuItemAlign-change']
        });
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            subject: 'item-plugin-' + classType + '-prop-brdMenu[0]',
            defaultContent: { value: rawElem.brdMenu },
            objectives: ['item-plugin-' + classType + '-prop-brdMenu-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            placement: 'bottom',
            subject: 'item-plugin-' + classType + '-prop-bgMenu[0]',
            defaultContent: { value: { 'color': rawElem.bgMenu } },
            objectives: ['item-plugin-' + classType + '-prop-bgMenu-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            placement: 'top',
            subject: 'item-plugin-' + classType + '-prop-bgSubMenu[0]',
            defaultContent: { value: { 'color': rawElem.bgSubMenu } },
            objectives: ['item-plugin-' + classType + '-prop-bgSubMenu-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            placement: 'top',
            subject: 'item-plugin-' + classType + '-prop-bgMobMenu[0]',
            defaultContent: { value: { 'color': rawElem.bgMobMenu } },
            objectives: ['item-plugin-' + classType + '-prop-bgMobMenu-change']
        });
        scenario.steps.push({
            title: ((dict.Choose && dict.Choose.title) ? dict.Choose.title : __('Choose')),
            text: ((dict.Choose && dict.Choose.text) ? dict.Choose.text : ''),
            audio: ((dict.Choose && dict.Choose.audio) ? dict.Choose.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-tab-menuItemStyles[0]',
            objectives: ['item-plugin-' + classType + '-prop-tab-menuItemStyles']
        });
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            subject: 'item-plugin-' + classType + '-prop-txtFont[0]',
            defaultContent: { value: rawElem.txtNormal.font },
            objectives: ['item-plugin-' + classType + '-prop-txtFont-change']
        });
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-txtSize[0]',
            defaultContent: { value: rawElem.txtNormal.size },
            objectives: ['item-plugin-' + classType + '-prop-txtSize-change']
        });
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            subject: 'item-plugin-' + classType + '-prop-textNormalStyle[0]',
            defaultContent: { value: rawElem.txtNormal.style },
            objectives: ['item-plugin-' + classType + '-prop-textNormalStyle-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-textNormalColor[0]',
            defaultContent: { value: rawElem.txtNormal.color },
            objectives: ['item-plugin-' + classType + '-prop-textNormalColor-change']
        });
        buildFullWidthStep(scenario, classType, elem);
        buildPropertiesApplyStep(scenario, classType);
        return 'item-plugin-' + classType + '-prop-close';
    }
    function buildMapsSteps(scenario, step, classType, elem) {
        buildPropertiesOpenStep(scenario, classType);
        var rawElem = elem;
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            requirements: ['timeout:500'],
            subject: 'item-plugin-' + classType + '-prop-gmapKey[0]',
            defaultContent: { 'value': rawElem.params.key },
            objectives: ['item-plugin-' + classType + '-prop-gmapKey-change']
        });
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-gmapAddress[0]',
            defaultContent: { value: rawElem.params.address, ll: rawElem.params.ll },
            objectives: ['item-plugin-' + classType + '-prop-gmapAddress-change']
        });
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-gmapZoomLevel[0]',
            defaultContent: { value: rawElem.params.zoom },
            objectives: ['item-plugin-' + classType + '-prop-gmapZoomLevel-change']
        });
        buildFullWidthStep(scenario, classType, elem);
        buildPropertiesApplyStep(scenario, classType);
        return 'item-plugin-' + classType + '-prop-close';
    }
    function buildTextSteps(scenario, step, classType, elem) {
        var rawElem = elem;
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            placement: 'right',
            subject: 'item-plugin-' + classType + '-edit-btn[0]',
            objectives: ['item-plugin-' + classType + '-edit-start']
        });
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            subject: 'item-plugin-' + classType + '[0]',
            objectives: ['item-plugin-' + classType + '-edit-select']
        });
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '[0]',
            defaultContent: { value: rawElem.textDivValue },
            objectives: ['item-plugin-' + classType + '-edit-text']
        });
        scenario.steps.push({
            title: ((dict.Click && dict.Click.title) ? dict.Click.title : __('Click')),
            text: ((dict.Click && dict.Click.text) ? dict.Click.text : ''),
            subject: "item-plugin-TextArea-edit-cmd-closebtn[0]",
            objectives: ["item-plugin-TextArea-edit-end"]
        });
        return null;
    }
    function buildPictureSteps(scenario, step, classType, elem) {
        step.defaultContent = { src: elem.getSrc() };
        if (step.forceBounds)
            step.forceBounds.event = 'item-plugin-' + classType + '-edit-loaded';
        buildFullWidthStep(scenario, classType, elem, true);
        return null;
    }
    function buildLineSteps(scenario, step, classType, elem) {
        buildPropertiesOpenStep(scenario, classType);
        var rawElem = elem;
        if (rawElem.orientation === 0) {
            scenario.steps.push({
                title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
                text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
                requirements: ['timeout:500'],
                subject: 'item-plugin-' + classType + '-prop-lineOrientationVert[0]',
                defaultContent: { value: true },
                objectives: ['item-plugin-' + classType + '-prop-lineOrientationVert-change']
            });
        }
        else if (rawElem.orientation === 1) {
            scenario.steps.push({
                title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
                text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
                subject: 'item-plugin-' + classType + '-prop-lineOrientationHoriz[0]',
                defaultContent: { value: true },
                objectives: ['item-plugin-' + classType + '-prop-lineOrientationHoriz-change']
            });
        }
        if (rawElem.style === 'solid') {
            scenario.steps.push({
                title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
                text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
                subject: 'item-plugin-' + classType + '-prop-lineStyleSolid[0]',
                defaultContent: { value: true },
                objectives: ['item-plugin-' + classType + '-prop-lineStyleSolid-change']
            });
        }
        else if (rawElem.style === 'dashed') {
            scenario.steps.push({
                title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
                text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
                subject: 'item-plugin-' + classType + '-prop-lineStyleDashed[0]',
                defaultContent: { value: true },
                objectives: ['item-plugin-' + classType + '-prop-lineStyleDashed-change']
            });
        }
        else if (rawElem.style === 'dotted') {
            scenario.steps.push({
                title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
                text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
                subject: 'item-plugin-' + classType + '-prop-lineStyleDotted[0]',
                defaultContent: { value: true },
                objectives: ['item-plugin-' + classType + '-prop-lineStyleDotted-change']
            });
        }
        else if (rawElem.style === 'double') {
            scenario.steps.push({
                title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
                text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
                subject: 'item-plugin-' + classType + '-prop-lineStyleDouble[0]',
                defaultContent: { value: true },
                objectives: ['item-plugin-' + classType + '-prop-lineStyleDouble-change']
            });
        }
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-lineSize[0]',
            defaultContent: { value: rawElem.size },
            objectives: ['item-plugin-' + classType + '-prop-lineSize-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-lineColor[0]',
            defaultContent: { value: rawElem.color },
            objectives: ['item-plugin-' + classType + '-prop-lineColor-change']
        });
        buildPropertiesApplyStep(scenario, classType);
        return 'item-plugin-' + classType + '-prop-close';
    }
    function buildShapeSteps(scenario, step, classType, elem) {
        buildPropertiesOpenStep(scenario, classType);
        var rawElem = elem;
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            requirements: ['timeout:500'],
            subject: 'item-plugin-' + classType + '-prop-opacity[0]',
            defaultContent: { value: rawElem.opacity * 100 },
            objectives: ['item-plugin-' + classType + '-prop-opacity-change']
        });
        scenario.steps.push({
            title: ((dict.Choose && dict.Choose.title) ? dict.Choose.title : __('Choose')),
            text: ((dict.Choose && dict.Choose.text) ? dict.Choose.text : ''),
            audio: ((dict.Choose && dict.Choose.audio) ? dict.Choose.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-border[0]',
            defaultContent: { value: rawElem.border },
            objectives: ['item-plugin-' + classType + '-prop-border-change']
        });
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-borderRadius[0]',
            defaultContent: { value: rawElem.borderRadius },
            objectives: ['item-plugin-' + classType + '-prop-borderRadius-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-background[0]',
            defaultContent: { value: rawElem.background },
            objectives: ['item-plugin-' + classType + '-prop-background-change']
        });
        buildFullWidthStep(scenario, classType, elem);
        buildPropertiesApplyStep(scenario, classType);
        return 'item-plugin-' + classType + '-prop-close';
    }
    function buildButtonSteps(scenario, step, classType, elem) {
        buildPropertiesOpenStep(scenario, classType);
        var rawElem = elem;
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            requirements: ['timeout:500'],
            subject: 'item-plugin-' + classType + '-prop-buttonText[0]',
            defaultContent: { value: rawElem.text },
            objectives: ['item-plugin-' + classType + '-prop-buttonText-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-txtFont[0]',
            defaultContent: { value: rawElem.txt.font },
            objectives: ['item-plugin-' + classType + '-prop-txtFont-change']
        });
        scenario.steps.push({
            title: ((dict.Edit && dict.Edit.title) ? dict.Edit.title : __('Edit')),
            text: ((dict.Edit && dict.Edit.text) ? dict.Edit.text : ''),
            audio: ((dict.Edit && dict.Edit.audio) ? dict.Edit.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-txtSize[0]',
            defaultContent: { value: rawElem.txt.size },
            objectives: ['item-plugin-' + classType + '-prop-txtSize-change']
        });
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            subject: 'item-plugin-' + classType + '-prop-txtAlign[0]',
            defaultContent: { value: rawElem.txt.align },
            objectives: ['item-plugin-' + classType + '-prop-txtAlign-change']
        });
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            subject: 'item-plugin-' + classType + '-prop-border[0]',
            defaultContent: { value: rawElem.border },
            objectives: ['item-plugin-' + classType + '-prop-border-change']
        });
        scenario.steps.push({
            title: ((dict.Change && dict.Change.title) ? dict.Change.title : __('Change')),
            text: ((dict.Change && dict.Change.text) ? dict.Change.text : ''),
            audio: ((dict.Change && dict.Change.audio) ? dict.Change.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-bgNormal[0]',
            defaultContent: { value: rawElem.bgNormal },
            objectives: ['item-plugin-' + classType + '-prop-bgNormal-change']
        });
        buildPropertiesApplyStep(scenario, classType);
        return 'item-plugin-' + classType + '-prop-close';
    }
    function buildCreateStep(scenario, classType, elem, requirement, useOverlay) {
        var pOff = getOffset(elem, useOverlay);
        var pos = elem.getLocation();
        var rHoff = USE_VARIATION ? Math.round(Math.random() * (30 + 30) - 30) : 0;
        var rVoff = USE_VARIATION ? Math.round(Math.random() * (30 + 30) - 30) : 0;
        var step = {
            title: ((dict.Add && dict.Add.title) ? dict.Add.title.replace('%s', __(classType)) : (__('Add') + ' ' + classType)),
            text: ((dict.Add && dict.Add.text) ? dict.Add.text : ''),
            block: elem.getParent().id,
            subject: 'toolbar-plugin-' + classType,
            objectives: ['add-plugin-' + classType],
            forceBounds: {
                top: pOff.top + pos.top + rVoff,
                left: pOff.left + pos.left + rHoff
            }
        };
        if (requirement)
            step.requirements = [requirement];
        scenario.steps.push(step);
        return step;
    }
    function buildResizeStep(scenario, classType, elem, requirement, useOverlay) {
        var pOff = getOffset(elem, useOverlay);
        var pos = elem.getLocation();
        if (USE_VARIATION) {
            scenario.steps.push({
                title: ((dict.Move && dict.Move.title) ? dict.Move.title.replace('%s', __(classType)) : __('Move')),
                text: ((dict.Move && dict.Move.text) ? dict.Move.text : ''),
                subject: 'item-plugin-' + classType + '-move-btn[0]',
                requirements: (requirement ? [requirement] : []),
                objectives: ['item-plugin-' + classType + '-move-start'],
                forceBounds: {
                    event: 'item-plugin-' + classType + '-move-end',
                    top: pOff.top + pos.top,
                    left: pOff.left + pos.left
                }
            });
        }
        scenario.steps.push({
            title: ((dict.Resize && dict.Resize.title) ? dict.Resize.title.replace('%s', __(classType)) : __('Resize')),
            text: ((dict.Resize && dict.Resize.text) ? dict.Resize.text : ''),
            audio: ((dict.Resize && dict.Resize.audio) ? dict.Resize.audio : ''),
            placement: 'right',
            subject: 'item-plugin-' + classType + '[0]',
            requirements: (USE_VARIATION ? ['item-plugin-' + classType + '-move-end'] : (requirement ? [requirement] : [])),
            objectives: ['item-plugin-' + classType + '-resize-start'],
            forceBounds: {
                event: 'item-plugin-' + classType + '-resize-end',
                width: elem.getWidth(),
                height: elem.getHeight()
            }
        });
    }
    function buildFullWidthStep(scenario, classType, elem, openDialog, requirement) {
        if (openDialog === void 0) { openDialog = false; }
        if (requirement === void 0) { requirement = null; }
        if (!elem.isFullWidth)
            return;
        if (openDialog) {
            buildPropertiesOpenStep(scenario, classType);
            requirement = 'timeout:500';
        }
        scenario.steps.push({
            title: ((dict.Choose && dict.Choose.title) ? dict.Choose.title : __('Choose')),
            text: ((dict.Choose && dict.Choose.text) ? dict.Choose.text : ''),
            audio: ((dict.Choose && dict.Choose.audio) ? dict.Choose.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-tab-options[0]',
            requirements: (requirement ? [requirement] : []),
            objectives: ['item-plugin-' + classType + '-prop-tab-options']
        });
        scenario.steps.push({
            title: ((dict.Select && dict.Select.title) ? dict.Select.title : __('Select')),
            text: ((dict.Select && dict.Select.text) ? dict.Select.text : ''),
            subject: 'item-plugin-' + classType + '-prop-fullWidth[0]',
            defaultContent: { value: elem.isFullWidth },
            objectives: ['item-plugin-' + classType + '-prop-fullWidth-change']
        });
        if (openDialog)
            buildPropertiesApplyStep(scenario, classType);
    }
    function buildPropertiesOpenStep(scenario, classType, requirement) {
        if (requirement === void 0) { requirement = null; }
        scenario.steps.push({
            title: ((dict.Properties && dict.Properties.title) ? dict.Properties.title : __('Properties')),
            text: ((dict.Properties && dict.Properties.text) ? dict.Properties.text : ''),
            audio: ((dict.Properties && dict.Properties.audio) ? dict.Properties.audio : ''),
            subject: 'item-plugin-' + classType + '-edit-btn[0]',
            requirements: (requirement ? [requirement] : []),
            objectives: ['item-plugin-' + classType + '-prop-open']
        });
    }
    function buildPropertiesApplyStep(scenario, classType) {
        scenario.steps.push({
            title: ((dict.Apply && dict.Apply.title) ? dict.Apply.title : __('Apply')),
            text: ((dict.Apply && dict.Apply.text) ? dict.Apply.text : ''),
            audio: ((dict.Apply && dict.Apply.audio) ? dict.Apply.audio : ''),
            subject: 'item-plugin-' + classType + '-prop-apply[0]',
            objectives: ['item-plugin-' + classType + '-prop-apply']
        });
    }
    function getOffset(elem, useOverlay) {
        var pOff;
        if (useOverlay) {
            var parent_1 = elem.getParent();
            pOff = parent_1.container.offset();
            pOff.top -= (lastBuilder ? lastBuilder.body.position().top : 128);
        }
        else {
            pOff = { left: 0, top: 0 };
        }
        return pOff;
    }
});
define("HelpSystem/AnimTween", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var AnimTween = (function () {
        function AnimTween(durration, fps, onStep, onStart, onEnd, onDispose) {
            if (onStep === void 0) { onStep = null; }
            if (onStart === void 0) { onStart = null; }
            if (onEnd === void 0) { onEnd = null; }
            if (onDispose === void 0) { onDispose = null; }
            this.onStep = onStep;
            this.onStart = onStart;
            this.onEnd = onEnd;
            this.onDispose = onDispose;
            this.currKeyframe = 0;
            this.timeHandle = 0;
            this.keyframeLen = Math.round(1000.0 / fps);
            this.numKeyframes = Math.ceil(durration / this.keyframeLen);
        }
        AnimTween.prototype.start = function () {
            var _this = this;
            if (this.timeHandle)
                clearInterval(this.timeHandle);
            this.currKeyframe = 0;
            if (this.onStart)
                this.onStart.call(this, this);
            this.timeHandle = setInterval(function () { return _this.step(); }, this.keyframeLen);
            return this;
        };
        AnimTween.prototype.step = function () {
            if (this.onStep)
                this.onStep.call(this, this);
            this.currKeyframe++;
            if (this.currKeyframe >= this.numKeyframes) {
                this.end();
            }
        };
        AnimTween.prototype.end = function (noCallback) {
            if (noCallback === void 0) { noCallback = false; }
            if (!noCallback && this.onEnd)
                this.onEnd.call(this, this);
            if (this.timeHandle)
                clearInterval(this.timeHandle);
            this.currKeyframe = 0;
        };
        AnimTween.prototype.dispose = function () {
            if (this.onDispose)
                this.onDispose.call(this, this);
            this.end(true);
        };
        return AnimTween;
    }());
    exports.AnimTween = AnimTween;
});
define("HelpSystem/VirtualCursor", ["require", "exports", "HelpSystem/AnimTween"], function (require, exports, AnimTween_1) {
    "use strict";
    exports.__esModule = true;
    var VirtualCursor = (function () {
        function VirtualCursor() {
            var _this = this;
            this.tween = null;
            this.elem = $('<div>')
                .css({ position: 'fixed', zIndex: 99999, left: 200, top: 200 });
            this.pointer = $('<svg width="334" height="465" viewBox="0 0 33.2 42.6">'
                + '<path style="fill:#000000;stroke:#ffffff;stroke-width:2;" d="m 32.4,28.4 c -0.2,0.1 -0.4,0.1 -0.6,0.1 L 14.5,28 c -0.4,0 -0.9,0.2 -1.1,0.5 L 2.6,42.1 C 2.5,42.3 2.3,42.4 2.1,42.5 1.8,42.6 1.4,42.7 1.1,42.6 0.5,42.4 0.2,41.9 0.2,41.3 L 0,1.4 C 0,0.9 0.3,0.4 0.8,0.1 1.3,-0.2 1.9,0 2.3,0.3 L 32.7,26 c 0.5,0.4 0.6,1 0.4,1.6 -0.1,0.4 -0.4,0.6 -0.7,0.8 z" />'
                + '</svg>')
                .css({ width: 24, height: 25, position: 'relative', zIndex: 3 })
                .appendTo(this.elem);
            this.clickIndicator = $('<div>').addClass('click-pulse')
                .css({
                zIndex: 1,
                borderRadius: 30,
                border: '2px solid #000',
                opacity: 0,
                position: 'absolute'
            })
                .appendTo(this.elem);
            this.clickIndicator.clone().css({ borderColor: '#fff' }).appendTo(this.elem);
            this.clickIndicator.clone().css({ marginLeft: '-120px' }).appendTo(this.elem);
            this.clickIndicator.clone().css({ marginLeft: '120px' }).appendTo(this.elem);
            this.elem.on('click', function () { return _this.animClick(); });
        }
        VirtualCursor.prototype.getElem = function () { return this.elem; };
        VirtualCursor.prototype.dispose = function () {
            this.elem.detach();
        };
        VirtualCursor.prototype.animClick = function (onDone, multi) {
            if (onDone === void 0) { onDone = null; }
            if (multi === void 0) { multi = false; }
            var list = this.elem.children('.click-pulse');
            list.eq(0).addClass('vcursor-click-pulse');
            if (multi) {
                list.eq(2).addClass('vcursor-click-pulse');
                list.eq(3).addClass('vcursor-click-pulse');
            }
            setTimeout(function () { return list.eq(1).addClass('vcursor-click-pulse'); }, 100);
            setTimeout(function () {
                list.removeClass('vcursor-click-pulse');
                if (onDone)
                    onDone();
            }, 500);
        };
        VirtualCursor.prototype.moveTo = function (destination, onDone, durration, fps) {
            var _this = this;
            if (onDone === void 0) { onDone = null; }
            if (durration === void 0) { durration = 200; }
            if (fps === void 0) { fps = 24; }
            if (this.tween)
                this.tween.dispose();
            var dest = { left: 0, top: 0 }, difX = 0, difY = 0;
            if (destination.left && typeof destination.left === 'number')
                dest.left = destination.left;
            if (destination.top && typeof destination.top === 'number')
                dest.top = destination.top;
            this.tween = new AnimTween_1.AnimTween(durration, fps, function () {
                var subjectPos = _this.elem.offset();
                _this.elem.css({ left: subjectPos.left + difX, top: subjectPos.top - window.scrollY + difY });
            }, function (tween) {
                var subjectPos = _this.elem.offset();
                difX = ((dest.left && typeof dest.left === 'number')
                    ? (dest.left - subjectPos.left)
                    : 0) / tween.numKeyframes;
                difY = ((dest.top && typeof dest.top === 'number')
                    ? (dest.top - subjectPos.top)
                    : 0) / tween.numKeyframes;
            }, onDone).start();
        };
        return VirtualCursor;
    }());
    exports.VirtualCursor = VirtualCursor;
});
define("GridAndGuidesDialog", ["require", "exports", "Dialog", "VerticalLayout", "Service", "HorizontalLayout"], function (require, exports, Dialog_4, VerticalLayout_3, Service_6, HorizontalLayout_2) {
    "use strict";
    exports.__esModule = true;
    var GridAndGuidesDialog = (function (_super) {
        __extends(GridAndGuidesDialog, _super);
        function GridAndGuidesDialog() {
            var _this = _super.call(this, '', false) || this;
            _this.setTitleVisible(true);
            _this.setFooterVisible(true);
            _this.setSize(500, null);
            _this.setTitle(__("Grid and guides"));
            _this.setContent(new Service_6["default"].UIBuilder({ type: VerticalLayout_3.VerticalLayout, children: [
                    { type: HorizontalLayout_2.HorizontalLayout, css: { marginTop: -15 }, children: [
                            { type: VerticalLayout_3.VerticalLayout, css: { marginTop: 15 }, children: [
                                    { type: 'Label', text: __('Snapping') },
                                    { type: 'CheckBox', label: __('Snap to grid'), id: "snapToGrid" },
                                    { type: 'CheckBox', label: __('Snap to guides'), id: "snapToGuides" },
                                    { type: 'CheckBox', label: __('Snap to objects'), id: "snapToObjects" }
                                ] },
                            { type: VerticalLayout_3.VerticalLayout, css: { marginTop: 15 }, children: [
                                    { type: 'Label', text: __('Display') },
                                    { type: 'CheckBox', label: __('Show distances'), id: "showHelpers" },
                                    { type: 'CheckBox', label: __('Show grid'), id: "showGrid" },
                                    { type: 'CheckBox', label: __('Show guides'), id: "showGuides" },
                                    { type: 'CheckBox', label: __('Show layout'), id: "showLayout" }
                                ] }
                        ] },
                    { type: HorizontalLayout_2.HorizontalLayout, children: [
                            { type: VerticalLayout_3.VerticalLayout, css: { marginTop: 15 }, children: [
                                    { type: 'Label', text: __('Grid size') },
                                    { type: 'SizeSelector', id: "gridSize", min: 5, max: 100 }
                                ] },
                            { type: VerticalLayout_3.VerticalLayout, css: { marginTop: 15 }, children: [
                                    { type: 'Label', text: __('Grid color') },
                                    { type: 'ColorSelector', id: "gridColor" }
                                ] }
                        ] },
                ] }, _this.fields), true);
            _this.addButton(__("Cancel"), function () {
                _this.setVisible(false);
            }, false);
            _this.addButton(__("Apply"), function () {
                if (_this.saveFields())
                    _this.setVisible(false);
            }, true);
            return _this;
        }
        GridAndGuidesDialog.getInstance = function () {
            if (!GridAndGuidesDialog.instance)
                GridAndGuidesDialog.instance = new GridAndGuidesDialog();
            return GridAndGuidesDialog.instance;
        };
        GridAndGuidesDialog.open = function () {
            var dialog = GridAndGuidesDialog.getInstance();
            dialog.updateFields();
            dialog.setVisible(true);
        };
        GridAndGuidesDialog.prototype.saveFields = function () {
            wb_builder.gridSetVisible(this.fields.showGrid.getValue());
            wb_builder.gridSetSize(this.fields.gridSize.getValue());
            wb_builder.gridSetColor(this.fields.gridColor.getValue());
            wb_builder.setCookie('wb_showgrid', (wb_builder.showGrid ? 'Y' : 'N') + '/' + wb_builder.gridSize + '/' + wb_builder.gridColor);
            wb_builder.guidesSetVisible(this.fields.showGuides.getValue());
            wb_builder.setCookie('wb_showguides', (wb_builder.showGuides ? 'Y' : 'N'));
            wb_builder.showMeasurementHelpers = this.fields.showHelpers.getValue();
            wb_builder.setCookie('wb_showhelpers', (wb_builder.showMeasurementHelpers ? 'Y' : 'N'));
            wb_builder.showLayout = this.fields.showLayout.getValue();
            wb_builder.setCookie('wb_showlayout', (wb_builder.showLayout ? 'Y' : 'N'));
            wb_builder.snapToGrid = this.fields.snapToGrid.getValue();
            wb_builder.setCookie('wb_snapgrid', (wb_builder.snapToGrid ? 'Y' : 'N'));
            wb_builder.snapToGuides = this.fields.snapToGuides.getValue();
            wb_builder.setCookie('wb_snapguides', (wb_builder.snapToGuides ? 'Y' : 'N'));
            wb_builder.snapToObjects = this.fields.snapToObjects.getValue();
            wb_builder.setCookie('wb_snapobjects', (wb_builder.snapToObjects ? 'Y' : 'N'));
            return true;
        };
        GridAndGuidesDialog.prototype.updateFields = function () {
            this.fields.showGrid.setValue(wb_builder.showGrid);
            this.fields.showGuides.setValue(wb_builder.showGuides);
            this.fields.showHelpers.setValue(wb_builder.showMeasurementHelpers);
            this.fields.showLayout.setValue(wb_builder.showLayout);
            this.fields.snapToGrid.setValue(wb_builder.snapToGrid);
            this.fields.snapToGuides.setValue(wb_builder.snapToGuides);
            this.fields.snapToObjects.setValue(wb_builder.snapToObjects);
            this.fields.gridSize.setValue(wb_builder.gridSize);
            this.fields.gridColor.setValue(wb_builder.gridColor);
        };
        return GridAndGuidesDialog;
    }(Dialog_4["default"]));
    exports.GridAndGuidesDialog = GridAndGuidesDialog;
});
define("util/MenuList", ["require", "exports", "Service", "BuilderEvent", "MenuConfirmDialog"], function (require, exports, Service_7, BuilderEvent_3, MenuConfirmDialog_1) {
    "use strict";
    exports.__esModule = true;
    var MenuItemStruct = (function () {
        function MenuItemStruct(lvl) {
            if (lvl === void 0) { lvl = 0; }
            this.lvl = lvl;
            this.id = 0;
            this.uID = '';
            this.menuUID = '';
        }
        MenuItemStruct.fromMenuItem = function (smi, menu, lvl) {
            if (lvl === void 0) { lvl = 0; }
            var mi = new MenuItemStruct(lvl);
            mi.miElem = smi;
            mi.id = parseInt('' + smi.id, 10);
            mi.uID = '' + menu.menuUID + '_' + smi.id;
            mi.menuUID = menu.menuUID;
            mi.type = smi.type;
            mi.fullName = __tr(smi.name, '__DEFAULT__', __('New Item'), true, true);
            mi.name = Service_7["default"].element.truncate(mi.fullName, 36);
            if (smi.type === 'external') {
                mi.url = smi.url;
            }
            else {
                mi.pageId = parseInt('' + smi.targetId, 10);
            }
            return mi;
        };
        MenuItemStruct.fromPage = function (page, lvl) {
            if (lvl === void 0) { lvl = 0; }
            var mi = new MenuItemStruct(lvl);
            mi.type = 'page';
            mi.fullName = __tr(page.title, '__DEFAULT__', __('New Page'), true, true);
            mi.name = mi.fullName ? Service_7["default"].element.truncate(mi.fullName, 36) : '';
            mi.pageId = parseInt('' + page.id, 10);
            return mi;
        };
        MenuItemStruct.fromAnchor = function (anchor, smi, lvl) {
            if (lvl === void 0) { lvl = 0; }
            var mi = new MenuItemStruct(lvl);
            mi.id = parseInt('' + smi.id, 10);
            mi.uID = smi.uID + '_' + anchor;
            mi.menuUID = smi.menuUID;
            mi.type = smi.type;
            mi.fullName = anchor;
            mi.name = mi.fullName ? ('#' + Service_7["default"].element.truncate(mi.fullName, 36)) : '';
            mi.pageId = parseInt('' + smi.pageId, 10);
            mi.anchor = anchor;
            return mi;
        };
        MenuItemStruct.prototype.isCurrent = function () { return this.type === 'page' && wb_builder.pageId === this.pageId; };
        MenuItemStruct.prototype.isExternal = function () { return this.type === 'external'; };
        MenuItemStruct.prototype.isInternal = function () { return this.type === 'internal' || this.type === 'page' || this.type === 'anchor'; };
        MenuItemStruct.prototype.isEmpty = function () { return this.type === 'empty'; };
        MenuItemStruct.prototype.isContent = function () { return this.type === 'page'; };
        MenuItemStruct.prototype.navigate = function () {
            if (this.isInternal() && this.pageId) {
                wb_builder.goToPage(this.pageId);
            }
            else if (this.isExternal() && this.url) {
                window.open(this.url, '_blank');
                window.focus();
            }
            else if (!this.isEmpty()) {
                throw new Error('Wrong target');
            }
        };
        MenuItemStruct.prototype.preview = function () {
            if (!this.isInternal() || !this.pageId)
                return;
            wb_builder.previewPage(this.pageId, wb_builder.previewToolbar, false, true);
        };
        return MenuItemStruct;
    }());
    exports.MenuItemStruct = MenuItemStruct;
    var MenuStruct = (function () {
        function MenuStruct(menuElem) {
            this.menuElem = menuElem;
            this.items = [];
        }
        MenuStruct.fromMenu = function (menuElem, anchorMode, useTypeLabels, pageIdItemNameIndex) {
            if (anchorMode === void 0) { anchorMode = false; }
            if (useTypeLabels === void 0) { useTypeLabels = false; }
            var menu = new MenuStruct(menuElem);
            MenuStruct.buildItems(menu, null, 0, anchorMode, useTypeLabels, pageIdItemNameIndex);
            return menu;
        };
        MenuStruct.fromPage = function (page) {
            var menu = new MenuStruct(null);
            menu.items.push(MenuItemStruct.fromPage(page));
            return menu;
        };
        MenuStruct.buildItems = function (menu, menuItemElem, lvl, anchorMode, useTypeLabels, pageIdItemNameIndex) {
            if (!menu.menuElem)
                return;
            var smenu = menuItemElem ? menuItemElem : menu.menuElem;
            for (var i in smenu.items) {
                if (!smenu.items.hasOwnProperty(i))
                    continue;
                var smi = smenu.items[i];
                var mi = MenuItemStruct.fromMenuItem(smi, menu.menuElem, lvl);
                menu.items.push(mi);
                if (useTypeLabels && mi.type == 'page' && mi.pageId && (('#' + mi.pageId) in wb_builder.site.pages)) {
                    pageIdItemNameIndex['#' + mi.pageId] = mi.name;
                }
                if (anchorMode && mi.isInternal() && mi.pageId && (('#' + mi.pageId) in wb_builder.site.pages)) {
                    var anchors = wb_builder.site.getAnchors(wb_builder.site.pages['#' + mi.pageId].id);
                    for (var j in anchors) {
                        if (!anchors.hasOwnProperty(j))
                            continue;
                        var ami = MenuItemStruct.fromAnchor(anchors[j], mi, lvl + 1);
                        menu.items.push(ami);
                    }
                }
                if (smi.items)
                    MenuStruct.buildItems(menu, smi, lvl + 1, anchorMode, useTypeLabels, pageIdItemNameIndex);
            }
        };
        MenuStruct.prototype.isEditable = function () { return true; };
        MenuStruct.prototype.isRemovable = function () {
            return Object.keys(Service_7["default"].menu.getElemList(true)).length > 1;
        };
        MenuStruct.prototype.edit = function () {
            if (this.menuElem && this.isEditable())
                editMenu(this.menuElem);
        };
        MenuStruct.prototype.remove = function () {
            if (this.menuElem && this.isRemovable())
                removeMenu(this.menuElem);
        };
        return MenuStruct;
    }());
    exports.MenuStruct = MenuStruct;
    function getItemInfo(itemId, menu, menuUID) {
        itemId = String(itemId);
        if (itemId.substring(0, 1) !== '#') {
            itemId = '#' + itemId;
        }
        var menuItem, menuId, menu_, menuItemId;
        var menus = (menu ? { 'menu': menu } : Service_7["default"].menu.getElemList(true));
        if (!menu && menuUID) {
            var mm = Service_7["default"].menu.getMenuByUID(menuUID);
            if (mm)
                menus = { menuUID: mm };
        }
        for (menuId in menus) {
            menu_ = menus[menuId];
            for (menuItemId in menu_.items) {
                if (menuItemId === itemId) {
                    return menu_.items[menuItemId];
                }
                else {
                    menuItem = getItemInfo(itemId, menu_.items[menuItemId]);
                    if (menuItem) {
                        return menuItem;
                    }
                }
            }
        }
        return null;
    }
    exports.getItemInfo = getItemInfo;
    function editMenu(menuElem) {
        if (menuElem.elem) {
            menuElem.openEditMenuItems(false);
        }
        else if (menuElem.menuType === 'strange') {
            var loadPageId, inPa = Object.keys(menuElem.includePages);
            if (menuElem.isCommon && inPa.length > 0) {
                for (var i = 0; i < inPa.length; i++) {
                    if (('#' + inPa[i]) in wb_builder.site.pages) {
                        loadPageId = parseInt(inPa[i], 10);
                        break;
                    }
                }
            }
            else if (!menuElem.isCommon && menuElem.pageId) {
                loadPageId = menuElem.pageId;
            }
            if (loadPageId) {
                wb_builder.goToPage(loadPageId, null, function () {
                    setTimeout(function () {
                        var m = Service_7["default"].menu.getMenuByUID(menuElem.menuUID);
                        if (m)
                            m.openEditMenuItems(false);
                    }, 500);
                });
            }
        }
    }
    var removedMenuList = [];
    function removeMenu(menuElem) {
        if (!menuElem)
            return;
        MenuConfirmDialog_1.confirmDelete(function () {
            Service_7["default"].menu.removeStrangeMenu(menuElem, true);
            if (menuElem.menuType === 'strange') {
                removedMenuList.push({ menuUID: menuElem.menuUID, pageId: menuElem.pageId, isCommon: menuElem.isCommon });
                BuilderEvent_3.GlobalEvents.triggerEvent('pages.changed', new BuilderEvent_3.PagesChangedBuilderEvent());
            }
            else {
                menuElem.remove(false, true, true);
            }
        });
    }
    function clearRemovedMenuList() { removedMenuList = []; }
    exports.clearRemovedMenuList = clearRemovedMenuList;
    function getRemovedMenuList() { return removedMenuList; }
    exports.getRemovedMenuList = getRemovedMenuList;
    function buildMenuStruct(anchorMode, noEmpty, menu, useTypeLabels) {
        var menuList = {};
        if (menu) {
            menuList[menu.menuId] = menu;
        }
        else {
            menuList = Service_7["default"].menu.getElemList(true);
        }
        var menus = [], p, pageIdItemNameIndex = {};
        for (var k in menuList) {
            if (!menuList.hasOwnProperty(k))
                continue;
            var menuStruct = MenuStruct.fromMenu(menuList[k], anchorMode, useTypeLabels, pageIdItemNameIndex);
            if (menuStruct.items.length > 0)
                menus.push(menuStruct);
        }
        if (useTypeLabels) {
            for (var _i = 0, menus_1 = menus; _i < menus_1.length; _i++) {
                var m = menus_1[_i];
                for (var _a = 0, _b = m.items; _a < _b.length; _a++) {
                    var mi = _b[_a];
                    var typeLabel = (mi.type === 'external' ? '(' + __('external') + ')'
                        : (mi.type === 'anchor' ? '(' + __('anchor') + ')'
                            : (mi.type === 'empty' ? '(' + __('Empty').toLowerCase() + ')'
                                : (mi.type === 'internal' && (('#' + mi.pageId) in pageIdItemNameIndex))
                                    ? ' &rarr; ' + pageIdItemNameIndex['#' + mi.pageId] : '')));
                    mi.name += (typeLabel ? '<span class="sub">' + typeLabel + '</span>' : '');
                }
            }
        }
        if (noEmpty && menus.length == 0 && (p = wb_builder.site.pages['#' + wb_builder.pageId])) {
            menus.push(MenuStruct.fromPage(p));
        }
        return menus;
    }
    exports.buildMenuStruct = buildMenuStruct;
});
define("Serializable", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var Serializable = (function () {
        function Serializable() {
        }
        Serializable.copy = function (value, target, skipSerializable, filter) {
            if (target === void 0) { target = null; }
            if (skipSerializable === void 0) { skipSerializable = false; }
            if (filter === void 0) { filter = null; }
            if (!skipSerializable && value instanceof Serializable) {
                var res = value.serialize();
                if (target) {
                    res = Serializable.copy(res, target);
                }
                return res;
            }
            else if (value instanceof Array) {
                var arr = [];
                for (var i = 0; i < value.length; i++) {
                    if (!filter || filter.call(value, i, value[i])) {
                        arr.push(Serializable.copy(value[i]));
                    }
                }
                return arr;
            }
            else if (value instanceof Object) {
                var obj = target ? target : {};
                for (var k in value) {
                    if (value.hasOwnProperty(k) && typeof value[k] !== 'function' && (!filter || filter.call(value, k, value[k]))) {
                        obj[k] = Serializable.copy(value[k]);
                    }
                }
                return obj;
            }
            else if (typeof value === 'function') {
                return null;
            }
            return value;
        };
        Serializable.deserializeArray = function (valueType, data, target) {
            if (data === void 0) { data = null; }
            if (target === void 0) { target = null; }
            var arr = target ? target : [];
            if (data instanceof Array) {
                for (var i = 0; i < data.length; i++) {
                    var item = new valueType();
                    item.deserialize(data[i]);
                    arr.push(item);
                }
            }
            return arr;
        };
        Serializable.serializeValue = function (data, target, filter, skipSerializable) {
            if (target === void 0) { target = null; }
            if (filter === void 0) { filter = null; }
            if (skipSerializable === void 0) { skipSerializable = false; }
            return Serializable.copy(data, target, skipSerializable, filter);
        };
        Serializable.prototype.deserialize = function (data) {
            if (data === void 0) { data = null; }
            if (data && typeof data === 'object')
                Serializable.copy(data, this);
        };
        Serializable.prototype.serialize = function () {
            return Serializable.copy(this, null, true);
        };
        return Serializable;
    }());
    exports.Serializable = Serializable;
});
define("store/StoreItem", ["require", "exports", "Serializable"], function (require, exports, Serializable_1) {
    "use strict";
    exports.__esModule = true;
    var StoreItemCustomFieldValue = (function (_super) {
        __extends(StoreItemCustomFieldValue, _super);
        function StoreItemCustomFieldValue(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.fieldId = 0;
            _this.value = null;
            _this.deserialize(data);
            return _this;
        }
        return StoreItemCustomFieldValue;
    }(Serializable_1.Serializable));
    exports.StoreItemCustomFieldValue = StoreItemCustomFieldValue;
    var StoreItem = (function (_super) {
        __extends(StoreItem, _super);
        function StoreItem(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = '';
            _this.description = '';
            _this.price = 0;
            _this.weight = 0;
            _this.quantity = 0;
            _this.sku = '';
            _this.image = null;
            _this.altImages = [];
            _this.itemType = 0;
            _this.categories = [];
            _this.isHidden = false;
            _this.customFields = [];
            _this.dateTimeCreated = null;
            _this.dateTimeModified = null;
            _this.seoTitle = '';
            _this.seoDescription = '';
            _this.seoKeywords = '';
            _this.seoAlias = '';
            _this.deserialize(data);
            return _this;
        }
        return StoreItem;
    }(Serializable_1.Serializable));
    exports.StoreItem = StoreItem;
});
define("store/StoreItemTypeField", ["require", "exports", "Serializable"], function (require, exports, Serializable_2) {
    "use strict";
    exports.__esModule = true;
    var StoreItemTypeField = (function (_super) {
        __extends(StoreItemTypeField, _super);
        function StoreItemTypeField(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = '';
            _this.type = 0;
            _this.isHidden = false;
            _this.isSearchable = false;
            _this.isSearchInterval = false;
            _this.deserialize(data);
            return _this;
        }
        return StoreItemTypeField;
    }(Serializable_2.Serializable));
    exports.StoreItemTypeField = StoreItemTypeField;
});
define("store/StoreItemType", ["require", "exports", "Serializable"], function (require, exports, Serializable_3) {
    "use strict";
    exports.__esModule = true;
    var StoreItemType = (function (_super) {
        __extends(StoreItemType, _super);
        function StoreItemType(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = '';
            _this.fields = [];
            _this.deserialize(data);
            return _this;
        }
        return StoreItemType;
    }(Serializable_3.Serializable));
    exports.StoreItemType = StoreItemType;
});
define("store/StoreItemFieldType", ["require", "exports", "Serializable"], function (require, exports, Serializable_4) {
    "use strict";
    exports.__esModule = true;
    var StoreItemFieldTypeOption = (function (_super) {
        __extends(StoreItemFieldTypeOption, _super);
        function StoreItemFieldTypeOption(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = '';
            _this.deserialize(data);
            return _this;
        }
        return StoreItemFieldTypeOption;
    }(Serializable_4.Serializable));
    exports.StoreItemFieldTypeOption = StoreItemFieldTypeOption;
    var StoreItemFieldType = (function (_super) {
        __extends(StoreItemFieldType, _super);
        function StoreItemFieldType(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = '';
            _this.type = StoreItemFieldType.TYPE_INPUT;
            _this.typeId = 0;
            _this.options = [];
            _this.isTranslatable = true;
            _this.hasEmptyOption = false;
            _this.isStatic = false;
            _this.deserialize(data);
            return _this;
        }
        StoreItemFieldType.buildStaticTypes = function () {
            return [
                new StoreItemFieldType({ id: 1, name: __('Text Field'), type: StoreItemFieldType.TYPE_INPUT, isStatic: true }),
                new StoreItemFieldType({ id: 2, name: __('Text Area'), type: StoreItemFieldType.TYPE_TEXTAREA, isStatic: true }),
                new StoreItemFieldType({ id: 3, name: __('Check Box'), type: StoreItemFieldType.TYPE_CHECKBOX, isStatic: true }),
                new StoreItemFieldType({ id: 4, name: __('Radio Box'), type: StoreItemFieldType.TYPE_RADIOBOX, isStatic: true }),
                new StoreItemFieldType({ id: 5, name: __('Dropdown Box'), type: StoreItemFieldType.TYPE_DROPDOWN, isStatic: true })
            ];
        };
        StoreItemFieldType.hasSupportForOptions = function (selType) {
            return (selType === StoreItemFieldType.TYPE_CHECKBOX
                || selType === StoreItemFieldType.TYPE_RADIOBOX
                || selType === StoreItemFieldType.TYPE_DROPDOWN);
        };
        StoreItemFieldType.TYPE_INPUT = 'input';
        StoreItemFieldType.TYPE_TEXTAREA = 'textarea';
        StoreItemFieldType.TYPE_CHECKBOX = 'checkbox';
        StoreItemFieldType.TYPE_RADIOBOX = 'radiobox';
        StoreItemFieldType.TYPE_DROPDOWN = 'dropdown';
        return StoreItemFieldType;
    }(Serializable_4.Serializable));
    exports.StoreItemFieldType = StoreItemFieldType;
});
define("store/StoreCategory", ["require", "exports", "Serializable"], function (require, exports, Serializable_5) {
    "use strict";
    exports.__esModule = true;
    var StoreCategory = (function (_super) {
        __extends(StoreCategory, _super);
        function StoreCategory(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.parentId = 0;
            _this.name = '';
            _this.description = '';
            _this.image = null;
            _this.viewType = 'thumbs';
            _this.deserialize(data);
            return _this;
        }
        return StoreCategory;
    }(Serializable_5.Serializable));
    exports.StoreCategory = StoreCategory;
});
define("store/StoreDestinationZone", ["require", "exports", "Serializable"], function (require, exports, Serializable_6) {
    "use strict";
    exports.__esModule = true;
    var StoreDestinationZone = (function (_super) {
        __extends(StoreDestinationZone, _super);
        function StoreDestinationZone(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = "";
            _this.countries = [];
            _this.deserialize(data);
            return _this;
        }
        return StoreDestinationZone;
    }(Serializable_6.Serializable));
    exports.StoreDestinationZone = StoreDestinationZone;
});
define("store/StoreTaxRule", ["require", "exports", "Serializable"], function (require, exports, Serializable_7) {
    "use strict";
    exports.__esModule = true;
    var StoreTaxRuleRate = (function (_super) {
        __extends(StoreTaxRuleRate, _super);
        function StoreTaxRuleRate(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.destinationZoneId = 0;
            _this.rate = 0;
            _this.deserialize(data);
            return _this;
        }
        return StoreTaxRuleRate;
    }(Serializable_7.Serializable));
    exports.StoreTaxRuleRate = StoreTaxRuleRate;
    var StoreTaxRule = (function (_super) {
        __extends(StoreTaxRule, _super);
        function StoreTaxRule(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = "";
            _this.rates = [];
            _this.deserialize(data);
            return _this;
        }
        return StoreTaxRule;
    }(Serializable_7.Serializable));
    exports.StoreTaxRule = StoreTaxRule;
});
define("store/StoreShippingMethod", ["require", "exports", "Serializable"], function (require, exports, Serializable_8) {
    "use strict";
    exports.__esModule = true;
    var StoreShippingMethodType;
    (function (StoreShippingMethodType) {
        StoreShippingMethodType[StoreShippingMethodType["FREE"] = 0] = "FREE";
        StoreShippingMethodType[StoreShippingMethodType["FLAT_RATE"] = 1] = "FLAT_RATE";
        StoreShippingMethodType[StoreShippingMethodType["BY_WEIGHT"] = 2] = "BY_WEIGHT";
        StoreShippingMethodType[StoreShippingMethodType["BY_SUBTOTAL"] = 3] = "BY_SUBTOTAL";
    })(StoreShippingMethodType = exports.StoreShippingMethodType || (exports.StoreShippingMethodType = {}));
    function buildTypeList() {
        return [
            { id: StoreShippingMethodType.FREE, name: __('Free') },
            { id: StoreShippingMethodType.FLAT_RATE, name: __('Flat rate') },
            { id: StoreShippingMethodType.BY_WEIGHT, name: __('By weight') },
            { id: StoreShippingMethodType.BY_SUBTOTAL, name: __('By subtotal') },
        ];
    }
    exports.buildTypeList = buildTypeList;
    var StoreShippingMethodRange = (function () {
        function StoreShippingMethodRange(from, to, value) {
            if (from === void 0) { from = 0; }
            if (to === void 0) { to = 0; }
            if (value === void 0) { value = 0; }
            this.from = from;
            this.to = to;
            this.value = value;
            if (isNaN(this.from))
                this.from = 0;
            if (isNaN(this.to))
                this.to = 0;
            if (isNaN(this.value))
                this.value = 0;
        }
        return StoreShippingMethodRange;
    }());
    exports.StoreShippingMethodRange = StoreShippingMethodRange;
    var StoreShippingMethod = (function (_super) {
        __extends(StoreShippingMethod, _super);
        function StoreShippingMethod(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.id = 0;
            _this.name = "";
            _this.destinationZoneId = 0;
            _this.type = StoreShippingMethodType.FREE;
            _this.ranges = [];
            _this.estimatedShippingTime = { from: 0, to: 0 };
            _this.deserialize(data);
            return _this;
        }
        return StoreShippingMethod;
    }(Serializable_8.Serializable));
    exports.StoreShippingMethod = StoreShippingMethod;
});
define("store/StoreTypes", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var StoreCurrency = (function () {
        function StoreCurrency(code, prefix, postfix) {
            this.code = code;
            this.prefix = prefix;
            this.postfix = postfix;
        }
        return StoreCurrency;
    }());
    exports.StoreCurrency = StoreCurrency;
    var StorePriceOptions = (function () {
        function StorePriceOptions(decimalPoint, decimalPlaces, thousandsSeparator) {
            if (decimalPoint === void 0) { decimalPoint = '.'; }
            if (decimalPlaces === void 0) { decimalPlaces = 2; }
            if (thousandsSeparator === void 0) { thousandsSeparator = ''; }
            this.decimalPoint = decimalPoint;
            this.decimalPlaces = decimalPlaces;
            this.thousandsSeparator = thousandsSeparator;
        }
        return StorePriceOptions;
    }());
    exports.StorePriceOptions = StorePriceOptions;
});
define("UniqueIdentifier", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var UniqueIdentifier = (function () {
        function UniqueIdentifier() {
        }
        UniqueIdentifier.newId = function (list) {
            var i, id = 1;
            for (i = 0; i < list.length; i++) {
                if (id <= list[i].id)
                    id = list[i].id + 1;
            }
            return id;
        };
        UniqueIdentifier.assignIds = function (list) {
            var i, id = UniqueIdentifier.newId(list);
            for (i = 0; i < list.length; i++) {
                if (!list[i].id) {
                    list[i].id = id;
                    id++;
                }
            }
            return list;
        };
        return UniqueIdentifier;
    }());
    exports.UniqueIdentifier = UniqueIdentifier;
});
define("store/StoreModule", ["require", "exports", "store/StoreItem", "store/StoreItemType", "store/StoreItemFieldType", "store/StoreCategory", "store/StoreDestinationZone", "store/StoreTaxRule", "store/StoreShippingMethod", "store/StoreTypes", "Serializable", "UniqueIdentifier", "store/StoreItem", "store/StoreCategory"], function (require, exports, StoreItem_1, StoreItemType_1, StoreItemFieldType_1, StoreCategory_1, StoreDestinationZone_1, StoreTaxRule_1, StoreShippingMethod_1, StoreTypes_1, Serializable_9, UniqueIdentifier_1, StoreItem_2, StoreCategory_2) {
    "use strict";
    exports.__esModule = true;
    exports.Item = StoreItem_2.StoreItem;
    exports.Category = StoreCategory_2.StoreCategory;
    var itemTypesIdx = {};
    var itemFieldTypesIdx = {};
    var StoreModule = (function () {
        function StoreModule() {
            this.needToSave = false;
            this.needToTranslateItems = false;
            this.items = [];
            this.itemTypes = [];
            this.itemFieldTypes = [];
            this.categories = [];
            this.destinationZones = [];
            this.taxRules = [];
            this.shippingMethods = [];
            this.billingShippingRequired = null;
            this.currency = new StoreTypes_1.StoreCurrency('USD', '$', '');
            this.priceOptions = new StoreTypes_1.StorePriceOptions();
            this.minOrderPrice = 0;
            this.noPhotoImage = null;
            this.watermarkImage = null;
            this.showDates = false;
            this.showItemId = false;
            this.advancedInvoiceDocNumMode = false;
            this.invoiceDocumentNumberFormat = "INV {N:8}";
            this.termsCheckboxEnabled = false;
            this.termsCheckboxText = __('I agree to the Terms and Conditions');
            this.currencies = [
                new StoreTypes_1.StoreCurrency('USD', '$', ''),
                new StoreTypes_1.StoreCurrency('EUR', '€', ''),
                new StoreTypes_1.StoreCurrency('GBP', '£', ''),
                new StoreTypes_1.StoreCurrency('AED', '', ''),
                new StoreTypes_1.StoreCurrency('AFN', '', ''),
                new StoreTypes_1.StoreCurrency('ALL', '', ''),
                new StoreTypes_1.StoreCurrency('AMD', '', ' ֏'),
                new StoreTypes_1.StoreCurrency('ANG', '', ''),
                new StoreTypes_1.StoreCurrency('AOA', '', ''),
                new StoreTypes_1.StoreCurrency('ARS', '$', ''),
                new StoreTypes_1.StoreCurrency('AUD', 'A$', ''),
                new StoreTypes_1.StoreCurrency('AWG', '', ''),
                new StoreTypes_1.StoreCurrency('AZN', '', ' ₼'),
                new StoreTypes_1.StoreCurrency('BAM', '', ''),
                new StoreTypes_1.StoreCurrency('BBD', '', ''),
                new StoreTypes_1.StoreCurrency('BDT', '', ''),
                new StoreTypes_1.StoreCurrency('BGN', '', ' лв.'),
                new StoreTypes_1.StoreCurrency('BHD', '', ''),
                new StoreTypes_1.StoreCurrency('BIF', '', ''),
                new StoreTypes_1.StoreCurrency('BMD', '', ''),
                new StoreTypes_1.StoreCurrency('BND', '', ''),
                new StoreTypes_1.StoreCurrency('BOB', '', ''),
                new StoreTypes_1.StoreCurrency('BRL', '', ''),
                new StoreTypes_1.StoreCurrency('BSD', '', ''),
                new StoreTypes_1.StoreCurrency('BTN', '', ''),
                new StoreTypes_1.StoreCurrency('BWP', '', ''),
                new StoreTypes_1.StoreCurrency('BYN', '', ' Br'),
                new StoreTypes_1.StoreCurrency('BZD', '', ''),
                new StoreTypes_1.StoreCurrency('CAD', 'C$', ''),
                new StoreTypes_1.StoreCurrency('CDF', '', ''),
                new StoreTypes_1.StoreCurrency('CHF', '', ' Fr'),
                new StoreTypes_1.StoreCurrency('CLP', '', ' $'),
                new StoreTypes_1.StoreCurrency('CNY', '', '¥'),
                new StoreTypes_1.StoreCurrency('COP', '$', ''),
                new StoreTypes_1.StoreCurrency('CRC', '', ''),
                new StoreTypes_1.StoreCurrency('CUC', '', ''),
                new StoreTypes_1.StoreCurrency('CUP', '', ''),
                new StoreTypes_1.StoreCurrency('CVE', '', ''),
                new StoreTypes_1.StoreCurrency('CZK', '', ' Kč'),
                new StoreTypes_1.StoreCurrency('DJF', '', ''),
                new StoreTypes_1.StoreCurrency('DKK', '', ' kr'),
                new StoreTypes_1.StoreCurrency('DOP', '', ''),
                new StoreTypes_1.StoreCurrency('DZD', '', ''),
                new StoreTypes_1.StoreCurrency('EGP', '', ' L.E.'),
                new StoreTypes_1.StoreCurrency('ERN', '', ''),
                new StoreTypes_1.StoreCurrency('ETB', '', ''),
                new StoreTypes_1.StoreCurrency('FJD', '', ''),
                new StoreTypes_1.StoreCurrency('FKP', '', ''),
                new StoreTypes_1.StoreCurrency('GEL', '', ''),
                new StoreTypes_1.StoreCurrency('GGP', '', ''),
                new StoreTypes_1.StoreCurrency('GHS', '', ''),
                new StoreTypes_1.StoreCurrency('GIP', '', ''),
                new StoreTypes_1.StoreCurrency('GMD', '', ''),
                new StoreTypes_1.StoreCurrency('GNF', '', ''),
                new StoreTypes_1.StoreCurrency('GTQ', '', ' Q'),
                new StoreTypes_1.StoreCurrency('GYD', '', ''),
                new StoreTypes_1.StoreCurrency('HKD', 'HK$', ''),
                new StoreTypes_1.StoreCurrency('HNL', '', ''),
                new StoreTypes_1.StoreCurrency('HRK', '', ' kn'),
                new StoreTypes_1.StoreCurrency('HTG', '', ''),
                new StoreTypes_1.StoreCurrency('HUF', '', ' Ft'),
                new StoreTypes_1.StoreCurrency('IDR', 'Rp', ''),
                new StoreTypes_1.StoreCurrency('ILS', '₪', ''),
                new StoreTypes_1.StoreCurrency('IMP', '', ''),
                new StoreTypes_1.StoreCurrency('INR', '₹', ''),
                new StoreTypes_1.StoreCurrency('IQD', '', ''),
                new StoreTypes_1.StoreCurrency('IRR', '', ''),
                new StoreTypes_1.StoreCurrency('ISK', '', ' kr'),
                new StoreTypes_1.StoreCurrency('JEP', '', ''),
                new StoreTypes_1.StoreCurrency('JMD', '', ''),
                new StoreTypes_1.StoreCurrency('JOD', '', ''),
                new StoreTypes_1.StoreCurrency('JPY', '¥', ''),
                new StoreTypes_1.StoreCurrency('KES', '', ''),
                new StoreTypes_1.StoreCurrency('KGS', '', ''),
                new StoreTypes_1.StoreCurrency('KHR', '', ''),
                new StoreTypes_1.StoreCurrency('KMF', '', ''),
                new StoreTypes_1.StoreCurrency('KPW', '', ''),
                new StoreTypes_1.StoreCurrency('KRW', '₩', ''),
                new StoreTypes_1.StoreCurrency('KWD', '', ''),
                new StoreTypes_1.StoreCurrency('KYD', '', ''),
                new StoreTypes_1.StoreCurrency('KZT', '', ' тңг'),
                new StoreTypes_1.StoreCurrency('LAK', '', ''),
                new StoreTypes_1.StoreCurrency('LBP', '', ''),
                new StoreTypes_1.StoreCurrency('LKR', '', ''),
                new StoreTypes_1.StoreCurrency('LRD', '', ''),
                new StoreTypes_1.StoreCurrency('LSL', '', ''),
                new StoreTypes_1.StoreCurrency('LYD', '', ''),
                new StoreTypes_1.StoreCurrency('MAD', '', ''),
                new StoreTypes_1.StoreCurrency('MDL', '', ' lei'),
                new StoreTypes_1.StoreCurrency('MGA', '', ''),
                new StoreTypes_1.StoreCurrency('MKD', '', ''),
                new StoreTypes_1.StoreCurrency('MMK', '', ''),
                new StoreTypes_1.StoreCurrency('MNT', '', ''),
                new StoreTypes_1.StoreCurrency('MOP', '', ''),
                new StoreTypes_1.StoreCurrency('MRU', '', ''),
                new StoreTypes_1.StoreCurrency('MUR', '', ''),
                new StoreTypes_1.StoreCurrency('MVR', '', ''),
                new StoreTypes_1.StoreCurrency('MWK', '', ''),
                new StoreTypes_1.StoreCurrency('MXN', 'Mex$', ''),
                new StoreTypes_1.StoreCurrency('MYR', 'RM', ''),
                new StoreTypes_1.StoreCurrency('MZN', '', ''),
                new StoreTypes_1.StoreCurrency('NAD', '', ''),
                new StoreTypes_1.StoreCurrency('NGN', '', ''),
                new StoreTypes_1.StoreCurrency('NIO', '', ''),
                new StoreTypes_1.StoreCurrency('NOK', '', ' kr'),
                new StoreTypes_1.StoreCurrency('NPR', '', ''),
                new StoreTypes_1.StoreCurrency('NZD', 'NZ$', ''),
                new StoreTypes_1.StoreCurrency('OMR', '', ''),
                new StoreTypes_1.StoreCurrency('PAB', '', ''),
                new StoreTypes_1.StoreCurrency('PEN', 'S/ ', ''),
                new StoreTypes_1.StoreCurrency('PGK', '', ''),
                new StoreTypes_1.StoreCurrency('PHP', '₱', ''),
                new StoreTypes_1.StoreCurrency('PKR', '', ''),
                new StoreTypes_1.StoreCurrency('PLN', '', ' zł'),
                new StoreTypes_1.StoreCurrency('PRB', '', ''),
                new StoreTypes_1.StoreCurrency('PYG', '', ''),
                new StoreTypes_1.StoreCurrency('QAR', '', ' QR'),
                new StoreTypes_1.StoreCurrency('RON', '', ' Lei'),
                new StoreTypes_1.StoreCurrency('RSD', '', ' din'),
                new StoreTypes_1.StoreCurrency('RUB', '', ' ₽'),
                new StoreTypes_1.StoreCurrency('RWF', '', ''),
                new StoreTypes_1.StoreCurrency('SAR', '', ' SR'),
                new StoreTypes_1.StoreCurrency('SBD', '', ''),
                new StoreTypes_1.StoreCurrency('SCR', '', ''),
                new StoreTypes_1.StoreCurrency('SDG', '', ''),
                new StoreTypes_1.StoreCurrency('SEK', '', ' kr'),
                new StoreTypes_1.StoreCurrency('SGD', 'S$', ''),
                new StoreTypes_1.StoreCurrency('SHP', '', ''),
                new StoreTypes_1.StoreCurrency('SLL', '', ''),
                new StoreTypes_1.StoreCurrency('SOS', '', ''),
                new StoreTypes_1.StoreCurrency('SRD', '', ''),
                new StoreTypes_1.StoreCurrency('SSP', '', ''),
                new StoreTypes_1.StoreCurrency('STN', '', ''),
                new StoreTypes_1.StoreCurrency('SYP', '', ''),
                new StoreTypes_1.StoreCurrency('SZL', '', ''),
                new StoreTypes_1.StoreCurrency('THB', '', ' ฿'),
                new StoreTypes_1.StoreCurrency('TJS', '', ''),
                new StoreTypes_1.StoreCurrency('TMT', '', ' m'),
                new StoreTypes_1.StoreCurrency('TND', '', ''),
                new StoreTypes_1.StoreCurrency('TOP', '', ''),
                new StoreTypes_1.StoreCurrency('TRY', '', ' TL'),
                new StoreTypes_1.StoreCurrency('TTD', '', ''),
                new StoreTypes_1.StoreCurrency('TVD', '', ''),
                new StoreTypes_1.StoreCurrency('TWD', 'NT$', ''),
                new StoreTypes_1.StoreCurrency('TZS', '', ''),
                new StoreTypes_1.StoreCurrency('UAH', '', ' грн'),
                new StoreTypes_1.StoreCurrency('UGX', '', ''),
                new StoreTypes_1.StoreCurrency('UYU', '', ''),
                new StoreTypes_1.StoreCurrency('UZS', '', ' som'),
                new StoreTypes_1.StoreCurrency('VEF', 'Bs. ', ''),
                new StoreTypes_1.StoreCurrency('VES', '', ''),
                new StoreTypes_1.StoreCurrency('VND', '', '₫'),
                new StoreTypes_1.StoreCurrency('VUV', '', ''),
                new StoreTypes_1.StoreCurrency('WST', '', ''),
                new StoreTypes_1.StoreCurrency('XAF', '', ''),
                new StoreTypes_1.StoreCurrency('XCD', '', ''),
                new StoreTypes_1.StoreCurrency('XOF', '', ''),
                new StoreTypes_1.StoreCurrency('XPF', '', ''),
                new StoreTypes_1.StoreCurrency('YER', '', ''),
                new StoreTypes_1.StoreCurrency('ZAR', 'R ', ''),
                new StoreTypes_1.StoreCurrency('ZMW', '', '')
            ];
            this.contactForm = { content: { button: __('Inquire'), fields: [
                        { checked: true, name: __('Name') },
                        { checked: true, name: __('Email') },
                        { checked: false }, { checked: false },
                        { checked: true, name: __('Address') },
                        { checked: false }, { checked: false }, { checked: false }, { checked: false },
                        { checked: true, name: __('Comments') }
                    ] } };
            this.companyInfo = "";
            this.paymentGateways = [];
            this.dataLoaded = false;
            this.builder = null;
            this.saveProvider = false;
        }
        StoreModule.prototype.init = function (builder) {
            this.builder = builder;
            this.needToTranslateItems = this.builder.translateStoreItems ? true : false;
        };
        StoreModule.prototype.sortItems = function () {
            this.items.sort(function (a, b) { return (a.itemType == b.itemType) ? 0 : (a.itemType < b.itemType ? -1 : 1); });
        };
        StoreModule.prototype.prepareIdexes = function () {
            itemTypesIdx = {};
            for (var _i = 0, _a = this.itemTypes; _i < _a.length; _i++) {
                var item = _a[_i];
                itemTypesIdx['#' + item.id] = item;
            }
            itemFieldTypesIdx = {};
            for (var _b = 0, _c = this.itemFieldTypes; _b < _c.length; _b++) {
                var item = _c[_b];
                itemFieldTypesIdx['#' + item.id] = item;
            }
        };
        StoreModule.prototype.findItemTypeById = function (id) {
            return (('#' + id) in itemTypesIdx) ? itemTypesIdx['#' + id] : null;
        };
        StoreModule.prototype.findItemFieldTypeById = function (id) {
            return (('#' + id) in itemFieldTypesIdx) ? itemFieldTypesIdx['#' + id] : null;
        };
        StoreModule.prototype.findItemTypeField = function (itemType, id) {
            for (var _i = 0, _a = itemType.fields; _i < _a.length; _i++) {
                var field = _a[_i];
                if (field.id === id)
                    return field;
            }
            return null;
        };
        StoreModule.prototype.buildSearchBlob = function (item) {
            var value = __tr(item.name) + '; ' + item.id;
            var itemType = this.findItemTypeById(item.itemType);
            if (itemType) {
                for (var _i = 0, _a = item.customFields; _i < _a.length; _i++) {
                    var field = _a[_i];
                    value += '; ' + this.stringifyFieldValue(field, this.findItemTypeField(itemType, field.fieldId));
                }
            }
            return value.toLowerCase();
        };
        StoreModule.prototype.stringifyFieldValue = function (customFieldValue, fieldData) {
            if (!customFieldValue || !fieldData)
                return null;
            var fieldValue = customFieldValue.value;
            var fieldTypeData = this.findItemFieldTypeById(fieldData.type);
            if (fieldTypeData && fieldTypeData.options && fieldTypeData.options.length > 0) {
                var fieldValueArr = isNaN(fieldValue) ? fieldValue : [fieldValue];
                if (fieldValueArr instanceof Array) {
                    var fieldValueArrNew = [];
                    for (var _i = 0, _a = fieldTypeData.options; _i < _a.length; _i++) {
                        var opt = _a[_i];
                        for (var _b = 0, fieldValueArr_1 = fieldValueArr; _b < fieldValueArr_1.length; _b++) {
                            var val = fieldValueArr_1[_b];
                            if (opt.id != val)
                                continue;
                            fieldValueArrNew.push(__tr(opt.name));
                            break;
                        }
                    }
                    fieldValue = fieldValueArrNew.join(', ');
                }
            }
            else {
                fieldValue = __tr(fieldValue);
            }
            if (typeof fieldValue === 'string')
                fieldValue = JSON.stringify(fieldValue);
            if (isNaN(fieldValue) && !fieldValue)
                return null;
            return fieldValue;
        };
        StoreModule.prototype.formatDate = function (date) {
            if (!date)
                return '';
            var parts = date.match(/([0-9]+)\-([0-9]+)\-([0-9]+)\ ([0-9]+)\:([0-9]+)\:([0-9]+)/);
            if (!parts)
                return '';
            return parts[1] + '-' + parts[2] + '-' + parts[3] + ' ' + parts[4] + ':' + parts[5];
        };
        StoreModule.prototype.buildDate = function () {
            var date = new Date(), year = ('' + date.getFullYear()), month = ('' + (date.getMonth() + 1)), day = ('' + date.getDate()), hours = ('' + date.getHours()), minutes = ('' + date.getMinutes()), seconds = ('' + date.getSeconds());
            return year
                + '-' + ((month.length == 1) ? ('0' + month) : month)
                + '-' + ((day.length == 1) ? ('0' + day) : day)
                + ' ' + ((hours.length == 1) ? ('0' + hours) : hours)
                + ':' + ((minutes.length == 1) ? ('0' + minutes) : minutes)
                + ':' + ((seconds.length == 1) ? ('0' + seconds) : seconds);
        };
        StoreModule.prototype.getFormattedPrice = function (price, point, places, currency, thousandsSeparator) {
            if (thousandsSeparator === void 0) { thousandsSeparator = this.priceOptions.thousandsSeparator; }
            point = point ? point : this.priceOptions.decimalPoint;
            places = places ? places : this.priceOptions.decimalPlaces;
            price = (price + '').replace(/[^0-9+\-Ee.]/g, '');
            var n = !isFinite(+price) ? 0 : +price;
            var prec = !isFinite(+places) ? 0 : Math.abs(places);
            var sep = (typeof thousandsSeparator === 'undefined') ? '' : thousandsSeparator;
            var dec = (typeof point === 'undefined') ? '.' : point;
            var toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.round(n * k) / k;
            };
            var s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
            if (s[0].length > 3) {
                s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
            }
            if ((s[1] || '').length < prec) {
                s[1] = s[1] || '';
                s[1] += new Array(prec - s[1].length + 1).join('0');
            }
            price = s.join(dec);
            var prefix = currency ? currency.prefix : '';
            var postfix = currency ? (currency.postfix ? currency.postfix : ((currency.code && !prefix) ? (' ' + currency.code) : '')) : '';
            return prefix + price + postfix;
        };
        StoreModule.prototype.load = function (func, noDefault) {
            var _this = this;
            var url = (this.builder ? this.builder.lnBaseUrl : '') + 'store/data/?tr=' + (this.needToTranslateItems ? '1' : '0') + '&nodefault=' + (noDefault ? '1' : '0');
            this.dataLoaded = false;
            $.get(url).done(function (data) {
                _this.dataLoaded = true;
                if (data) {
                    if (data.items) {
                        _this.items = UniqueIdentifier_1.UniqueIdentifier.assignIds(Serializable_9.Serializable.deserializeArray(StoreItem_1.StoreItem, data.items));
                    }
                    if (data.itemTypes) {
                        _this.itemTypes = UniqueIdentifier_1.UniqueIdentifier.assignIds(Serializable_9.Serializable.deserializeArray(StoreItemType_1.StoreItemType, data.itemTypes));
                    }
                    if (data.itemFieldTypes) {
                        _this.itemFieldTypes = UniqueIdentifier_1.UniqueIdentifier.assignIds(Serializable_9.Serializable.deserializeArray(StoreItemFieldType_1.StoreItemFieldType, data.itemFieldTypes, StoreItemFieldType_1.StoreItemFieldType.buildStaticTypes()));
                    }
                    if (data.categories) {
                        _this.categories = UniqueIdentifier_1.UniqueIdentifier.assignIds(Serializable_9.Serializable.deserializeArray(StoreCategory_1.StoreCategory, data.categories));
                    }
                    if (data.destinationZones) {
                        _this.destinationZones = UniqueIdentifier_1.UniqueIdentifier.assignIds(Serializable_9.Serializable.deserializeArray(StoreDestinationZone_1.StoreDestinationZone, data.destinationZones));
                    }
                    if (data.taxRules) {
                        _this.taxRules = UniqueIdentifier_1.UniqueIdentifier.assignIds(Serializable_9.Serializable.deserializeArray(StoreTaxRule_1.StoreTaxRule, data.taxRules));
                    }
                    if (data.shippingMethods) {
                        _this.shippingMethods = UniqueIdentifier_1.UniqueIdentifier.assignIds(Serializable_9.Serializable.deserializeArray(StoreShippingMethod_1.StoreShippingMethod, data.shippingMethods));
                    }
                    if ('billingShippingRequired' in data) {
                        _this.billingShippingRequired = data.billingShippingRequired;
                    }
                    if (data.currency)
                        _this.currency = data.currency;
                    if (data.priceOptions)
                        _this.priceOptions = data.priceOptions;
                    if (data.currencies)
                        _this.currencies = data.currencies;
                    if (data.noPhotoImage)
                        _this.noPhotoImage = data.noPhotoImage;
                    if (data.watermarkImage)
                        _this.watermarkImage = data.watermarkImage;
                    _this.showDates = data.showDates ? true : false;
                    _this.showItemId = data.showItemId ? true : false;
                    if (data.contactForm)
                        _this.contactForm = data.contactForm;
                    if (data.paymentGateways)
                        _this.paymentGateways = data.paymentGateways;
                    if (data.invoiceDocumentNumberFormat)
                        _this.invoiceDocumentNumberFormat = data.invoiceDocumentNumberFormat;
                    if (data.companyInfo)
                        _this.companyInfo = data.companyInfo;
                    if (data.termsCheckboxEnabled)
                        _this.termsCheckboxEnabled = data.termsCheckboxEnabled;
                    if (data.termsCheckboxText)
                        _this.termsCheckboxText = data.termsCheckboxText;
                    if (data.minOrderPrice)
                        _this.minOrderPrice = data.minOrderPrice;
                    if (data.hasOwnProperty("advancedInvoiceDocNumMode")) {
                        _this.advancedInvoiceDocNumMode = !!data.advancedInvoiceDocNumMode;
                    }
                    else {
                        _this.advancedInvoiceDocNumMode = !/^([^{}]+ |){N:\d+}$/i.test(_this.invoiceDocumentNumberFormat);
                    }
                }
                if (!_this.saveProvider && _this.builder) {
                    _this.saveProvider = true;
                    _this.builder.regSaveDataProvider('store', function () { return (_this.needToSave ? _this.serialize() : null); });
                }
                if (typeof func === 'function')
                    func.call(_this);
            }).fail(function () {
                console.error('Loading store data failed.');
            });
        };
        StoreModule.prototype.serialize = function () {
            return {
                currency: this.currency,
                priceOptions: this.priceOptions,
                items: Serializable_9.Serializable.copy(this.items),
                itemTypes: Serializable_9.Serializable.copy(this.itemTypes),
                itemFieldTypes: Serializable_9.Serializable.serializeValue(this.itemFieldTypes, null, function (idx, itm) { return !itm.isStatic; }),
                categories: Serializable_9.Serializable.copy(this.categories),
                destinationZones: Serializable_9.Serializable.copy(this.destinationZones),
                taxRules: Serializable_9.Serializable.copy(this.taxRules),
                shippingMethods: Serializable_9.Serializable.copy(this.shippingMethods),
                billingShippingRequired: this.billingShippingRequired,
                noPhotoImage: this.noPhotoImage,
                watermarkImage: this.watermarkImage,
                showDates: this.showDates,
                showItemId: this.showItemId,
                contactForm: this.contactForm,
                paymentGateways: this.paymentGateways,
                advancedInvoiceDocNumMode: this.advancedInvoiceDocNumMode,
                invoiceDocumentNumberFormat: this.invoiceDocumentNumberFormat,
                companyInfo: this.companyInfo,
                termsCheckboxEnabled: this.termsCheckboxEnabled,
                termsCheckboxText: this.termsCheckboxText,
                minOrderPrice: this.minOrderPrice
            };
        };
        return StoreModule;
    }());
    exports.Module = new StoreModule();
});
define("List", ["require", "exports", "UIComponent"], function (require, exports, UIComponent_7) {
    "use strict";
    exports.__esModule = true;
    var List = (function (_super) {
        __extends(List, _super);
        function List() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        List.prototype.buildInit = function (data, fields) {
            var _this = this;
            this._control = new WB_ListControl({
                type: (data.itemType ? data.itemType : null),
                editable: (!!data.editable),
                sortable: (('sortable' in data) ? (!!data.sortable) : true),
                addNewItemsToBeginning: (('addNewItemsToBeginning' in data) ? data.addNewItemsToBeginning : false),
                newItemButtonText: (('newItemButtonText' in data) ? data.newItemButtonText : null)
            });
            this._elem = this._control.elem;
            if (data.listHeight)
                this._control.setHeight(data.listHeight);
            if (typeof data.select === 'function') {
                (function (el, func) {
                    _this._control.options.onSelect = function (obj) { return func.call(el, fields, obj, this); };
                })(this, data.select);
            }
            if (typeof data.selectNone === 'function') {
                (function (el, func) {
                    _this._control.options.onSelectNone = function () { return func.call(el, fields); };
                })(this, data.selectNone);
            }
            if (typeof data.add === 'function') {
                (function (el, func) {
                    el._control.options.onAdd = function (obj) { return func.call(el, fields, obj, this.get(0)); };
                })(this, data.add);
            }
            if (typeof data.remove === 'function') {
                (function (el, func) {
                    el._control.options.onRemove = function (obj) { return func.call(el, fields, obj, this.get(0)); };
                })(this, data.remove);
            }
        };
        List.prototype.setValue = function (value) {
            this._control.setValue(value);
        };
        List.prototype.getValue = function () {
            return this._control.getValue();
        };
        List.prototype.setItemIcon = function (li, icon) {
            this._control.setItemIcon(li, icon);
        };
        List.prototype.addItem = function (item, noStyleUpdate, icon, disabled) {
            return this._control.addItem(item, noStyleUpdate, icon, disabled);
        };
        List.prototype.setItemLiEnabled = function (li, enabled) {
            this._control.setItemLiEnabled(li, enabled);
        };
        List.prototype.addSeparator = function () {
            this._control.addSeparator();
        };
        List.prototype.removeAllItems = function () {
            this._control.removeAllItems();
        };
        List.prototype.selectFirst = function () {
            this._control.selectFirst();
        };
        List.prototype.selectItemLi = function (li) {
            this._control.selectItemLi(li);
        };
        List.prototype.getItemsLi = function () {
            return this._control.getItemsLi();
        };
        List.prototype.getItems = function (asInst) {
            if (asInst === void 0) { asInst = false; }
            return this._control.getItems(asInst);
        };
        List.prototype.getLastSelected = function () {
            return this._control.lastSelected;
        };
        List.prototype.getLastSelectedLi = function () {
            return this._control.lastSelectedLi;
        };
        ;
        return List;
    }(UIComponent_7.UIComponent));
    exports.List = List;
});
define("DropdownBox", ["require", "exports", "UIComponent"], function (require, exports, UIComponent_8) {
    "use strict";
    exports.__esModule = true;
    var currentlyOpen = null, docCallback = null, searchIdx = -1;
    var DropdownBox = (function (_super) {
        __extends(DropdownBox, _super);
        function DropdownBox(options) {
            var _this = _super.call(this) || this;
            _this._open = false;
            _this._items = [];
            _this._itemsIndex = {};
            _this._selectedItem = null;
            _this._itemMouseEnterFunc = null;
            _this._itemMouseLeaveFunc = null;
            _this.fields = {};
            _this.editItem = null;
            _this.optionsSource = null;
            _this.multiselect = false;
            _this.addSelectAll = false;
            _this.multilevel = false;
            _this.parentMustBeSelected = false;
            _this.onEditFunc = null;
            _this.selectAllItems = {};
            _this._elem
                .addClass('input-group wb-combobox-controll')
                .on('keydown', function (e) {
                if (!_this._open)
                    return undefined;
                var nItem, itemTop, itemHeight, menuScrollTop = _this._menu.scrollTop(), menuHeight = _this._menu.outerHeight(), item = Item.fromElem(_this._menu.children('li.hover').eq(0));
                if (!item && _this._selectedItem) {
                    item = _this._selectedItem;
                }
                else if (!item && _this._items.length > 0) {
                    item = _this._items[0];
                }
                else if (!item) {
                    return undefined;
                }
                if (e.which === 13) {
                    _this.setOpen(false);
                    _this.selectItem(item);
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
                else if (e.which === 27) {
                    _this.setOpen(false);
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
                else if (e.which === 38) {
                    nItem = Item.fromElem(item._elem.prev('li'));
                    if (nItem) {
                        item._elem.removeClass('hover');
                        nItem._elem.addClass('hover');
                        itemTop = nItem._elem.get(0).offsetTop;
                        if (itemTop <= menuScrollTop) {
                            _this._menu.scrollTop(itemTop);
                        }
                    }
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
                else if (e.which === 40) {
                    nItem = Item.fromElem(item._elem.next('li'));
                    if (nItem) {
                        item._elem.removeClass('hover');
                        nItem._elem.addClass('hover');
                        itemTop = nItem._elem.get(0).offsetTop;
                        itemHeight = nItem._elem.outerHeight();
                        if ((itemTop + itemHeight) >= (menuScrollTop + menuHeight)) {
                            _this._menu.scrollTop(itemTop - menuHeight + itemHeight);
                        }
                    }
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
                return undefined;
            }).on('keypress', function (e) {
                if (!_this._open)
                    return undefined;
                var n, i = ((searchIdx >= 0) ? searchIdx : 0), ch = String.fromCharCode(e.which).toLowerCase(), itemTop, itemHeight, menuScrollTop = _this._menu.scrollTop(), menuHeight = _this._menu.outerHeight();
                for (n = 0; n < _this._items.length; n++) {
                    var title = _this._items[i].getTitle();
                    if (title && title.toLowerCase().charAt(0) === ch && searchIdx !== i) {
                        _this._items[i]._elem.parent().children('li').removeClass('hover');
                        _this._items[i]._elem.addClass('hover');
                        itemTop = _this._items[i]._elem.get(0).offsetTop;
                        itemHeight = _this._items[i]._elem.outerHeight();
                        if (itemTop <= menuScrollTop) {
                            _this._menu.scrollTop(itemTop);
                        }
                        else if ((itemTop + itemHeight) >= (menuScrollTop + menuHeight)) {
                            _this._menu.scrollTop(itemTop - menuHeight + itemHeight);
                        }
                        searchIdx = i;
                        break;
                    }
                    i++;
                    if (i >= _this._items.length)
                        i = 0;
                }
                e.preventDefault();
                e.stopPropagation();
                return false;
            });
            _this._input = $('<input>')
                .addClass('form-control')
                .attr({ type: 'text', readonly: 'readonly' })
                .appendTo(_this._elem)
                .on('click', function (e) { _this.onOpen(); e.stopPropagation(); return false; });
            _this._group = $('<div>').addClass('input-group-btn').appendTo(_this._elem);
            _this._btn = $('<button>')
                .addClass('btn btn-default dropdown-toggle')
                .attr({ type: 'button' })
                .append($('<span>').addClass('caret'))
                .appendTo(_this._group)
                .on('click', function (e) { _this.onOpen(); e.stopPropagation(); return false; });
            _this._menu = $('<ul>').addClass('dropdown-menu').appendTo(_this._group);
            _this._itemMouseEnterFunc = function () {
                var li = $(this);
                li.parent().children('li').removeClass('hover');
                li.addClass('hover');
            };
            _this._itemMouseLeaveFunc = function () {
                var li = $(this);
                li.removeClass('hover');
            };
            if (!docCallback) {
                $(document.body).on('click', docCallback = function () {
                    if (currentlyOpen)
                        currentlyOpen.setOpen(false);
                });
            }
            if (options && options.length) {
                for (var i = 0; i < options.length; i++) {
                    _this.addItem(options[i]);
                }
            }
            return _this;
        }
        DropdownBox.prototype.buildInit = function (data, fields) {
            var _this = this;
            this.fields = fields;
            if (data.css && typeof data.css === 'object' && data.css.width) {
                this._input.css({ width: (data.css.width - 26) });
            }
            if ('editable' in data) {
                this.setEditable(!!data.editable);
            }
            if (('edit' in data) && (typeof data.edit === 'function')) {
                this.onEditFunc = data.edit;
            }
            if ('multiselect' in data) {
                this.multiselect = !!data.multiselect;
            }
            if ('addSelectAll' in data) {
                this.addSelectAll = !!data.addSelectAll;
            }
            if ('parentMustBeSelected' in data) {
                this.parentMustBeSelected = !!data.parentMustBeSelected;
            }
            if (data.options && data.options instanceof Array) {
                this.optionsSource = data.options;
            }
            this.reload();
            if ('multilevel' in data) {
                this.setMultilevel(!!data.multilevel);
            }
            if (('change' in data) && (typeof data.change === 'function')) {
                (function (el, func) { el.on('change', function () { func.call(el, fields); }); })(this, data.change);
            }
            if (this.multilevel && this.parentMustBeSelected) {
                this.getElem().on("change", function () {
                    _this.setMultilevel(_this.multilevel);
                });
            }
            if (data.value)
                this.setValue(data.value);
        };
        DropdownBox.prototype.getValue = function (multiSelect) {
            if (multiSelect === void 0) { multiSelect = false; }
            if (multiSelect) {
                var i = void 0, list = [], items = this.getSelectedItems();
                for (i = 0; i < items.length; i++) {
                    list.push(items[i].getId());
                }
                return list;
            }
            else {
                var item = this.getSelectedItem();
                return item ? item.getId() : null;
            }
        };
        DropdownBox.prototype.setValue = function (value, multiSelect) {
            if (multiSelect === void 0) { multiSelect = false; }
            var i, item;
            if (multiSelect) {
                this.selectItem(null, false, false);
                for (i = 0; i < value.length; i++) {
                    item = this.getItemById(value[i]);
                    if (item)
                        this.selectItem(item, true, false);
                }
                this.updateValueText();
                this.setMultilevel(this.multilevel);
            }
            else {
                item = this.getItemById(value);
                if (!item)
                    item = this.getItem(0);
                this.selectItem(item);
            }
        };
        DropdownBox.prototype.setEditable = function (editable) {
            var _this = this;
            if (editable && !this.editItem) {
                this.editItem = new Item(__('Edit'), '__eidt__', {}, '', 'glyphicon glyphicon-pencil', false, true);
                this.editItem.on('click', function () { _this.onEdit(_this.fields); return false; });
            }
            else if (!editable && this.editItem) {
                this.removeItem(this.editItem);
                this.editItem = null;
            }
        };
        DropdownBox.prototype.onSelectAllClick = function (e) {
            e.stopImmediatePropagation();
            e.preventDefault();
            var data = e.target ? $(e.target).data() : null;
            if (data && data.hasOwnProperty("action") && data.hasOwnProperty("parentId")) {
                for (var _i = 0, _a = this._items; _i < _a.length; _i++) {
                    var item = _a[_i];
                    if (!item.multiSelect || item.nonSelectable)
                        continue;
                    var original = item.getOriginal();
                    if (!original || !this.isItemChildOf(original, data.parentId))
                        continue;
                    item.setChecked(data.action === "select");
                }
                if (this.parentMustBeSelected)
                    this.setMultilevel(this.multilevel);
                this.updateValueText();
            }
        };
        DropdownBox.prototype.reload = function (fromSource) {
            if (fromSource === void 0) { fromSource = null; }
            var selItems = this.getValue(this.multiselect);
            var elItem, saItem;
            this.removeAllItems();
            if (fromSource instanceof Array)
                this.optionsSource = fromSource;
            if (this.optionsSource instanceof Array) {
                for (var n = 0; n < this.optionsSource.length; n++) {
                    if (typeof this.optionsSource[n] === 'object' && this.optionsSource[n]) {
                        if (this.multiselect && this.addSelectAll) {
                            var parentId = (this.optionsSource[n].hasOwnProperty("parentId") ? this.optionsSource[n].parentId : 0);
                            var parentKey = "#" + parentId;
                            if (!this.selectAllItems.hasOwnProperty(parentKey)) {
                                saItem = new Item("Select All / Deselect All", "__select_all__" + parentId, { parentId: parentId }, "<small><a data-action=\"select\" data-parent-id=\"" + parentId + "\">Select All</a> / <a data-action=\"deselect\" data-parent-id=\"" + parentId + "\">Deselect All</a></small>", "", false, true);
                                saItem.on("click", this.onSelectAllClick.bind(this));
                                this.selectAllItems[parentKey] = saItem;
                                this.addItem(saItem);
                            }
                        }
                        elItem = new Item(__tr(this.optionsSource[n].name), this.optionsSource[n].id, this.optionsSource[n], this.optionsSource[n].html, '', this.multiselect);
                        this.addItem(elItem);
                    }
                }
            }
            if (this.editItem)
                this.addItem(this.editItem);
            if (this.multilevel)
                this.setMultilevel(this.multilevel);
            this.setValue(selItems, this.multiselect);
        };
        DropdownBox.prototype.isItemChildOf = function (item, parentId) {
            if (!parentId)
                return true;
            if (!item || !item.hasOwnProperty("parentId"))
                return null;
            if ("" + item.parentId === "" + parentId)
                return true;
            if (!item.parentId)
                return false;
            var parent = this.getItemById(item.parentId);
            if (!parent)
                return null;
            return this.isItemChildOf(parent.getOriginal(), parentId);
        };
        DropdownBox.prototype.getLevel = function (item, lvl) {
            if (!item)
                return lvl;
            var key = '#' + item.parentId;
            return (item.parentId && (key in this._itemsIndex)) ? this.getLevel(this._itemsIndex[key].getOriginal(), lvl + 1) : lvl;
        };
        DropdownBox.prototype.setMultilevel = function (multilevel) {
            this.multilevel = multilevel;
            if (multilevel) {
                for (var _i = 0, _a = this._items; _i < _a.length; _i++) {
                    var item = _a[_i];
                    var original = item.getOriginal();
                    var parent_2 = (this.parentMustBeSelected && original && original.parentId) ? this.getItemById(original.parentId) : null;
                    if (!parent_2 || parent_2.getChecked())
                        item.getElem().css({ display: "", paddingLeft: 20 * this.getLevel(original, 0) });
                    else
                        item.getElem().css({ display: "none" });
                }
            }
            else {
                for (var _b = 0, _c = this._items; _b < _c.length; _b++) {
                    var item = _c[_b];
                    item.getElem().css({ paddingLeft: 0 });
                }
            }
        };
        DropdownBox.prototype.onEdit = function (fields) {
            if (typeof this.onEditFunc === 'function')
                this.onEditFunc.call(this, fields);
        };
        DropdownBox.prototype.onOpen = function () {
            if (!this._enabled)
                return;
            this.setOpen(!this._open);
        };
        DropdownBox.prototype.getItems = function () {
            return this._items;
        };
        DropdownBox.prototype.getItemById = function (id) {
            var k = '#' + id;
            return (k in this._itemsIndex) ? this._itemsIndex[k] : null;
        };
        DropdownBox.prototype.getItem = function (index) {
            return (index >= 0 && index < this._items.length) ? this._items[index] : null;
        };
        DropdownBox.prototype.selectItem = function (item, select, updateValueAndStyles) {
            if (select === void 0) { select = false; }
            if (updateValueAndStyles === void 0) { updateValueAndStyles = true; }
            var i, idx, value = '';
            if (!item) {
                this._selectedItem = null;
                if (updateValueAndStyles)
                    this._input.val('');
                if (select === false) {
                    for (i = 0; i < this._items.length; i++) {
                        if (this._items[i].multiSelect)
                            this._items[i].setChecked(false);
                    }
                }
            }
            else if (!item.nonSelectable) {
                if (item.multiSelect) {
                    this._selectedItem = null;
                    if (this._items.indexOf(item) >= 0) {
                        item.setChecked((select || select === null || typeof select === 'undefined'));
                    }
                    if (updateValueAndStyles)
                        this.updateValueText();
                }
                else {
                    idx = this._items.indexOf(item);
                    if (idx >= 0) {
                        this._selectedItem = item;
                        if (updateValueAndStyles)
                            this.updateValueText();
                    }
                }
            }
            if (updateValueAndStyles && this.multilevel && this.parentMustBeSelected)
                this.setMultilevel(this.multilevel);
        };
        DropdownBox.prototype.updateValueText = function () {
            var i, value = "";
            if (this.multiselect) {
                for (i = 0; i < this._items.length; i++) {
                    if (this._items[i].getChecked()) {
                        if (this.parentMustBeSelected) {
                            var original = this._items[i].getOriginal();
                            if (original && original.parentId) {
                                var parent_3 = this.getItemById(original.parentId);
                                if (parent_3 && !parent_3.getChecked())
                                    continue;
                            }
                        }
                        value += (value.length ? '; ' : '') + this._items[i].getTitle();
                    }
                }
                this._input.val(value);
            }
            else {
                var item = this.getSelectedItem();
                this._input.val(item ? item.getTitle() : "");
            }
        };
        DropdownBox.prototype.getSelectedItem = function () {
            return this._selectedItem;
        };
        DropdownBox.prototype.getSelectedItems = function () {
            var i, list = [];
            for (i = 0; i < this._items.length; i++) {
                if (this._items[i].getChecked())
                    list.push(this._items[i]);
            }
            return list;
        };
        DropdownBox.prototype.addItem = function (item) {
            var _this = this;
            var idx = this._items.indexOf(item);
            if (idx < 0) {
                this._items.push(item);
                if (item._id)
                    this._itemsIndex['#' + item._id] = item;
                this._menu.append(item._elem);
                item._selectFunc = function () {
                    if (item.multiSelect) {
                        _this.selectItem(item, !item.getChecked());
                    }
                    else {
                        _this.selectItem(item);
                    }
                    if (!item.multiSelect)
                        _this.setOpen(false);
                    _this.trigger('change');
                    if (item.multiSelect)
                        return false;
                    return undefined;
                };
                item.on('click', item._selectFunc);
                item.on('mouseenter', this._itemMouseEnterFunc);
                item.on('mouseleave', this._itemMouseLeaveFunc);
                if (this._items.length === 1) {
                    this.selectItem(item);
                }
            }
        };
        DropdownBox.prototype.removeItem = function (item) {
            var idx = this._items.indexOf(item);
            if (idx >= 0) {
                this._items.splice(idx, 1);
                if (item._id) {
                    delete this._itemsIndex['#' + item._id];
                }
                item._elem.detach();
                if (item._selectFunc) {
                    item.off('click', item._selectFunc);
                    item.off('mouseenter', this._itemMouseEnterFunc);
                    item.off('mouseleave', this._itemMouseLeaveFunc);
                }
            }
        };
        DropdownBox.prototype.removeAllItem = function () {
            this.removeAllItems();
        };
        DropdownBox.prototype.removeAllItems = function () {
            for (var i = 0; i < this._items.length; i++) {
                this._items[i]._elem.detach();
                if (this._items[i]._selectFunc) {
                    this._items[i].off('click', this._items[i]._selectFunc);
                    this._items[i].off('mouseenter', this._itemMouseEnterFunc);
                    this._items[i].off('mouseleave', this._itemMouseLeaveFunc);
                }
            }
            this._items.splice(0, this._items.length);
            this._itemsIndex = {};
            this.selectAllItems = {};
            this.selectItem(null);
        };
        DropdownBox.prototype.setOpen = function (open) {
            this._open = !!open;
            if (this._open) {
                if (currentlyOpen && currentlyOpen !== this)
                    currentlyOpen.setOpen(false);
                currentlyOpen = this;
                var w = this._input.outerWidth(false), css = { width: (this._input.outerWidth(false) + this._group.outerWidth(false)) + 'px' };
                if (wb_builder.rtl) {
                    css.right = ('-' + w + 'px');
                }
                else {
                    css.left = ('-' + w + 'px');
                }
                this._menu.css(css);
                this._group.addClass('open');
                if (this._selectedItem) {
                    this._selectedItem._elem.addClass('hover');
                    this._selectedItem._elem.get(0).scrollIntoView(false);
                    searchIdx = this._items.indexOf(this._selectedItem);
                }
                else {
                    searchIdx = -1;
                }
            }
            else {
                this._group.removeClass('open');
                if (currentlyOpen === this)
                    currentlyOpen = null;
            }
        };
        DropdownBox.prototype.getOpen = function () {
            return this._open;
        };
        DropdownBox.prototype.addMenuStyleClass = function (styleClass) {
            this._menu.addClass(styleClass);
        };
        DropdownBox.prototype.setEnabled = function (enabled) {
            _super.prototype.setEnabled.call(this, enabled);
            if (this._enabled) {
                this._btn.removeClass('disabled');
                this._elem.css({ cursor: '' });
            }
            else {
                this.setOpen(false);
                this._btn.addClass('disabled');
                this._elem.css({ cursor: 'not-allowed' });
            }
        };
        DropdownBox.prototype.on = function (event, func) {
            if (event === 'change') {
                this._input.on(event, func);
            }
            else {
                _super.prototype.on.call(this, event, func);
            }
            return this;
        };
        DropdownBox.prototype.off = function (event, func) {
            if (event === 'change') {
                this._input.off(event, func);
            }
            else {
                _super.prototype.off.call(this, event, func);
            }
            return this;
        };
        DropdownBox.prototype.trigger = function (event, extraParameters) {
            if (event === 'change') {
                this._input.trigger(event, extraParameters);
            }
            else {
                _super.prototype.trigger.call(this, event, extraParameters);
            }
            return this;
        };
        return DropdownBox;
    }(UIComponent_8.UIComponent));
    exports.DropdownBox = DropdownBox;
    var Item = (function () {
        function Item(title, id, original, htmlTitle, icon, multiSelect, nonSelectable) {
            if (original === void 0) { original = null; }
            if (htmlTitle === void 0) { htmlTitle = ''; }
            if (icon === void 0) { icon = ''; }
            if (multiSelect === void 0) { multiSelect = false; }
            if (nonSelectable === void 0) { nonSelectable = false; }
            this._original = null;
            this._cbwElem = null;
            this._cbElem = null;
            this._iconElem = null;
            this._selectFunc = null;
            this._selected = false;
            this._checked = false;
            this.multiSelect = false;
            this.nonSelectable = false;
            this._id = id;
            this._elem = $('<li>');
            this._elem.data('__META_INST__', this);
            if (multiSelect) {
                this.multiSelect = true;
                this._cbElem = $('<input>').attr({ type: 'checkbox' });
                this._cbwElem = $('<div>').addClass('wb-combobox-controll-cb').append(this._cbElem).appendTo(this._elem);
            }
            if (icon) {
                this._iconElem = $('<span>').addClass('wb-combobox-controll-icon').addClass(icon);
            }
            this.nonSelectable = !!nonSelectable;
            this._aElem = $('<a>').attr({ href: 'javascript:void(0)' }).appendTo(this._elem);
            this.setTitle(title);
            if (htmlTitle)
                this.setHtmlTitle(htmlTitle);
            this._original = original;
        }
        Item.fromElem = function (elem) {
            return elem.data('__META_INST__');
        };
        Item.prototype.getElem = function () {
            return this._elem;
        };
        Item.prototype.getId = function () {
            return this._id;
        };
        Item.prototype.getOriginal = function () {
            return this._original;
        };
        Item.prototype.setSelected = function (selected) {
            this._selected = !!selected;
            if (this._selected) {
                this._elem.addClass('active');
            }
            else {
                this._elem.removeClass('active');
            }
        };
        Item.prototype.getSelected = function () {
            return this._selected;
        };
        Item.prototype.setChecked = function (checked) {
            this._checked = !!checked;
            if (this._cbElem)
                this._cbElem.get(0).checked = this._checked;
        };
        Item.prototype.getChecked = function () {
            return this._checked;
        };
        Item.prototype.setTitle = function (title) {
            this._title = title;
            if (this._iconElem)
                this._iconElem.detach();
            this._aElem.text((this._title || this._id === 0) ? (this._title ? this._title : '\xA0') : ('[' + __('no name') + ']'));
            if (this._iconElem)
                this._aElem.prepend(this._iconElem);
        };
        Item.prototype.setHtmlTitle = function (title) {
            if (this._iconElem)
                this._iconElem.detach();
            this._aElem.html(title ? title : '');
            if (this._iconElem)
                this._aElem.prepend(this._iconElem);
        };
        Item.prototype.getTitle = function () {
            return this._title;
        };
        Item.prototype.on = function (event, func) {
            if (event === 'click') {
                this._aElem.on(event, func);
                if (this._cbwElem)
                    this._cbwElem.on(event, func);
            }
            else {
                this._elem.on(event, func);
            }
            return this;
        };
        Item.prototype.off = function (event, func) {
            if (event === 'click') {
                this._aElem.off(event, func);
            }
            else {
                this._elem.off(event, func);
            }
            return this;
        };
        return Item;
    }());
    exports.Item = Item;
    DropdownBox.Item = Item;
    exports["default"] = DropdownBox;
});
define("CustomContainer", ["require", "exports", "UIContainer"], function (require, exports, UIContainer_6) {
    "use strict";
    exports.__esModule = true;
    var CustomContainer = (function (_super) {
        __extends(CustomContainer, _super);
        function CustomContainer(tag) {
            return _super.call(this, (tag !== '%inherit%') ? tag : 'div') || this;
        }
        CustomContainer.prototype.buildInit = function (data, fields) {
            if (data.tag && this.tagType !== data.tag) {
                this.tagType = data.tag;
                this._elem = this._createElem();
            }
            if (data.content) {
                this._elem.append(data.content);
            }
        };
        CustomContainer.prototype.setContent = function (content) {
            this._elem.empty().append(content);
        };
        return CustomContainer;
    }(UIContainer_6.UIContainer));
    exports.CustomContainer = CustomContainer;
});
define("store/StoreOrders", ["require", "exports", "Service", "FlowLayout", "VerticalLayout", "DropdownBox", "Label", "PreloaderOverlay", "Dialog", "UIComponent", "store/StoreModule", "store/StoreTypes", "MsgDialog"], function (require, exports, Service_8, FlowLayout_2, VerticalLayout_4, DropdownBox_1, Label_3, PreloaderOverlay_2, Dialog_5, UIComponent_9, StoreModule_1, StoreTypes_2, MsgDialog_1) {
    "use strict";
    exports.__esModule = true;
    var ordersViewDialog = null;
    function viewOrders(builder) {
        if (!ordersViewDialog)
            ordersViewDialog = new OrdersDialog(builder);
        ordersViewDialog.setVisible(true);
    }
    exports.viewOrders = viewOrders;
    var StoreOrderState;
    (function (StoreOrderState) {
        StoreOrderState["PENDING"] = "pending";
        StoreOrderState["COMPLETE"] = "complete";
        StoreOrderState["FAILED"] = "failed";
        StoreOrderState["REFUNDED"] = "refunded";
        StoreOrderState["CANCELLED"] = "cancelled";
    })(StoreOrderState || (StoreOrderState = {}));
    var OrderListItem = (function () {
        function OrderListItem(item, actionCallback) {
            this.elem = null;
            this.detailsElem = null;
            this.detailsCell = null;
            this.removeButton = null;
            this.columns = [];
            this.data = item;
            this.actionCallback = actionCallback;
        }
        OrderListItem.prototype.getInvoiceLinkUrl = function () {
            return 'http://' + wb_builder.siteDomain + '/store-invoice/' + this.data.hash + (wb_builder.site.forceSlashes ? '/' : '');
        };
        OrderListItem.prototype.getElem = function () {
            var _this = this;
            if (!this.elem) {
                this.elem = $('<tr>');
                var currency = this.data.currency ? this.data.currency : null;
                var priceOptions = this.data.priceOptions ? this.data.priceOptions : new StoreTypes_2.StorePriceOptions();
                for (var i = 0; i < 8; i++) {
                    this.columns.push($('<td>').appendTo(this.elem));
                }
                var order = (('items' in this.data) && this.data.items) ? this.data.items : this.data.order;
                var canShowInvoice = false;
                if (typeof order !== 'string') {
                    for (var k in order) {
                        var item = order[k];
                        if (typeof item === "object") {
                            canShowInvoice = true;
                            break;
                        }
                    }
                }
                this.columns[0].text(this.data.transactionId);
                if (canShowInvoice && this.data.invoiceDocumentNumber)
                    this.columns[1].append($('<a target="_blank">').attr('href', this.getInvoiceLinkUrl()).text(this.data.invoiceDocumentNumber));
                this.columns[2].text(StoreModule_1.Module.formatDate(((('completeDateTime' in this.data) && this.data.completeDateTime) ? this.data.completeDateTime : this.data.dateTime)));
                this.columns[3].text(this.data.billingInfo ? (this.data.billingInfo.isCompany ? this.data.billingInfo.companyName : (this.data.billingInfo.firstName + " " + this.data.billingInfo.lastName)) : "");
                this.columns[4].text(this.data.billingInfo ? this.data.billingInfo.email : "");
                this.columns[5].text(StoreModule_1.Module.getFormattedPrice(this.data.price, priceOptions.decimalPoint, priceOptions.decimalPlaces, currency, priceOptions.thousandsSeparator));
                this.columns[6].text(OrderListItem.trState(this.data.state));
                var btn = $('<a href="javascript:void(0)">').text(__('Details'));
                this.columns[7].append(btn);
                btn.on("click touchend", function () {
                    if (_this.detailsElem)
                        _this.detailsElem.toggleClass("hidden");
                });
            }
            return this.elem;
        };
        OrderListItem.billingInfoFilter = function (obj, fieldName) {
            if (fieldName == "isCompany")
                return false;
            var isCompany = obj.isCompany;
            if (isCompany && (fieldName == "firstName" || fieldName == "lastName"))
                return false;
            if (!isCompany && (fieldName == "companyName" || fieldName == "companyCode" || fieldName == "companyVatCode"))
                return false;
            return true;
        };
        OrderListItem.prototype.getDetailsElem = function () {
            var _this = this;
            if (!this.detailsElem) {
                if (!this.elem)
                    this.getElem();
                this.detailsCell = $('<td>').css({ padding: "15px" });
                this.detailsCell.attr("colspan", this.columns.length);
                var currency = this.data.currency ? this.data.currency : null;
                var priceOptions = this.data.priceOptions ? this.data.priceOptions : new StoreTypes_2.StorePriceOptions();
                var order = (('items' in this.data) && this.data.items) ? this.data.items : this.data.order;
                var canShowInvoice = false;
                if (typeof order !== 'string') {
                    var tmp = [];
                    for (var k in order) {
                        var item = order[k];
                        if (typeof item === "object") {
                            canShowInvoice = true;
                            var name_1 = item.name;
                            if (typeof name_1 === "object") {
                                var defaultLang = wb_builder.site.getLastDefLang();
                                if (defaultLang && name_1.hasOwnProperty(defaultLang) && name_1[defaultLang] !== '')
                                    name_1 = name_1[defaultLang];
                                else if (wb_builder.site.currSelLang && name_1.hasOwnProperty(wb_builder.site.currSelLang) && name_1[wb_builder.site.currSelLang] !== '')
                                    name_1 = name_1[wb_builder.site.currSelLang];
                                else {
                                    for (var i in name_1) {
                                        if (name_1[i] !== '') {
                                            name_1 = name_1[i];
                                            break;
                                        }
                                    }
                                    if (typeof (name_1) !== 'string')
                                        name_1 = '';
                                }
                            }
                            tmp.push(name_1
                                + " (" + __('SKU') + ": " + item.sku + ")"
                                + " (" + __('Price') + ": " + StoreModule_1.Module.getFormattedPrice(item.price, priceOptions.decimalPoint, priceOptions.decimalPlaces, currency, priceOptions.thousandsSeparator) + ")"
                                + " (" + __('Qty') + ": " + item.quantity + ")");
                        }
                        else
                            tmp.push(item);
                    }
                    order = tmp.join("\n");
                }
                var row = void 0;
                var cell = void 0;
                this.detailsCell.append(row = $('<div class="row">'));
                var language = "";
                if (this.data.lang) {
                    language = this.data.lang;
                    for (var _i = 0, _a = wb_builder.availableLanguages; _i < _a.length; _i++) {
                        var siteLang = _a[_i];
                        if (siteLang.code == this.data.lang) {
                            language = siteLang.name + ' (' + siteLang.locale.replace("_", "-") + ')';
                            break;
                        }
                    }
                }
                var stateField = void 0;
                row.append(cell = $('<div class="col-sm-6">').css({ marginBottom: 15 }));
                cell.append($('<strong>').text(__('Order Details')));
                cell.append($('<div>').text(__('Order ID') + ': ' + this.data.transactionId));
                if (canShowInvoice && this.data.invoiceDocumentNumber)
                    cell.append($('<div>').text(__('Invoice') + ': ' + this.data.invoiceDocumentNumber));
                cell.append($('<div>').text(__('Payment gateway') + ': ' + this.data.gatewayId));
                if (language !== "")
                    cell.append($('<div>').text(__('Language') + ': ' + language));
                cell.append($('<div>').text(__('Date/Time') + ': ' + StoreModule_1.Module.formatDate(((('completeDateTime' in this.data) && this.data.completeDateTime) ? this.data.completeDateTime : this.data.dateTime))));
                cell.append($('<div>').text(__('Type') + ': ' + this.trType(this.data.type)));
                cell.append(stateField = $('<div>').css({ marginBottom: 10 }).text(__('State') + ': ' + OrderListItem.trState(this.data.state)));
                if (OrdersDialog.version >= 2) {
                    var dd = $('<span class="dropdown">'
                        + '<button class="btn btn-xs btn-default btn-raised" data-toggle="dropdown"><i class="fa fa-pencil"></i></button>'
                        + '</span>').css({ marginLeft: 5 });
                    var ul = $('<ul class="dropdown-menu">');
                    for (var sk in StoreOrderState) {
                        if (!StoreOrderState.hasOwnProperty(sk))
                            continue;
                        if (this.data.state === StoreOrderState[sk])
                            continue;
                        ul.append($('<li>').append($('<a href="javascript:void(0)">').data('state', StoreOrderState[sk]).text(OrderListItem.trState(StoreOrderState[sk]))));
                    }
                    dd.append(ul);
                    stateField.append(dd);
                    ul.on('click touchend', 'a', function (e) {
                        e.stopImmediatePropagation();
                        e.preventDefault();
                        var mi = $(e.target);
                        var newState = mi.data('state');
                        mi.closest('.dropdown').removeClass('open');
                        _this.actionCallback(_this, "setState", { state: newState });
                    });
                }
                row.append(cell = $('<div class="col-sm-6">').css({ marginBottom: 15 }));
                if (canShowInvoice && this.data.invoiceDocumentNumber)
                    cell.append($('<a class="btn btn-success" target="_blank"><i class="fa fa-file-pdf-o"></i></a>').css({ marginBottom: 5 }).attr('href', this.getInvoiceLinkUrl()).append(document.createTextNode(" " + __('Download invoice')))).append('<br />');
                if (OrdersDialog.version >= 2 && (this.data.state === StoreOrderState.PENDING || this.data.state === StoreOrderState.FAILED || this.data.state === StoreOrderState.REFUNDED || this.data.state === StoreOrderState.CANCELLED)) {
                    this.removeButton = $('<button class="btn btn-danger"><i class="fa fa-trash-o"></i></button>').css({ marginBottom: 5 }).append(document.createTextNode(" " + __('Remove order')));
                    cell.append(this.removeButton).append('<br />');
                    this.removeButton.on("click touchend", function (e) {
                        e.stopImmediatePropagation();
                        e.preventDefault();
                        if (confirm(__("Are you sure you want to remove this order?")))
                            _this.actionCallback(_this, "remove", null);
                    });
                }
                this.detailsCell.append(row = $('<div class="row">'));
                var billingInfo = (('billingInfo' in this.data) && this.data.billingInfo) ? this.objToString(this.data.billingInfo, "\n", OrderListItem.billingInfoFilter) : '';
                row.append(cell = $('<div class="col-sm-6">').css({ marginBottom: 15 }));
                cell.append($('<strong>').text(__('Billing Information')));
                cell.append($('<div>').css({ whiteSpace: 'pre-line' }).text(billingInfo));
                var deliveryInfo = (('deliveryInfo' in this.data) && this.data.deliveryInfo) ? this.objToString(this.data.deliveryInfo, "\n", OrderListItem.billingInfoFilter) : '';
                row.append(cell = $('<div class="col-sm-6">').css({ marginBottom: 15 }));
                cell.append($('<strong>').text(__('Delivery Information')));
                cell.append($('<div>').css({ whiteSpace: 'pre-line' }).text(deliveryInfo));
                this.detailsCell.append(row = $('<div class="row">'));
                row.append(cell = $('<div class="col-xs-12">').css({ marginBottom: 15 }));
                cell.append($('<strong>').text(__('Products')));
                cell.append($('<div>').css({ whiteSpace: 'pre-line', marginBottom: 10 }).text(order));
                if (this.data.taxAmount || this.data.shippingAmount)
                    cell.append($('<div>').css({ whiteSpace: 'pre-line' }).text(__('Subtotal') + ': ' + StoreModule_1.Module.getFormattedPrice(this.data.price - this.data.taxAmount - this.data.shippingAmount, priceOptions.decimalPoint, priceOptions.decimalPlaces, currency, priceOptions.thousandsSeparator)));
                if (this.data.taxAmount)
                    cell.append($('<div>').css({ whiteSpace: 'pre-line' }).text(__('Tax') + ': ' + StoreModule_1.Module.getFormattedPrice(this.data.taxAmount, priceOptions.decimalPoint, priceOptions.decimalPlaces, currency, priceOptions.thousandsSeparator)));
                if (this.data.shippingAmount)
                    cell.append($('<div>').css({ whiteSpace: 'pre-line' }).text(__('Shipping') + ': ' + StoreModule_1.Module.getFormattedPrice(this.data.shippingAmount, priceOptions.decimalPoint, priceOptions.decimalPlaces, currency, priceOptions.thousandsSeparator)));
                cell.append($('<div>').css({ whiteSpace: 'pre-line' }).text(__('Total') + ': ' + StoreModule_1.Module.getFormattedPrice(this.data.price, priceOptions.decimalPoint, priceOptions.decimalPlaces, currency, priceOptions.thousandsSeparator)));
                if (this.data.orderComment) {
                    this.detailsCell.append(row = $('<div class="row">'));
                    row.append(cell = $('<div class="col-xs-12">').css({ marginBottom: 15 }));
                    cell.append($('<strong>').text(__('Order Comments')));
                    cell.append($('<div>').css({ whiteSpace: 'pre-line' }).text(this.data.orderComment));
                }
                this.detailsElem = $('<tr>').addClass("hidden").append(this.detailsCell);
            }
            return this.detailsElem;
        };
        OrderListItem.prototype.getRemoveButton = function () {
            this.getDetailsElem();
            return this.removeButton;
        };
        OrderListItem.prototype.trType = function (value) {
            if (value === 'buy')
                return __('Purchase');
            return value;
        };
        OrderListItem.trState = function (value) {
            if (value === StoreOrderState.PENDING)
                return __('Pending');
            if (value === StoreOrderState.COMPLETE)
                return __('Complete');
            if (value === StoreOrderState.FAILED)
                return __('Failed');
            if (value === StoreOrderState.REFUNDED)
                return __('Refunded');
            if (value === StoreOrderState.CANCELLED)
                return __('Canceled');
            return value;
        };
        OrderListItem.prototype.trKey = function (value) {
            if (value === 'email')
                return __('Email');
            if (value === 'companyName')
                return __('Company Name');
            if (value === 'companyCode')
                return __('Company Code');
            if (value === 'companyVatCode')
                return __('Company TAX/VAT number');
            if (value === 'firstName')
                return __('First Name');
            if (value === 'lastName')
                return __('Last Name');
            if (value === 'address1' || value === 'address2')
                return __('Address');
            if (value === 'city')
                return __('City');
            if (value === 'region')
                return __('Region');
            if (value === 'postCode')
                return __('Post Code');
            if (value === 'countryCode')
                return __('Country Code');
            if (value === 'country')
                return __('Country');
            if (value === 'phone')
                return __('Phone Number');
            return value;
        };
        OrderListItem.prototype.objToString = function (obj, separator, filterFunc) {
            if (separator === void 0) { separator = ' / '; }
            var str = '';
            for (var k in obj) {
                if (!obj[k] || (filterFunc && !filterFunc(obj, k)))
                    continue;
                str += (str ? separator : '') + this.trKey(k) + ': ' + obj[k];
            }
            return str;
        };
        return OrderListItem;
    }());
    var OrderList = (function (_super) {
        __extends(OrderList, _super);
        function OrderList() {
            var _this = _super.call(this, 'div') || this;
            _this.css({ maxHeight: 400, overflowY: 'auto' });
            var respTable = $('<div>').addClass('table-responsive').appendTo(_this._elem), table = $('<table>').addClass('table table-bordered table-condensed')
                .css({ margin: 0 }).appendTo(respTable), thead = $('<thead>').appendTo(table);
            _this.tbody = $('<tbody>').appendTo(table);
            $('<tr>')
                .append($('<th>').css({ whiteSpace: 'nowrap' }).text(__('Order ID')))
                .append($('<th>').css({ whiteSpace: 'nowrap' }).text(__('Invoice')))
                .append($('<th>').css({ whiteSpace: 'nowrap' }).text(__('Date/Time')))
                .append($('<th>').text(__('Buyer')))
                .append($('<th>').text(__('Email')))
                .append($('<th>').text(__('Sum')))
                .append($('<th>').text(__('State')))
                .append($('<th>').text(''))
                .appendTo(thead);
            return _this;
        }
        OrderList.prototype.buildInit = function (data, fields) { };
        OrderList.prototype.removeAllItems = function () {
            this.tbody.children("tr").each(function (idx, elem) {
                if (elem.parentNode)
                    elem.parentNode.removeChild(elem);
            });
        };
        OrderList.prototype.addItem = function (item) {
            this.tbody.append(item.getElem());
            this.tbody.append(item.getDetailsElem());
        };
        return OrderList;
    }(UIComponent_9.UIComponent));
    var OrdersDialog = (function (_super) {
        __extends(OrdersDialog, _super);
        function OrdersDialog(builder) {
            var _this = _super.call(this, __('Store Orders Log')) || this;
            _this.lastUpdateData = [];
            _this.lastUpdateFilter = 'complete';
            _this.msgDialog = null;
            _this.setSize(992, null);
            _this.addButton(__('Close'));
            _this.urlDirect = (builder.site.publishWithForcedHttps ? 'https' : 'http') + '://' + builder.siteDomain + '/0/store-log';
            _this.url = (builder ? builder.lnBaseUrl : '') + 'store/remote-log/';
            var typeOptions = [
                { id: 'all', name: __('All') }
            ];
            for (var sk in StoreOrderState) {
                if (!StoreOrderState.hasOwnProperty(sk))
                    continue;
                typeOptions.push({
                    id: StoreOrderState[sk],
                    name: OrderListItem.trState(StoreOrderState[sk])
                });
            }
            Service_8["default"].UIBuilder.buildLayout({
                type: FlowLayout_2.FlowLayout,
                css: { position: 'absolute', right: '32px', top: '12px' },
                children: [
                    { type: Label_3.Label, text: __('Filter'), css: { marginTop: '6px' } },
                    { type: DropdownBox_1.DropdownBox, id: 'filter', value: _this.lastUpdateFilter, options: typeOptions,
                        change: function (fields) {
                            _this.lastUpdateFilter = fields.filter.getValue();
                            _this.updateDialogContent(_this.lastUpdateData, _this.lastUpdateFilter);
                        }, css: { maxWidth: 200 } }
                ]
            }, _this.headerElem, _this.fields);
            Service_8["default"].UIBuilder.buildLayout({ type: VerticalLayout_4.VerticalLayout, children: [
                    { type: 'CustomContainer', id: 'errorMessage', visible: false },
                    { type: PreloaderOverlay_2.PreloaderOverlay, id: 'preloader', visible: false, noParentLimit: true },
                    { type: OrderList, id: 'table' }
                ] }, _this.content.empty(), _this.fields);
            return _this;
        }
        OrdersDialog.prototype.updateDialogContent = function (data, state) {
            if (state === void 0) { state = 'all'; }
            this.fields.table.removeAllItems();
            var count = 0;
            for (var i = (data.length - 1); i >= 0; i--) {
                var item = data[i];
                if (state !== 'all' && state !== item.data.state)
                    continue;
                this.fields.table.addItem(item);
                count++;
            }
        };
        OrdersDialog.prototype.updateContent = function () {
            var _this = this;
            if (wb_builder.testMode)
                return;
            this.fields.preloader.setVisible(true);
            this.fields.filter.setEnabled(false);
            $.getJSON(this.url, function (data) {
                _this.fields.errorMessage.setVisible(false);
                if (!data || typeof data !== "object" || ('error' in data)) {
                    _this.lastUpdateData = [];
                    if (data && ("error" in data) && !wb_builder.testMode) {
                        _this.fields.errorMessage.setContent($('<div class="alert alert-danger" style="white-space: pre-wrap">').text(data.error.message));
                        _this.fields.errorMessage.setVisible(true);
                    }
                }
                else if (data.ok) {
                    var resp = data;
                    OrdersDialog.version = resp.version;
                    _this.lastUpdateData = [];
                    for (var _i = 0, _a = data.list; _i < _a.length; _i++) {
                        var itemData = _a[_i];
                        _this.lastUpdateData.push(new OrderListItem(itemData, _this.onOrderAction.bind(_this)));
                    }
                    if (OrdersDialog.version < 2 && !OrdersDialog.outdatedNotified) {
                        OrdersDialog.outdatedNotified = true;
                        _this.showNotification(__("Your published website is outdated and doesn't support latest store functionality. Please republish your website."));
                    }
                }
                _this.updateDialogContent(_this.lastUpdateData, _this.lastUpdateFilter);
            }).always(function () {
                _this.fields.preloader.setVisible(false);
                _this.fields.filter.setEnabled(true);
            });
        };
        OrdersDialog.prototype.onOrderAction = function (item, actionId, actionData) {
            var _this = this;
            if (actionId === "remove") {
                this.fields.preloader.setVisible(true);
                this.fields.filter.setEnabled(false);
                $.post(wb_builder.lnBaseUrl + 'store/remove-order/' + item.data.transactionId, actionData, function (data) {
                    if (!data || typeof data !== "object" || ('error' in data)) {
                        if (data && ("error" in data))
                            _this.showErrorMessage(data.error.message);
                        else
                            _this.showErrorMessage("Unable to send request");
                    }
                    else if (data.ok) {
                        setTimeout(_this.updateContent.bind(_this), 0);
                    }
                }, 'json').fail(function () {
                    _this.showErrorMessage("Unable to send request");
                }).always(function () {
                    _this.fields.preloader.setVisible(false);
                    _this.fields.filter.setEnabled(true);
                });
            }
            if (actionId === "setState") {
                this.fields.preloader.setVisible(true);
                this.fields.filter.setEnabled(false);
                $.post(wb_builder.lnBaseUrl + 'store/set-order-state/' + item.data.transactionId, actionData, function (data) {
                    if (!data || typeof data !== "object" || ('error' in data)) {
                        if (data && ("error" in data))
                            _this.showErrorMessage(data.error.message);
                        else
                            _this.showErrorMessage("Unable to send request");
                    }
                    else if (data.ok) {
                        setTimeout(_this.updateContent.bind(_this), 0);
                    }
                }, 'json').fail(function () {
                    _this.showErrorMessage("Unable to send request");
                }).always(function () {
                    _this.fields.preloader.setVisible(false);
                    _this.fields.filter.setEnabled(true);
                });
            }
        };
        OrdersDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (visible) {
                this.updateContent();
            }
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        OrdersDialog.prototype.showErrorMessage = function (message) {
            if (!this.msgDialog)
                this.msgDialog = new MsgDialog_1["default"]();
            this.msgDialog.setTitle(__('Error'));
            this.msgDialog.setMessage(message);
            this.msgDialog.setVisible(true);
        };
        OrdersDialog.prototype.showNotification = function (message) {
            if (!this.msgDialog)
                this.msgDialog = new MsgDialog_1["default"]();
            this.msgDialog.setTitle(__('Note'));
            this.msgDialog.setMessage(message);
            this.msgDialog.setVisible(true);
        };
        OrdersDialog.version = 1;
        OrdersDialog.outdatedNotified = false;
        return OrdersDialog;
    }(Dialog_5["default"]));
});
define("store/StoreItemFieldTypeDialog", ["require", "exports", "Service", "PropertyDialog", "UIComponent", "UIContainer", "VerticalLayout", "UIButton", "List", "AlertBox", "store/StoreModule", "store/StoreItemFieldType", "UniqueIdentifier"], function (require, exports, Service_9, PropertyDialog_1, UIComponent_10, UIContainer_7, VerticalLayout_5, UIButton_4, List_1, AlertBox_2, StoreModule_2, StoreItemFieldType_2, UniqueIdentifier_2) {
    "use strict";
    exports.__esModule = true;
    function showSettingsByType(fields, fieldType) {
        fields.translatable.setVisible(fieldType === 'input' || fieldType === 'textarea');
        fields.hasEmptyOption.setVisible(fieldType === 'dropdown');
        fields.optionsBlock.setVisible(StoreItemFieldType_2.StoreItemFieldType.hasSupportForOptions(fieldType));
        fields.settingsBlock.setVisible(fieldType === 'input' || fieldType === 'textarea' || fieldType === 'dropdown');
    }
    var ImporterElement = (function (_super) {
        __extends(ImporterElement, _super);
        function ImporterElement() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ImporterElement.prototype.buildInit = function (data, fields) {
            var _this = this;
            this.fields = fields;
            var elem = this.getElem();
            this.css({ overflow: 'hidden', position: 'relative' });
            this.on('mousemove', function (e) {
                if (!e)
                    return;
                var off = elem.offset();
                var fx = $(_this.filePicker).width();
                var fy = $(_this.filePicker).height();
                var x = e.pageX - off.left - fx / 2.0;
                var y = e.pageY - off.top - fy / 2.0;
                $(_this.filePicker).css({ left: x, top: y });
            });
            var btn = new UIButton_4.UIButton(__('Import') + ' (CSV)', UIButton_4.UIButton.STYLE_LINK, 'glyphicon glyphicon-import');
            btn.addClass('btn-sm');
            elem.append(btn.getElem());
            this.filePicker = $('<input>')
                .attr({ type: 'file', size: 1 })
                .css({
                width: 100,
                diplay: 'block',
                position: 'absolute',
                cursor: 'pointer',
                opacity: 0,
                filter: 'alpha(opacity=0)',
                left: 0,
                top: 0,
                zIndex: 6
            })
                .on('change', function () { if (_this.filePicker.files)
                _this.onFileSelect(_this.filePicker.files); })
                .get(0);
            elem.append(this.filePicker);
        };
        ImporterElement.prototype.onFileSelect = function (files) {
            var _this = this;
            if (files.length <= 0)
                return;
            var reader = new FileReader();
            reader.onload = function () {
                var data = reader.result ? _this.parseCSV(reader.result) : [];
                var columns = null;
                for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
                    var line = data_2[_i];
                    if (!columns) {
                        columns = line;
                        if (columns.length < 1) {
                            console.log('Warning: file has no columns');
                            break;
                        }
                        continue;
                    }
                    if (line.length > 0 && line[0] !== '') {
                        _this.fields.options.addOption(new StoreItemFieldType_2.StoreItemFieldTypeOption({ name: line[0] }));
                    }
                }
            };
            reader.readAsText(files[0]);
        };
        ImporterElement.prototype.parseCSV = function (text) {
            var res = [], c, cn, ignoreCommas = false, value = '', line = [], nextValue = function () {
                line.push(value);
                value = '';
            }, nextLine = function () {
                if (value.length > 0)
                    nextValue();
                if (line.length > 0)
                    res.push(line);
                line = [];
                ignoreCommas = false;
            };
            for (var i = 0; i < text.length; i++) {
                c = text[i];
                cn = ((i + 1) < text.length) ? text[i + 1] : null;
                if (c === ',' && !ignoreCommas) {
                    nextValue();
                }
                else if (c === "\n" || c === "\r") {
                    nextLine();
                }
                else if (c === '"') {
                    if (value.length == 0 && !ignoreCommas) {
                        ignoreCommas = true;
                    }
                    else if (ignoreCommas && cn === '"') {
                        i++;
                        value += c;
                    }
                    else if (ignoreCommas) {
                        ignoreCommas = false;
                    }
                    else {
                        value += c;
                    }
                }
                else {
                    value += c;
                }
            }
            nextLine();
            return res;
        };
        ImporterElement.isSupported = function () {
            return ('FileList' in window && 'File' in window && 'FileReader' in window);
        };
        return ImporterElement;
    }(UIComponent_10.UIComponent));
    var ItemTypeList = (function (_super) {
        __extends(ItemTypeList, _super);
        function ItemTypeList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ItemTypeList.prototype.buildInit = function (data, fields) {
            data.itemType = StoreItemFieldType_2.StoreItemFieldType;
            data.editable = true;
            data.select = this.onSelect;
            data.selectNone = this.onSelectNone;
            data.add = this.onAdd;
            _super.prototype.buildInit.call(this, data, fields);
        };
        ItemTypeList.prototype.setItemValue = function (item, fields) {
            var selItem = fields.type.getSelectedItem();
            item.name = fields.name.getValue();
            item.type = selItem ? selItem.getOriginal().type : '';
            item.typeId = fields.type.getValue();
            item.options = fields.options.getValue();
            item.isTranslatable = fields.translatable.getValue();
            item.hasEmptyOption = fields.hasEmptyOption.getValue();
        };
        ItemTypeList.prototype.getItemValue = function (item, fields) {
            fields.name.setValue(item.name ? item.name : '');
            fields.type.setValue(item.typeId);
            fields.options.setValue(item.options);
            fields.translatable.setValue(item.isTranslatable);
            fields.hasEmptyOption.setValue(item.hasEmptyOption);
            showSettingsByType(fields, item.type);
        };
        ItemTypeList.prototype.onSelect = function (fields, item) {
            fields.emptyInfo.setVisible(false);
            fields.fieldsBox.setVisible(true);
            var lastItem = this.getLastSelected();
            if (lastItem) {
                this.setItemValue(lastItem, fields);
            }
            this.getItemValue(item, fields);
        };
        ItemTypeList.prototype.onAdd = function (fields, item, li) {
            this.selectItemLi($(li));
        };
        ItemTypeList.prototype.onSelectNone = function (fields) {
            fields.fieldsBox.setVisible(false);
            fields.emptyInfo.setVisible(true);
        };
        return ItemTypeList;
    }(List_1.List));
    var OptionElementFields = (function () {
        function OptionElementFields() {
        }
        return OptionElementFields;
    }());
    var OptionElement = (function (_super) {
        __extends(OptionElement, _super);
        function OptionElement(option, list) {
            var _this = _super.call(this) || this;
            _this.option = option;
            _this.fields = new OptionElementFields();
            Service_9["default"].UIBuilder.buildLayout({ type: 'FlowLayout',
                css: { marginTop: 10 },
                verticalAlign: 'middle',
                children: [
                    { type: 'CustomContainer', tag: 'span', styleClass: 'glyphicon glyphicon-resize-vertical',
                        css: { cursor: 'move' }
                    },
                    { type: 'MultilangTextField', id: 'name', placeholder: __('Name'),
                        css: { width: 240 }
                    },
                    { type: 'Button', icon: 'glyphicon glyphicon-remove',
                        attr: { title: __('Remove') },
                        click: function () { return list.removeOption(_this); }
                    }
                ]
            }, _this, _this.fields);
            _this.load();
            return _this;
        }
        OptionElement.prototype.load = function () {
            this.fields.name.setValue(this.option.name);
        };
        OptionElement.prototype.store = function () {
            this.option.name = this.fields.name.getValue();
        };
        return OptionElement;
    }(UIContainer_7.UIContainer));
    var OptionsContainer = (function (_super) {
        __extends(OptionsContainer, _super);
        function OptionsContainer() {
            var _this = _super.call(this) || this;
            _this.optionElements = [];
            _this.dragging = null;
            _this.getElem().sortable({
                distance: 3,
                axis: 'y',
                items: '> div',
                cursor: 'move',
                start: function (e, ui) { return _this.onSortStart(e, ui); },
                stop: function (e, ui) { return _this.onSortStop(e, ui); }
            });
            return _this;
        }
        OptionsContainer.prototype.buildInit = function (data, fields) { };
        OptionsContainer.prototype.onSortStart = function (e, ui) {
            this.dragging = { idx: ui.item.index() };
            ui.placeholder.css({ marginBottom: 20 });
        };
        OptionsContainer.prototype.onSortStop = function (e, ui) {
            var idx = ui.item.index();
            if (!this.dragging || this.dragging.idx == idx)
                return;
            var elem = this.optionElements.splice(this.dragging.idx, 1);
            this.optionElements.splice(idx, 0, elem[0]);
            this.dragging = null;
        };
        OptionsContainer.prototype.setValue = function (options) {
            this.removeAllChildren();
            this.optionElements = [];
            for (var i = 0; i < options.length; i++) {
                this.addOption(options[i]);
            }
        };
        OptionsContainer.prototype.getValue = function () {
            return this.optionElements.map(function (el) { el.store(); return el.option; });
        };
        OptionsContainer.prototype.addOption = function (option) {
            var el = new OptionElement(option, this);
            this.optionElements.push(el);
            this.addChild(el);
        };
        OptionsContainer.prototype.removeOption = function (option) {
            var idx = this.optionElements.indexOf(option);
            if (idx >= 0) {
                var el = this.optionElements.splice(idx, 1);
                this.removeChild(el[0]);
            }
        };
        OptionsContainer.prototype.newOption = function () {
            this.addOption(new StoreItemFieldType_2.StoreItemFieldTypeOption());
        };
        return OptionsContainer;
    }(VerticalLayout_5.VerticalLayout));
    var StoreItemFieldTypeDialog = (function (_super) {
        __extends(StoreItemFieldTypeDialog, _super);
        function StoreItemFieldTypeDialog(saveFunc) {
            var _this = _super.call(this, '%inherit%') || this;
            _this.saveFunc = saveFunc;
            _super.prototype.__construct.call(_this, __('Field Types'), void 0, void 0, void 0, {
                noScroll: true,
                tabs: [
                    { children: [
                            { type: 'HorizontalLayout', columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                                    { type: ItemTypeList, id: 'tree', css: { height: 328 }, listHeight: 250 },
                                    { type: 'VerticalLayout', children: [
                                            { type: 'VerticalLayout', id: 'fieldsBox', spacing: 15, children: [
                                                    { type: 'HorizontalLayout', children: [
                                                            { type: 'VerticalLayout', children: [
                                                                    { type: 'Label', text: __('Name') },
                                                                    { type: 'TextField', id: 'name' }
                                                                ] },
                                                            { type: 'VerticalLayout', children: [
                                                                    { type: 'Label', text: __('Type') },
                                                                    { type: 'DropdownBox', id: 'type', options: StoreItemFieldType_2.StoreItemFieldType.buildStaticTypes(),
                                                                        change: function (fields) {
                                                                            var selItem = this.getSelectedItem();
                                                                            var selItemOri = selItem ? selItem.getOriginal() : null;
                                                                            var selType = selItemOri ? selItemOri.type : '';
                                                                            showSettingsByType(fields, selType);
                                                                        }
                                                                    }
                                                                ] }
                                                        ] },
                                                    { type: 'VerticalLayout', id: 'settingsBlock', children: [
                                                            { type: 'FlowLayout', children: [
                                                                    { type: 'CheckBox', label: __('Translatable'), id: 'translatable' },
                                                                    { type: 'CheckBox', label: __('Has empty option'), id: 'hasEmptyOption' }
                                                                ] }
                                                        ] },
                                                    { type: 'VerticalLayout', id: 'optionsBlock', children: [
                                                            { type: 'FlowLayout', verticalAlign: 'middle', children: [
                                                                    { type: 'Label', text: __('Options'), css: { marginBottom: 1 } },
                                                                    { type: 'Button', text: 'Add Option', buttonStyle: UIButton_4.UIButton.STYLE_LINK,
                                                                        icon: 'glyphicon glyphicon-plus',
                                                                        styleClass: 'btn-sm',
                                                                        click: function (e, fields) {
                                                                            fields.options.newOption();
                                                                        }
                                                                    },
                                                                    { type: ImporterElement, ignore: !ImporterElement.isSupported() }
                                                                ] },
                                                            { type: OptionsContainer, id: 'options' }
                                                        ] }
                                                ] },
                                            { type: 'AlertBox', id: 'emptyInfo',
                                                style: AlertBox_2["default"].STYLE_INFO,
                                                text: __('No items selected'),
                                                visible: false
                                            }
                                        ] }
                                ] }
                        ] }
                ],
                buttons: [
                    { name: __('Cancel') },
                    { name: __('Apply'), primary: true, click: function () { _this.applyData(); } }
                ]
            });
            return _this;
        }
        StoreItemFieldTypeDialog.prototype.applyData = function () {
            wb_builder.setPageModified(true);
            this.fields.tree.selectFirst();
            StoreModule_2.Module.itemFieldTypes = UniqueIdentifier_2.UniqueIdentifier.assignIds(StoreItemFieldType_2.StoreItemFieldType.buildStaticTypes().concat(this.fields.tree.getValue()));
            for (var i = 0; i < StoreModule_2.Module.itemFieldTypes.length; i++) {
                UniqueIdentifier_2.UniqueIdentifier.assignIds(StoreModule_2.Module.itemFieldTypes[i].options);
            }
            this.setVisible(false);
            if (typeof this.saveFunc === 'function')
                this.saveFunc.call(this);
        };
        StoreItemFieldTypeDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (noAction === void 0) { noAction = false; }
            if (ignoreEvent === void 0) { ignoreEvent = false; }
            if (visible && !noAction && !ignoreEvent) {
                this.fields.tree.setValue(StoreModule_2.Module.itemFieldTypes.filter(function (el) { return !el.isStatic; }));
                this.fields.tree.selectFirst();
            }
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        return StoreItemFieldTypeDialog;
    }(PropertyDialog_1["default"]));
    exports.StoreItemFieldTypeDialog = StoreItemFieldTypeDialog;
});
define("store/StoreItemTypeDialog", ["require", "exports", "Service", "PropertyDialog", "UIContainer", "VerticalLayout", "UIButton", "List", "DropdownBox", "store/StoreModule", "store/StoreItemType", "store/StoreItemTypeField", "store/StoreItemFieldType", "store/StoreItemFieldTypeDialog", "UniqueIdentifier"], function (require, exports, Service_10, PropertyDialog_2, UIContainer_8, VerticalLayout_6, UIButton_5, List_2, DropdownBox_2, StoreModule_3, StoreItemType_2, StoreItemTypeField_1, StoreItemFieldType_3, StoreItemFieldTypeDialog_1, UniqueIdentifier_3) {
    "use strict";
    exports.__esModule = true;
    var ItemTypeList = (function (_super) {
        __extends(ItemTypeList, _super);
        function ItemTypeList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ItemTypeList.prototype.buildInit = function (data, fields) {
            data.itemType = StoreItemType_2.StoreItemType;
            data.editable = true;
            data.select = this.onSelect;
            data.add = this.onAdd;
            _super.prototype.buildInit.call(this, data, fields);
        };
        ItemTypeList.prototype.setItemValue = function (item, fields) {
            item.name = fields.name.getValue();
            item.fields = fields.fields.getValue();
        };
        ItemTypeList.prototype.getItemValue = function (item, fields) {
            fields.name.setValue(item.name ? item.name : '');
            fields.fields.setValue(item.fields);
        };
        ItemTypeList.prototype.onSelect = function (fields, item) {
            var lastItem;
            if ((lastItem = this.getLastSelected())) {
                this.setItemValue(lastItem, fields);
            }
            this.getItemValue(item, fields);
            fields.name.setModified(false);
        };
        ItemTypeList.prototype.onAdd = function (fields, item, li) {
            this.selectItemLi($(li));
        };
        return ItemTypeList;
    }(List_2.List));
    var FieldTypeSelector = (function (_super) {
        __extends(FieldTypeSelector, _super);
        function FieldTypeSelector() {
            var _this = _super.call(this) || this;
            _this.setEditable(true);
            return _this;
        }
        FieldTypeSelector.prototype.buildInit = function (data, fields) {
            _super.prototype.buildInit.call(this, data, fields);
            if (typeof data.reloadParent === 'function')
                this.reloadParent = data.reloadParent;
        };
        FieldTypeSelector.prototype.onEdit = function (fields) {
            var _this = this;
            if (!FieldTypeSelector.typeDialog) {
                FieldTypeSelector.typeDialog = new StoreItemFieldTypeDialog_1.StoreItemFieldTypeDialog(function () {
                    if (_this.reloadParent)
                        _this.reloadParent();
                    stillNeedReload = true;
                });
            }
            FieldTypeSelector.typeDialog.setVisible(true);
        };
        FieldTypeSelector.prototype.reload = function () {
            this.optionsSource = StoreModule_3.Module.itemFieldTypes.filter(function (el) {
                return (!StoreItemFieldType_3.StoreItemFieldType.hasSupportForOptions(el.type) || !el.isStatic);
            });
            _super.prototype.reload.call(this);
        };
        FieldTypeSelector.typeDialog = null;
        return FieldTypeSelector;
    }(DropdownBox_2["default"]));
    var FieldElementFields = (function () {
        function FieldElementFields() {
        }
        return FieldElementFields;
    }());
    var FieldElement = (function (_super) {
        __extends(FieldElement, _super);
        function FieldElement(field, list) {
            var _this = _super.call(this) || this;
            _this.field = field;
            _this.fields = new FieldElementFields();
            var cbInit = function () {
                var elem = this.getElem();
                elem.css({ marginTop: -2, fontSize: 10 });
                elem.find('label').css({ minHeight: 13 });
                elem.find('input').css({ marginTop: 0, marginBottom: 0 });
            };
            Service_10["default"].UIBuilder.buildLayout({ type: 'FlowLayout',
                css: { marginTop: 10, background: '#fff' },
                verticalAlign: 'middle',
                children: [
                    { type: 'CustomContainer', tag: 'span', styleClass: 'glyphicon glyphicon-resize-vertical',
                        css: { cursor: 'move' }
                    },
                    { type: 'MultilangTextField', id: 'name', placeholder: __('Name'),
                        css: { width: 130 }
                    },
                    { type: FieldTypeSelector, id: 'type', css: { width: 190 },
                        reloadParent: function () { return list.reload(); },
                        change: function () { return _this.onTypeChange(); }
                    },
                    { type: 'VerticalLayout', attr: { title: __('Hidden') }, children: [
                            { type: 'CustomContainer', tag: 'span', styleClass: 'glyphicon glyphicon-eye-close' },
                            { type: 'CheckBox', id: 'hidden', init: cbInit }
                        ] },
                    { type: 'VerticalLayout', attr: { title: __('Searchable') }, children: [
                            { type: 'CustomContainer', id: 'searchableIcon', tag: 'span', styleClass: 'glyphicon glyphicon-search' },
                            { type: 'CheckBox', id: 'searchable', init: cbInit }
                        ] },
                    { type: 'VerticalLayout', attr: { title: __('Search interval') }, children: [
                            { type: 'CustomContainer', id: 'searchIntervalIcon', tag: 'span', styleClass: 'glyphicon glyphicon-search' },
                            { type: 'CheckBox', id: 'searchInterval', init: cbInit }
                        ] },
                    { type: 'Button', icon: 'glyphicon glyphicon-remove',
                        attr: { title: __('Remove') },
                        click: function () { return list.removeField(_this); }
                    }
                ]
            }, _this, _this.fields);
            _this.load();
            return _this;
        }
        FieldElement.prototype.onTypeChange = function () {
            var item = this.fields.type.getSelectedItem();
            var itemOri = item ? item.getOriginal() : null;
            if (!item || !itemOri || itemOri.isStatic) {
                this.fields.searchable.setValue(false);
                this.fields.searchInterval.setValue(false);
                this.fields.searchable.setEnabled(false);
                this.fields.searchInterval.setEnabled(false);
                this.fields.searchableIcon.css({ color: '#cccccc' });
                this.fields.searchIntervalIcon.css({ color: '#cccccc' });
            }
            else {
                this.fields.searchable.setEnabled(true);
                this.fields.searchInterval.setEnabled(true);
                this.fields.searchableIcon.css({ color: '' });
                this.fields.searchIntervalIcon.css({ color: '' });
            }
        };
        FieldElement.prototype.reload = function () {
            this.fields.type.reload();
        };
        FieldElement.prototype.load = function () {
            this.fields.type.reload();
            this.fields.name.setValue(this.field.name);
            this.fields.type.setValue(this.field.type);
            this.fields.hidden.setValue(this.field.isHidden);
            this.fields.searchable.setValue(this.field.isSearchable);
            this.fields.searchInterval.setValue(this.field.isSearchInterval);
            this.onTypeChange();
        };
        FieldElement.prototype.store = function () {
            this.field.name = this.fields.name.getValue();
            this.field.type = this.fields.type.getValue();
            this.field.isHidden = this.fields.hidden.getValue();
            this.field.isSearchable = this.fields.searchable.getValue();
            this.field.isSearchInterval = this.fields.searchInterval.getValue();
        };
        return FieldElement;
    }(UIContainer_8.UIContainer));
    var FieldsContainer = (function (_super) {
        __extends(FieldsContainer, _super);
        function FieldsContainer() {
            var _this = _super.call(this) || this;
            _this.fieldElements = [];
            _this.dragging = null;
            _this.getElem().sortable({
                distance: 3,
                axis: 'y',
                items: '> div',
                cursor: 'move',
                start: function (e, ui) { return _this.onSortStart(e, ui); },
                stop: function (e, ui) { return _this.onSortStop(e, ui); }
            });
            return _this;
        }
        FieldsContainer.prototype.buildInit = function (data, fields) { };
        FieldsContainer.prototype.onSortStart = function (e, ui) {
            this.dragging = { idx: ui.item.index() };
            ui.placeholder.css({ marginBottom: 20 });
        };
        FieldsContainer.prototype.onSortStop = function (e, ui) {
            var idx = ui.item.index();
            if (!this.dragging || this.dragging.idx == idx)
                return;
            var elem = this.fieldElements.splice(this.dragging.idx, 1);
            this.fieldElements.splice(idx, 0, elem[0]);
            this.dragging = null;
        };
        FieldsContainer.prototype.reload = function () {
            for (var _i = 0, _a = this.fieldElements; _i < _a.length; _i++) {
                var field = _a[_i];
                field.reload();
            }
        };
        FieldsContainer.prototype.setValue = function (fields) {
            this.removeAllChildren();
            this.fieldElements = [];
            for (var i = 0; i < fields.length; i++) {
                this.addField(fields[i]);
            }
        };
        FieldsContainer.prototype.getValue = function () {
            return this.fieldElements.map(function (el) { el.store(); return el.field; });
        };
        FieldsContainer.prototype.addField = function (field) {
            var el = new FieldElement(field, this);
            this.fieldElements.push(el);
            this.addChild(el);
        };
        FieldsContainer.prototype.removeField = function (field) {
            var idx = this.fieldElements.indexOf(field);
            if (idx >= 0) {
                var el = this.fieldElements.splice(idx, 1);
                this.removeChild(el[0]);
            }
        };
        FieldsContainer.prototype.newField = function () {
            this.addField(new StoreItemTypeField_1.StoreItemTypeField());
        };
        return FieldsContainer;
    }(VerticalLayout_6.VerticalLayout));
    var stillNeedReload = false;
    var StoreItemTypeDialog = (function (_super) {
        __extends(StoreItemTypeDialog, _super);
        function StoreItemTypeDialog(saveFunc) {
            var _this = _super.call(this, '%inherit%') || this;
            _this.saveFunc = saveFunc;
            _super.prototype.__construct.call(_this, __('Item Types'), void 0, void 0, void 0, {
                size: { width: 810 },
                noScroll: true,
                tabs: [
                    { children: [
                            { type: 'HorizontalLayout', columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                                    { type: ItemTypeList, id: 'tree', css: { height: 328 }, listHeight: 250 },
                                    { type: 'VerticalLayout', spacing: 15, children: [
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Item Name') },
                                                    { type: 'MultilangTextField', id: 'name' },
                                                    { type: 'FlowLayout', verticalAlign: 'middle', css: { marginTop: 15 }, children: [
                                                            { type: 'Label', text: __('Options'), css: { marginBottom: 1 } },
                                                            { type: 'Button', text: 'Add Option', buttonStyle: UIButton_5.UIButton.STYLE_LINK,
                                                                icon: 'glyphicon glyphicon-plus',
                                                                styleClass: 'btn-sm',
                                                                click: function (e, fields) {
                                                                    fields.fields.newField();
                                                                }
                                                            }
                                                        ] },
                                                    { type: FieldsContainer, id: 'fields' }
                                                ] }
                                        ] }
                                ] }
                        ] }
                ],
                buttons: [
                    { name: __('Cancel') },
                    { name: __('Apply'), primary: true, click: function () { _this.applyData(); } }
                ]
            });
            return _this;
        }
        StoreItemTypeDialog.prototype.applyData = function () {
            wb_builder.setPageModified(true);
            this.fields.tree.selectFirst();
            StoreModule_3.Module.itemTypes = UniqueIdentifier_3.UniqueIdentifier.assignIds(this.fields.tree.getValue());
            for (var i = 0; i < StoreModule_3.Module.itemTypes.length; i++) {
                UniqueIdentifier_3.UniqueIdentifier.assignIds(StoreModule_3.Module.itemTypes[i].fields);
            }
            this.setVisible(false);
            if (typeof this.saveFunc === 'function')
                this.saveFunc.call(this, false);
        };
        StoreItemTypeDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (noAction === void 0) { noAction = false; }
            if (ignoreEvent === void 0) { ignoreEvent = false; }
            if (visible && !noAction && !ignoreEvent) {
                stillNeedReload = false;
                this.fields.tree.setValue(StoreModule_3.Module.itemTypes);
                this.fields.tree.selectFirst();
            }
            else if (!visible && !noAction && !ignoreEvent) {
                if (stillNeedReload) {
                    if (typeof this.saveFunc === 'function')
                        this.saveFunc.call(this, true);
                }
            }
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        return StoreItemTypeDialog;
    }(PropertyDialog_2["default"]));
    exports.StoreItemTypeDialog = StoreItemTypeDialog;
});
define("Tree", ["require", "exports", "UIComponent", "UIButton", "VerticalLayout", "TreeListControl", "TreeListControl"], function (require, exports, UIComponent_11, UIButton_6, VerticalLayout_7, TreeListControl_1, TreeListControl_2) {
    "use strict";
    exports.__esModule = true;
    exports.TreeListItem = TreeListControl_2.Item;
    var Tree = (function (_super) {
        __extends(Tree, _super);
        function Tree() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.lastSelected = null;
            return _this;
        }
        Tree.prototype.buildInit = function (data, fields) {
            var _this = this;
            this.fields = fields;
            this.itemType = data.itemType;
            this.selectFunc = data.select;
            this.addFunc = data.add;
            this.css({ background: '#F5F5F5', border: '1px solid #E3E3E3', padding: '8px 2px' });
            this.tree = new TreeListControl_1["default"]();
            this.tree.selectFunc = function (item) {
                if (typeof _this.selectFunc === 'function') {
                    _this.selectFunc.call(_this, _this.fields, item.getOriginal());
                }
                if (_this.lastSelected) {
                    var ori = _this.lastSelected.getOriginal();
                    var title = ori ? __tr(ori.name) : null;
                    _this.lastSelected.setTitle(title ? title : '—');
                }
                _this.lastSelected = item;
            };
            this.addChild(this.tree);
            this.applyLayoutCellCss(0, { height: (data.listHeight ? data.listHeight : 306), overflowY: 'auto' });
            var newItemButton = new UIButton_6.UIButton(__('New Item'), UIButton_6.UIButton.STYLE_LINK, 'glyphicon glyphicon-plus');
            newItemButton.css({ marginLeft: -7 });
            newItemButton.on('click', function () {
                if (typeof _this.itemType === 'function') {
                    var item = new _this.itemType();
                    var li = new TreeListControl_1.Item(item.name ? __tr(item.name) : __('New Item'), null, item);
                    _this.tree.items.addItem(li);
                    _this.tree.updateTree();
                    if (typeof _this.addFunc === 'function') {
                        _this.addFunc.call(_this, _this.fields, item, li);
                    }
                }
            });
            this.addChild(newItemButton);
            this.addChild(new Note(__('Use Drag and Drop to sort and categorize items')));
        };
        ;
        Tree.prototype.getLastSelected = function () {
            return (this.lastSelected ? this.lastSelected.getOriginal() : null);
        };
        Tree.prototype.selectItemLi = function (li) {
            this.tree.selectItem(li);
        };
        Tree.prototype.selectFirst = function () {
            var firstItem = this.tree.items.getItem(0);
            if (firstItem)
                this.tree.selectItem(firstItem);
        };
        Tree.prototype.getItems = function (node, res) {
            if (res === void 0) { res = null; }
            if (!(res instanceof Array))
                res = [];
            for (var i = 0, c = node.getItemCount(); i < c; i++) {
                var item = node.getItem(i);
                if (!item)
                    continue;
                var ori = item.getOriginal();
                ori.parentId = node.isRoot() ? 0 : node.getOriginal().id;
                res.push(ori);
                if (item.getItemCount() > 0)
                    this.getItems(item, res);
            }
            return res;
        };
        Tree.prototype.getValue = function () {
            return this.getItems(this.tree.items);
        };
        Tree.prototype.setValue = function (items) {
            this.tree.items.removeAllItems();
            var itemIdx = {};
            for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
                var item = items_1[_i];
                itemIdx['#' + item.id] = new TreeListControl_1.Item(__tr(item.name), null, item);
            }
            for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
                var item = items_2[_a];
                if (item.parentId && ('#' + item.parentId) in itemIdx) {
                    itemIdx['#' + item.parentId].addItem(itemIdx['#' + item.id]);
                }
                else {
                    this.tree.items.addItem(itemIdx['#' + item.id]);
                }
            }
            this.tree.updateTree();
        };
        return Tree;
    }(VerticalLayout_7.VerticalLayout));
    exports.Tree = Tree;
    var Note = (function (_super) {
        __extends(Note, _super);
        function Note(text, icon) {
            var _this = _super.call(this) || this;
            _this.icon = 'glyphicon glyphicon-exclamation-sign';
            _this.text = null;
            _this.addClass('wb-page-tree-notice');
            var css = { marginTop: 0, marginRight: 0, marginLeft: 0 };
            if (wb_builder.rtl) {
                css.marginRight = 6;
            }
            else {
                css.marginLeft = 6;
            }
            _this.css(css);
            var sml = $('<small>').appendTo(_this._elem);
            _this.iconElem = $('<i>').appendTo(sml);
            _this.textElem = $('<span>').addClass('txt').appendTo(sml);
            _this.setText(text);
            _this.setIcon(icon ? icon : _this.icon);
            return _this;
        }
        Note.prototype.setText = function (text) {
            this.text = text;
            this.textElem.text(this.text);
        };
        Note.prototype.setIcon = function (icon) {
            this.icon = icon;
            this.iconElem.removeClass().addClass(this.icon);
        };
        return Note;
    }(UIComponent_11.UIComponent));
});
define("store/StoreCategoryDialog", ["require", "exports", "PropertyDialog", "Tree", "store/StoreModule", "store/StoreCategory", "UniqueIdentifier", "BuilderEvent"], function (require, exports, PropertyDialog_3, Tree_1, StoreModule_4, StoreCategory_3, UniqueIdentifier_4, BuilderEvent_4) {
    "use strict";
    exports.__esModule = true;
    var CatTree = (function (_super) {
        __extends(CatTree, _super);
        function CatTree() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CatTree.prototype.buildInit = function (data, fields) {
            data.itemType = StoreCategory_3.StoreCategory;
            data.select = this.onSelect;
            data.add = this.onAdd;
            _super.prototype.buildInit.call(this, data, fields);
        };
        CatTree.prototype.setItemValue = function (item, fields) {
            item.name = fields.name.getValue();
            if (fields.viewTypeThumbs.getValue())
                item.viewType = 'thumbs';
            if (fields.viewTypeTable.getValue())
                item.viewType = 'table';
            if (fields.description)
                item.description = fields.description.getValue();
            if (fields.image)
                item.image = fields.image.getValue();
        };
        CatTree.prototype.getItemValue = function (item, fields) {
            if (!item)
                item = new StoreCategory_3.StoreCategory();
            fields.name.setValue((item && item.name) ? item.name : '');
            fields.viewTypeThumbs.setValue(item.viewType == 'thumbs');
            fields.viewTypeTable.setValue(item.viewType == 'table');
            if (fields.description)
                fields.description.setValue(item.description ? item.description : '');
            if (fields.image)
                fields.image.setValue(item.image);
        };
        CatTree.prototype.onSelect = function (fields, item) {
            var lastItem = this.getLastSelected();
            if (lastItem) {
                this.setItemValue(lastItem, fields);
            }
            this.getItemValue(item, fields);
            fields.name.setModified(false);
        };
        CatTree.prototype.onAdd = function (fields, item, li) {
            this.selectItemLi(li);
            fields.name.focus();
        };
        return CatTree;
    }(Tree_1.Tree));
    var StoreCategoryDialog = (function (_super) {
        __extends(StoreCategoryDialog, _super);
        function StoreCategoryDialog(saveFunc) {
            var _this = _super.call(this, '%inherit%') || this;
            _this.saveFunc = saveFunc;
            _super.prototype.__construct.call(_this, __('Properties'), void 0, void 0, void 0, {
                noScroll: true,
                tabs: [
                    { children: [
                            { type: 'HorizontalLayout', columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                                    { type: CatTree, id: 'tree', css: { height: 328 }, listHeight: 230 },
                                    { type: 'VerticalLayout', spacing: 15, children: [
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Item Name') },
                                                    { type: 'MultilangTextField', id: 'name' }
                                                ] },
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('List View Type') },
                                                    { type: 'FlowLayout', children: [
                                                            { type: 'RadioBox', id: 'viewTypeThumbs', label: __('Thumbs'), group: 'viewType' },
                                                            { type: 'RadioBox', id: 'viewTypeTable', label: __('Table'), group: 'viewType' }
                                                        ] }
                                                ] }
                                        ] }
                                ] }
                        ] }
                ],
                buttons: [
                    { name: __('Cancel') },
                    { name: __('Apply'), primary: true, click: function () { _this.applyData(); } }
                ]
            });
            return _this;
        }
        StoreCategoryDialog.prototype.applyData = function () {
            wb_builder.setPageModified(true);
            this.fields.tree.selectFirst();
            StoreModule_4.Module.categories = UniqueIdentifier_4.UniqueIdentifier.assignIds(this.fields.tree.getValue());
            this.setVisible(false);
            if (typeof this.saveFunc === 'function')
                this.saveFunc.call(this);
            var e = new BuilderEvent_4.StoreCategoriesChangedBuilderEvent();
            BuilderEvent_4.GlobalEvents.triggerEvent("store.categories.changed", e);
        };
        StoreCategoryDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (noAction === void 0) { noAction = false; }
            if (ignoreEvent === void 0) { ignoreEvent = false; }
            this.fields.tree.setValue(StoreModule_4.Module.categories);
            this.fields.tree.selectFirst();
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        return StoreCategoryDialog;
    }(PropertyDialog_3["default"]));
    exports.StoreCategoryDialog = StoreCategoryDialog;
});
define("store/StoreCustomFieldContainer", ["require", "exports", "Service", "UIContainer", "VerticalLayout", "HorizontalLayout", "FlowLayout", "CheckBox", "RadioBox", "store/StoreModule", "store/StoreItemFieldType", "store/StoreItem"], function (require, exports, Service_11, UIContainer_9, VerticalLayout_8, HorizontalLayout_3, FlowLayout_3, CheckBox_1, RadioBox_1, StoreModule_5, StoreItemFieldType_4, StoreItem_3) {
    "use strict";
    exports.__esModule = true;
    var CheckBoxGroup = (function (_super) {
        __extends(CheckBoxGroup, _super);
        function CheckBoxGroup() {
            var _this = _super.call(this) || this;
            _this.options = [];
            _this.optionElements = [];
            _this.setSpacing(15);
            return _this;
        }
        CheckBoxGroup.prototype.buildInit = function (data, fields) {
            if (!data.options)
                return;
            this.options = data.options;
            for (var i = 0; i < this.options.length; i++) {
                this.optionElements.push(new CheckBox_1["default"](__tr(this.options[i].name), false, true));
                this.addChild(this.optionElements[i]);
            }
        };
        CheckBoxGroup.prototype.setValue = function (value) {
            var valueIdx = {};
            if (value instanceof Array) {
                for (var i = 0; i < value.length; i++) {
                    valueIdx['#' + value[i]] = true;
                }
            }
            else if (value && typeof value === 'object') {
                valueIdx = value;
            }
            for (var i = 0; i < this.options.length; i++) {
                var key = '#' + this.options[i].id;
                this.optionElements[i].setValue((key in valueIdx) ? valueIdx[key] : false);
            }
        };
        CheckBoxGroup.prototype.getValue = function () {
            var value = [];
            for (var i = 0; i < this.options.length; i++) {
                if (!this.optionElements[i].getValue())
                    continue;
                value.push(this.options[i].id);
            }
            return value;
        };
        return CheckBoxGroup;
    }(FlowLayout_3.FlowLayout));
    var RadioBoxGroup = (function (_super) {
        __extends(RadioBoxGroup, _super);
        function RadioBoxGroup() {
            var _this = _super.call(this) || this;
            _this.options = [];
            _this.optionElements = [];
            _this.setSpacing(15);
            return _this;
        }
        RadioBoxGroup.prototype.buildInit = function (data, fields) {
            if (!data.options)
                return;
            this.options = data.options;
            RadioBoxGroup.groupIdx++;
            var group = 'store_custom_fields' + RadioBoxGroup.groupIdx;
            for (var i = 0; i < this.options.length; i++) {
                this.optionElements.push(new RadioBox_1["default"](__tr(this.options[i].name), false, group, true));
                this.addChild(this.optionElements[i]);
            }
        };
        RadioBoxGroup.prototype.setValue = function (value) {
            var valueIdx = {};
            if (value instanceof Array) {
                for (var i = 0; i < value.length; i++) {
                    valueIdx['#' + value[i]] = true;
                }
            }
            else if (value && typeof value === 'object') {
                valueIdx = value;
            }
            for (var i = 0; i < this.options.length; i++) {
                var key = '#' + this.options[i].id;
                this.optionElements[i].setValue((key in valueIdx) ? valueIdx[key] : false);
            }
        };
        RadioBoxGroup.prototype.getValue = function () {
            var value = [];
            for (var i = 0; i < this.options.length; i++) {
                if (!this.optionElements[i].getValue())
                    continue;
                value.push(this.options[i].id);
            }
            return value;
        };
        RadioBoxGroup.groupIdx = 0;
        return RadioBoxGroup;
    }(FlowLayout_3.FlowLayout));
    var CustomFieldElementFields = (function () {
        function CustomFieldElementFields() {
        }
        return CustomFieldElementFields;
    }());
    var CustomFieldElement = (function (_super) {
        __extends(CustomFieldElement, _super);
        function CustomFieldElement(customField, itemTypeField, fieldType) {
            var _this = _super.call(this) || this;
            _this.customField = customField;
            _this.fields = new CustomFieldElementFields();
            _this.isTranslatable = true;
            _this.isTranslatable = fieldType.isTranslatable;
            var valueField;
            switch (fieldType.type) {
                case StoreItemFieldType_4.StoreItemFieldType.TYPE_INPUT:
                case StoreItemFieldType_4.StoreItemFieldType.TYPE_TEXTAREA:
                    if (_this.isTranslatable) {
                        valueField = { type: 'MultilangTextField', id: 'value',
                            textArea: (fieldType.type === StoreItemFieldType_4.StoreItemFieldType.TYPE_TEXTAREA)
                        };
                    }
                    else {
                        valueField = { type: 'TextField', id: 'value',
                            textArea: (fieldType.type === StoreItemFieldType_4.StoreItemFieldType.TYPE_TEXTAREA)
                        };
                    }
                    break;
                case StoreItemFieldType_4.StoreItemFieldType.TYPE_CHECKBOX:
                    valueField = { type: CheckBoxGroup, id: 'value', options: fieldType.options };
                    break;
                case StoreItemFieldType_4.StoreItemFieldType.TYPE_RADIOBOX:
                    valueField = { type: RadioBoxGroup, id: 'value', options: fieldType.options };
                    break;
                case StoreItemFieldType_4.StoreItemFieldType.TYPE_DROPDOWN:
                    var newOptions = fieldType.options.map(function (el) { return { id: el.id, name: __tr(el.name) }; });
                    if (fieldType.hasEmptyOption) {
                        newOptions.unshift({ id: 0, name: '' });
                    }
                    valueField = { type: 'DropdownBox', id: 'value', options: newOptions };
                    break;
            }
            Service_11["default"].UIBuilder.buildLayout({ type: 'VerticalLayout', children: [
                    { type: 'Label', html: __tr(itemTypeField.name) + (itemTypeField.isHidden ? '&nbsp;<span class="glyphicon glyphicon-eye-close"></span>' : '') },
                    valueField
                ] }, _this, _this.fields);
            _this.load();
            return _this;
        }
        CustomFieldElement.prototype.load = function () {
            if (this.fields.value)
                this.fields.value.setValue(((this.isTranslatable || (this.customField.value instanceof Array))
                    ? this.customField.value
                    : __tr(this.customField.value)));
        };
        CustomFieldElement.prototype.store = function () {
            if (this.fields.value)
                this.customField.value = this.fields.value.getValue();
        };
        return CustomFieldElement;
    }(UIContainer_9.UIContainer));
    var StoreCustomFieldContainer = (function (_super) {
        __extends(StoreCustomFieldContainer, _super);
        function StoreCustomFieldContainer() {
            var _this = _super.call(this) || this;
            _this.customFieldElements = [];
            _this.itemTypeId = 0;
            _this.setSpacing(15);
            return _this;
        }
        StoreCustomFieldContainer.prototype.buildInit = function (data, fields) { };
        StoreCustomFieldContainer.prototype.reload = function () {
            var val = this.getValue();
            this.setValue(val, this.itemTypeId);
        };
        StoreCustomFieldContainer.prototype.getValue = function () {
            return this.customFieldElements.map(function (itm) { itm.store(); return itm.customField; });
        };
        StoreCustomFieldContainer.prototype.setValue = function (value, itemTypeId) {
            this.itemTypeId = itemTypeId;
            this.removeAllChildren();
            this.customFieldElements = [];
            var valMap = {};
            for (var i = 0; i < value.length; i++) {
                valMap['#' + value[i].fieldId] = value[i];
            }
            var fldMap = {};
            for (var i = 0; i < StoreModule_5.Module.itemFieldTypes.length; i++) {
                fldMap['#' + StoreModule_5.Module.itemFieldTypes[i].id] = StoreModule_5.Module.itemFieldTypes[i];
            }
            var line = null;
            for (var i = 0; i < StoreModule_5.Module.itemTypes.length; i++) {
                var itemType = StoreModule_5.Module.itemTypes[i];
                if (itemType.id !== itemTypeId)
                    continue;
                for (var n = 0; n < itemType.fields.length; n++) {
                    if ((n % 2) === 0) {
                        line = new HorizontalLayout_3.HorizontalLayout();
                        this.addChild(line);
                    }
                    var key = '#' + itemType.fields[n].id;
                    var fldKey = '#' + itemType.fields[n].type;
                    this.customFieldElements.push(new CustomFieldElement(((key in valMap) ? valMap[key] : new StoreItem_3.StoreItemCustomFieldValue({ fieldId: itemType.fields[n].id })), itemType.fields[n], fldMap[fldKey]));
                    if (line)
                        line.addChild(this.customFieldElements[n]);
                }
                break;
            }
        };
        return StoreCustomFieldContainer;
    }(VerticalLayout_8.VerticalLayout));
    exports.StoreCustomFieldContainer = StoreCustomFieldContainer;
});
define("WYSIWYGControl", ["require", "exports", "UIComponent", "BuilderEvent"], function (require, exports, UIComponent_12, BuilderEvent_5) {
    "use strict";
    exports.__esModule = true;
    var WYSIWYGControl = (function (_super) {
        __extends(WYSIWYGControl, _super);
        function WYSIWYGControl(tag) {
            var _this = _super.call(this, (tag === '%inherit%') ? tag : 'div') || this;
            _this.value = "";
            _this.editorChosenLanguage = null;
            return _this;
        }
        WYSIWYGControl.prototype.buildInit = function (data, fields) {
            var _this = this;
            this._contentId = "wb_wysiwyg_control_" + (WYSIWYGControl.nextId++);
            this._elem.css({
                position: "relative",
                lineHeight: "normal",
                height: data.height ? data.height : 83
            });
            this.textDiv = $("<div class=\"wb-wysiwyg-control\">");
            if (wb_builder.locale === 'ar_AE' || wb_builder.locale === 'he_IL' || wb_builder.locale === 'fa_IR')
                this.textDiv.addClass("rtl");
            this.textDiv.attr("id", this._contentId);
            this._elem.append(this.textDiv);
            this.editorChosenLanguage = wb_builder.site.currSelLang;
            if (data.hasOwnProperty("value") && data.value)
                this.setValue(data.value);
            BuilderEvent_5.GlobalEvents.on("languages.update", function () {
                var exists = false, lang;
                for (var i = 0; (lang = wb_builder.site.languages[i]); i++) {
                    if (lang.code === _this.editorChosenLanguage) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    _this.setValue(_this.textDiv.html(), _this.editorChosenLanguage);
                    _this.onSwitchLanguage(wb_builder.site.currSelLang, true);
                    _this.editorChosenLanguage = wb_builder.site.currSelLang;
                }
                setTimeout(_this.initEditor.bind(_this), 10);
            });
            this._editorConfig = {
                toolbar: [
                    ['Bold', 'Italic', 'Underline', 'RemoveFormat'],
                    ['WBLink', 'Unlink'],
                    ['Languages']
                ],
                on: {
                    selectionChange: function (e) {
                        if (e.data.selection && e.data.selection.getSelectedText()) {
                        }
                    },
                    afterCommandExec: function () {
                    }
                }
            };
            if (data.hasOwnProperty("config"))
                this._editorConfig = $.extend(this._editorConfig, data.config);
            var a = $;
            var b = (a.hasOwnProperty("browser") ? a.browser : { msie: false });
            if (b.msie) {
                var html = this.textDiv.html();
                html = html.replace(/(<p[^>]*>)&nbsp;(<\/p>)/ig, '$1\xad$2');
                this.textDiv.html(html);
            }
            this.updateStyle();
            setTimeout(function () {
                _this.initEditor();
            }, 1000);
        };
        WYSIWYGControl.prototype.updateStyle = function () {
            if (this._enabled) {
                this.textDiv.attr("contenteditable", "true");
                this.textDiv.removeClass("disabled");
            }
            else {
                this.textDiv.removeAttr("contenteditable");
                this.textDiv.addClass("disabled");
            }
        };
        WYSIWYGControl.prototype.initEditor = function () {
            var _this = this;
            if ($("#" + this._contentId).length) {
                if (this._editor) {
                    this._editor.focus();
                    this._editor.destroy();
                    this._editor = null;
                }
                if (this._enabled) {
                    if (!this._editorConfig.hasOwnProperty("stylesSet")) {
                        var styles = CKEDITOR.stylesSet.get("wb_site_styles");
                        if (!styles) {
                            styles = CKEDITOR.stylesSet.add("wb_site_styles", []);
                        }
                        styles.splice(0, styles.length);
                        for (var i = 0; i < wb_builder.site.styles.length; i++) {
                            var s = wb_builder.site.styles[i];
                            var selector = /^\.([^\ ]+)(?:\ |$)/i.exec(s.selector);
                            if (!selector)
                                continue;
                            styles.push({
                                name: s.name, element: (s.tag ? s.tag : "span"), attributes: { "class": selector[1] }
                            });
                        }
                        this._editorConfig.stylesSet = 'wb_site_styles';
                    }
                    this._editor = CKEDITOR.inline(this._contentId, this._editorConfig);
                    this._editor.wbTextAreaInstance = this;
                    setTimeout(function () {
                        var el = $("#cke_" + _this._contentId);
                        el.css({ "z-index": 2000 });
                    }, 1000);
                }
            }
            else {
                clearTimeout(this._timeout);
                this._timeout = setTimeout(function () { return _this.initEditor(); }, 1000);
            }
        };
        WYSIWYGControl.prototype.updateValue = function (html, langCode) {
            var i, lang, newValue;
            if (typeof html === "object") {
                this.value = html;
            }
            else {
                langCode = langCode || this.editorChosenLanguage || wb_builder.site.currSelLang;
                if (typeof this.value === 'string') {
                    if (wb_builder.site.languages.length) {
                        newValue = {};
                        for (i = 0; (lang = wb_builder.site.languages[i]); i++) {
                            if (lang.code === langCode)
                                newValue[lang.code] = html;
                            else if (lang.code === wb_builder.site.getLastDefLang())
                                newValue[lang.code] = this.value;
                            else { }
                        }
                        this.value = newValue;
                    }
                    else {
                        this.value = html;
                    }
                }
                else if (typeof this.value === 'object') {
                    newValue = {};
                    for (i = 0; (lang = wb_builder.site.languages[i]); i++) {
                        if (lang.code in this.value)
                            newValue[lang.code] = this.value[lang.code];
                    }
                    newValue[langCode] = html;
                    this.value = newValue;
                }
            }
            return this;
        };
        WYSIWYGControl.prototype.setValue = function (html, langCode) {
            this.updateValue(html, langCode);
            var htmlVal;
            if (typeof html === "object")
                htmlVal = html[langCode || this.editorChosenLanguage || wb_builder.site.currSelLang] || "";
            else
                htmlVal = html;
            if (this._editor)
                this._editor.setData(htmlVal);
            else
                this.textDiv.html(htmlVal);
            return this;
        };
        WYSIWYGControl.prototype.getValue = function () {
            var html;
            if (this._editor)
                html = this._editor.getData();
            else
                html = this.textDiv.html();
            return this.updateValue(html).value;
        };
        WYSIWYGControl.prototype.onSwitchLanguage = function (langCode, fromEditor) {
            this.textDiv.html(((typeof this.value === "string") ? this.value : this.value[langCode]) || "");
        };
        WYSIWYGControl.prototype.setEnabled = function (enabled) {
            _super.prototype.setEnabled.call(this, enabled);
            this.initEditor();
            this.updateStyle();
        };
        WYSIWYGControl.convertPlainTextToHtml = function (text) {
            if (text === null)
                return "";
            if (typeof text === "object") {
                for (var i in text) {
                    if (text.hasOwnProperty(i))
                        text[i] = WYSIWYGControl.convertPlainTextToHtml(text[i]);
                }
                return text;
            }
            text = "" + text;
            if (/<(p|u|i|a|b|em|hr|br|ul|li|tr|td|th|h[1-6]|div|span|table|strong)\b.*>/i.test(text))
                return text;
            var outText = "<p>";
            var newLineCount = 0;
            var c;
            for (var i = 0, il = text.length - 1; i <= il; i++) {
                c = text.charAt(i);
                if (c == "\r")
                    continue;
                if (c == "\n") {
                    newLineCount++;
                    if (newLineCount > 1) {
                        outText += "</p>\n<p>";
                        newLineCount = 0;
                    }
                }
                else {
                    if (newLineCount) {
                        outText += "<br />\n";
                        newLineCount = 0;
                    }
                    outText += c;
                }
            }
            if (newLineCount)
                outText += "<br />\n";
            outText += "</p>";
            if (outText == "<p></p>")
                outText = "";
            return outText;
        };
        WYSIWYGControl.nextId = 0;
        return WYSIWYGControl;
    }(UIComponent_12.UIComponent));
    exports.WYSIWYGControl = WYSIWYGControl;
});
define("store/StorePropertyDialog", ["require", "exports", "UIComponent", "TextField", "List", "DropdownBox", "store/StoreModule", "store/StoreOrders", "store/StoreItem", "store/StoreCategory", "store/StoreItemTypeDialog", "store/StoreCategoryDialog", "store/StoreCustomFieldContainer", "UniqueIdentifier", "WYSIWYGControl", "BuilderEvent"], function (require, exports, UIComponent_13, TextField_1, List_3, DropdownBox_3, StoreModule_6, StoreOrders, StoreItem_4, StoreCategory_4, StoreItemTypeDialog_1, StoreCategoryDialog_1, StoreCustomFieldContainer_1, UniqueIdentifier_5, WYSIWYGControl_1, BuilderEvent_6) {
    "use strict";
    exports.__esModule = true;
    var tmpItemName = null;
    var tmpItemImages = [];
    var ItemList = (function (_super) {
        __extends(ItemList, _super);
        function ItemList() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.initHeight = 300;
            _this.footerHeight = -1;
            _this.batchAdd = false;
            return _this;
        }
        ItemList.prototype.buildInit = function (data, fields) {
            var _this = this;
            data.itemType = StoreItem_4.StoreItem;
            data.editable = true;
            data.select = this.onSelect;
            data.add = this.onAdd;
            _super.prototype.buildInit.call(this, data, fields);
            this.filterField = new TextField_1["default"]('', __('Filter'));
            this.filterField.css({ marginBottom: 5 });
            this.filterField.on('change keyup', function () { _this.onFilter(); });
            this.getElem().prepend(this.filterField.getElem());
        };
        ItemList.prototype.onFilter = function () {
            var text = this.filterField.getValue();
            this._control.list.children('li').each(function () {
                var obj = $(this).wbGetClassInstance(), searchBlob = StoreModule_6.Module.buildSearchBlob(obj);
                var ok = searchBlob.indexOf(text.toLowerCase()) >= 0;
                $(this).css({ display: ok ? 'block' : 'none' });
            });
        };
        ItemList.prototype.updateHeight = function (fields) {
            if (!fields.mainBody)
                return;
            if (this.footerHeight < 0) {
                var h = this.getElem().height();
                if (h > this.initHeight)
                    this.initHeight = h;
                this.footerHeight = this.initHeight - this._control.list.height();
                this.footerHeight += this.filterField.getElem().outerHeight(true);
            }
            var ph = Math.max(fields.mainBody.getElem().height(), this.initHeight);
            this._control.setHeight(ph - this.footerHeight);
            this.css({ height: ph });
        };
        ItemList.prototype.setItemValue = function (item, fields) {
            var beforeStr = JSON.stringify(item);
            item.name = fields.name.getValue();
            item.description = fields.description.getValue();
            item.price = parseFloat(fields.price.getValue());
            if (isNaN(item.price))
                item.price = 0;
            item.sku = fields.sku.getValue();
            item.weight = parseFloat(fields.weight.getValue());
            if (isNaN(item.weight))
                item.weight = 0;
            item.quantity = parseInt(fields.quantity.getValue(), 10);
            if (isNaN(item.quantity))
                item.quantity = 0;
            item.altImages = fields.altImages.getValues();
            item.image = ((item.altImages && item.altImages.length > 0) ? item.altImages.shift() : null) || null;
            item.itemType = fields.itemType.getValue();
            item.categories = fields.categories.getValue(true);
            item.isHidden = fields.isHidden.getValue();
            item.customFields = fields.customFields.getValue();
            item.seoTitle = fields.seoTitle.getValue();
            item.seoDescription = fields.seoDescription.getValue();
            item.seoAlias = fields.seoAlias.getValue();
            var afterStr = JSON.stringify(item);
            var dateTime = StoreModule_6.Module.buildDate();
            if (!item.dateTimeCreated)
                item.dateTimeCreated = dateTime;
            if (!item.dateTimeModified || beforeStr !== afterStr)
                item.dateTimeModified = dateTime;
        };
        ItemList.prototype.getItemValue = function (item, fields) {
            var description = item.description ? WYSIWYGControl_1.WYSIWYGControl.convertPlainTextToHtml(item.description) : '<p></p>';
            var images = [];
            if (item.image && item.image !== "")
                images.push(item.image);
            if (item.altImages && item.altImages.length) {
                for (var _i = 0, _a = item.altImages; _i < _a.length; _i++) {
                    var image = _a[_i];
                    images.push(image);
                }
            }
            fields.name.setValue(item.name ? item.name : '');
            fields.description.setValue(description);
            fields.price.setValue(item.price);
            fields.sku.setValue(item.sku ? item.sku : '');
            fields.weight.setValue(item.weight);
            fields.quantity.setValue(item.quantity);
            fields.altImages.setValues(images);
            fields.itemType.setValue(item.itemType);
            fields.categories.setValue(item.categories, true);
            fields.seoTitle.setValue(item.seoTitle ? item.seoTitle : '');
            fields.seoDescription.setValue(item.seoDescription ? item.seoDescription : '');
            fields.seoAlias.setValue(item.seoAlias ? item.seoAlias : '');
            var selItem = fields.itemType.getSelectedItem();
            var selItemOri = selItem ? selItem.getOriginal() : null;
            if (!item.itemType && selItemOri) {
                item.itemType = selItemOri.id;
            }
            fields.isHidden.setValue(item.isHidden);
            fields.dates.getElem().html((item.id ? __('ID') + ': ' + item.id + '<br />' : '')
                + __('Created') + ': ' + (item.dateTimeCreated ? StoreModule_6.Module.formatDate(item.dateTimeCreated) : '&mdash;')
                + '<br />' + __('Modified') + ': ' + (item.dateTimeModified ? StoreModule_6.Module.formatDate(item.dateTimeModified) : '&mdash;'));
            fields.customFields.setValue(item.customFields, item.itemType);
            tmpItemName = __tr(item.name, wb_builder.site.getLastDefLang(), null, true);
            tmpItemImages = [];
            if (item.image)
                tmpItemImages.push(item.image);
            for (var i = 0; i < item.altImages.length; i++) {
                tmpItemImages.push(item.altImages[i]);
            }
        };
        ItemList.prototype.onSelect = function (fields, item) {
            var _this = this;
            var lastItem;
            if ((lastItem = this.getLastSelected())) {
                this.setItemValue(lastItem, fields);
            }
            this.getItemValue(item, fields);
            setTimeout(function () { return _this.updateHeight(fields); }, 40);
        };
        ItemList.prototype.onAdd = function (fields, item, li) {
            if (!this.batchAdd) {
                this.selectItemLi($(li));
                if ('scrollIntoView' in li)
                    li.scrollIntoView();
                fields.name.focus();
            }
        };
        ItemList.prototype.setValue = function (value) {
            this.batchAdd = true;
            _super.prototype.setValue.call(this, value);
            this.batchAdd = false;
        };
        return ItemList;
    }(List_3.List));
    var ItemTypeSelector = (function (_super) {
        __extends(ItemTypeSelector, _super);
        function ItemTypeSelector() {
            var _this = _super.call(this) || this;
            _this.setEditable(true);
            StoreModule_6.Module.prepareIdexes();
            return _this;
        }
        ItemTypeSelector.prototype.onEdit = function (fields) {
            var _this = this;
            editItemTypes(function (fromChild) {
                if (fromChild === void 0) { fromChild = false; }
                StoreModule_6.Module.prepareIdexes();
                if (!fromChild)
                    _this.reload();
                if (fields.customFields)
                    fields.customFields.reload();
            });
        };
        ItemTypeSelector.prototype.reload = function () {
            this.optionsSource = StoreModule_6.Module.itemTypes;
            _super.prototype.reload.call(this);
        };
        return ItemTypeSelector;
    }(DropdownBox_3.DropdownBox));
    var CatSelector = (function (_super) {
        __extends(CatSelector, _super);
        function CatSelector() {
            var _this = _super.call(this) || this;
            _this.singleOrNone = false;
            _this.setEditable(true);
            return _this;
        }
        CatSelector.prototype.buildInit = function (data, fields) {
            var _this = this;
            _super.prototype.buildInit.call(this, data, fields);
            this.singleOrNone = data.singleOrNone;
            if (this.singleOrNone) {
                this.multiselect = false;
                this.setEditable(false);
                this.reload();
            }
            var handler = function (e) {
                if (document.body.contains(_this.getElem().get(0)))
                    _this.reload();
                else
                    BuilderEvent_6.GlobalEvents.off("store.categories.changed", handler);
            };
            BuilderEvent_6.GlobalEvents.on("store.categories.changed", handler);
        };
        CatSelector.prototype.onEdit = function (fields) {
            var _this = this;
            editCategories(function () { _this.reload(); });
        };
        CatSelector.prototype.reload = function () {
            this.multiselect = !this.singleOrNone;
            this.optionsSource = StoreModule_6.Module.categories.map(function (e) { return e; });
            if (this.singleOrNone)
                this.optionsSource.unshift(new StoreCategory_4.StoreCategory({ name: __('All') }));
            _super.prototype.reload.call(this);
            this.setMultilevel(true);
        };
        ;
        return CatSelector;
    }(DropdownBox_3.DropdownBox));
    var plugin, getData;
    var uiLayout = {
        size: { width: 810 },
        tabs: [
            { name: __('Edit Item'), children: [
                    { type: 'HorizontalLayout', id: 'mainBody', columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                            { type: ItemList, id: 'tree', css: { height: 328 }, listHeight: 250, addNewItemsToBeginning: true },
                            { type: 'VerticalLayout', spacing: 15, children: [
                                    { type: 'HorizontalLayout', columnWeights: [8, 4], columnWeightsSmall: [8, 4], children: [
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Item Name') },
                                                    { type: 'MultilangTextField', id: 'name', onChange: function (e, value) {
                                                            tmpItemName = __tr(value, wb_builder.site.getLastDefLang(), null, true);
                                                        } }
                                                ] },
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Price') },
                                                    { type: 'TextField', id: 'price', change: function () {
                                                            var value = '' + Math.round(parseFloat(this.getValue()) * 100) / 100;
                                                            this.setValue(/^\d+\.\d$/.test(value) ? value + '0' : value);
                                                        } }
                                                ] }
                                        ] },
                                    { type: 'HorizontalLayout', columnWeights: [4, 4, 4], columnWeightsSmall: [4, 4, 4], children: [
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Item Options') },
                                                    { type: ItemTypeSelector, id: 'itemType' }
                                                ] },
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Categories') },
                                                    { type: CatSelector, id: 'categories' }
                                                ] },
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('SKU'),
                                                        helpText: __('Stock keeping unit, a unique identifier for each distinct product (optional)'),
                                                        helpPlacement: 'top'
                                                    },
                                                    { type: 'TextField', id: 'sku' }
                                                ] }
                                        ] },
                                    { type: 'HorizontalLayout', columnWeights: [4, 4, 4], columnWeightsSmall: [4, 4, 4], children: [
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Weight') },
                                                    { type: 'TextField', id: 'weight' }
                                                ] },
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Quantity'),
                                                        helpText: __('Quantity of items in your stock (for your reference only). You should update it manually.'),
                                                        helpPlacement: 'top'
                                                    },
                                                    { type: 'TextField', id: 'quantity' }
                                                ] }
                                        ] },
                                    { type: 'VerticalLayout', children: [
                                            { type: 'Label', text: __('Description') },
                                            { type: 'WYSIWYGControl', id: 'description', forcePasteAsPlainText: true, textArea: true, height: 170,
                                                config: {
                                                    toolbar: [
                                                        ['Styles', 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'Wbcolor', 'Wbbgcolor', 'RemoveFormat'],
                                                        ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
                                                        ['NumberedList', 'BulletedList', 'WBLink', 'Unlink', 'Anchor'],
                                                        ['ShowBlocks', '|', 'More', 'Less'],
                                                        ['Languages']
                                                    ]
                                                }
                                            }
                                        ] },
                                    { type: 'HorizontalLayout', columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                                            { type: 'VerticalLayout', children: [
                                                    { type: 'Label', text: __('Images') },
                                                    { type: 'ImageSelector', id: 'altImages', multiselect: true, usePictureManager: true, customContent: function () {
                                                            var catName = (tmpItemName ? tmpItemName : __('New Item')) + ' (' + __('Store Item') + ')';
                                                            var obj = {};
                                                            obj[catName] = tmpItemImages;
                                                            return obj;
                                                        } }
                                                ] },
                                            { type: 'CustomContainer', id: 'dates', css: { color: '#9b9b9b', fontSize: '12px', textAlign: 'right' } }
                                        ] },
                                    { type: 'VerticalLayout', children: [
                                            { type: 'Label', text: __('SEO Title') },
                                            { type: 'MultilangTextField', id: 'seoTitle' }
                                        ] },
                                    { type: 'VerticalLayout', children: [
                                            { type: 'Label', text: __('SEO Description') },
                                            { type: 'MultilangTextField', id: 'seoDescription', textArea: true }
                                        ] },
                                    { type: 'VerticalLayout', children: [
                                            { type: 'Label', text: __('User friendly URL'), helpText: __('This is an alias for the item details page. For example if you specify value "apple" then the page will have URL "yourwebsite.com/store/apple".') },
                                            { type: 'MultilangTextField', id: 'seoAlias' }
                                        ] },
                                    { type: 'HorizontalLayout', children: [
                                            { type: 'CheckBox', id: 'isHidden', label: __('Hidden') }
                                        ] },
                                    { type: StoreCustomFieldContainer_1.StoreCustomFieldContainer, id: 'customFields' }
                                ] }
                        ] }
                ] },
            { name: __('Settings'), children: [
                    { type: 'HorizontalLayout', columnWeights: [3, 3, 3, 3], columnWeightsSmall: [3, 3, 3, 3], children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Currency') },
                                    { type: 'DropdownBox', id: 'currencyCode',
                                        init: function () {
                                            var i, item;
                                            for (i = 0; i < StoreModule_6.Module.currencies.length; i++) {
                                                item = new DropdownBox_3.DropdownBox.Item(StoreModule_6.Module.currencies[i].code, StoreModule_6.Module.currencies[i].code, StoreModule_6.Module.currencies[i]);
                                                this.addItem(item);
                                                if (i === 0)
                                                    this.selectItem(item);
                                            }
                                        },
                                        change: function (fields) {
                                            var currency = this.getSelectedItem();
                                            if (currency && currency.getOriginal()) {
                                                fields.currencyPrefix.setValue(currency.getOriginal().prefix);
                                                fields.currencyPostfix.setValue(currency.getOriginal().postfix);
                                            }
                                            fields.pricePreview.update();
                                        }
                                    }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Price prefix') },
                                    { type: 'TextField', id: 'currencyPrefix', change: function (fields) { fields.pricePreview.update(); } }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Price postfix') },
                                    { type: 'TextField', id: 'currencyPostfix', change: function (fields) { fields.pricePreview.update(); } }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Preview') },
                                    { type: 'CustomContainer', id: 'pricePreview',
                                        css: { paddingTop: 7 },
                                        init: function (def, fields) {
                                            var _this = this;
                                            this.update = function () {
                                                var val = '12705.4968', prefix = fields.currencyPrefix.getValue(), postfix = fields.currencyPostfix.getValue(), places = fields.decimalPlaces.getValue(), point = fields.decimalPoint.getValue(), thousandsSep = fields.thousandsSeparator.getValue();
                                                val = StoreModule_6.Module.getFormattedPrice(val, point, places, null, thousandsSep);
                                                if (!prefix && !postfix)
                                                    postfix = ' ' + fields.currencyCode.getValue();
                                                if (prefix)
                                                    val = prefix + val;
                                                if (postfix)
                                                    val = val + postfix;
                                                _this.getElem().text(val);
                                            };
                                        }
                                    }
                                ] }
                        ] },
                    { type: 'HorizontalLayout', columnWeights: [3, 3, 3, 3], columnWeightsSmall: [3, 3, 3, 3], css: { marginTop: 15 }, children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Thousands Separator') },
                                    { type: 'DropdownBox', id: 'thousandsSeparator',
                                        options: [
                                            { 'id': '', 'name': __('No separator') },
                                            { 'id': ' ', 'name': ' ' },
                                            { 'id': '.', 'name': '.' },
                                            { 'id': ',', 'name': ',' }
                                        ],
                                        change: function (fields) { fields.pricePreview.update(); }
                                    }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Decimal Point') },
                                    { type: 'DropdownBox', id: 'decimalPoint',
                                        options: [
                                            { 'id': '.', 'name': '.' },
                                            { 'id': ',', 'name': ',' }
                                        ],
                                        change: function (fields) { fields.pricePreview.update(); }
                                    }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Decimal Places') },
                                    { type: 'DropdownBox', id: 'decimalPlaces',
                                        options: [
                                            { 'id': '0', 'name': '0' },
                                            { 'id': '1', 'name': '1' },
                                            { 'id': '2', 'name': '2' },
                                            { 'id': '3', 'name': '3' },
                                            { 'id': '4', 'name': '4' }
                                        ],
                                        change: function (fields) { fields.pricePreview.update(); }
                                    }
                                ] }
                        ] },
                    { type: 'HorizontalLayout', columnWeights: [3, 3, 3, 3], columnWeightsSmall: [3, 3, 3, 3], css: { marginTop: 15 }, children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Items per page') },
                                    { type: 'SizeSelector', id: 'itemsPerPage', min: 0, max: 100 }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Website Category') },
                                    { type: CatSelector, id: 'category', singleOrNone: true }
                                ] }
                        ] },
                    { type: 'HorizontalLayout', columnWeights: [3, 3, 2, 2, 2], columnWeightsSmall: [3, 3, 2, 2, 2], css: { marginTop: 15 }, children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Thumbnail Size') },
                                    { type: 'FlowLayout', verticalAlign: 'middle', spacing: 5, children: [
                                            { type: 'TextField', id: 'thumbWidth', css: { width: 70 } },
                                            { type: 'Label', html: '&times;', css: { fontWeight: 'normal', fontSize: 18 } },
                                            { type: 'TextField', id: 'thumbHeight', css: { width: 70 } }
                                        ] }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Image Size') },
                                    { type: 'FlowLayout', verticalAlign: 'middle', spacing: 5, children: [
                                            { type: 'TextField', id: 'imageWidth', css: { width: 70 } },
                                            { type: 'Label', html: '&times;', css: { fontWeight: 'normal', fontSize: 18 } },
                                            { type: 'TextField', id: 'imageHeight', css: { width: 70 } }
                                        ] }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Image Border') },
                                    { type: 'BorderSelector', id: 'imageBorder', showRadius: true }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('No-photo Image') },
                                    { type: 'ImageSelector', id: 'noPhotoImage' }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Watermark Image'),
                                        helpText: __('Please avoid using image bigger than 1000x1000 pixels for watermark. Too big image may cause errors while trying to preview or publish website.'),
                                        helpPlacement: 'top'
                                    },
                                    { type: 'ImageSelector', id: 'watermarkImage' }
                                ] }
                        ] },
                    { type: 'HorizontalLayout', css: { marginTop: 15 }, children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Contact Form') },
                                    { type: 'ContactForm', id: 'contactForm' }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('My Orders') },
                                    { type: 'Button', text: __('Check Orders'), click: function () { return StoreOrders.viewOrders(wb_builder); } }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: '' },
                                    { type: 'CheckBox', label: __('Show created/modified dates'), id: 'showDates' },
                                    { type: 'CheckBox', label: __('Show item ID in details page'), id: 'showItemId' }
                                ] }
                        ] },
                    { type: 'HorizontalLayout', css: { marginTop: 15 }, children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Product list') },
                                    { type: 'CheckBox', id: 'showAddToCartInList', label: __('Show "%s" button').replace('%s', __('Add to cart')) },
                                    { type: 'CheckBox', id: 'showBuyNowInList', label: __('Show "%s" button').replace('%s', __('Buy Now')) }
                                ] }
                        ] }
                ] },
            { name: __('Style'), children: [
                    { type: 'VerticalLayout', css: { marginTop: 15 }, children: [
                            { type: 'Label', text: __('Name Style') },
                            { type: 'FontSelector', id: 'nameStyle', horizontal: true }
                        ] },
                    { type: 'VerticalLayout', css: { marginTop: 15 }, children: [
                            { type: 'Label', text: __('Price Style') },
                            { type: 'FontSelector', id: 'priceStyle', horizontal: true }
                        ] },
                    { type: 'VerticalLayout', css: { marginTop: 15 }, children: [
                            { type: 'Label', text: __('Label Style') },
                            { type: 'FontSelector', id: 'labelStyle', horizontal: true, noAlign: true }
                        ] },
                    { type: 'VerticalLayout', css: { marginTop: 15 }, children: [
                            { type: 'Label', text: __('Description/SKU Style') },
                            { type: 'FontSelector', id: 'descStyle', horizontal: true, noAlign: true }
                        ] }
                ] },
            { name: __('Filters'), children: [
                    { type: 'VerticalLayout', css: { marginTop: 15 }, children: [
                            { type: 'Label', text: __('Filter position') },
                            { type: 'FlowLayout', children: [
                                    { type: 'RadioBox', id: 'filterPositionTop', group: 'filterPosition', label: __('Top') },
                                    { type: 'RadioBox', id: 'filterPositionLeft', group: 'filterPosition', label: __('Left') },
                                    { type: 'RadioBox', id: 'filterPositionRight', group: 'filterPosition', label: __('Right') }
                                ] },
                            { type: 'Label', text: __('Visibility'), css: { marginTop: 15 } },
                            { type: 'CheckBox', id: 'showTextFilter', label: __('Show text search filter') },
                            { type: 'CheckBox', id: 'showPriceFilter', label: __('Show price filter') },
                            { type: 'CheckBox', id: 'showSorting', label: __('Show sorting dropdown') },
                            { type: 'CheckBox', id: 'showViewSwitch', label: __('Show item list view switch') }
                        ] }
                ] }
        ],
        callbackFunc: function (fields) { applyData(fields); }
    };
    var itemTypeDialog;
    function editItemTypes(callback) {
        var thisCallback = callback;
        if (!itemTypeDialog) {
            itemTypeDialog = new StoreItemTypeDialog_1.StoreItemTypeDialog(function () {
                plugin.updateStyle();
                if (typeof thisCallback === 'function')
                    thisCallback.call(plugin);
            });
        }
        itemTypeDialog.setVisible(true);
    }
    var catDialog;
    function editCategories(callback) {
        var thisCallback = callback;
        if (!catDialog) {
            catDialog = new StoreCategoryDialog_1.StoreCategoryDialog(function () {
                plugin.updateStyle();
                if (typeof thisCallback === 'function')
                    thisCallback.call(plugin);
            });
        }
        catDialog.setVisible(true);
    }
    function build(elem, dataProvider) {
        plugin = elem;
        getData = dataProvider;
        return uiLayout;
    }
    exports.build = build;
    function applyData(fields) {
        var data = getData();
        StoreModule_6.Module.currency.code = fields.currencyCode.getValue();
        StoreModule_6.Module.currency.prefix = fields.currencyPrefix.getValue();
        StoreModule_6.Module.currency.postfix = fields.currencyPostfix.getValue();
        StoreModule_6.Module.priceOptions.decimalPoint = fields.decimalPoint.getValue();
        StoreModule_6.Module.priceOptions.decimalPlaces = fields.decimalPlaces.getValue();
        StoreModule_6.Module.priceOptions.thousandsSeparator = fields.thousandsSeparator.getValue();
        StoreModule_6.Module.contactForm = fields.contactForm.getValue();
        StoreModule_6.Module.noPhotoImage = fields.noPhotoImage.getValue();
        StoreModule_6.Module.watermarkImage = fields.watermarkImage.getValue();
        StoreModule_6.Module.showDates = fields.showDates.getValue();
        StoreModule_6.Module.showItemId = fields.showItemId.getValue();
        data.content.thumbWidth = parseInt(fields.thumbWidth.getValue(), 10);
        data.content.thumbHeight = parseInt(fields.thumbHeight.getValue(), 10);
        data.content.imageWidth = parseInt(fields.imageWidth.getValue(), 10);
        data.content.imageHeight = parseInt(fields.imageHeight.getValue(), 10);
        data.content.imageBorder = fields.imageBorder.getValue();
        data.content.nameStyle = fields.nameStyle.getValue();
        data.content.priceStyle = fields.priceStyle.getValue();
        data.content.descStyle = fields.descStyle.getValue();
        data.content.labelStyle = fields.labelStyle.getValue();
        data.content.itemsPerPage = fields.itemsPerPage.getValue();
        data.content.category = fields.category.getValue();
        data.content.showAddToCartInList = fields.showAddToCartInList.getValue();
        data.content.showBuyNowInList = fields.showBuyNowInList.getValue();
        data.content.showTextFilter = fields.showTextFilter.getValue();
        data.content.showPriceFilter = fields.showPriceFilter.getValue();
        data.content.showSorting = fields.showSorting.getValue();
        data.content.showViewSwitch = fields.showViewSwitch.getValue();
        if (fields.filterPositionLeft.getValue())
            data.content.filterPosition = "left";
        else if (fields.filterPositionRight.getValue())
            data.content.filterPosition = "right";
        else
            data.content.filterPosition = "top";
        fields.tree.selectFirst();
        StoreModule_6.Module.items = UniqueIdentifier_5.UniqueIdentifier.assignIds(fields.tree.getValue());
        plugin.updateStyle();
    }
    function updateData(fields) {
        var data = getData();
        fields.currencyCode.setValue(StoreModule_6.Module.currency.code);
        fields.currencyPrefix.setValue(StoreModule_6.Module.currency.prefix);
        fields.currencyPostfix.setValue(StoreModule_6.Module.currency.postfix);
        fields.decimalPoint.setValue(StoreModule_6.Module.priceOptions.decimalPoint);
        fields.decimalPlaces.setValue(StoreModule_6.Module.priceOptions.decimalPlaces);
        fields.thousandsSeparator.setValue(StoreModule_6.Module.priceOptions.thousandsSeparator);
        fields.noPhotoImage.setValue(StoreModule_6.Module.noPhotoImage);
        fields.watermarkImage.setValue(StoreModule_6.Module.watermarkImage);
        fields.showDates.setValue(StoreModule_6.Module.showDates);
        fields.showItemId.setValue(StoreModule_6.Module.showItemId);
        fields.pricePreview.update();
        fields.contactForm.setValue(StoreModule_6.Module.contactForm);
        fields.thumbWidth.setValue(data.content.thumbWidth);
        fields.thumbHeight.setValue(data.content.thumbHeight);
        fields.imageWidth.setValue(data.content.imageWidth);
        fields.imageHeight.setValue(data.content.imageHeight);
        fields.imageBorder.setValue(data.content.imageBorder);
        fields.nameStyle.setValue(data.content.nameStyle);
        fields.priceStyle.setValue(data.content.priceStyle);
        fields.descStyle.setValue(data.content.descStyle);
        fields.labelStyle.setValue(data.content.labelStyle);
        fields.itemsPerPage.setValue(data.content.itemsPerPage);
        fields.category.reload();
        fields.category.setValue(data.content.category);
        fields.showAddToCartInList.setValue(data.content.hasOwnProperty('showAddToCartInList') && data.content.showAddToCartInList);
        fields.showBuyNowInList.setValue(data.content.hasOwnProperty('showBuyNowInList') && data.content.showBuyNowInList);
        fields.showTextFilter.setValue(data.content.hasOwnProperty('showTextFilter') ? data.content.showTextFilter : true);
        fields.showPriceFilter.setValue(data.content.hasOwnProperty('showPriceFilter') ? data.content.showPriceFilter : true);
        fields.showSorting.setValue(data.content.hasOwnProperty('showSorting') ? data.content.showSorting : true);
        fields.showViewSwitch.setValue(data.content.hasOwnProperty('showViewSwitch') ? data.content.showViewSwitch : true);
        fields.itemType.reload();
        fields.itemType.setValue(null);
        fields.categories.reload();
        fields.categories.setValue([], true);
        fields.tree.setValue(StoreModule_6.Module.items);
        fields.tree.selectFirst();
        var pos = data.content.hasOwnProperty('filterPosition') ? data.content.filterPosition : "top";
        fields.filterPositionLeft.setValue(pos === "left");
        fields.filterPositionRight.setValue(pos === "right");
        fields.filterPositionTop.setValue(pos === "top");
    }
    exports.updateData = updateData;
});
define("KindaPromise", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var KindaPromise = (function () {
        function KindaPromise(defFunc) {
            var _this = this;
            this.resolveFuncList = [];
            this.rejectFuncList = [];
            this.bothFuncList = [];
            this.rejectVal = null;
            this.result = 0;
            defFunc(function (r) { return _this.resolve(r); }, function (m) { return _this.reject(m); });
        }
        KindaPromise.prototype.resolve = function (result) {
            this.resolveVal = result;
            this.result = 1;
            for (var _i = 0, _a = this.resolveFuncList; _i < _a.length; _i++) {
                var func = _a[_i];
                func.call(this, this.resolveVal);
            }
            for (var _b = 0, _c = this.bothFuncList; _b < _c.length; _b++) {
                var func = _c[_b];
                func.call(this);
            }
        };
        KindaPromise.prototype.reject = function (message) {
            this.rejectVal = message;
            this.result = -1;
            for (var _i = 0, _a = this.rejectFuncList; _i < _a.length; _i++) {
                var func = _a[_i];
                func.call(this, this.rejectVal);
            }
            for (var _b = 0, _c = this.bothFuncList; _b < _c.length; _b++) {
                var func = _c[_b];
                func.call(this);
            }
        };
        KindaPromise.prototype.then = function (func) {
            this.resolveFuncList.push(func);
            if (this.result > 0)
                func.call(this, this.resolveVal);
            return this;
        };
        KindaPromise.prototype["catch"] = function (func) {
            this.rejectFuncList.push(func);
            if (this.result < 0)
                func.call(this, this.rejectVal);
            return this;
        };
        KindaPromise.prototype["finally"] = function (func) {
            this.bothFuncList.push(func);
            if (this.result != 0)
                func.call(this);
            return this;
        };
        return KindaPromise;
    }());
    exports.KindaPromise = KindaPromise;
});
define("store/StoreCountry", ["require", "exports", "KindaPromise"], function (require, exports, KindaPromise_1) {
    "use strict";
    exports.__esModule = true;
    var StoreCountry = (function () {
        function StoreCountry(code, name, parentId) {
            if (parentId === void 0) { parentId = 0; }
            this.code = code;
            this.name = name;
            this.parentId = 0;
            this.id = code;
            this.parentId = parentId;
        }
        return StoreCountry;
    }());
    exports.StoreCountry = StoreCountry;
    var countryList = null;
    function getCountryList() {
        if (!countryList) {
            return new KindaPromise_1.KindaPromise(function (resolve, reject) {
                $.getJSON(wb_builder.lnBaseUrl + 'store/country-list')
                    .done(function (result) {
                    var ci;
                    countryList = [];
                    for (var _i = 0, result_1 = result; _i < result_1.length; _i++) {
                        var c = result_1[_i];
                        countryList.push(new StoreCountry(c.code, c.name));
                        for (var _a = 0, _b = c.regions; _a < _b.length; _a++) {
                            var r = _b[_a];
                            countryList.push(new StoreCountry(c.code + '-' + r.code, r.name, c.code));
                        }
                    }
                    resolve(countryList);
                })
                    .fail(function () { return reject(null); });
            });
        }
        return new KindaPromise_1.KindaPromise(function (resolve, reject) {
            if (countryList)
                resolve(countryList);
            else
                reject(null);
        });
    }
    exports.getCountryList = getCountryList;
});
define("store/StoreDestinationZoneDialog", ["require", "exports", "List", "TextField", "DropdownBox", "PropertyDialog", "UniqueIdentifier", "store/StoreDestinationZone", "store/StoreCountry", "store/StoreModule", "HorizontalLayout", "VerticalLayout", "Label"], function (require, exports, List_4, TextField_2, DropdownBox_4, PropertyDialog_4, UniqueIdentifier_6, StoreDestinationZone_2, StoreCountry_1, StoreModule_7, HorizontalLayout_4, VerticalLayout_9, Label_4) {
    "use strict";
    exports.__esModule = true;
    var singleInstance = null;
    var saveListeners = [];
    function addSaveListener(func) {
        saveListeners.push(func);
    }
    exports.addSaveListener = addSaveListener;
    function open() {
        if (!singleInstance) {
            singleInstance = new StoreDestinationZoneDialog();
        }
        singleInstance.setVisible(true);
    }
    exports.open = open;
    var StoreDestinationZoneList = (function (_super) {
        __extends(StoreDestinationZoneList, _super);
        function StoreDestinationZoneList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        StoreDestinationZoneList.prototype.buildInit = function (data, fields) {
            data.itemType = StoreDestinationZone_2.StoreDestinationZone;
            data.editable = true;
            data.select = this.onSelect;
            data.selectNone = this.onSelectNone;
            data.add = this.onAdd;
            _super.prototype.buildInit.call(this, data, fields);
        };
        StoreDestinationZoneList.prototype.setItemValue = function (item, fields) {
            item.name = fields.name.getValue();
            if (fields.countriesLoaded) {
                item.countries = fields.countries.getValue(true);
            }
        };
        StoreDestinationZoneList.prototype.getItemValue = function (item, fields) {
            fields.name.setValue(item.name ? item.name : '');
            fields.countries.setValue(item.countries, true);
        };
        StoreDestinationZoneList.prototype.onSelect = function (fields, item) {
            var lastItem;
            if ((lastItem = this.getLastSelected())) {
                this.setItemValue(lastItem, fields);
            }
            this.getItemValue(item, fields);
            fields.editPanel.setVisible(item ? true : false);
        };
        StoreDestinationZoneList.prototype.onSelectNone = function (fields) {
            fields.editPanel.setVisible(false);
        };
        StoreDestinationZoneList.prototype.onAdd = function (fields, item, li) {
            this.selectItemLi($(li));
        };
        return StoreDestinationZoneList;
    }(List_4.List));
    var StoreDestinationZoneDialog = (function (_super) {
        __extends(StoreDestinationZoneDialog, _super);
        function StoreDestinationZoneDialog() {
            var _this = _super.call(this, __('Destination Zones'), {
                noScroll: true,
                tabs: [
                    { children: [
                            { type: HorizontalLayout_4.HorizontalLayout, columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                                    { type: StoreDestinationZoneList, id: 'list', css: { height: 328 }, listHeight: 250 },
                                    { type: VerticalLayout_9.VerticalLayout, id: 'editPanel', spacing: 15, children: [
                                            { type: VerticalLayout_9.VerticalLayout, children: [
                                                    { type: Label_4.Label, text: __('Name') },
                                                    { type: TextField_2["default"], id: 'name' }
                                                ] },
                                            { type: VerticalLayout_9.VerticalLayout, children: [
                                                    { type: Label_4.Label, text: __('Countries') },
                                                    { type: DropdownBox_4["default"], id: 'countries',
                                                        multiselect: true,
                                                        addSelectAll: true,
                                                        multilevel: true,
                                                        parentMustBeSelected: true,
                                                        init: function () {
                                                            StoreCountry_1.getCountryList().then(function (res) {
                                                                _this.fields.countries.reload(res);
                                                                var lastItem = _this.fields.list.getLastSelected();
                                                                if (lastItem)
                                                                    _this.fields.list.onSelect(_this.fields, lastItem);
                                                                _this.fields.countriesLoaded = true;
                                                            });
                                                        }
                                                    }
                                                ] }
                                        ] }
                                ] }
                        ] }
                ],
                buttons: [
                    { name: __('Cancel') },
                    { name: __('Apply'), primary: true, click: function () { _this.applyData(); } }
                ]
            }) || this;
            _this.fields.countriesLoaded = false;
            return _this;
        }
        StoreDestinationZoneDialog.prototype.applyData = function () {
            wb_builder.setPageModified(true);
            this.fields.list.selectFirst();
            StoreModule_7.Module.destinationZones = UniqueIdentifier_6.UniqueIdentifier.assignIds(this.fields.list.getValue());
            this.setVisible(false);
            for (var _i = 0, saveListeners_1 = saveListeners; _i < saveListeners_1.length; _i++) {
                var func = saveListeners_1[_i];
                if (typeof func === 'function')
                    func.call(this);
            }
        };
        StoreDestinationZoneDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (noAction === void 0) { noAction = false; }
            if (ignoreEvent === void 0) { ignoreEvent = false; }
            if (visible && !ignoreEvent) {
                this.fields.list.setValue(StoreModule_7.Module.destinationZones);
                this.fields.list.selectFirst();
            }
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        return StoreDestinationZoneDialog;
    }(PropertyDialog_4["default"]));
    exports.StoreDestinationZoneDialog = StoreDestinationZoneDialog;
});
define("ItemContainer", ["require", "exports", "UIContainer", "VerticalLayout"], function (require, exports, UIContainer_10, VerticalLayout_10) {
    "use strict";
    exports.__esModule = true;
    var ItemContainerItem = (function (_super) {
        __extends(ItemContainerItem, _super);
        function ItemContainerItem(item, list) {
            var _this = _super.call(this) || this;
            _this.item = item;
            _this.list = list;
            _this.buildLayout();
            _this.load();
            return _this;
        }
        ItemContainerItem.prototype.reload = function () { };
        return ItemContainerItem;
    }(UIContainer_10.UIContainer));
    exports.ItemContainerItem = ItemContainerItem;
    var ItemContainer = (function (_super) {
        __extends(ItemContainer, _super);
        function ItemContainer() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.itemElements = [];
            return _this;
        }
        ItemContainer.prototype.buildInit = function (data, fields) {
            if (data.itemType)
                this.itemType = data.itemType;
            if (data.itemElemType)
                this.itemElemType = data.itemElemType;
        };
        ItemContainer.prototype.reload = function () {
            for (var _i = 0, _a = this.itemElements; _i < _a.length; _i++) {
                var item = _a[_i];
                item.reload();
            }
        };
        ItemContainer.prototype.setValue = function (items) {
            this.removeAllChildren();
            this.itemElements = [];
            for (var i = 0; i < items.length; i++) {
                this.addItem(items[i]);
            }
        };
        ItemContainer.prototype.getValue = function () {
            return this.itemElements.map(function (el) { el.store(); return el.item; });
        };
        ItemContainer.prototype.addItem = function (item) {
            var el = new this.itemElemType(item, this);
            this.itemElements.push(el);
            this.addChild(el);
        };
        ItemContainer.prototype.removeItemElem = function (elem) {
            var idx = this.itemElements.indexOf(elem);
            if (idx >= 0) {
                var el = this.itemElements.splice(idx, 1);
                this.removeChild(el[0]);
            }
        };
        ItemContainer.prototype.newItem = function () {
            this.addItem(new this.itemType());
        };
        return ItemContainer;
    }(VerticalLayout_10.VerticalLayout));
    exports.ItemContainer = ItemContainer;
});
define("store/StoreTaxRuleDialog", ["require", "exports", "List", "TextField", "DropdownBox", "PropertyDialog", "UniqueIdentifier", "store/StoreTaxRule", "store/StoreModule", "HorizontalLayout", "VerticalLayout", "FlowLayout", "Label", "store/StoreDestinationZoneDialog", "Service", "UIButton", "ItemContainer"], function (require, exports, List_5, TextField_3, DropdownBox_5, PropertyDialog_5, UniqueIdentifier_7, StoreTaxRule_2, StoreModule_8, HorizontalLayout_5, VerticalLayout_11, FlowLayout_4, Label_5, StoreDestinationZoneDialog_1, Service_12, UIButton_7, ItemContainer_1) {
    "use strict";
    exports.__esModule = true;
    var singleInstance = null;
    var saveListeners = [];
    function addSaveListener(func) {
        saveListeners.push(func);
    }
    exports.addSaveListener = addSaveListener;
    function open() {
        if (!singleInstance) {
            singleInstance = new StoreTaxRuleDialog();
        }
        singleInstance.setVisible(true);
    }
    exports.open = open;
    var StoreTaxRuleList = (function (_super) {
        __extends(StoreTaxRuleList, _super);
        function StoreTaxRuleList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        StoreTaxRuleList.prototype.buildInit = function (data, fields) {
            data.itemType = StoreTaxRule_2.StoreTaxRule;
            data.editable = true;
            data.select = this.onSelect;
            data.selectNone = this.onSelectNone;
            data.add = this.onAdd;
            _super.prototype.buildInit.call(this, data, fields);
        };
        StoreTaxRuleList.prototype.setItemValue = function (item, fields) {
            item.name = fields.name.getValue();
            item.rates = fields.rates.getValue();
        };
        StoreTaxRuleList.prototype.getItemValue = function (item, fields) {
            fields.name.setValue(item.name ? item.name : '');
            fields.rates.setValue(item.rates);
        };
        StoreTaxRuleList.prototype.onSelect = function (fields, item) {
            var lastItem;
            if ((lastItem = this.getLastSelected())) {
                this.setItemValue(lastItem, fields);
            }
            this.getItemValue(item, fields);
            fields.editPanel.setVisible(!!item);
        };
        StoreTaxRuleList.prototype.onSelectNone = function (fields) {
            fields.editPanel.setVisible(false);
        };
        StoreTaxRuleList.prototype.onAdd = function (fields, item, li) {
            this.selectItemLi($(li));
        };
        return StoreTaxRuleList;
    }(List_5.List));
    var RateElementFields = (function () {
        function RateElementFields() {
        }
        return RateElementFields;
    }());
    var RateElement = (function (_super) {
        __extends(RateElement, _super);
        function RateElement() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RateElement.prototype.buildLayout = function () {
            var _this = this;
            this.fields = new RateElementFields();
            Service_12["default"].UIBuilder.buildLayout({ type: FlowLayout_4.FlowLayout,
                verticalAlign: 'middle',
                css: { marginTop: 10 },
                children: [
                    { type: DropdownBox_5["default"], id: 'destinationZone', styleClass: 'input-group-sm',
                        css: { width: 200 },
                        options: StoreModule_8.Module.destinationZones,
                        editable: true,
                        edit: function () { return StoreDestinationZoneDialog_1.open(); }
                    },
                    { type: TextField_3["default"], id: 'rate', styleClass: 'input-sm', css: { width: 70 } },
                    { type: Label_5.Label, text: '%', css: { width: 10, margin: 0 } },
                    { type: UIButton_7.UIButton, icon: 'glyphicon glyphicon-remove', styleClass: 'btn-sm',
                        attr: { title: __('Remove') },
                        click: function () { return _this.list.removeItemElem(_this); }
                    }
                ]
            }, this, this.fields);
            StoreDestinationZoneDialog_1.addSaveListener(function () { _this.fields.destinationZone.reload(StoreModule_8.Module.destinationZones); });
        };
        RateElement.prototype.load = function () {
            this.fields.destinationZone.setValue(this.item.destinationZoneId);
            this.fields.rate.setValue(this.item.rate);
        };
        RateElement.prototype.store = function () {
            this.item.destinationZoneId = this.fields.destinationZone.getValue();
            this.item.rate = parseFloat(this.fields.rate.getValue());
            if (isNaN(this.item.rate))
                this.item.rate = 0;
        };
        return RateElement;
    }(ItemContainer_1.ItemContainerItem));
    var StoreTaxRuleDialog = (function (_super) {
        __extends(StoreTaxRuleDialog, _super);
        function StoreTaxRuleDialog() {
            var _this = _super.call(this, __('Tax Rules'), {
                noScroll: true,
                tabs: [
                    { children: [
                            { type: HorizontalLayout_5.HorizontalLayout, columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                                    { type: StoreTaxRuleList, id: 'list', css: { height: 328 }, listHeight: 250 },
                                    { type: VerticalLayout_11.VerticalLayout, id: 'editPanel', spacing: 15, children: [
                                            { type: HorizontalLayout_5.HorizontalLayout, children: [
                                                    { type: VerticalLayout_11.VerticalLayout, children: [
                                                            { type: Label_5.Label, text: __('Name') },
                                                            { type: TextField_3["default"], id: 'name' }
                                                        ] }
                                                ] },
                                            { type: VerticalLayout_11.VerticalLayout, children: [
                                                    { type: FlowLayout_4.FlowLayout, verticalAlign: 'middle', children: [
                                                            { type: Label_5.Label, text: __('Rates'), css: { marginBottom: 1 } },
                                                            { type: UIButton_7.UIButton, text: __('Add Rate'), buttonStyle: UIButton_7.UIButton.STYLE_LINK,
                                                                icon: 'glyphicon glyphicon-plus',
                                                                styleClass: 'btn-sm',
                                                                click: function (e, fields) {
                                                                    fields.rates.newItem();
                                                                }
                                                            }
                                                        ] },
                                                    { type: ItemContainer_1.ItemContainer, id: 'rates', itemType: StoreTaxRule_2.StoreTaxRuleRate, itemElemType: RateElement }
                                                ] }
                                        ] }
                                ] }
                        ] }
                ],
                buttons: [
                    { name: __('Cancel') },
                    { name: __('Apply'), primary: true, click: function () { _this.applyData(); } }
                ]
            }) || this;
            return _this;
        }
        StoreTaxRuleDialog.prototype.applyData = function () {
            wb_builder.setPageModified(true);
            this.fields.list.selectFirst();
            StoreModule_8.Module.taxRules = UniqueIdentifier_7.UniqueIdentifier.assignIds(this.fields.list.getValue());
            this.setVisible(false);
            for (var _i = 0, saveListeners_2 = saveListeners; _i < saveListeners_2.length; _i++) {
                var func = saveListeners_2[_i];
                if (typeof func === 'function')
                    func.call(this);
            }
        };
        StoreTaxRuleDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (noAction === void 0) { noAction = false; }
            if (ignoreEvent === void 0) { ignoreEvent = false; }
            if (visible && !ignoreEvent) {
                this.fields.list.setValue(StoreModule_8.Module.taxRules);
                this.fields.list.selectFirst();
            }
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        return StoreTaxRuleDialog;
    }(PropertyDialog_5["default"]));
    exports.StoreTaxRuleDialog = StoreTaxRuleDialog;
});
define("store/StoreRangesControl", ["require", "exports", "Service", "TextField", "FlowLayout", "Label", "UIButton", "ItemContainer", "store/StoreModule"], function (require, exports, Service_13, TextField_4, FlowLayout_5, Label_6, UIButton_8, ItemContainer_2, StoreModule_9) {
    "use strict";
    exports.__esModule = true;
    var RangeElementFields = (function () {
        function RangeElementFields() {
        }
        return RangeElementFields;
    }());
    var RangeElement = (function (_super) {
        __extends(RangeElement, _super);
        function RangeElement() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RangeElement.prototype.buildLayout = function () {
            var _this = this;
            this.fields = new RangeElementFields();
            Service_13["default"].UIBuilder.buildLayout({ type: FlowLayout_5.FlowLayout,
                verticalAlign: 'middle',
                css: { marginTop: 10 },
                children: [
                    { type: TextField_4["default"], id: 'from', styleClass: 'input-sm', css: { width: 60 } },
                    { type: Label_6.Label, text: '-', css: { width: 10, textAlign: 'center', margin: 0 } },
                    { type: TextField_4["default"], id: 'to', styleClass: 'input-sm', css: { width: 60 } },
                    { type: TextField_4["default"], id: 'value', styleClass: 'input-sm', css: { width: 80, marginLeft: 20 } },
                    { type: Label_6.Label, id: 'currency', text: '', css: { width: 30, fontWeight: 'normal', margin: 0 } },
                    { type: UIButton_8.UIButton, icon: 'glyphicon glyphicon-remove', styleClass: 'btn-sm',
                        attr: { title: __('Remove') },
                        click: function () { return _this.list.removeItemElem(_this); }
                    }
                ]
            }, this, this.fields);
        };
        RangeElement.prototype.load = function () {
            this.fields.from.setValue(this.item.from);
            this.fields.to.setValue(this.item.to);
            this.fields.value.setValue(this.item.value);
            if (StoreModule_9.Module.currency)
                this.fields.currency.setText(StoreModule_9.Module.currency.code);
        };
        RangeElement.prototype.store = function () {
            this.item.from = parseFloat(this.fields.from.getValue());
            this.item.to = parseFloat(this.fields.to.getValue());
            this.item.value = parseFloat(this.fields.value.getValue());
        };
        return RangeElement;
    }(ItemContainer_2.ItemContainerItem));
    exports.RangeElement = RangeElement;
});
define("store/StoreShippingMethodDialog", ["require", "exports", "List", "TextField", "DropdownBox", "PropertyDialog", "UniqueIdentifier", "store/StoreShippingMethod", "store/StoreModule", "store/StoreDestinationZoneDialog", "VerticalLayout", "HorizontalLayout", "Label", "FlowLayout", "UIButton", "ItemContainer", "store/StoreRangesControl"], function (require, exports, List_6, TextField_5, DropdownBox_6, PropertyDialog_6, UniqueIdentifier_8, StoreShippingMethod_2, StoreModule_10, StoreDestinationZoneDialog_2, VerticalLayout_12, HorizontalLayout_6, Label_7, FlowLayout_6, UIButton_9, ItemContainer_3, StoreRangesControl_1) {
    "use strict";
    exports.__esModule = true;
    var singleInstance = null;
    var saveListeners = [];
    function addSaveListener(func) {
        saveListeners.push(func);
    }
    exports.addSaveListener = addSaveListener;
    function open() {
        if (!singleInstance) {
            singleInstance = new StoreShippingMethodDialog();
        }
        singleInstance.setVisible(true);
    }
    exports.open = open;
    var StoreShippingMethodList = (function (_super) {
        __extends(StoreShippingMethodList, _super);
        function StoreShippingMethodList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        StoreShippingMethodList.prototype.buildInit = function (data, fields) {
            data.itemType = StoreShippingMethod_2.StoreShippingMethod;
            data.editable = true;
            data.select = this.onSelect;
            data.selectNone = this.onSelectNone;
            data.add = this.onAdd;
            _super.prototype.buildInit.call(this, data, fields);
        };
        StoreShippingMethodList.prototype.setItemValue = function (item, fields) {
            item.name = fields.name.getValue();
            item.destinationZoneId = fields.destinationZone.getValue();
            item.type = fields.type.getValue();
            switch (item.type) {
                case StoreShippingMethod_2.StoreShippingMethodType.FREE:
                    item.ranges = [];
                    break;
                case StoreShippingMethod_2.StoreShippingMethodType.FLAT_RATE:
                    item.ranges = [new StoreShippingMethod_2.StoreShippingMethodRange(0, 0, parseFloat(fields.price.getValue()))];
                    break;
                case StoreShippingMethod_2.StoreShippingMethodType.BY_WEIGHT:
                    item.ranges = fields.byWeight.getValue();
                    break;
                case StoreShippingMethod_2.StoreShippingMethodType.BY_SUBTOTAL:
                    item.ranges = fields.bySubtotal.getValue();
                    break;
            }
            item.estimatedShippingTime.from = parseInt(fields.shippingTimeFrom.getValue(), 10);
            if (isNaN(item.estimatedShippingTime.from))
                item.estimatedShippingTime.from = 0;
            item.estimatedShippingTime.to = parseInt(fields.shippingTimeTo.getValue(), 10);
            if (isNaN(item.estimatedShippingTime.to))
                item.estimatedShippingTime.to = 0;
        };
        StoreShippingMethodList.prototype.getItemValue = function (item, fields) {
            fields.name.setValue(item.name ? item.name : '');
            fields.destinationZone.setValue(item.destinationZoneId);
            fields.type.setValue(item.type);
            fields.type.trigger('change');
            fields.priceLabel.setText(__('Price') + (StoreModule_10.Module.currency ? (' (' + StoreModule_10.Module.currency.code + ')') : ''));
            fields.price.setValue(0);
            fields.byWeight.setValue([]);
            fields.bySubtotal.setValue([]);
            switch (item.type) {
                case StoreShippingMethod_2.StoreShippingMethodType.FLAT_RATE:
                    if (item.ranges.length > 0)
                        fields.price.setValue(item.ranges[0].value);
                    break;
                case StoreShippingMethod_2.StoreShippingMethodType.BY_WEIGHT:
                    fields.byWeight.setValue(item.ranges);
                    break;
                case StoreShippingMethod_2.StoreShippingMethodType.BY_SUBTOTAL:
                    fields.bySubtotal.setValue(item.ranges);
                    break;
            }
            fields.shippingTimeFrom.setValue(item.estimatedShippingTime.from);
            fields.shippingTimeTo.setValue(item.estimatedShippingTime.to);
        };
        StoreShippingMethodList.prototype.onSelect = function (fields, item) {
            var lastItem;
            if ((lastItem = this.getLastSelected())) {
                this.setItemValue(lastItem, fields);
            }
            this.getItemValue(item, fields);
            fields.editPanel.setVisible(item ? true : false);
        };
        StoreShippingMethodList.prototype.onSelectNone = function (fields) {
            fields.editPanel.setVisible(false);
        };
        StoreShippingMethodList.prototype.onAdd = function (fields, item, li) {
            this.selectItemLi($(li));
        };
        return StoreShippingMethodList;
    }(List_6.List));
    var StoreShippingMethodDialog = (function (_super) {
        __extends(StoreShippingMethodDialog, _super);
        function StoreShippingMethodDialog() {
            var _this = _super.call(this, __('Shipping Methods'), {
                noScroll: true,
                tabs: [
                    { children: [
                            { type: HorizontalLayout_6.HorizontalLayout, columnWeights: [4, 8], columnWeightsSmall: [4, 8], children: [
                                    { type: StoreShippingMethodList, id: 'list', css: { height: 328 }, listHeight: 250 },
                                    { type: VerticalLayout_12.VerticalLayout, id: 'editPanel', spacing: 15, children: [
                                            { type: HorizontalLayout_6.HorizontalLayout, children: [
                                                    { type: VerticalLayout_12.VerticalLayout, children: [
                                                            { type: Label_7.Label, text: __('Name') },
                                                            { type: TextField_5["default"], id: 'name' }
                                                        ] },
                                                    { type: VerticalLayout_12.VerticalLayout, children: [
                                                            { type: Label_7.Label, text: __('Destination Zone') },
                                                            { type: DropdownBox_6["default"], id: 'destinationZone',
                                                                options: StoreModule_10.Module.destinationZones,
                                                                editable: true,
                                                                edit: function () { return StoreDestinationZoneDialog_2.open(); }
                                                            }
                                                        ] }
                                                ] },
                                            { type: VerticalLayout_12.VerticalLayout, children: [
                                                    { type: Label_7.Label, text: __('Type') },
                                                    { type: DropdownBox_6["default"], id: 'type',
                                                        options: StoreShippingMethod_2.buildTypeList(),
                                                        change: function () { _this.showBlockByType(); }
                                                    }
                                                ] },
                                            { type: VerticalLayout_12.VerticalLayout, id: 'blockTypeFlatRate', children: [
                                                    { type: Label_7.Label, id: 'priceLabel', text: __('Price') },
                                                    { type: TextField_5["default"], id: 'price' }
                                                ] },
                                            { type: VerticalLayout_12.VerticalLayout, id: 'blockTypeByWeight', children: [
                                                    { type: FlowLayout_6.FlowLayout, verticalAlign: 'middle', children: [
                                                            { type: Label_7.Label, text: __('Ranges'), css: { marginBottom: 1 } },
                                                            { type: UIButton_9.UIButton, text: __('Add Range'), buttonStyle: UIButton_9.UIButton.STYLE_LINK,
                                                                icon: 'glyphicon glyphicon-plus',
                                                                styleClass: 'btn-sm',
                                                                click: function (e, fields) {
                                                                    fields.byWeight.newItem();
                                                                }
                                                            }
                                                        ] },
                                                    { type: ItemContainer_3.ItemContainer, id: 'byWeight', itemType: StoreShippingMethod_2.StoreShippingMethodRange, itemElemType: StoreRangesControl_1.RangeElement }
                                                ] },
                                            { type: VerticalLayout_12.VerticalLayout, id: 'blockTypeBySubtotal', children: [
                                                    { type: FlowLayout_6.FlowLayout, verticalAlign: 'middle', children: [
                                                            { type: Label_7.Label, text: __('Ranges'), css: { marginBottom: 1 } },
                                                            { type: UIButton_9.UIButton, text: __('Add Range'), buttonStyle: UIButton_9.UIButton.STYLE_LINK,
                                                                icon: 'glyphicon glyphicon-plus',
                                                                styleClass: 'btn-sm',
                                                                click: function (e, fields) {
                                                                    fields.bySubtotal.newItem();
                                                                }
                                                            }
                                                        ] },
                                                    { type: ItemContainer_3.ItemContainer, id: 'bySubtotal', itemType: StoreShippingMethod_2.StoreShippingMethodRange, itemElemType: StoreRangesControl_1.RangeElement }
                                                ] },
                                            { type: VerticalLayout_12.VerticalLayout, children: [
                                                    { type: Label_7.Label, text: __('Estimated Delivery Time (days)') },
                                                    { type: FlowLayout_6.FlowLayout, children: [
                                                            { type: TextField_5["default"], id: 'shippingTimeFrom', css: { width: 80 } },
                                                            { type: Label_7.Label, html: '&mdash;', css: { fontWeight: 'normal', margin: '4px 0' } },
                                                            { type: TextField_5["default"], id: 'shippingTimeTo', css: { width: 80 } }
                                                        ] }
                                                ] }
                                        ] }
                                ] }
                        ] }
                ],
                buttons: [
                    { name: __('Cancel') },
                    { name: __('Apply'), primary: true, click: function () { _this.applyData(); } }
                ]
            }) || this;
            StoreDestinationZoneDialog_2.addSaveListener(function () { _this.fields.destinationZone.reload(StoreModule_10.Module.destinationZones); });
            return _this;
        }
        StoreShippingMethodDialog.prototype.showBlockByType = function () {
            this.fields.blockTypeFlatRate.setVisible(false);
            this.fields.blockTypeByWeight.setVisible(false);
            this.fields.blockTypeBySubtotal.setVisible(false);
            switch (this.fields.type.getValue()) {
                case StoreShippingMethod_2.StoreShippingMethodType.FLAT_RATE:
                    this.fields.blockTypeFlatRate.setVisible(true);
                    break;
                case StoreShippingMethod_2.StoreShippingMethodType.BY_WEIGHT:
                    this.fields.blockTypeByWeight.setVisible(true);
                    break;
                case StoreShippingMethod_2.StoreShippingMethodType.BY_SUBTOTAL:
                    this.fields.blockTypeBySubtotal.setVisible(true);
                    break;
            }
        };
        StoreShippingMethodDialog.prototype.applyData = function () {
            wb_builder.setPageModified(true);
            this.fields.list.selectFirst();
            StoreModule_10.Module.shippingMethods = UniqueIdentifier_8.UniqueIdentifier.assignIds(this.fields.list.getValue());
            this.setVisible(false);
            for (var _i = 0, saveListeners_3 = saveListeners; _i < saveListeners_3.length; _i++) {
                var func = saveListeners_3[_i];
                if (typeof func === 'function')
                    func.call(this);
            }
        };
        StoreShippingMethodDialog.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            if (noAction === void 0) { noAction = false; }
            if (ignoreEvent === void 0) { ignoreEvent = false; }
            if (visible && !ignoreEvent) {
                this.fields.list.setValue(StoreModule_10.Module.shippingMethods);
                this.fields.list.selectFirst();
                this.showBlockByType();
            }
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
        };
        return StoreShippingMethodDialog;
    }(PropertyDialog_6["default"]));
    exports.StoreShippingMethodDialog = StoreShippingMethodDialog;
});
define("store/StoreCart", ["require", "exports", "Element", "UIComponent", "ElementRegister", "Service", "store/StoreModule", "store/StoreOrders", "ToolTipControl", "store/StoreDestinationZoneDialog", "store/StoreTaxRuleDialog", "store/StoreShippingMethodDialog"], function (require, exports, Element_1, UIComponent_14, ElementRegister_1, Service_14, StoreModule_11, StoreOrders, ToolTipControl_2, StoreDestinationZoneDialog_3, StoreTaxRuleDialog_1, StoreShippingMethodDialog_1) {
    "use strict";
    exports.__esModule = true;
    function dataValidate(data) {
        if (data && !data.width) {
            data.width = 155;
            data.height = 64;
        }
        return data;
    }
    var PaymentGatewayList = (function (_super) {
        __extends(PaymentGatewayList, _super);
        function PaymentGatewayList() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.items = [];
            _this.onChange = null;
            _this.uiFields = null;
            return _this;
        }
        PaymentGatewayList.prototype.buildInit = function (data, fields) {
            var _this = this;
            this.uiFields = fields;
            if (typeof (data.change) === 'function') {
                var changeFunc_1 = data.change;
                this.onChange = function () { changeFunc_1.call(_this, fields); };
            }
        };
        PaymentGatewayList.prototype.update = function () {
            var thisSelf = this, i, j, item, fld, keyFld, list = ElementRegister_1["default"].getPaymentGateways(), elem = this.getElem();
            elem.empty();
            this.items = [];
            var _loop_4 = function () {
                item = { api: list[i], key: null, enabler: null, indicator: null };
                var helpElem = null;
                if (('helpText' in list[i]) && list[i].helpText) {
                    if (typeof list[i].helpText === 'string') {
                        helpElem = (new ToolTipControl_2["default"]('?', list[i].helpText)).elem;
                    }
                    else if (typeof list[i].helpText === 'function') {
                        helpElem = list[i].helpText();
                        if (helpElem) {
                            helpElem.attr('title', __('Click for more information'));
                            helpElem.tooltip({ placement: 'top' });
                        }
                    }
                }
                else if (('pageUrl' in list[i]) && list[i].pageUrl) {
                    var label = list[i].pageUrl.replace(/^https?:\/\//, '').replace(/\/$/, '');
                    var url = '<a href="' + list[i].pageUrl + '" target="_blank">' + label + '</a>';
                    helpElem = (new ToolTipControl_2["default"]('?', url)).elem;
                }
                if (('keyFieldDef' in list[i]) && list[i].keyFieldDef) {
                    keyFld = list[i].keyFieldDef;
                }
                else {
                    keyFld = { type: 'HorizontalLayout', noPadding: true, children: [] };
                    for (j = 1; j < 6; j++) {
                        var idx = (j === 1) ? '' : j;
                        if ((('keyField' + idx) in list[i]) && list[i]['keyField' + idx]) {
                            fld = (typeof list[i]['keyField' + idx] === 'object')
                                ? list[i]['keyField' + idx]
                                : { type: 'TextField', placeholder: list[i]['keyField' + idx] };
                            fld.id = 'key' + idx;
                            fld.enabled = false;
                            keyFld.children.push(fld);
                        }
                    }
                }
                keyFld.afterInit = function (def, fields) {
                    var indicator = $('<div>').css({
                        position: 'absolute', left: 8, top: 0, width: 3, padding: 0, height: '100%', background: '#eee'
                    });
                    indicator.data('setEnabled', function (enabled) {
                        if (enabled) {
                            indicator.css('background', '#0c0');
                        }
                        else {
                            indicator.css('background', '#eee');
                        }
                    });
                    this.getElem().append(indicator);
                    fields.indicator = indicator;
                };
                Service_14["default"].UIBuilder.buildLayout({
                    type: 'HorizontalLayout',
                    css: { marginTop: 5 },
                    columnWeights: [3, 9],
                    columnWeightsSmall: [3, 9],
                    children: [
                        { type: 'CheckBox', id: 'enabler', label: list[i].name, css: { marginTop: 7 }, change: function (fields) {
                                var enabled = this.getValue();
                                for (var j_1 = 1; j_1 < 6; j_1++) {
                                    var idx = (j_1 === 1) ? '' : j_1;
                                    if (('key' + idx) in fields && fields['key' + idx] && (typeof fields['key' + idx].setEnabled === 'function'))
                                        fields['key' + idx].setEnabled(enabled);
                                }
                                if (fields.indicator)
                                    fields.indicator.data('setEnabled')(enabled);
                                if (thisSelf.onChange)
                                    thisSelf.onChange();
                                if (enabled && (typeof fields.api.onEnable === "function"))
                                    fields.api.onEnable.call(fields, thisSelf, StoreModule_11.Module);
                                if (!enabled && (typeof fields.api.onDisable === "function"))
                                    fields.api.onDisable.call(fields, thisSelf, StoreModule_11.Module);
                            }, init: function () {
                                if (helpElem)
                                    this.getElem().append(helpElem);
                            } },
                        keyFld
                    ]
                }, elem, item);
                this_2.items.push(item);
            };
            var this_2 = this;
            for (i = 0; i < list.length; i++) {
                _loop_4();
            }
            for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
                item = _a[_i];
                if (typeof item.api.onInit === "function")
                    item.api.onInit.call(item, this, StoreModule_11.Module);
            }
        };
        ;
        PaymentGatewayList.prototype.getActiveCount = function () {
            var count = 0;
            for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
                var item = _a[_i];
                if (item.enabler && item.enabler.getValue())
                    count++;
            }
            return count;
        };
        PaymentGatewayList.prototype.getValue = function () {
            var i, gateway, gateways = [];
            for (i = 0; i < this.items.length; i++) {
                var item = this.items[i];
                if (!item.enabler || !item.enabler.getValue() || !item.key || !item.key.getValue())
                    continue;
                gateway = $.extend({}, this.items[i].api);
                for (var j = 1; j < 6; j++) {
                    var idx = (j === 1) ? '' : j;
                    if ((('key' + idx) in this.items[i]) && this.items[i]['key' + idx])
                        gateway['key' + idx] = this.items[i]['key' + idx].getValue();
                }
                gateways.push(gateway);
            }
            return gateways;
        };
        PaymentGatewayList.prototype.setValue = function (gateways) {
            if (!gateways)
                gateways = [];
            var i, n;
            for (i = 0; i < this.items.length; i++) {
                var item = this.items[i];
                if (!item.enabler)
                    continue;
                item.enabler.setValue(false);
                item.enabler.trigger('change');
                for (var j = 1; j < 6; j++) {
                    var idx = (j === 1) ? '' : j;
                    var defaultValue = item.api.hasOwnProperty('keyField' + idx + 'DefaultValue') ? item.api['keyField' + idx + 'DefaultValue'] : '';
                    if ((('key' + idx) in item) && item['key' + idx])
                        item['key' + idx].setValue(defaultValue);
                }
                for (n = 0; n < gateways.length; n++) {
                    if (item.api.id === gateways[n].id && gateways[n].key) {
                        item.enabler.setValue(true);
                        item.enabler.trigger('change');
                        for (var j = 1; j < 6; j++) {
                            var idx = (j === 1) ? '' : j;
                            if ((('key' + idx) in this.items[i]) && this.items[i]['key' + idx])
                                this.items[i]['key' + idx].setValue(gateways[n]['key' + idx]);
                        }
                    }
                }
            }
        };
        PaymentGatewayList.prototype.getUiFields = function () {
            return this.uiFields;
        };
        return PaymentGatewayList;
    }(UIComponent_14.UIComponent));
    var StoreCart = (function (_super) {
        __extends(StoreCart, _super);
        function StoreCart(data) {
            var _this = _super.call(this, dataValidate(data)) || this;
            _this._data = data;
            _this.setMinSize(22, 22);
            if (_this._data.content.name === undefined)
                _this._data.content.name = __('Shopping Cart');
            if (!_this._data.content.image)
                _this._data.content.image = null;
            _this.updateStyle(true);
            if (_this.controls)
                _this.controls.bind('dblclick', function () { return _this.comProperties(); });
            StoreModule_11.Module.needToSave = true;
            StoreModule_11.Module.load(function () { return _this.updateStyle(); });
            return _this;
        }
        StoreCart.prototype.serialize = function () {
            var data = _super.prototype.serialize.call(this);
            data.content = {};
            for (var k in this._data.content) {
                data.content[k] = this._data.content[k];
            }
            return data;
        };
        StoreCart.prototype.onSwitchLanguage = function (langCode) {
            _super.prototype.onSwitchLanguage.call(this, langCode);
            this.updateStyle(false, langCode);
        };
        StoreCart.prototype.updateStyle = function (initial, langCode) {
            if (langCode === void 0) { langCode = null; }
            _super.prototype.updateStyle.call(this, initial, langCode);
            langCode = langCode || this.system.site.currSelLang;
            this.container.empty();
            var img = null, span = null;
            if (this._data.content.image) {
                img = $('<img>').attr({
                    src: wb_builder.makeLocalUrl(this._data.content.image),
                    alt: __tr(this._data.content.name, langCode),
                    title: __tr(this._data.content.name, langCode)
                });
            }
            else {
                span = $('<span>').css(wb_builder.site.rtl ? 'marginLeft' : 'marginRight', 4).append($('<i>').addClass('store-cart-icon'));
            }
            var cont = $('<div>').addClass('wb-store-cart');
            if (img)
                cont.append(img);
            var inner = $('<div>');
            if (span)
                inner.append(span);
            inner.append($('<span>')
                .append($('<span>').text(__tr(this._data.content.name, langCode)))
                .append('&nbsp;').append($('<span style="display: inline-block;">').text('(0)')));
            cont.append(inner).appendTo(this.container);
            return;
        };
        StoreCart.prototype.comProperties = function () {
            var _this = this;
            var onAdvInvDocNumModeChange = function (fields) {
                var adv = fields.advancedInvoiceDocNumModeOn.getValue();
                fields.simpleInvDocNumCont.setVisible(!adv);
                fields.advancedInvDocNumCont.setVisible(adv);
            };
            var onSimpleInvDocNumFmtChange = function (fields) {
                var fmt = "";
                var series = fields.invoiceDocumentNumberSeries.getValue();
                if (series !== null && series !== "")
                    fmt += series + " ";
                fmt += "{N:" + fields.invoiceDocumentNumberLength.getValue() + "}";
                fields.invoiceDocumentNumberFormat.setValue(fmt);
                fields.simpleInvoiceDocNumPreview.setContent(StoreCart.getSimpleInvoiceDocumentNumberPreviewHtml(fmt));
                fields.advancedInvoiceDocNumPreview.setContent(StoreCart.getAdvancedInvoiceDocumentNumberPreviewHtml(fmt));
            };
            var onAdvancedInvDocNumFmtChange = function (fields) {
                StoreCart.parseAdvancedInvoiceDocumentNumberFormat(fields);
                fields.simpleInvoiceDocNumPreview.setContent(StoreCart.getSimpleInvoiceDocumentNumberPreviewHtml(fields.invoiceDocumentNumberFormat.getValue()));
                fields.advancedInvoiceDocNumPreview.setContent(StoreCart.getAdvancedInvoiceDocumentNumberPreviewHtml(fields.invoiceDocumentNumberFormat.getValue()));
            };
            var fields = Element_1["default"].prototype.comProperties.call(this, {
                size: { width: 870 },
                tabs: [
                    { children: [
                            { type: 'HorizontalLayout', columnWeights: [3, 9], columnWeightsSmall: [3, 9], children: [
                                    { type: 'VerticalLayout', children: [
                                            { type: 'Label', text: __('Name') },
                                            { type: 'MultilangTextField', id: 'name' },
                                            { type: 'Label', text: __('Image'), css: { marginTop: 15 } },
                                            { type: 'ImageSelector', id: 'image' },
                                            { type: 'CheckBox', label: __('Require Billing/Shipping Information'), id: 'billingShippingRequired',
                                                css: { marginTop: 15 }
                                            },
                                            { type: 'Label', text: __('My Orders'), css: { marginTop: 15 } },
                                            { type: 'Button', text: __('Check Orders'), click: function () { return StoreOrders.viewOrders(wb_builder); } },
                                            { type: 'Label', text: __('Destination Zones'), css: { marginTop: 15 } },
                                            { type: 'Button', text: __('Destination Zones'), click: function () { return StoreDestinationZoneDialog_3.open(); } },
                                            { type: 'Label', text: __('Tax Rules'), css: { marginTop: 15 } },
                                            { type: 'Button', text: __('Tax Rules'), click: function () { return StoreTaxRuleDialog_1.open(); } },
                                            { type: 'Label', text: __('Shipping Methods'), css: { marginTop: 15 } },
                                            { type: 'Button', text: __('Shipping Methods'), click: function () { return StoreShippingMethodDialog_1.open(); } }
                                        ] },
                                    { type: 'VerticalLayout', children: [
                                            { type: 'Label', text: __('Payment Gateways') },
                                            { type: PaymentGatewayList, id: 'paymentGatewayList', change: function (fields) {
                                                    fields.billingShippingRequired.setVisible(fields.paymentGatewayList.getActiveCount() > 0);
                                                } }
                                        ] }
                                ] }
                        ] },
                    { name: __('Invoices'), children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Seller details in invoice'), css: { marginTop: 15 }, helpText: __('This information is added to "Seller" section of all invoices.') },
                                    { type: 'CustomContainer', id: 'companyInfoPlaceholder', css: { height: 0, position: 'relative' }, content: '<div style="position: absolute; left: 0; top: 0; max-width: 100%; padding: 7px 13px; color: #999;"></div>', init: function () {
                                            var child = this.getElem().children();
                                            child.append($('<div/>').text(__('Company LLC')));
                                            child.append($('<div/>').text(__('Code: 0000000000')));
                                            child.append($('<div/>').text(__('Tax: 0000000000')));
                                            child.append($('<div/>').text(__('Address: Empire State Building, 350 5th Ave, New York, NY 10118, USA')));
                                            child.append($('<div/>').text(__('Bank account number: XX00 0000 0000 0000')));
                                        } },
                                    { type: 'TextField', id: 'companyInfo', textArea: true, css: { height: 200, 'white-space': 'nowrap', 'background-color': 'transparent' }, on: {
                                            "change focus blur paste cut keyup keydown touchstart touchend touchcancel": function () {
                                                fields.companyInfoPlaceholder.setVisible(fields.companyInfo.getValue() === "");
                                            }
                                        } },
                                    { type: 'Label', text: __('Invoice document number'), css: { marginTop: 15 } },
                                    { type: 'FlowLayout', spacing: 30, children: [
                                            { type: 'RadioBox', id: "advancedInvoiceDocNumModeOff", label: __("Simple"), inline: true, group: "advancedInvoiceDocNumMode", change: onAdvInvDocNumModeChange },
                                            { type: 'RadioBox', id: "advancedInvoiceDocNumModeOn", label: __("Advanced"), inline: true, group: "advancedInvoiceDocNumMode", change: onAdvInvDocNumModeChange }
                                        ] },
                                    { type: 'VerticalLayout', id: "simpleInvDocNumCont", children: [
                                            { type: 'HorizontalLayout', columnWeights: [3, 3], columnWeightsSmall: [6, 6], children: [
                                                    { type: 'VerticalLayout', children: [
                                                            { type: 'Label', text: __('Series'), css: { marginTop: 15 } },
                                                            { type: 'TextField', id: 'invoiceDocumentNumberSeries', on: {
                                                                    keydown: function (e, fields) {
                                                                        if (e.key === "{" || e.key === "}") {
                                                                            e.preventDefault();
                                                                            e.stopImmediatePropagation();
                                                                        }
                                                                    },
                                                                    keyup: function (e, fields) {
                                                                        var val = fields.invoiceDocumentNumberSeries.getValue();
                                                                        if (/[{}]/.test(val))
                                                                            fields.invoiceDocumentNumberSeries.setValue(val.replace(/[{}]/g, ""));
                                                                        onSimpleInvDocNumFmtChange(fields);
                                                                    }
                                                                } },
                                                        ] },
                                                    { type: 'VerticalLayout', children: [
                                                            { type: 'Label', text: __('Number length'), css: { marginTop: 15 } },
                                                            { type: 'SizeSelector', id: 'invoiceDocumentNumberLength', min: 1, max: 20, step: 1, change: onSimpleInvDocNumFmtChange },
                                                        ] },
                                                ] },
                                            { type: 'CustomContainer', id: "simpleInvoiceDocNumPreview", styleClass: "alert alert-warning", css: { "font-size": "12px", marginTop: 15 },
                                                content: StoreCart.getSimpleInvoiceDocumentNumberPreviewHtml(StoreModule_11.Module.invoiceDocumentNumberFormat) }
                                        ] },
                                    { type: 'VerticalLayout', id: "advancedInvDocNumCont", children: [
                                            { type: 'Label', text: __('Format'), css: { marginTop: 15 } },
                                            { type: 'TextField', id: 'invoiceDocumentNumberFormat', on: {
                                                    keyup: function (e, fields) {
                                                        onAdvancedInvDocNumFmtChange(fields);
                                                    }
                                                } },
                                            { type: 'HorizontalLayout', columnWeights: [6, 6], columnWeightsSmall: [12, 12], children: [
                                                    { type: 'CustomContainer', styleClass: "alert alert-info", css: { "font-size": "12px", overflow: "auto", height: 340, marginTop: 15 },
                                                        content: '<strong>' + __('Supported variables') + '</strong>:<br />'
                                                            + __('{YYYY} - 4 digit year number.') + '<br />'
                                                            + __('{YY} - 2 digit year number.') + '<br />'
                                                            + __('{MM} - 2 digit month number.') + '<br />'
                                                            + __('{DD} - 2 digit day of month number.') + '<br />'
                                                            + __('{N} - counter value of current series.') + '<br />'
                                                            + __('{RN} - counter value of current series for date represented by {YYYY}, {YY}, {MM}, and/or {DD} variables.') + '<br />'
                                                            + __('{%1$s:#} - zero padded value of {%1$s}. Replace "#" with number of digits the counter value should have to produce fixed length document numbers.').replace(/%1\$s/g, "N") + '<br />'
                                                            + __('{%1$s:#} - zero padded value of {%1$s}. Replace "#" with number of digits the counter value should have to produce fixed length document numbers.').replace(/%1\$s/g, "RN") + '<br />'
                                                            + '<br />'
                                                            + '<strong>' + __('Please note that different invoice series and document number formats have separate counters starting from 1.') + '</strong>'
                                                    },
                                                    { type: 'CustomContainer', id: "advancedInvoiceDocNumPreview", styleClass: "alert alert-warning", css: { "font-size": "12px", overflow: "auto", height: 340, marginTop: 15 },
                                                        content: StoreCart.getAdvancedInvoiceDocumentNumberPreviewHtml(StoreModule_11.Module.invoiceDocumentNumberFormat) }
                                                ] }
                                        ] }
                                ] }
                        ] },
                    { name: __('Advanced'), children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'CheckBox', id: 'termsCheckboxEnabled', label: __('Require customer to agree to terms and conditions') },
                                    { type: 'WYSIWYGControl', id: 'termsCheckboxText', css: { height: 100, marginTop: 10 }, config: {
                                            forcePasteAsPlainText: true
                                        } },
                                    { type: 'Label', text: __('Minimum order price'), id: 'minOrderPriceLabel', css: { marginTop: 15 } },
                                    { type: 'SizeSelector', id: 'minOrderPrice', min: 0, precision: 2, step: 1, noFixedWidth: true, css: { width: 150 } }
                                ] }
                        ] }
                ],
                callbackFunc: function (fields) {
                    _this._data.content.name = fields.name.getValue();
                    _this._data.content.image = fields.image.getValue();
                    StoreModule_11.Module.paymentGateways = fields.paymentGatewayList.getValue();
                    if (StoreModule_11.Module.paymentGateways.length > 0) {
                        StoreModule_11.Module.billingShippingRequired = fields.billingShippingRequired.getValue();
                    }
                    StoreModule_11.Module.advancedInvoiceDocNumMode = fields.advancedInvoiceDocNumModeOn.getValue();
                    StoreModule_11.Module.invoiceDocumentNumberFormat = fields.invoiceDocumentNumberFormat.getValue();
                    StoreModule_11.Module.companyInfo = fields.companyInfo.getValue();
                    StoreModule_11.Module.termsCheckboxEnabled = fields.termsCheckboxEnabled.getValue();
                    StoreModule_11.Module.termsCheckboxText = fields.termsCheckboxText.getValue();
                    StoreModule_11.Module.minOrderPrice = fields.minOrderPrice.getValue();
                    _this.updateStyle();
                }
            });
            fields.paymentGatewayList.update();
            fields.name.setValue(this._data.content.name);
            fields.image.setValue(this._data.content.image);
            fields.billingShippingRequired.setValue(StoreModule_11.Module.billingShippingRequired !== false);
            fields.billingShippingRequired.setVisible(StoreModule_11.Module.paymentGateways.length > 0);
            fields.paymentGatewayList.setValue(StoreModule_11.Module.paymentGateways);
            fields.advancedInvoiceDocNumModeOff.setValue(!StoreModule_11.Module.advancedInvoiceDocNumMode);
            fields.advancedInvoiceDocNumModeOn.setValue(StoreModule_11.Module.advancedInvoiceDocNumMode);
            fields.invoiceDocumentNumberFormat.setValue(StoreModule_11.Module.invoiceDocumentNumberFormat);
            fields.companyInfo.setValue(StoreModule_11.Module.companyInfo);
            fields.termsCheckboxEnabled.setValue(StoreModule_11.Module.termsCheckboxEnabled);
            fields.termsCheckboxText.setValue(StoreModule_11.Module.termsCheckboxText);
            fields.minOrderPrice.setValue(StoreModule_11.Module.minOrderPrice);
            fields.minOrderPriceLabel.setText(__('Minimum order price') + (StoreModule_11.Module.currency ? (' (' + StoreModule_11.Module.currency.code + ')') : ''));
            fields.simpleInvDocNumCont.setVisible(!StoreModule_11.Module.advancedInvoiceDocNumMode);
            fields.advancedInvDocNumCont.setVisible(StoreModule_11.Module.advancedInvoiceDocNumMode);
            StoreCart.parseAdvancedInvoiceDocumentNumberFormat(fields);
            onAdvancedInvDocNumFmtChange(fields);
            return fields;
        };
        StoreCart.parseAdvancedInvoiceDocumentNumberFormat = function (fields) {
            var fmt = fields.invoiceDocumentNumberFormat.getValue();
            var matches = fmt.match(/^([^{}]+ |){N:(\d+)}$/i);
            if (matches) {
                fields.advancedInvoiceDocNumModeOff.setEnabled(true);
                fields.invoiceDocumentNumberSeries.setValue((matches[1] === "") ? "" : matches[1].substring(0, matches[1].length - 1));
                fields.invoiceDocumentNumberLength.setValue(matches[2]);
            }
            else
                fields.advancedInvoiceDocNumModeOff.setEnabled(false);
        };
        StoreCart.getSimpleInvoiceDocumentNumberPreviewHtml = function (docNumFmt) {
            var html = '<strong>' + __('Preview invoice document numbers') + '</strong>:<br />';
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, '%1$s', "2017", "17", "11", "22", 1, 1, 1, 1);
            html += '...<br />';
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, '%1$s', "2017", "17", "11", "22", 17, 17, 17, 17);
            html += '...<br />';
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, '%1$s', "2017", "17", "11", "22", 2103, 2103, 2103, 2103);
            return html;
        };
        StoreCart.getAdvancedInvoiceDocumentNumberPreviewHtml = function (docNumFmt) {
            var html = '<strong>' + __('Preview invoice document numbers') + '</strong>:<br />';
            var year = (new Date()).getFullYear();
            var currYear = year + '';
            var nextYear = (year + 1) + '';
            var currYearShort = (currYear + '').substring(2);
            var nextYearShort = (nextYear + '').substring(2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), currYear, currYearShort, "11", "22", 1, 1, 1, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), currYear, currYearShort, "11", "22", 2, 2, 2, 2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), currYear, currYearShort, "11", "27", 3, 3, 3, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), currYear, currYearShort, "11", "27", 4, 4, 4, 2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), currYear, currYearShort, "12", "15", 5, 5, 1, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), currYear, currYearShort, "12", "15", 6, 6, 2, 2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), currYear, currYearShort, "12", "19", 7, 7, 3, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), currYear, currYearShort, "12", "19", 8, 8, 4, 2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), nextYear, nextYearShort, "01", "01", 9, 1, 1, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), nextYear, nextYearShort, "01", "01", 10, 2, 2, 2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), nextYear, nextYearShort, "01", "09", 11, 3, 3, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), nextYear, nextYearShort, "01", "09", 12, 4, 4, 2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), nextYear, nextYearShort, "02", "07", 13, 5, 1, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), nextYear, nextYearShort, "02", "07", 14, 6, 2, 2);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - first invoice on %2$s.'), nextYear, nextYearShort, "02", "14", 15, 7, 3, 1);
            html += StoreCart.getInvoiceDocumentNumberPreviewLineHtml(docNumFmt, __('%1$s - second invoice on %2$s.'), nextYear, nextYearShort, "02", "14", 16, 8, 4, 2);
            return html;
        };
        StoreCart.getInvoiceDocumentNumberPreviewLineHtml = function (docNumFmt, previewLineText, fullYear, shortYear, month, day, nCounter, rnCounterYearly, rnCounterMonthly, rnCounterDaily) {
            return previewLineText
                .replace("%1$s", StoreCart.getDocumentNumber(docNumFmt, fullYear, shortYear, month, day, nCounter, rnCounterYearly, rnCounterMonthly, rnCounterDaily))
                .replace("%2$s", fullYear + '-' + month + '-' + day)
                + '<br />';
        };
        StoreCart.getDocumentNumber = function (docNumFmt, fullYear, shortYear, month, day, nCounter, rnCounterYearly, rnCounterMonthly, rnCounterDaily) {
            var rnCounter = nCounter;
            if (/{DD}/i.test(docNumFmt))
                rnCounter = rnCounterDaily;
            else if (/{MM}/i.test(docNumFmt))
                rnCounter = rnCounterMonthly;
            else if (/{(YY|YYYY)}/i.test(docNumFmt))
                rnCounter = rnCounterYearly;
            docNumFmt = docNumFmt
                .replace(/{YYYY}/ig, fullYear)
                .replace(/{YY}/ig, shortYear)
                .replace(/{MM}/ig, month)
                .replace(/{DD}/ig, day)
                .replace(/{N}/ig, nCounter.toString())
                .replace(/{RN}/ig, rnCounter.toString());
            var mtc;
            var rx = /{N:(\d+)}/ig;
            while (mtc = rx.exec(docNumFmt)) {
                var num = nCounter.toString();
                for (var i = parseInt(mtc[1]), il = num.length; i > il; i--)
                    num = '0' + num;
                docNumFmt = docNumFmt.replace(mtc[0], num);
            }
            rx = /{RN:(\d+)}/ig;
            while (mtc = rx.exec(docNumFmt)) {
                var num = rnCounter.toString();
                for (var i = parseInt(mtc[1]), il = num.length; i > il; i--)
                    num = '0' + num;
                docNumFmt = docNumFmt.replace(mtc[0], num);
            }
            return docNumFmt;
        };
        return StoreCart;
    }(Element_1["default"]));
    exports.StoreCart = StoreCart;
    ElementRegister_1["default"].registerClass('StoreCart', StoreCart);
});
define("store/Store", ["require", "exports", "ElementRegister", "Element", "Service", "TextControl", "BorderControl", "store/StoreModule", "store/StorePropertyDialog", "store/StoreCart"], function (require, exports, ElementRegister_2, Element_2, Service_15, TextControl_1, BorderControl_1, StoreModule_12, StorePropertyDialog) {
    "use strict";
    exports.__esModule = true;
    var Store = (function (_super) {
        __extends(Store, _super);
        function Store(data) {
            var _this = _super.call(this, Store.dataValidate(data)) || this;
            _this._prodListElem = null;
            _this._data = data;
            var i, defStyle = {}, styles = wb_builder.site.styles;
            for (i = 0; i < styles.length; i++) {
                if (styles[i].selector === '.wb-stl-normal') {
                    defStyle = TextControl_1["default"].buildCss({
                        color: styles[i].sys.text.color,
                        size: styles[i].sys.text.size,
                        font: styles[i].sys.text.font,
                        style: {}
                    });
                }
            }
            if (!_this._data.content)
                _this._data.content = {};
            if (!_this._data.content.currencyCode)
                _this._data.content.currencyCode = 'USD';
            if (!_this._data.content.currencyPrefix)
                _this._data.content.currencyPrefix = '$';
            if (!_this._data.content.currencyPostfix)
                _this._data.content.currencyPostfix = '';
            if (!_this._data.content.thumbWidth)
                _this._data.content.thumbWidth = 200;
            if (!_this._data.content.thumbHeight)
                _this._data.content.thumbHeight = 200;
            if (!_this._data.content.imageWidth)
                _this._data.content.imageWidth = 300;
            if (!_this._data.content.imageHeight)
                _this._data.content.imageHeight = 300;
            if (!_this._data.content.imageBorder) {
                _this._data.content.imageBorder = BorderControl_1["default"].buildCss({
                    color: '#eeeeee',
                    style: 'solid',
                    weight: 1,
                    radius: 0
                });
            }
            if (!_this._data.content.nameStyle) {
                _this._data.content.nameStyle = $.extend(true, {}, defStyle);
                _this._data.content.nameStyle.style.bold = true;
                _this._data.content.nameStyle = TextControl_1["default"].buildCss(_this._data.content.nameStyle);
            }
            if (!_this._data.content.priceStyle)
                _this._data.content.priceStyle = defStyle;
            if (!_this._data.content.descStyle)
                _this._data.content.descStyle = defStyle;
            if (!_this._data.content.labelStyle)
                _this._data.content.labelStyle = defStyle;
            if (!_this._data.content.itemsPerPage)
                _this._data.content.itemsPerPage = (_this._data.id ? 0 : 8);
            if (!_this._data.content.category)
                _this._data.content.category = 0;
            _this.updateStyle(true);
            if (_this.controls)
                _this.controls.bind('dblclick', function () { return _this.comProperties(); });
            StoreModule_12.Module.needToSave = true;
            StoreModule_12.Module.load(function () { return _this.updateStyle(); });
            Store.elemList.push(_this);
            return _this;
        }
        Store.dataValidate = function (data) {
            if (data && !data.width) {
                data.width = 900;
                data.height = 620;
            }
            return data;
        };
        Store.reloadAll = function (except) {
            for (var i = 0, item = void 0; (item = Store.elemList[i]); i++) {
                if (item === except) {
                    continue;
                }
                item.updateStyle(false, null, true);
            }
        };
        Store.prototype.serialize = function () {
            var data = _super.prototype.serialize.call(this);
            data.content = {};
            for (var k in this._data.content) {
                data.content[k] = this._data.content[k];
            }
            return data;
        };
        Store.prototype.updateContentSize = function () {
            _super.prototype.updateContentSize.call(this);
            if (this._prodListElem)
                this._prodListElem.parent().css({ width: this.getWidth(), height: this.getHeight() });
        };
        Store.prototype.onSwitchLanguage = function (langCode) {
            _super.prototype.onSwitchLanguage.call(this, langCode);
            this.updateStyle(false, langCode);
        };
        Store.prototype.updateStyle = function (initial, langCode, updateThisOnly) {
            if (langCode === void 0) { langCode = null; }
            if (updateThisOnly === void 0) { updateThisOnly = false; }
            _super.prototype.updateStyle.call(this, initial, langCode);
            langCode = langCode || this.system.site.currSelLang;
            if (!this._prodListElem) {
                var base = $('<div>').addClass('wb-store')
                    .css({ width: this.getWidth(), height: this.getHeight() });
                $('<div>').addClass('wb-store-filters')
                    .append($('<select>').addClass('wb-store-cat-select form-control')
                    .append($('<option>').attr({ value: '' }).text(__('All'))))
                    .appendTo(base);
                this._prodListElem = $('<div>').addClass('wb-store-list').css({ textAlign: 'center' }).appendTo(base);
                this.container.append(base);
            }
            if (this._data.content.category) {
                this.container.find('.wb-store-cat-select').hide();
            }
            else {
                this.container.find('.wb-store-cat-select').show();
            }
            this._prodListElem.empty();
            var i, item, el, price, priceStr, thumb, img, name, priceVal, thisSelf = this, currency = StoreModule_12.Module.currency, items = StoreModule_12.Module.items, thumbWidth = (thisSelf._data.content.thumbWidth ? thisSelf._data.content.thumbWidth : 0), thumbHeight = (thisSelf._data.content.thumbHeight ? thisSelf._data.content.thumbHeight : 0), maxItems = ((this._data.content.itemsPerPage && this._data.content.itemsPerPage > 0)
                ? Math.min(items.length, this._data.content.itemsPerPage)
                : items.length), cc = 0;
            var thumbWrapperWidth = thumbWidth + BorderControl_1["default"].getBorderWidth(thisSelf._data.content.imageBorder, 3) + BorderControl_1["default"].getBorderWidth(thisSelf._data.content.imageBorder, 1);
            var thumbWrapperHeight = thumbHeight + BorderControl_1["default"].getBorderWidth(thisSelf._data.content.imageBorder, 0) + BorderControl_1["default"].getBorderWidth(thisSelf._data.content.imageBorder, 2);
            for (i = 0; i < items.length; i++) {
                if (cc >= maxItems)
                    break;
                item = items[i];
                if (item.isHidden)
                    continue;
                if (this._data.content.category && item.categories.indexOf(this._data.content.category) < 0)
                    continue;
                cc++;
                el = $('<div>').addClass('wb-store-item').css({ maxWidth: (thumbWrapperWidth + 2) });
                thumb = $('<div>').addClass('wb-store-thumb').css({
                    width: thumbWrapperWidth,
                    height: thumbWrapperHeight
                }).css(thisSelf._data.content.imageBorder.css).appendTo(el);
                if (item.image) {
                    img = $('<img>').attr({ src: wb_builder.makeLocalUrl(item.image), alt: '' }).appendTo(thumb);
                    (function (img, src) {
                        var image = new Image();
                        image.onload = function () {
                            var ow = this.width, oh = this.height, w = thumbWidth, h = thumbHeight, nw, nh;
                            nw = w;
                            nh = Math.round(oh * w / ow);
                            if (nh < h) {
                                nh = h;
                                nw = Math.round(ow * h / oh);
                            }
                            img.css({
                                width: nw,
                                maxWidth: nw,
                                height: nh,
                                maxHeight: nh,
                                marginLeft: Math.round((w - nw) / 2.0),
                                marginTop: Math.round((h - nh) / 2.0)
                            });
                        };
                        image.onerror = function () { };
                        image.src = src;
                    })(img, wb_builder.makeLocalUrl(item.image));
                }
                else {
                    $('<span>').addClass('wb-store-nothumb glyphicon glyphicon-picture')
                        .appendTo(thumb);
                }
                name = $('<div>').addClass('wb-store-name').text(__tr(item.name, langCode, __tr(item.name, wb_builder.site.getLastDefLang()))).appendTo(el);
                if (this._data.content.nameStyle.css)
                    name.css(this._data.content.nameStyle.css);
                if (item.price > 0) {
                    priceStr = StoreModule_12.Module.getFormattedPrice(item.price);
                    if (priceStr) {
                        priceVal = '' + currency.prefix + priceStr + ((!currency.prefix && !currency.postfix) ? (' ' + currency.code) : currency.postfix);
                        price = $('<div>').addClass('wb-store-price').text(priceVal).appendTo(el);
                        if (this._data.content.priceStyle.css)
                            price.css(this._data.content.priceStyle.css);
                    }
                }
                this._prodListElem.append(el);
            }
            if (!updateThisOnly) {
                Store.reloadAll(this);
            }
        };
        Store.prototype.comProperties = function () {
            var _this = this;
            var fields = _super.prototype.comProperties.call(this, StorePropertyDialog.build(this, function () { return _this._data; }));
            StorePropertyDialog.updateData(fields);
            return fields;
        };
        Store.elemList = [];
        return Store;
    }(Element_2["default"]));
    exports.Store = Store;
    ElementRegister_2["default"].registerClass('Store', Store);
    Service_15["default"].Store = { Module: StoreModule_12.Module };
});
define("TemplateChooser", ["require", "exports", "Dialog", "UIComponent", "PreloaderOverlay", "HelpSystem/HelpSystemPlayer", "Service", "Confirm", "DropdownBox", "ElementRegister", "TextField", "UIButton", "BuilderEvent"], function (require, exports, Dialog_6, UIComponent_15, PreloaderOverlay_3, HelpSystemPlayer_1, Service_16, Confirm_2, DropdownBox_7, ElementRegister_3, TextField_6, UIButton_10, BuilderEvent_7) {
    "use strict";
    exports.__esModule = true;
    var changeListeners = [];
    var TemplateChooserFields = (function () {
        function TemplateChooserFields() {
        }
        return TemplateChooserFields;
    }());
    var CategoryDropdown = (function (_super) {
        __extends(CategoryDropdown, _super);
        function CategoryDropdown() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CategoryDropdown.prototype.buildInit = function (data, fields) {
            var _this = this;
            data.change = function (fields) { return _this.onChange(fields); };
            _super.prototype.buildInit.call(this, data, fields);
            this.chooser = data.chooser;
        };
        CategoryDropdown.prototype.onChange = function (fields) {
            var item = this.getSelectedItem();
            if (!item)
                return;
            var original = item.getOriginal();
            if (typeof original.customContentAppender === 'function') {
                this.chooser.loadCustomContent(original.customContentAppender);
            }
            else {
                this.chooser.loadTemplates(item.getId());
            }
            fields.categoryList.selectItem(item.getId());
        };
        CategoryDropdown.prototype.addAllItems = function (items) {
            for (var i = 0; i < items.length; i++) {
                this.addItem(new DropdownBox_7["default"].Item(items[i].name + (items[i].templateCount !== false ? ' (' + items[i].templateCount + ')' : ''), items[i].id, items[i]));
            }
        };
        return CategoryDropdown;
    }(DropdownBox_7["default"]));
    var CategoryList = (function (_super) {
        __extends(CategoryList, _super);
        function CategoryList() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.items = [];
            return _this;
        }
        CategoryList.prototype.buildInit = function (data, fields) { this.chooser = data.chooser; };
        CategoryList.prototype.removeAllItems = function () {
            this.getElem().empty();
        };
        CategoryList.prototype.addAllItems = function (items) {
            for (var i = 0; i < items.length; i++) {
                this.addItem(items[i]);
            }
        };
        CategoryList.prototype.addItem = function (item) {
            var _this = this;
            this.items.push(item);
            var thisItem = item, thisElem = this, aElem;
            item.elem = $('<div>').addClass('wb-tpl-cats-item');
            aElem = $('<a>')
                .attr({ href: 'javascript:void(0)' })
                .text(item.name)
                .on('click', function () {
                thisElem.selectItem(thisItem.id);
                if (typeof thisItem.customContentAppender === 'function') {
                    _this.chooser.loadCustomContent(thisItem.customContentAppender);
                }
                else {
                    _this.chooser.loadTemplates(thisItem.id);
                }
                _this.chooser.fields.categoryListCombo.selectItem(_this.chooser.fields.categoryListCombo.getItemById(thisItem.id));
                return false;
            });
            if (item.templateCount !== false) {
                aElem.append($('<span>').text('(' + item.templateCount + ')'));
            }
            item.elem.append(aElem).appendTo(this.getElem());
            if (item.isPrivate)
                aElem.append($('<span>').addClass('glyphicon glyphicon-lock'));
        };
        CategoryList.prototype.selectItem = function (id) {
            for (var i = 0; i < this.items.length; i++) {
                var elem = this.items[i].elem;
                if (!elem)
                    continue;
                if (id === this.items[i].id) {
                    elem.addClass('active');
                }
                else {
                    elem.removeClass('active');
                }
            }
        };
        return CategoryList;
    }(UIComponent_15.UIComponent));
    var TemplateList = (function (_super) {
        __extends(TemplateList, _super);
        function TemplateList() {
            var _this = _super.call(this) || this;
            _this.cont = $('<div>').addClass('wb-tpl-list-body').appendTo(_this.getElem());
            return _this;
        }
        TemplateList.prototype.buildInit = function (data, fields) { this.chooser = data.chooser; };
        TemplateList.prototype.removeAllItems = function () {
            this.cont.empty();
        };
        TemplateList.prototype.addAllItems = function (items) {
            for (var i = 0; i < items.length; i++) {
                this.addItem(items[i]);
            }
        };
        TemplateList.prototype.addItem = function (item) {
            var _this = this;
            var thisItem = item, img, text, selectBtn, guideBtn, upgradeUrl, itemElem = $('<div>').addClass('wb-tpl-list-item');
            if (typeof item.customContentAppender === 'function') {
                itemElem.appendTo(this.cont);
                item.customContentAppender(itemElem);
            }
            else {
                itemElem.attr({ 'aria-haspopup': 'true' })
                    .on('touchend', function () {
                    $(this).parent().children().removeClass('active');
                    $(this).toggleClass('active');
                    return false;
                });
                itemElem.append($('<div>')
                    .append($('<div>').addClass('wb-tpl-list-overlay')
                    .append($('<div>'))
                    .append($('<div class="wb-tpl-btns' + (item.available ? '' : ' wb-tpl-noavail') + '">')
                    .append((selectBtn = $('<button>').addClass('btn btn-success btn-lg')
                    .attr({ type: 'button' })
                    .append($('<span>').addClass('fa fa-pencil-square-o'))
                    .append(__('Select'))))
                    .append($('<div>').addClass('wb-line2')
                    .append($('<a>').addClass('btn btn-default btn-outline')
                    .attr({ target: '_blank', href: item.previewUrl })
                    .append($('<span>').addClass('fa fa-search'))
                    .on('touchend', function (e) { e.stopImmediatePropagation(); })
                    .append(__('Preview')))
                    .append((guideBtn = $('<button>').addClass('btn btn-default btn-outline')
                    .attr({ type: 'button', title: __('See how template was made') })
                    .append($('<span>').addClass('fa fa-play-circle-o'))
                    .on('click touchend', function () { _this.onBtnPlay(thisItem.id); return false; })
                    .append(__('Guide')))))))
                    .append($('<div/>').addClass('cimg').append(img = $('<img src=""/>').attr({ src: item.thumb })))
                    .append((text = $('<span/>').text(item.name))))
                    .appendTo(this.cont);
                img.removeAttr('width').removeAttr('height');
                if (item.isPrivate)
                    text.append($('<span>').addClass('glyphicon glyphicon-lock'));
                if (item.current) {
                    text.append($('<span>').text(__('(current template)')));
                    itemElem.addClass('current');
                }
                if (item.available) {
                    selectBtn.on('click touchend', function () { _this.onBtnSelect(thisItem.id); return false; });
                }
                else {
                    selectBtn.detach();
                    guideBtn.detach();
                    if (wb_builder.isZyro) {
                        upgradeUrl = 'http://cpanel.zyro.com/accounts/upgrade';
                    }
                    else {
                        upgradeUrl = (wb_builder.upgradeUrl ? wb_builder.upgradeUrl : null);
                    }
                    var premHTML = (wb_builder.premiumButtonType === 'expired')
                        ? '<div><span class="exp">' + __('Ask administrator to enable this feature') + '</span></div>'
                        : '<div>' + __('Available in %sPremium version%s')
                            .replace('%s', '<span class="glyphicon glyphicon-star"></span><span class="txt">' +
                            (upgradeUrl ? ('<a href="' + upgradeUrl + '" target="_blank">') : '<a href="javascript:void(0)">')).replace('%s', '</a>') + '</span></div>';
                    itemElem.find('.wb-tpl-list-overlay').show();
                    itemElem.children('div').prepend($('<div>').addClass('wb-tpl-list-onlypro').html(premHTML));
                }
            }
        };
        TemplateList.prototype.onBtnSelect = function (id) {
            service.applyTemplateWithDialog(id, null, null, this.chooser, this.chooser.fields.loader);
        };
        TemplateList.prototype.onBtnPlay = function (id) {
            service.applyTemplateWithDialog(id, function () {
                HelpSystemPlayer_1["default"].loadRemote('.', true);
            }, null, this.chooser, this.chooser.fields.loader);
        };
        return TemplateList;
    }(UIComponent_15.UIComponent));
    var TemplateChooser = (function (_super) {
        __extends(TemplateChooser, _super);
        function TemplateChooser() {
            var _this = _super.call(this, __('Select template'), true, null, true) || this;
            _this.contentLoaded = false;
            _this.templates = [];
            _this.categories = [];
            _this.onResizeCalback = null;
            _this.fields = new TemplateChooserFields();
            _this.setContent(new Service_16["default"].UIBuilder([
                { type: PreloaderOverlay_3.PreloaderOverlay, id: 'loader', value: 100, visible: false },
                { type: 'HorizontalLayout',
                    columnWeights: [2, 10],
                    columnWeightsSmall: [3, 9],
                    debug: true,
                    children: [
                        { type: 'VerticalLayout', rowStyleClass: ['visible-xs-block'], children: [
                                { type: CategoryDropdown, id: 'categoryListCombo', css: { margin: '15px 15px 0 15px' }, chooser: _this },
                                { type: CategoryList, id: 'categoryList', styleClass: 'wb-tpl-cats hidden-xs', css: { height: 300 }, chooser: _this }
                            ] },
                        { type: 'VerticalLayout', children: [
                                { type: TemplateList, id: 'list', styleClass: 'wb-tpl-list', css: { height: 300 }, chooser: _this },
                                { type: 'CustomContainer', id: 'content' }
                            ] }
                    ]
                }
            ], _this.fields), true);
            _this.closeButton = _this.addButton(__('Close'));
            _this.baseElem.addClass('wb-tpl-dialog');
            var logo = $('<div>').addClass('wb-tpl-logo');
            if (wb_builder.whiteLabel.logo)
                logo.css({ backgroundImage: "url('" + wb_builder.baseUrl + "builder-logo')" });
            _this.title.before(logo);
            return _this;
        }
        TemplateChooser.prototype.getDefaultCategoryId = function (fields, categories) {
            var itemId = null, params = {}, parts, i, s;
            if ((s = window.location.search.split('?')) && s.length === 2 && (s = s[1].split('&'))) {
                for (i = 0; i < s.length; i++) {
                    parts = s[i].split('=');
                    if (parts.length === 2)
                        params[parts[0]] = decodeURIComponent(parts[1]);
                }
            }
            if (fields && fields.categoryList && params.tpl && fields.categoryListCombo.getItemById(params.tpl)) {
                itemId = params.tpl;
            }
            if (!itemId) {
                itemId = (categories.length > 0) ? categories[0].id : null;
            }
            return itemId;
        };
        TemplateChooser.prototype.reloadContents = function () {
            var _this = this;
            this.fields.loader.setVisible(true);
            var params = {};
            if (!ElementRegister_3["default"].isClassEnabled('Store'))
                params.exclude = 'E-commerce';
            $.getJSON(service.getApiUrl('template/categories', params)).done(function (data) {
                if (!wb_builder.hideImport)
                    data.push(_this.createImportCategoryData());
                _this.fields.loader.setVisible(false);
                if (typeof data === 'object') {
                    _this.categories = data;
                    _this.fields.categoryList.removeAllItems();
                    _this.fields.categoryListCombo.removeAllItems();
                    _this.fields.categoryList.addAllItems(_this.categories);
                    _this.fields.categoryListCombo.addAllItems(_this.categories);
                    if (_this.categories.length > 0) {
                        var itemId = _this.getDefaultCategoryId(_this.fields, _this.categories);
                        _this.fields.categoryList.selectItem(itemId);
                        _this.fields.categoryListCombo.selectItem(itemId ? _this.fields.categoryListCombo.getItemById(itemId) : null);
                        _this.loadTemplates(itemId);
                    }
                }
                else {
                    console.error('Template category loading format error');
                }
            }).fail(function () {
                _this.fields.loader.setVisible(false);
                console.error('Template category loading error');
            });
        };
        TemplateChooser.prototype.createImportCategoryData = function () {
            var _this = this;
            return {
                id: '__import__',
                name: __('Website import'),
                templateCount: false,
                isPrivate: false,
                customContentAppender: function (elem) {
                    _this.appendImportForm(elem, true);
                }
            };
        };
        TemplateChooser.prototype.createImportTemplateData = function () {
            var _this = this;
            return {
                id: '__import__',
                name: '',
                categoryId: '',
                thumb: '',
                previewUrl: '',
                isPrivate: false,
                current: false,
                available: true,
                customContentAppender: function (elem) {
                    _this.appendImportForm(elem, false);
                }
            };
        };
        TemplateChooser.prototype.appendImportForm = function (elem, big) {
            var _this = this;
            if (big === void 0) { big = false; }
            var input = new TextField_6["default"]('', 'www.');
            var button = new UIButton_10.UIButton(__('Import'), UIButton_10.UIButton.STYLE_SUCCESS);
            button.addClass('btn-lg');
            if (wb_builder.enableImport) {
                button.on('click', function () {
                    var url = input.getValue();
                    if (!url)
                        return;
                    if (!/^https?:\/\//.test(url))
                        url = 'http://' + url;
                    if (Service_16["default"].websiteImporter.checkUrl(url)) {
                        _this.setVisible(false);
                    }
                    Service_16["default"].websiteImporter.importWebsite({ url: url }, 1, true);
                });
            }
            else {
                button.getElem().attr('disabled', 'disabled');
            }
            input.getElem().on('keydown', function (e) {
                var key = e.which || e.keyCode;
                if (key === 13) {
                    button.trigger('click');
                }
            });
            var cont = $('<div>').addClass('wb-tpl-list-import');
            var innerCont = $('<div>')
                .append($('<p>').text(__('Import Any Website')))
                .append(input.getElem())
                .append(button.getElem());
            if (big && !wb_builder.enableImport) {
                innerCont.append($('<div>').text(__('Ask administrator to enable this feature')));
            }
            cont.append(innerCont);
            elem.append(cont);
            if (big) {
                input.getElem().addClass('input-lg');
                cont.addClass('big');
                $(window).on('resize', function () {
                    $('.wb-tpl-list-import.big').css('height', elem.parents('.modal-body').outerHeight() + 'px');
                });
                $(window).trigger('resize');
                setTimeout(function () { return $(window).trigger('resize'); }, 100);
            }
            else {
                cont.on('mouseenter', function () { input.getElem().trigger('focus'); });
                cont.on('mouseleave', function () { input.getElem().trigger('blur'); });
                elem.append($('<div>').append(cont));
                $(window).on('resize', function () {
                    cont.css('height', (Math.min(cont.width(), 484) / 484 * 330) + 'px');
                    if (cont.width() * cont.height() < 65100) {
                        cont.addClass('smaller');
                        cont.find('.btn').removeClass('btn-lg');
                    }
                    else {
                        cont.removeClass('smaller');
                        cont.find('.btn').addClass('btn-lg');
                    }
                });
                $(window).trigger('resize');
                setTimeout(function () { return $(window).trigger('resize'); }, 100);
            }
        };
        TemplateChooser.prototype.loadTemplates = function (categoryId) {
            var _this = this;
            this.fields.loader.setVisible(true);
            $.getJSON(service.getApiUrl('template/list/' + categoryId + '?qty=' + (wb_builder.enableImport ? 5 : 6))).done(function (data) {
                _this.fields.loader.setVisible(false);
                if (typeof data === 'object') {
                    if (wb_builder.enableImport && !wb_builder.hideImport && categoryId === 'rnd') {
                        data.unshift(_this.createImportTemplateData());
                    }
                    _this.templates = data;
                    _this.fields.content.getElem().hide();
                    _this.fields.list.getElem().show();
                    _this.fields.list.removeAllItems();
                    _this.fields.list.addAllItems(_this.templates);
                }
                else {
                    console.error('Template loading format error');
                }
            }).fail(function () {
                _this.fields.loader.setVisible(false);
                console.error('Template loading error');
            });
        };
        TemplateChooser.prototype.loadCustomContent = function (contentAppender) {
            this.fields.content.getElem().empty();
            this.fields.content.getElem().show();
            this.fields.list.getElem().hide();
            contentAppender(this.fields.content.getElem());
        };
        TemplateChooser.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            var _this = this;
            var ea = new BuilderEvent_7.VisibilityChangedBuilderEvent(visible);
            BuilderEvent_7.GlobalEvents.triggerEvent(visible ? "templates.show" : "templates.hide", ea);
            if (!ea.defaultPrevented) {
                _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
                if (visible) {
                    this.fields.loader.setVisible(false);
                    if (parseInt('' + wb_builder.pageId, 10) <= 0) {
                        this.closeButton.hide();
                        this.xButton.hide();
                    }
                    else {
                        this.closeButton.show();
                        this.xButton.show();
                    }
                    if (!this.contentLoaded) {
                        this.contentLoaded = true;
                        this.reloadContents();
                    }
                    if (!this.onResizeCalback) {
                        this.onResizeCalback = function () {
                            _this.setMaximised(true);
                            var h = _this.content.css({
                                padding: 0,
                                overflowX: 'hidden',
                                overflowY: 'auto'
                            }).height();
                            _this.fields.categoryList.css({ height: h });
                            _this.fields.list.css({ height: h });
                        };
                    }
                    this.setMaximised(true);
                    setTimeout(function () { if (_this.onResizeCalback)
                        _this.onResizeCalback(); }, 500);
                    $(window).on('resize', this.onResizeCalback);
                }
                else {
                    if (this.onResizeCalback)
                        $(window).off('resize', this.onResizeCalback);
                }
            }
        };
        return TemplateChooser;
    }(Dialog_6["default"]));
    exports["default"] = TemplateChooser;
    var TemplateChooserService = (function () {
        function TemplateChooserService() {
        }
        TemplateChooserService.prototype.getTemplates = function (categoryId) {
            if (categoryId === void 0) { categoryId = null; }
            if (!categoryId)
                categoryId = 'all';
            return $.getJSON(this.getApiUrl('template/list/' + categoryId));
        };
        TemplateChooserService.prototype.getApiUrl = function (action, params) {
            var paramsStr = [];
            if (params)
                for (var name_2 in params) {
                    if (!name_2 || params[name_2] === null)
                        continue;
                    paramsStr.push(name_2 + '=' + encodeURIComponent(params[name_2]));
                }
            return wb_builder.baseUrl + (wb_builder.locale ? (wb_builder.locale.replace('_', '-') + '/') : '')
                + action + ((paramsStr.length > 0) ? ('?' + paramsStr.join('&')) : '');
        };
        TemplateChooserService.prototype.applyTemplate = function (templateId, callback, caller, loader) {
            if (callback === void 0) { callback = null; }
            if (caller === void 0) { caller = null; }
            if (loader === void 0) { loader = null; }
            var thisCallback = callback;
            if (loader)
                loader.setVisible(true);
            $.getJSON(this.getApiUrl('template/select/' + templateId)).done(function (data) {
                if (loader)
                    loader.setVisible(false);
                if (typeof data === 'object') {
                    if (data.ok) {
                        wb_builder.pageId = data.pageId;
                        wb_builder.template = data.template;
                        wb_builder.meta = data.meta;
                        wb_builder.oriSiteWidth = data.oriSiteWidth;
                        Service_16["default"].Store.Module.load(null, true);
                        Service_16["default"].Store.Module.needToTranslateItems = (data.template.categoryId === 'E-commerce');
                        if (caller)
                            caller.setVisible(false);
                        setTimeout(function () {
                            wb_builder.loadPage(data.pageId, true, function () {
                                if (thisCallback && (typeof thisCallback === 'function'))
                                    thisCallback.call(caller);
                            });
                        }, 500);
                        for (var i = 0; i < changeListeners.length; i++) {
                            changeListeners[i].call(caller);
                        }
                    }
                    else {
                        console.error('Template apply failed');
                    }
                }
                else {
                    console.error('Template apply format error');
                }
            }).fail(function () {
                if (loader)
                    loader.setVisible(false);
                console.error('Template apply error');
            });
        };
        TemplateChooserService.prototype.applyTemplateWithDialog = function (templateId, callback, closeFunc, caller, loader) {
            var _this = this;
            if (callback === void 0) { callback = null; }
            if (closeFunc === void 0) { closeFunc = null; }
            if (caller === void 0) { caller = null; }
            if (loader === void 0) { loader = null; }
            var thisCallback = callback;
            if (parseInt('' + wb_builder.pageId, 10) > 0) {
                Confirm_2["default"].showDialog(__('Change template'), $('<div class="wb_change_template_dlg">' +
                    '<div class="qq">' + __('Are you sure you want to change current template?') + '</div>' +
                    '<div class="red">' + __('Once changed your information will be lost.') + '</div>' +
                    '</div>'), [
                    {
                        title: __('No, keep current template'),
                        func: function () {
                            if (typeof closeFunc === 'function')
                                closeFunc.call(_this);
                        }
                    },
                    {
                        title: __('Yes, change template'),
                        cssClass: 'btn-danger',
                        func: function () {
                            _this.applyTemplate(templateId, thisCallback, caller, loader);
                        }
                    }
                ], 480);
                if (Confirm_2["default"].dialog)
                    Confirm_2["default"].dialog.setCenterButtons(true);
            }
            else {
                this.applyTemplate(templateId, thisCallback, caller, loader);
            }
        };
        TemplateChooserService.prototype.addChangeListener = function (func) {
            if (typeof func === 'function')
                changeListeners.push(func);
        };
        TemplateChooserService.prototype.removeChangeListener = function (func) {
            var idx = (typeof func === 'function') ? changeListeners.indexOf(func) : -1;
            if (idx >= 0)
                changeListeners.splice(idx, 1);
        };
        return TemplateChooserService;
    }());
    exports.TemplateChooserService = TemplateChooserService;
    var service = new TemplateChooserService();
    Service_16["default"].templates = service;
});
define("HelpSystem/Types", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
});
define("HelpSystem/HelpOverlayTemplatesPanel", ["require", "exports", "Service", "UIComponent", "UIContainer"], function (require, exports, Service_17, UIComponent_16, UIContainer_11) {
    "use strict";
    exports.__esModule = true;
    var HelpOverlayTemplatesPanel = (function (_super) {
        __extends(HelpOverlayTemplatesPanel, _super);
        function HelpOverlayTemplatesPanel(helpOverlay) {
            var _this = _super.call(this) || this;
            _this.helpOverlay = helpOverlay;
            _this.itemCount = 0;
            _this.itemOffset = 0;
            _this.itemShowCount = 6;
            _this.leftBtn = new ArrowButton('wb-hlp-tpl-list-left', 'fa fa-chevron-left', function () { _this.slide(-1); });
            _this.rightBtn = new ArrowButton('wb-hlp-tpl-list-right', 'fa fa-chevron-right', function () { _this.slide(1); });
            _this.itemsWrap = (new UIContainer_11.UIContainer()).addClass('wb-hlp-tpl-list-wrap');
            _this.itemsElem = (new UIContainer_11.UIContainer())
                .addClass('wb-hlp-tpl-list-items')
                .addChild(_this.itemsWrap);
            _this._elem.addClass('wb-hlp-tpl-list')
                .append(_this.leftBtn.getElem())
                .append(_this.rightBtn.getElem())
                .append(_this.itemsElem.getElem());
            return _this;
        }
        HelpOverlayTemplatesPanel.prototype.slide = function (dir) {
            if (dir === void 0) { dir = 0; }
            this.itemOffset -= dir;
            if (this.itemOffset < (this.itemShowCount - this.itemCount)) {
                this.itemOffset = this.itemShowCount - this.itemCount;
            }
            if (this.itemOffset > 0)
                this.itemOffset = 0;
            this.itemsWrap.css({ left: (this.itemOffset * 160) + 'px' });
            this.rightBtn.setVisible((this.itemOffset > (this.itemShowCount - this.itemCount)));
            this.leftBtn.setVisible((this.itemOffset < 0));
        };
        HelpOverlayTemplatesPanel.prototype.clear = function () {
            this.itemsWrap.removeAllChildren();
            this.itemCount = 0;
            this.itemOffset = 0;
            this.slide(0);
        };
        HelpOverlayTemplatesPanel.prototype.addTemplate = function (tpl) {
            this.itemsWrap.addChild(new TemplateItem(tpl, this.helpOverlay));
            this.itemCount++;
        };
        HelpOverlayTemplatesPanel.prototype.reload = function (showThisTpl) {
            var _this = this;
            if (showThisTpl === void 0) { showThisTpl = true; }
            this.clear();
            this.addTemplate({
                scenarioId: 'introduction',
                icon: 'fa fa-rocket',
                name: __('Basic Tutorial'),
                duration: '~1 ' + __('min')
            });
            if (showThisTpl)
                this.addTemplate({
                    scenarioId: '.',
                    icon: 'fa fa-cogs',
                    name: __('See how template was made'),
                    duration: '~5 ' + __('min')
                });
            Service_17["default"].templates.getTemplates().done(function (data) {
                if (data)
                    for (var _i = 0, data_3 = data; _i < data_3.length; _i++) {
                        var tpl = data_3[_i];
                        if (tpl.isPrivate)
                            continue;
                        tpl.duration = '~5 ' + __('min');
                        _this.addTemplate(tpl);
                    }
                _this.slide(0);
            })
                .fail(function () { _this.setVisible(false); });
        };
        return HelpOverlayTemplatesPanel;
    }(UIComponent_16.UIComponent));
    exports.HelpOverlayTemplatesPanel = HelpOverlayTemplatesPanel;
    var TemplateItem = (function (_super) {
        __extends(TemplateItem, _super);
        function TemplateItem(tpl, helpOverlay) {
            var _this = _super.call(this) || this;
            var iconCont = $('<div>').addClass('wb-hlp-tpl-list-item-icon');
            if (tpl.icon) {
                iconCont.append($('<span>').addClass(tpl.icon));
            }
            else {
                iconCont
                    .append($('<span>').addClass('fa fa-play-circle-o wb-hlp-tpl-list-item-play'))
                    .append($('<img>').attr({ src: tpl.thumb, alt: tpl.name }));
            }
            var nameElem = $('<span>').addClass('wb-hlp-tpl-list-item-name').text(tpl.name);
            if (tpl.duration)
                nameElem
                    .append($('<span>').addClass('wb-hlp-tpl-list-item-durr').text('(' + tpl.duration + ')'));
            _this._elem.addClass('wb-hlp-tpl-list-item')
                .append(iconCont)
                .append(nameElem);
            _this.on('click', function () { helpOverlay.runScenario(tpl); });
            return _this;
        }
        return TemplateItem;
    }(UIComponent_16.UIComponent));
    var ArrowButton = (function (_super) {
        __extends(ArrowButton, _super);
        function ArrowButton(cls, icon, click) {
            var _this = _super.call(this, 'span') || this;
            _this._elem.addClass(cls)
                .append($('<span>').addClass(icon));
            _this.on('click touchstart', click);
            return _this;
        }
        return ArrowButton;
    }(UIComponent_16.UIComponent));
});
define("DefaultUI/PluginToolbar", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    function constructPluginToolbar(builder, collapseCallback, def) {
        if (def === void 0) { def = null; }
        var widgets = [];
        if (!def || typeof def !== 'object') {
            def = {
                type: 'widget',
                click: function () {
                    if (!this.id)
                        return;
                    var cx = $(window).width() / 2, cy = $(window).height() / 2;
                    builder.addElementAt(this.id, cx, cy);
                    return false;
                }
            };
        }
        var plugins = builder.getElementPlugins(), first = true;
        var extIcon;
        for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
            var plugin = plugins_1[_i];
            if (first) {
                first = false;
            }
            else {
                widgets.push({ type: '-' });
            }
            var group = {
                type: 'group',
                collapsable: (!('collapsable' in plugin.group) || (plugin.group.collapsable ? true : false)),
                collapseCallback: collapseCallback,
                icon: (((typeof def.icon === 'function') && (extIcon = def.icon(plugin.group.id))) ? extIcon : plugin.group.icon),
                name: plugin.group.name,
                items: []
            };
            if ('id' in plugin.group)
                group.id = plugin.group.id;
            if ('borderless' in plugin.group)
                group.borderless = (plugin.group.borderless ? true : false);
            for (var _a = 0, _b = plugin.items; _a < _b.length; _a++) {
                var itemDef = _b[_a];
                extIcon = ((typeof def.icon === 'function') && (extIcon = def.icon(itemDef.id))) ? extIcon : null;
                var item = {
                    type: def.type,
                    id: itemDef.id,
                    icon: (extIcon ? extIcon : itemDef.icon),
                    iconImage: ((itemDef.iconImage && !extIcon) ? true : false),
                    name: itemDef.name,
                    active: ((typeof def.isActive === 'function')
                        ? def.isActive(itemDef)
                        : ((typeof itemDef.active === 'function') ? itemDef.active : (itemDef.active ? true : false))),
                    click: def.click
                };
                if ('borderless' in itemDef)
                    item.borderless = (itemDef.borderless ? true : false);
                group.items.push(item);
            }
            widgets.push(group);
        }
        return widgets;
    }
    exports.constructPluginToolbar = constructPluginToolbar;
});
define("HelpSystem/HelpOverlay", ["require", "exports", "Service", "UserInput", "Dialog", "WidgetToolbar", "HelpSystem/AnimTween", "HelpSystem/HelpOverlayTemplatesPanel", "UIComponent", "ElementBox", "BuilderEvent", "DefaultUI/PluginToolbar"], function (require, exports, Service_18, UserInput_2, Dialog_7, WidgetToolbar_1, AnimTween_2, HelpOverlayTemplatesPanel_1, UIComponent_17, ElementBox_1, BuilderEvent_8, PluginToolbar_1) {
    "use strict";
    exports.__esModule = true;
    var helpDlg, helpOverlay, availableScenarioIdx = {};
    var helpUrl = null;
    var builder = null;
    var HelpOverlaySection = (function () {
        function HelpOverlaySection(boundsFunc, element, isFixed, isGroup, isEnabled) {
            var _a;
            if (isFixed === void 0) { isFixed = false; }
            if (isGroup === void 0) { isGroup = false; }
            if (isEnabled === void 0) { isEnabled = true; }
            this.boundsFunc = boundsFunc;
            this.element = element;
            this.isFixed = isFixed;
            this.isGroup = isGroup;
            this.isEnabled = isEnabled;
            this.isGroupOpen = false;
            this.groupItems = [];
            this.bounds = this.boundsFunc(this.element);
            if ('getClassType' in this.element) {
                this.scenarioId = this.element.getClassType();
            }
            else {
                _a = this.element.getId().split('__'), this.scenarioId = _a[1];
            }
        }
        HelpOverlaySection.prototype.toggleGroup = function () {
            if (!this.isGroup)
                return;
            this.isGroupOpen = !this.isGroupOpen;
            this.element.setOpen(this.isGroupOpen);
            for (var _i = 0, _a = this.groupItems; _i < _a.length; _i++) {
                var itm = _a[_i];
                itm.isEnabled = this.isGroupOpen;
                if (itm.isEnabled)
                    itm.bounds = itm.boundsFunc(itm.element);
            }
        };
        HelpOverlaySection.prototype.addGroupItem = function (item) {
            if (!this.isGroup)
                return;
            this.groupItems.push(item);
        };
        HelpOverlaySection.prototype.hitTest = function (x, y, sx, sy) {
            if (!this.isEnabled)
                return false;
            var dx = (this.isFixed ? sx : x);
            var dy = (this.isFixed ? sy : y);
            return (dx >= this.bounds.left && dx <= (this.bounds.left + this.bounds.width)
                && dy >= this.bounds.top && dy <= (this.bounds.top + this.bounds.height));
        };
        return HelpOverlaySection;
    }());
    var HelpOverlay = (function (_super) {
        __extends(HelpOverlay, _super);
        function HelpOverlay(builder) {
            var _this = _super.call(this) || this;
            _this.builder = builder;
            _this.isClosable = true;
            _this.isVisible = false;
            _this.sections = [];
            _this.selectedSection = null;
            _this.widgetToolbar = null;
            _this._elem.addClass('wb-hlp-overlay')
                .append(_this.buildInfoFeature()
                .append((_this.tplBlock = new HelpOverlayTemplatesPanel_1.HelpOverlayTemplatesPanel(_this)).setVisible(false).getElem()))
                .on('mousemove', function (e) { return _this.onMouseMove(e); });
            _this.marker = $('<div>').addClass('wb-hlp-overlay-marker')
                .on('click', function () { return _this.onSectionClick(); });
            _this._elem.append(_this.marker);
            _this.closeBtn = $('<div>').addClass('wb-hlp-overlay-close')
                .html('&times;')
                .on('click', function () { return closeHelpOverlay(); });
            _this._elem.append(_this.closeBtn);
            $(document.body).append(_this._elem);
            return _this;
        }
        HelpOverlay.prototype.setClosable = function (closable) {
            this.isClosable = closable;
            if (closable) {
                this.closeBtn.show();
            }
            else {
                this.closeBtn.hide();
            }
        };
        HelpOverlay.prototype.buildInfoFeature = function () {
            var elem = $('<div>').addClass('wb-hlp-overlay-info');
            var wrp = $('<div>').addClass('wb-info-wrp').appendTo(elem);
            wrp.html('<br/>' + __("Click on element to start interactive help or press 'ESC' to close.") + '<br/>');
            $('<img>').addClass('wb-arrow-a').attr({ src: 'modules/builder/img/arrow.svg', alt: '' })
                .prependTo(wrp);
            $('<img>').addClass('wb-arrow-b').attr({ src: 'modules/builder/img/arrow.svg', alt: '' })
                .appendTo(wrp);
            return elem;
        };
        HelpOverlay.prototype.buildBigLink = function (elem, name, icon, scenarioId) {
            var _this = this;
            return $('<div>')
                .css({ fontSize: '24px', marginTop: '30px', cursor: 'pointer' })
                .append($('<span>').addClass(icon).css({
                display: 'inline-block',
                verticalAlign: 'middle',
                marginRight: '10px',
                fontSize: '1.5em'
            }))
                .append($('<span>').css({
                display: 'inline-block',
                verticalAlign: 'middle',
                textDecoration: 'underline'
            }).text(name))
                .on('click', function () {
                setTimeout(function () { _this.setVisible(false, true); }, 100);
                Service_18["default"].HelpSystemPlayer.loadRemote(scenarioId, false, function () {
                    _this.setVisible(true);
                });
            })
                .appendTo(elem);
        };
        HelpOverlay.prototype.onSectionClick = function () {
            var _this = this;
            if (!this.selectedSection)
                return;
            if (this.selectedSection.isGroup) {
                for (var _i = 0, _a = this.sections; _i < _a.length; _i++) {
                    var sec = _a[_i];
                    if (sec === this.selectedSection)
                        continue;
                    if (sec.isGroup && sec.isGroupOpen)
                        sec.toggleGroup();
                }
                this.selectedSection.toggleGroup();
            }
            else {
                var scenarioId = this.selectedSection.scenarioId;
                setTimeout(function () { _this.setVisible(false, true); }, 100);
                Service_18["default"].HelpSystemPlayer.loadRemote(scenarioId, false, function () {
                    _this.setVisible(true);
                });
            }
        };
        HelpOverlay.prototype.onMouseMove = function (e) {
            if (!this.isVisible)
                return;
            var found = false;
            for (var _i = 0, _a = this.sections; _i < _a.length; _i++) {
                var sec = _a[_i];
                if (!sec.hitTest(e.pageX, e.pageY, e.originalEvent.clientX, e.originalEvent.clientY))
                    continue;
                this.selectedSection = sec;
                this.marker.css({
                    display: 'block',
                    left: sec.bounds.left,
                    top: sec.bounds.top,
                    width: sec.bounds.width,
                    height: sec.bounds.height,
                    position: (sec.isFixed ? 'fixed' : 'absolute')
                });
                found = true;
                break;
            }
            if (!found)
                this.marker.css({ display: 'none' });
        };
        HelpOverlay.prototype.indexSections = function (builder) {
            if (this.widgetToolbar) {
                this.widgetToolbar.elem.parent().remove();
                this.widgetToolbar = null;
            }
            var self = this, uiManager = Service_18["default"].uiManager.getManager();
            this.widgetToolbar = Object.create(WidgetToolbar_1["default"]).init(PluginToolbar_1.constructPluginToolbar(Service_18["default"].uiManager.getApiInstance(), function () { }, {
                type: 'item',
                isActive: function (itemDef) { return (itemDef.id && (itemDef.id in availableScenarioIdx)) ? true : false; },
                click: function () {
                    if (!this.id || !this.enabled)
                        return;
                    setTimeout(function () { self.setVisible(false, true); }, 100);
                    Service_18["default"].HelpSystemPlayer.loadRemote(this.id, false, function () {
                        self.setVisible(true);
                    });
                },
                icon: function (id) { return uiManager.lookupUIIconClass('plugin', id); }
            }), 'wb-help-overlay-widgets', true);
            if (this.widgetToolbar) {
                $('<div>').addClass('wb-help-overlay-widgets-wrp')
                    .append($('<div>').append(this.widgetToolbar.elem))
                    .css({ top: 74, height: 60 })
                    .appendTo(this._elem);
            }
            this.sections = [];
        };
        HelpOverlay.prototype.setHeight = function (height) {
            this._elem.css({ height: height });
        };
        HelpOverlay.prototype.setTemplatesVisible = function (visible, showThisTpl) {
            if (showThisTpl === void 0) { showThisTpl = true; }
            if (!visible) {
                this.tplBlock.setVisible(false);
                return;
            }
            this.tplBlock.reload(showThisTpl);
            this.tplBlock.setVisible(true);
        };
        HelpOverlay.prototype.setVisible = function (visible, fadeOut) {
            var _this = this;
            if (fadeOut === void 0) { fadeOut = false; }
            if (this.isVisible === visible)
                return this;
            this.isVisible = visible;
            this.marker.css({ display: 'none' });
            if (fadeOut && !visible) {
                var step_1, opacity_1 = 1;
                new AnimTween_2.AnimTween(600, 24, function () { opacity_1 -= step_1; _this._elem.css({ opacity: opacity_1 }); }, function (tween) { step_1 = 1.0 / tween.numKeyframes; }, function (tween) { _this._elem.css({ display: 'none' }); tween.dispose(); }).start();
            }
            else {
                this._elem.css({ display: (visible ? 'block' : 'none'), opacity: 1 });
            }
            if (visible && this.widgetToolbar)
                this.widgetToolbar.ajustSize();
            var ea = new BuilderEvent_8.VisibilityChangedBuilderEvent(visible);
            BuilderEvent_8.GlobalEvents.triggerEvent(visible ? "help.show" : "help.hide", ea);
            return this;
        };
        HelpOverlay.prototype.runScenario = function (tpl) {
            var _this = this;
            if (tpl.id) {
                if (this.builder.testMode && !this.isClosable) {
                    Service_18["default"].templates.applyTemplate(tpl.id, function () {
                        Service_18["default"].HelpSystemPlayer.loadRemote('.', true, function () {
                            _this.setVisible(true);
                        });
                    }, this);
                }
                else {
                    this.setVisible(false);
                    Service_18["default"].templates.applyTemplateWithDialog(tpl.id, function () {
                        Service_18["default"].HelpSystemPlayer.loadRemote('.', true, function () {
                            _this.setVisible(true);
                        });
                    }, function () {
                        _this.setVisible(true);
                    }, this);
                }
            }
            else if (tpl.scenarioId) {
                setTimeout(function () { _this.setVisible(false, true); }, 100);
                Service_18["default"].HelpSystemPlayer.loadRemote(tpl.scenarioId, false, function () {
                    _this.setVisible(true);
                });
            }
        };
        return HelpOverlay;
    }(UIComponent_17.UIComponent));
    exports.HelpOverlay = HelpOverlay;
    function openHelpOverlay(builder, closable) {
        if (closable === void 0) { closable = true; }
        if (!helpOverlay) {
            helpOverlay = new HelpOverlay(builder);
            UserInput_2.UserInput.addHotKey('Esc', function () { return closeHelpOverlay(); });
        }
        helpOverlay.indexSections(builder);
        helpOverlay.setClosable(closable);
        helpOverlay.setTemplatesVisible(true, closable);
        helpOverlay.setVisible(true);
    }
    function closeHelpOverlay() {
        helpOverlay.setVisible(false);
    }
    function openHelpDialog(customUrl, builder) {
        if (!helpDlg) {
            helpDlg = new Dialog_7["default"](__('Help'));
            helpDlg.dialog.addClass('wb-help-dialog');
            helpDlg.setSize(1024, null);
            helpDlg.setNoScroll();
            var iframe = $('<iframe>').css({ border: 'none', width: '100%', height: 400 });
            iframe.attr('frameborder', 0);
            if (customUrl) {
                iframe.attr('src', customUrl);
            }
            else {
                iframe.attr('src', '//site.pro/help/?bare=1&lang=' + builder.locale);
            }
            helpDlg.setContent(iframe);
            helpDlg.setAutoResize(true, function (bh) { return iframe.height(bh - 15); });
            if (!customUrl) {
                helpDlg.addButton(__('Download video tour'), function () {
                    location.href = builder.baseUrl + 'help-video/';
                }, false, 'btn-success').css({ float: (builder.rtl ? 'right' : 'left') });
            }
            helpDlg.addButton(__('Close'));
        }
        helpDlg.setVisible(true);
    }
    function openHelp(closable) {
        if (closable === void 0) { closable = true; }
        if (!builder || !isHelpAvailable())
            return;
        if (helpUrl && typeof helpUrl === 'string') {
            openHelpDialog(helpUrl, builder);
        }
        else {
            openHelpOverlay(builder, closable);
        }
    }
    exports.openHelp = openHelp;
    function handleUrlHashChange(preLoad) {
        if (preLoad === void 0) { preLoad = false; }
        if (!location.hash || !location.hash.match(/^#helpOverlay$/))
            return false;
        ElementBox_1["default"].setVisible(false);
        if (!preLoad)
            openHelp(false);
        return true;
    }
    function isHelpAvailable() {
        return (helpUrl !== false);
    }
    exports.isHelpAvailable = isHelpAvailable;
    function init(builderInst) {
        builder = builderInst;
        helpUrl = __trr(builder.helpUrl);
        if (!isHelpAvailable())
            return;
        $.getJSON(builder.baseUrl + 'scenario/list').then(function (res) { for (var _i = 0, res_1 = res; _i < res_1.length; _i++) {
            var id = res_1[_i];
            availableScenarioIdx[id] = true;
        } }, function () { return console.log('Error loading scenario list.'); });
        window.addEventListener('hashchange', function () { handleUrlHashChange(); }, false);
        handleUrlHashChange(true);
    }
    exports.init = init;
    function handlePageLoad() {
        if (!handleUrlHashChange()) {
        }
    }
    exports.handlePageLoad = handlePageLoad;
});
define("admin/Templates", ["require", "exports", "Dialog", "Service", "CustomContainer", "MsgDialog", "TextField", "DropdownBox", "Label", "VerticalLayout"], function (require, exports, Dialog_8, Service_19, CustomContainer_1, MsgDialog_2, TextField_7, DropdownBox_8, Label_8, VerticalLayout_13) {
    "use strict";
    exports.__esModule = true;
    var dialog, msgDialog;
    function saveAsTemplate() {
        var fields;
        if (!dialog) {
            dialog = new Dialog_8["default"](__('Save template'));
            dialog.setSize(300);
            dialog.setNoScroll();
            dialog.setContent(new Service_19["default"].UIBuilder({
                type: VerticalLayout_13.VerticalLayout,
                children: [
                    { type: Label_8.Label, text: __('Name') },
                    { type: TextField_7["default"], id: 'fldName' },
                    { type: Label_8.Label, text: __('Category'), css: { marginTop: 15 } },
                    { type: DropdownBox_8["default"], id: 'fldCategory' },
                    { type: Label_8.Label, text: __('Screenshot'), css: { marginTop: 15 } },
                    { type: 'ImageSelector', id: 'image' },
                    { type: 'CheckBox', id: 'fldSaveAs', label: __('Overwrite existing template') },
                    { type: 'CheckBox', id: 'fldIsPrivate', label: __('Make private') },
                    { type: 'CheckBox', id: 'fldNonTranslatable', label: __('Do not translate') },
                    { type: CustomContainer_1.CustomContainer, styleClass: 'alert alert-warning',
                        css: { marginTop: 15, marginBottom: 0 },
                        init: function () {
                            this.getElem()
                                .append('<span class="glyphicon glyphicon-exclamation-sign"></span>')
                                .append('&nbsp;' + __('Unused files will not be saved'));
                        }
                    }
                ]
            }, dialog.fields), true);
            fields = dialog.fields;
            dialog.addButton(__('Cancel'));
            dialog.addButton(__('Save'), function () {
                dialog.hide();
                $.post(wb_builder.baseUrl + 'tplsave/', {
                    name: fields.fldName.getValue(),
                    category: fields.fldCategory.getValue(),
                    image: fields.image.getValue(),
                    overwrite: (fields.fldSaveAs.getValue() ? 1 : 0),
                    isPrivate: (fields.fldIsPrivate.getValue() ? 1 : 0),
                    nonTranslatable: (fields.fldNonTranslatable.getValue() ? 1 : 0)
                }).done(function (data) {
                    if (!msgDialog) {
                        msgDialog = new MsgDialog_2["default"](__('Save template'));
                    }
                    if (data.complete) {
                        msgDialog.setMessage(__('Template saved successfully'), null, 'success');
                    }
                    else {
                        msgDialog.setMessage(data.error ? data.error : 'Unknown Error', __('Error'), 'error');
                    }
                    msgDialog.show();
                }).fail(function () {
                    if (!msgDialog) {
                        msgDialog = new MsgDialog_2["default"](__('Save template'));
                    }
                    msgDialog.setMessage(__('Saving template failed'), __('Error'), 'error');
                    msgDialog.show();
                });
            }, true);
        }
        fields = dialog.fields;
        fields.fldName.setValue(wb_builder.template.localId);
        fields.fldIsPrivate.setValue((wb_builder.template.isPrivate ? true : false));
        fields.fldNonTranslatable.setValue((wb_builder.template.nonTranslatable ? true : false));
        $.getJSON(wb_builder.baseUrl + 'tpllist/', function (data) {
            var selItem = null, item;
            if (data && data.length) {
                fields.fldCategory.removeAllItems();
                for (var _i = 0, data_4 = data; _i < data_4.length; _i++) {
                    var li = data_4[_i];
                    item = new DropdownBox_8["default"].Item(li.name, li.id, li);
                    fields.fldCategory.addItem(item);
                    if (li.id === wb_builder.template.categoryId) {
                        selItem = item;
                    }
                }
                fields.fldCategory.selectItem(selItem);
            }
        });
        dialog.show();
    }
    exports.saveAsTemplate = saveAsTemplate;
});
define("BlocksAdmin", ["require", "exports", "Service", "Dialog", "MsgDialog"], function (require, exports, Service_20, Dialog_9, MsgDialog_3) {
    "use strict";
    exports.__esModule = true;
    var BlocksAdminModule = (function () {
        function BlocksAdminModule() {
        }
        BlocksAdminModule.openDialog = function () {
            if (!BlocksAdminModule.dialog) {
                BlocksAdminModule.dialog = new AdminDialog();
            }
            BlocksAdminModule.dialog.setVisible(true);
        };
        return BlocksAdminModule;
    }());
    exports.BlocksAdminModule = BlocksAdminModule;
    var AdminDialog = (function (_super) {
        __extends(AdminDialog, _super);
        function AdminDialog() {
            var _this = _super.call(this, __('Save block'), false) || this;
            _this.setContent(new Service_20["default"].UIBuilder([
                { type: 'VerticalLayout', id: 'container' }
            ], _this.fields));
            _this.addButton(__('Cancel'), function () {
                _this.setVisible(false);
            });
            _this.addButton(__('Save'), function () {
                if (!_this.msgDialog)
                    _this.msgDialog = new MsgDialog_3["default"]('Save block');
                $.post(wb_builder.baseUrl + 'blocks/save-block', {
                    id: _this.fields.blockId.getValue(),
                    icon: _this.fields.icon.getValue(),
                    config: JSON.stringify(_this.getConfig()),
                    gallery: JSON.stringify(Service_20["default"].element.getUsedMediaGalleryItems(_this.getSelectedElements())),
                    elements: JSON.stringify(_this.getElementsData(_this.getSelectedElements()))
                }, function (data) {
                    if (data.complete) {
                        _this.msgDialog.setMessage('Block saved successfully', '', 'success');
                        Service_20["default"].Blocks.Module.reload();
                    }
                    else {
                        _this.msgDialog.setMessage(data.error.message, 'Error', 'error');
                    }
                    _this.msgDialog.show();
                }).error(function () {
                    _this.msgDialog.setMessage('Saving block failed', 'Error', 'error');
                    _this.msgDialog.show();
                });
                _this.setVisible(false);
            }, true);
            return _this;
        }
        AdminDialog.prototype.onShow = function () {
            if (this.hasSelectedElements()) {
                this.showSavingBlock();
            }
            else {
                this.showEmptyBlock();
            }
        };
        AdminDialog.prototype.showSavingBlock = function () {
            if (!this.savingBlock) {
                this.savingBlock = (new Service_20["default"].UIBuilder([{
                        type: 'VerticalLayout', children: [
                            { type: 'Label', text: 'Block ID', helpText: 'The format of block has to be <em>Category/Block ID</em> (for example "Contacts/5").<br />You can use any category name (it will be created if does not exist) and any block ID (number or string).' },
                            { type: 'TextField', id: 'blockId' }
                        ]
                    },
                    { type: 'VerticalLayout', css: { marginTop: 15 }, children: [
                            { type: 'Label', text: 'Icon' },
                            { type: 'ImageSelector', id: 'icon' }
                        ] }
                ], this.fields)).getElem();
                this.fields.container.getElem().append(this.savingBlock);
            }
            if (this.emptyBlock)
                this.emptyBlock.hide();
            this.savingBlock.show();
        };
        AdminDialog.prototype.showEmptyBlock = function () {
            if (!this.emptyBlock) {
                this.emptyBlock = $('<div>').addClass('alert alert-info')
                    .html('No selected elements found');
                this.fields.container.getElem().append(this.emptyBlock);
            }
            if (this.savingBlock)
                this.savingBlock.hide();
            this.emptyBlock.show();
        };
        AdminDialog.prototype.getConfig = function () {
            var styles = [];
            var styleList = wb_builder.site.styles;
            for (var i = 0, c = styleList.length; i < c; i++) {
                styles.push(styleList[i].serialize());
            }
            return {
                'styles': styles
            };
        };
        AdminDialog.prototype.getElementsData = function (elems) {
            var data = [];
            for (var i = 0, c = elems.length; i < c; i++) {
                var elemData = elems[i].serialize();
                data.push(elemData);
            }
            return data;
        };
        AdminDialog.prototype.getSelectedElements = function () {
            var elems = Service_20["default"].element.getSelected();
            var list = [];
            for (var i in elems) {
                list.push(elems[i]);
            }
            return list;
        };
        AdminDialog.prototype.hasSelectedElements = function () {
            return (this.getSelectedElements().length > 0);
        };
        return AdminDialog;
    }(Dialog_9["default"]));
    function openDialog() {
        BlocksAdminModule.openDialog();
    }
    exports.openDialog = openDialog;
});
define("ElementStylesAdmin", ["require", "exports", "Service", "Dialog", "MsgDialog"], function (require, exports, Service_21, Dialog_10, MsgDialog_4) {
    "use strict";
    exports.__esModule = true;
    var ElementStylesAdminModule = (function () {
        function ElementStylesAdminModule() {
        }
        ElementStylesAdminModule.openDialog = function () {
            if (!ElementStylesAdminModule.dialog) {
                ElementStylesAdminModule.dialog = new ElementStylesDialog();
            }
            ElementStylesAdminModule.dialog.setVisible(true);
        };
        return ElementStylesAdminModule;
    }());
    exports.ElementStylesAdminModule = ElementStylesAdminModule;
    var ElementStylesDialog = (function (_super) {
        __extends(ElementStylesDialog, _super);
        function ElementStylesDialog() {
            var _this = _super.call(this, __('Save Element Style'), false) || this;
            _this.setContent(new Service_21["default"].UIBuilder([
                { type: 'VerticalLayout', id: 'container' }
            ], _this.fields));
            _this.addButton(__('Cancel'), function () {
                _this.setVisible(false);
            });
            _this.addButton(__('Save'), function () {
                if (!_this.msgDialog)
                    _this.msgDialog = new MsgDialog_4["default"](__('Save Element Style'));
                $.post(wb_builder.lnBaseUrl + 'element-styles/save', {
                    id: _this.fields.styleId.getValue(),
                    gallery: JSON.stringify(Service_21["default"].element.getUsedMediaGalleryItems([_this.getSelectedElement()])),
                    data: JSON.stringify(_this.getElementData(_this.getSelectedElement()))
                }, function (data) {
                    if (data.complete) {
                        _this.msgDialog.setMessage(__('Element style saved successfully'), '', 'success');
                        wb_builder.predefinedElementStyles = data.styles;
                    }
                    else {
                        _this.msgDialog.setMessage(data.error.message, 'Error', 'error');
                    }
                    _this.msgDialog.show();
                }).error(function () {
                    _this.msgDialog.setMessage(__('Saving element style failed'), 'Error', 'error');
                    _this.msgDialog.show();
                });
                _this.setVisible(false);
            }, true);
            return _this;
        }
        ElementStylesDialog.prototype.onShow = function () {
            var elem = this.getSelectedElement();
            if (!elem) {
                this.showEmptyBlock();
            }
            else {
                this.showSavingBlock();
            }
        };
        ElementStylesDialog.prototype.showSavingBlock = function () {
            if (!this.savingBlock) {
                this.savingBlock = (new Service_21["default"].UIBuilder([{
                        type: 'VerticalLayout', children: [
                            { type: 'Label', text: 'Style ID', helpText: __('ID of the new element style. If field is left blank then next available number will be used automatically. Otherwise if style with specified ID already exists it will be overwritten.') },
                            { type: 'TextField', id: 'styleId' }
                        ]
                    }
                ], this.fields)).getElem();
                this.fields.container.getElem().append(this.savingBlock);
            }
            if (this.emptyBlock)
                this.emptyBlock.hide();
            this.savingBlock.show();
        };
        ElementStylesDialog.prototype.showEmptyBlock = function () {
            if (!this.emptyBlock) {
                this.emptyBlock = $('<div>').addClass('alert alert-info')
                    .html(__('Exactly one element must be selected'));
                this.fields.container.getElem().append(this.emptyBlock);
            }
            if (this.savingBlock)
                this.savingBlock.hide();
            this.emptyBlock.show();
        };
        ElementStylesDialog.prototype.getElementData = function (elem) {
            return elem ? elem.serialize() : null;
        };
        ElementStylesDialog.prototype.getSelectedElement = function () {
            var elems = Service_21["default"].element.getSelected();
            var elem = null;
            for (var i in elems) {
                if (elem !== null)
                    return null;
                elem = elems[i];
            }
            return elem;
        };
        return ElementStylesDialog;
    }(Dialog_10["default"]));
    function openDialog() {
        ElementStylesAdminModule.openDialog();
    }
    exports.openDialog = openDialog;
});
define("PluginApi/BuilderApi", ["require", "exports", "Confirm", "ElementRegister", "Service", "GridAndGuidesDialog", "ModeManager", "util/MenuList", "HelpSystem/HelpOverlay", "RemoteLoginDialog", "admin/Templates", "BlocksAdmin", "ElementStylesAdmin"], function (require, exports, Confirm_3, ElementRegister_4, Service_22, GridAndGuidesDialog_1, ModeManager_1, MenuList_1, HelpOverlay_1, RemoteLoginDialog_1, Templates_1, BlocksAdmin, ElementStylesAdmin) {
    "use strict";
    exports.__esModule = true;
    var BuilderApi = (function () {
        function BuilderApi(builder) {
            this.builder = builder;
        }
        BuilderApi.prototype.getSiteMenus = function () { return MenuList_1.buildMenuStruct(false, false, null, true); };
        BuilderApi.prototype.getLanguage = function () {
            for (var _i = 0, _a = this.builder.availableLanguages; _i < _a.length; _i++) {
                var lang = _a[_i];
                if (lang.code != this.builder.langCode)
                    continue;
                return lang;
            }
            return null;
        };
        BuilderApi.prototype.getLanguages = function () { return this.builder.availableLanguages; };
        BuilderApi.prototype.setLanguage = function (language) {
            window.location.href = this.builder.baseUrl + (language["default"] ? "" : (language.code + "/"));
        };
        BuilderApi.prototype.getSiteDomain = function () { return this.builder.siteDomain; };
        BuilderApi.prototype.getSiteUrl = function () { return 'http://' + this.builder.siteDomain; };
        BuilderApi.prototype.getLogoUrl = function () {
            return this.builder.whiteLabel.logo ? this.builder.baseUrl + 'builder-logo' : '';
        };
        BuilderApi.prototype.getBaseUrl = function (includeLanguage) {
            if (includeLanguage === void 0) { includeLanguage = false; }
            return includeLanguage ? this.builder.lnBaseUrl : this.builder.baseUrl;
        };
        BuilderApi.prototype.getPanelUrl = function () { return this.builder.panelUrl; };
        BuilderApi.prototype.getSignUpInfo = function () {
            var info = this.builder.testSignUpBtn;
            return info ? {
                title: __trr(info.title),
                url: __trr(info.url).replace('{{siteDomain}}', this.builder.siteDomain)
            } : null;
        };
        BuilderApi.prototype.getElementPlugins = function () {
            var list = [], itemDef, k;
            for (var _i = 0, _a = this.builder.pluginToolbar; _i < _a.length; _i++) {
                var group = _a[_i];
                if (!(group.id in this.builder.pluginGroups))
                    continue;
                var groupItems = {
                    group: this.builder.pluginGroups[group.id],
                    items: []
                };
                for (var _b = 0, _c = group.items; _b < _c.length; _b++) {
                    var className = _c[_b];
                    itemDef = null;
                    for (k in ElementRegister_4["default"].pluginRegistry) {
                        if (('textId' in ElementRegister_4["default"].pluginRegistry[k]) && ElementRegister_4["default"].pluginRegistry[k].textId === className) {
                            itemDef = ElementRegister_4["default"].pluginRegistry[k];
                            break;
                        }
                    }
                    if (!itemDef && (className in ElementRegister_4["default"].pluginRegistry)) {
                        itemDef = ElementRegister_4["default"].pluginRegistry[className];
                    }
                    if (!itemDef)
                        continue;
                    groupItems.items.push(itemDef);
                }
                if (groupItems.items.length)
                    list.push(groupItems);
            }
            return list;
        };
        BuilderApi.prototype.getElementPluginGroups = function () {
            return this.builder.pluginGroups;
        };
        BuilderApi.prototype.isRtl = function () { return this.builder.rtl; };
        BuilderApi.prototype.isTouchDevice = function () { return this.builder.isTouchDevice; };
        BuilderApi.prototype.isTestMode = function () { return this.builder.testMode; };
        BuilderApi.prototype.isAdminMode = function () { return this.builder.adminMode; };
        BuilderApi.prototype.isImportAvailable = function () { return this.builder.enableImport; };
        BuilderApi.prototype.isImportVisible = function () { return !this.builder.hideImport; };
        BuilderApi.prototype.showImportDialog = function () { Service_22["default"].websiteImporter.showImportDialog(); };
        BuilderApi.prototype.isHistoryUndoAvailable = function () { return this.builder.historyHasUndo(); };
        BuilderApi.prototype.isHistoryRedoAvailable = function () { return this.builder.historyHasRedo(); };
        BuilderApi.prototype.isPublishAvailable = function () {
            return ((!this.isTestMode() || RemoteLoginDialog_1["default"].available() || this.builder.testSignUpBtn)
                && !this.isAdminMode()) ? true : false;
        };
        BuilderApi.prototype.publish = function () { this.builder.publish(); };
        BuilderApi.prototype.preview = function () { this.builder.preview(this.builder.previewToolbar); };
        BuilderApi.prototype.reloadPreview = function () { this.builder.preview(this.builder.previewToolbar, true); };
        BuilderApi.prototype.hidePreview = function () { this.builder.previewToolbar.close(); };
        BuilderApi.prototype.setPreviewWidth = function (width) { this.builder.previewToolbar.setPreviewWidth(width); };
        BuilderApi.prototype.save = function (useDialog, callback) {
            this.builder.save(useDialog, callback);
        };
        BuilderApi.prototype.isTemplateSavingAvailable = function () { return this.isAdminMode(); };
        BuilderApi.prototype.isTemplateSavingEnabled = function () { return this.builder.locale == 'en_US'; };
        ;
        BuilderApi.prototype.showSaveAsTemplateDialog = function () { this.builder.save(false, function (success) { if (success)
            Templates_1.saveAsTemplate(); }, null, false, false, false); };
        BuilderApi.prototype.isBlockSavingAvailable = function () { return this.isAdminMode() && !this.builder.isEnterprise; };
        BuilderApi.prototype.isBlockSavingEnabled = function () { return this.builder.locale == 'en_US'; };
        ;
        BuilderApi.prototype.showSaveBlockDialog = function () { BlocksAdmin.openDialog(); };
        BuilderApi.prototype.isElementStyleSavingAvailable = function () { return this.isAdminMode() && !this.builder.isEnterprise; };
        BuilderApi.prototype.isElementStyleSavingEnabled = function () { return this.builder.locale == 'en_US'; };
        ;
        BuilderApi.prototype.showSaveElementStyleDialog = function () { ElementStylesAdmin.openDialog(); };
        BuilderApi.prototype.goToPage = function (pageId, customUrl) { this.builder.goToPage(pageId, customUrl); };
        BuilderApi.prototype.historyUndo = function () { this.builder.historyUndo(); };
        BuilderApi.prototype.historyRedo = function () { this.builder.historyRedo(); };
        BuilderApi.prototype.showBackupRestoreDialog = function () { this.builder.backupRestore(); };
        BuilderApi.prototype.showTemplateChooser = function () { this.builder.templateChooser.setVisible(true); };
        BuilderApi.prototype.resetSite = function (needComfirmDialog) {
            var _this = this;
            if (needComfirmDialog === void 0) { needComfirmDialog = false; }
            if (needComfirmDialog) {
                Confirm_3["default"].showDialog(__("Reset"), $('<div class="wb_change_template_dlg">' +
                    '<div class="qq">' + __("Are you sure you want to reset current template?") + '</div>' +
                    '<div class="red">' + __("Once reset your information will be lost.") + '</div>' +
                    '</div>'), [
                    {
                        title: __("No, keep current template")
                    },
                    {
                        title: __("Yes, reset template"),
                        cssClass: "btn-danger",
                        func: function () { _this.resetSite(false); }
                    }
                ], 480);
                if (Confirm_3["default"].dialog)
                    Confirm_3["default"].dialog.setCenterButtons(true);
                return;
            }
            this.builder.setPageModified(false);
            location.href = this.builder.resetUrl;
        };
        BuilderApi.prototype.addElementAt = function (elementId, cx, cy) {
            var _this = this;
            if (!elementId)
                return;
            var bounds, container = null, lastContainer = null;
            for (var id in this.builder.bodyInstance.blocks) {
                var block = this.builder.bodyInstance.blocks[id];
                bounds = block.getBoundingClientRect();
                lastContainer = block;
                if (bounds.left <= cx && (bounds.left + bounds.width) >= cx && bounds.top <= cy && (bounds.top + bounds.height) >= cy) {
                    container = lastContainer;
                    break;
                }
            }
            if (!container)
                container = lastContainer;
            if (container) {
                ElementRegister_4["default"].createElement(elementId, function (item) {
                    if (!container)
                        return;
                    Service_22["default"].element.unselectAll();
                    item.setLocation(_this.builder.autoSnapX(cx - bounds.left - item.getWidth() / 2), _this.builder.autoSnapY(cy - bounds.top - item.getHeight() / 2, container.id));
                    container.addElement(item);
                    item.setSelected(true);
                    item.setControlsVisible(true);
                    _this.builder.setPageModified(true);
                });
            }
        };
        BuilderApi.prototype.sortAndAutoAlignElements = function () { ModeManager_1["default"].sortAndAutoAlignElements(); };
        BuilderApi.prototype.isAutoLayoutEnabled = function () { return ModeManager_1["default"].isAutoLayoutEnabled(); };
        BuilderApi.prototype.isAutoLayoutAvailable = function () { return this.builder.enableAutoLayout; };
        BuilderApi.prototype.setAutoLayoutEnabled = function (enabled) { ModeManager_1["default"].setAutoLayoutEnabled(enabled); };
        BuilderApi.prototype.setMode = function (mode) { ModeManager_1["default"].setModeWithPrompt(mode); };
        BuilderApi.prototype.getModeEnabled = function (mode) { return ModeManager_1["default"].getModeEnabled(mode); };
        BuilderApi.prototype.setModeEnabled = function (mode, enabled) { ModeManager_1["default"].setModeEnabled(mode, enabled); };
        BuilderApi.prototype.isFullScreenSupported = function () {
            return this.builder.goFullScreen(true);
        };
        BuilderApi.prototype.toggleFullScreen = function () {
            return this.builder.goFullScreen(false);
        };
        BuilderApi.prototype.showSiteSEODialog = function () {
            if (this.builder.site)
                this.builder.site.changeSiteSEO();
        };
        BuilderApi.prototype.showSiteBackgroundDialog = function () {
            if (this.builder.site)
                this.builder.site.changeBackground();
        };
        BuilderApi.prototype.showSiteStylesDialog = function () {
            if (this.builder.site)
                this.builder.site.changeStyles();
        };
        BuilderApi.prototype.showSiteFaviconDialog = function () {
            if (this.builder.site)
                this.builder.site.changeFavicon();
        };
        BuilderApi.prototype.showSitePropertiesDialog = function () {
            if (this.builder.site)
                this.builder.site.changeProperties();
        };
        BuilderApi.prototype.showGridAndGuidesDialog = function () {
            GridAndGuidesDialog_1.GridAndGuidesDialog.open();
        };
        BuilderApi.prototype.getSiteLanding = function () {
            return this.builder.site && this.builder.site.landing;
        };
        BuilderApi.prototype.setSiteLanding = function (enabled) {
            if (this.builder.site)
                this.builder.site.setLanding(enabled, false);
        };
        BuilderApi.prototype.hideContextMenus = function () {
            Service_22["default"].contextMenu.hideAll();
        };
        BuilderApi.prototype.isHelpAvailable = function () { return HelpOverlay_1.isHelpAvailable(); };
        BuilderApi.prototype.showHelp = function () { HelpOverlay_1.openHelp(); };
        BuilderApi.prototype.logout = function () {
            window.location.href = this.builder.logoutUrl;
        };
        BuilderApi.prototype.init = function (elem) {
            this.builder.body = $(elem)
                .append('<div id="site"><div class="site_cover"></div></div>');
            this.builder.siteCover = $(".site_cover", this.builder.body);
            this.builder.container = $(document.body);
            if (this.builder.isTouchDevice)
                this.builder.body.css({ maxWidth: '100%', overflowX: 'scroll' });
            this.builder.initContinue();
        };
        return BuilderApi;
    }());
    exports.BuilderApi = BuilderApi;
});
define("PluginApi/UIManager", ["require", "exports", "PluginApi/BuilderApi", "Service"], function (require, exports, BuilderApi_1, Service_23) {
    "use strict";
    exports.__esModule = true;
    var UIManager = (function () {
        function UIManager(builder) {
        }
        UIManager.prototype.lookupUIElement = function (type, id) {
            return null;
        };
        UIManager.prototype.lookupUIIconClass = function (type, elementId) {
            return null;
        };
        UIManager.prototype.closeAll = function () { };
        return UIManager;
    }());
    exports.UIManager = UIManager;
    var uiManagers = {};
    var uiManager = null;
    var builderApi = null;
    function registerUI(id, ctor) {
        uiManagers[id] = ctor;
    }
    exports.registerUI = registerUI;
    function init(builder) {
        var lastManagerId = Object.keys(uiManagers).pop();
        if (!lastManagerId)
            throw new Error('No UI manager');
        var uiManagerCls = uiManagers[lastManagerId];
        builderApi = new BuilderApi_1.BuilderApi(builder);
        uiManager = new uiManagerCls(builderApi);
    }
    exports.init = init;
    function getApiInstance() {
        if (!builderApi)
            throw new Error('You can only use this after initialization');
        return builderApi;
    }
    exports.getApiInstance = getApiInstance;
    function getManager() {
        if (!uiManager)
            throw new Error('You can only use this after initialization');
        return uiManager;
    }
    exports.getManager = getManager;
    Service_23["default"].uiManager = {
        getApiInstance: getApiInstance,
        getManager: getManager
    };
});
define("HelpSystem/HelpSystemPlayer", ["require", "exports", "ElementRegister", "UserInput", "Site", "Dialog", "HelpSystem/Scenario", "HelpSystem/PlayerControls", "HelpSystem/Tooltip", "HelpSystem/PlayerCanvas", "HelpSystem/ScenarioBuilder", "HelpSystem/AnimTween", "HelpSystem/VirtualCursor", "Service", "jquery", "BuilderEvent", "PluginApi/UIManager"], function (require, exports, ElementRegister_5, UserInput_3, Site_1, Dialog_11, Scenario_2, PlayerControls_1, Tooltip_1, PlayerCanvas_1, ScenarioBuilder_1, AnimTween_3, VirtualCursor_1, Service_24, $, BuilderEvent_9, UIManager_1) {
    "use strict";
    exports.__esModule = true;
    var instance, builder;
    var HelpSystemPlayer = (function () {
        function HelpSystemPlayer() {
            var _this = this;
            this.scenario = null;
            this.stepIndex = -1;
            this.selfTip = null;
            this.stepParams = [];
            this.forceList = [];
            this.audio = null;
            this.bgAudio = null;
            this.autoAdvance = false;
            this.performInProgress = false;
            this.performStack = [];
            this.debug = false;
            this.vDesktop = null;
            this.subjectMap = {};
            this.currElemSubject = null;
            this.canvas = null;
            this.cursor = null;
            this.timerHandles = { eventDelay: 0, stepDelay: 0, resizeTween: null, moveTween: null };
            this.hotkeysEnabled = false;
            this.waitForAudio = false;
            this.doneCallback = null;
            this.playToggleLock = false;
            this.controls = PlayerControls_1.PlayerControls.init(function () {
                if (_this.playToggleLock)
                    return;
                _this.playToggleLock = true;
                setTimeout(function () { _this.playToggleLock = false; }, 300);
                if (_this.autoAdvance && !_this.performInProgress) {
                    _this.autoAdvance = false;
                    _this.controls.getFields().playBtn.getElem().attr({ title: __('Play') });
                    _this.controls.getFields().playBtn.setIcon('fa fa-play');
                    _this.controls.getFields().nextBtn.setEnabled(true);
                }
                else if (!_this.performInProgress) {
                    _this.controls.getFields().nextBtn.setEnabled(false);
                    _this.controls.getFields().playBtn.getElem().attr({ title: __('Stop') });
                    _this.controls.getFields().playBtn.setIcon('fa fa-pause');
                    _this.perform(true);
                }
            }, function () {
                if (!_this.autoAdvance && !_this.performInProgress)
                    _this.perform(false);
            }, function () {
                _this.end();
            }, function (speed, speedMax) {
                if (!_this.scenario)
                    return;
                var k = 0.6;
                _this.scenario.stepDelay = HelpSystemPlayer.STEP_DELAY + Math.round(HelpSystemPlayer.STEP_DELAY * (6 - speed) * k);
            });
            this.controls.setVisible(false);
            $(document.body).append(this.controls.getElem());
            UserInput_3.UserInput.addHotKey('esc', function () { if (_this.hotkeysEnabled)
                _this.end(); });
            window.addEventListener('hashchange', function () { _this.handleUrlHashChange(); }, false);
        }
        HelpSystemPlayer.init = function (builderInstance) {
            builder = builderInstance;
            if (!instance)
                instance = new HelpSystemPlayer();
            Service_24["default"].HelpSystemPlayer = HelpSystemPlayer;
            ScenarioBuilder_1.init(builderInstance);
            return instance;
        };
        HelpSystemPlayer.notify = function (event, subject) {
            if (subject === void 0) { subject = null; }
            if (!instance)
                return;
            instance.handleEvent(event, subject);
        };
        HelpSystemPlayer.loadRemote = function (name, live, doneCallback) {
            if (live === void 0) { live = false; }
            if (doneCallback === void 0) { doneCallback = null; }
            if (!instance || !name)
                return;
            if (name === '.') {
                instance.load(ScenarioBuilder_1.buildFromCurrent(builder, !live));
                instance.start(false, true, !live, !live, doneCallback);
            }
            else {
                $.getJSON(builder.lnBaseUrl + 'scenario/load/' + name).then(function (res) {
                    if (res) {
                        instance.load(res);
                        instance.start(false, true, !live, false, doneCallback);
                    }
                    else {
                        console.log("Scenario '" + name + "' not found.");
                    }
                }, function () {
                    console.log('Error loading scenario.');
                });
            }
        };
        HelpSystemPlayer.getCanvas = function () {
            return instance ? instance.canvas : null;
        };
        HelpSystemPlayer.prototype.handlePageLoad = function (serverSideScenario) {
            var _this = this;
            if (serverSideScenario === void 0) { serverSideScenario = null; }
            if (serverSideScenario) {
                this.load(serverSideScenario);
                setTimeout(function () { _this.start(); }, 1000);
            }
            else {
                this.handleUrlHashChange();
            }
        };
        HelpSystemPlayer.prototype.handleUrlHashChange = function () {
            if (!location.hash || !location.hash.match(/^#scenario=.+$/))
                return;
            var paramsStr = location.hash.split('=', 2)[1];
            location.hash = '';
            var paramsArr = paramsStr.split('/');
            var scenarioId = (paramsArr.length > 0) ? paramsArr[0] : null;
            var live = (paramsArr.length > 1) ? (paramsArr[1] ? true : false) : false;
            console.log('Scenario', scenarioId, live);
            if (scenarioId)
                HelpSystemPlayer.loadRemote(scenarioId, live);
        };
        HelpSystemPlayer.prototype.handleEvent = function (event, subject) {
            var _this = this;
            if (subject === void 0) { subject = null; }
            if (this.debug)
                console.log("Handle event " + event + " - subject: " + (subject ? 'Y' : 'N'));
            if (!this.scenario || this.stepIndex < 0)
                return;
            this.processForces(event);
            var step = this.scenario.steps[this.stepIndex];
            var match;
            if (!this.selfTip) {
                if (step.requirements && step.requirements.length > 0) {
                    var _loop_5 = function (i) {
                        if (!step.requirements[i])
                            return "continue";
                        if (step.requirements[i] === event) {
                            step.requirements.splice(i, 1);
                            if (this_3.debug)
                                console.log("Satisfy requirement " + event + ", remaining " + step.requirements.length);
                        }
                        else if ((match = step.requirements[i].match(/^timeout:([0-9]+)$/i))) {
                            if (this_3.timerHandles.eventDelay)
                                clearTimeout(this_3.timerHandles.eventDelay);
                            this_3.timerHandles.eventDelay = setTimeout(function () {
                                if (step.requirements)
                                    _this.handleEvent(step.requirements[i], null);
                            }, parseInt(match[1], 10));
                        }
                    };
                    var this_3 = this;
                    for (var i = (step.requirements.length - 1); i >= 0; i--) {
                        _loop_5(i);
                    }
                }
                if (!step.requirements || step.requirements.length === 0) {
                    if (this.debug)
                        console.log("Render step", step);
                    this.renderStep(step, this.stepParams);
                    this.stepParams = [];
                }
            }
            if (this.selfTip || (!step.subject && (!step.requirements || step.requirements.length === 0))) {
                if (step.objectives && step.objectives.length > 0) {
                    for (var i = (step.objectives.length - 1); i >= 0; i--) {
                        if (step.objectives[i] === event) {
                            if (!this.currElemSubject && event && event.match(/^add-plugin-[^-]+$/) && subject) {
                                this.currElemSubject = subject;
                            }
                            step.objectives.splice(i, 1);
                            this.stepParams.push(subject);
                            if (this.debug)
                                console.log("Complete objective " + event + ", remaining " + step.objectives.length);
                        }
                    }
                }
                if (!step.objectives || step.objectives.length === 0) {
                    if (this.currElemSubject && step.forceBounds) {
                        if (this.debug)
                            console.log("Queue force bounds", step.forceBounds);
                        this.forceList.unshift(Object.assign({ subject: this.currElemSubject }, step.forceBounds));
                        this.processForces(event);
                    }
                    if (!this.currElemSubject && step.forceBounds) {
                        console.error('Error no subject for forcing');
                    }
                    if (this.debug)
                        console.log("Advance step");
                    this.next();
                }
                else if (event == 'scenario-start' && this.autoAdvance && this.stepIndex === 0) {
                    this.handleAutoAdvance();
                }
            }
        };
        HelpSystemPlayer.prototype.processForces = function (event) {
            for (var i = (this.forceList.length - 1); i >= 0; i--) {
                var forceBounds = this.forceList[i];
                if (forceBounds.event && forceBounds.event !== event)
                    continue;
                this.forceList.splice(i, 1);
                if (this.debug)
                    console.log("Force bounds", forceBounds);
                if (forceBounds.subject)
                    Scenario_2.applyBounds(forceBounds.subject, forceBounds);
            }
        };
        HelpSystemPlayer.prototype.renderStep = function (step, params) {
            var _this = this;
            this.clearStep();
            var subject = this.resolveTargetPath(step.subject, params, step.id, true);
            if (subject) {
                if (!this.scenario)
                    return;
                this.selfTip = new Tooltip_1.Tooltip(step, subject, function () { _this.clearStep(); });
                if (step.audio) {
                    if (this.debug)
                        console.log("Play audio: " + step.audio);
                    if (this.audio)
                        this.audio.pause();
                    this.audio = new Audio((this.scenario.baseUrl ? this.scenario.baseUrl : '') + step.audio);
                    this.audio.onload = function () {
                        if (!_this.audio)
                            return;
                        if (_this.debug)
                            console.log("Audio loaded: " + step.audio);
                        _this.audio.play();
                    };
                    this.audio.onerror = function () {
                        console.error("Failed to load audio: " + step.audio);
                    };
                    this.audio.load();
                    this.audio.play();
                }
            }
            else {
                if (step.subject)
                    console.error("No subject: " + step.subject);
            }
        };
        HelpSystemPlayer.prototype.updateUrl = function (url, scenario) {
            if (!this.canvas || !scenario || !scenario.baseUrl || url.match(/^(http|https):\/\/.+/i))
                return url;
            return scenario.baseUrl + url;
        };
        HelpSystemPlayer.prototype.clearStep = function () {
            if (this.selfTip) {
                this.selfTip.el.remove();
                this.selfTip = null;
                this.currElemSubject = null;
            }
        };
        HelpSystemPlayer.prototype.resolveTargetPath = function (path, params, mappingId, trackElemSubject) {
            if (mappingId === void 0) { mappingId = null; }
            if (trackElemSubject === void 0) { trackElemSubject = false; }
            if (!path)
                return null;
            var pathParts = path.split('[');
            var idxStr = (pathParts.length > 1 && pathParts[1].length > 1) ? pathParts[1].substring(0, pathParts[1].length - 1) : null;
            var idx = (idxStr && idxStr.match(/^[0-9]+$/)) ? parseInt(idxStr, 10) : -1;
            var hasIndex = (pathParts.length > 1);
            if (isNaN(idx))
                idx = -1;
            pathParts = pathParts[0].split('-');
            var manager = UIManager_1.getManager();
            switch (pathParts[0]) {
                case 'desktop':
                    if (!this.vDesktop)
                        return null;
                    return new Tooltip_1.ScenarioStepSubject(this.vDesktop, 'right');
                case 'preview':
                    var sub = (pathParts[1] + '-' + pathParts[2]);
                    if (sub === 'close-btn') {
                        var elem = manager.lookupUIElement('preview', 'close');
                        if (elem)
                            elem.elem.css({ position: 'relative' });
                        return elem;
                    }
                    else if (sub === 'resize-border') {
                        if (pathParts.length > 3 && pathParts[3] === 'left') {
                            return new Tooltip_1.ScenarioStepSubject(builder.previewToolbar.getResizerElement(true), 'right', 200, 8);
                        }
                        else {
                            return new Tooltip_1.ScenarioStepSubject(builder.previewToolbar.getResizerElement(false), 'left', 200, -4);
                        }
                    }
                    break;
                case 'toolbar':
                    if (pathParts[1] === 'ctrl') {
                        var elemId = pathParts[2];
                        if (elemId === 'config') {
                            if (pathParts.length > 3 && pathParts[3]) {
                                elemId += '-' + pathParts[3];
                            }
                        }
                        var sub_1 = manager.lookupUIElement('control', elemId);
                        if (sub_1)
                            return sub_1;
                    }
                    else if (pathParts[1] === 'plugin') {
                        var sub_2 = manager.lookupUIElement('plugin', pathParts[2]);
                        if (sub_2)
                            return sub_2;
                    }
                    break;
                case 'item':
                    if (pathParts[1] === 'plugin') {
                        var list = void 0;
                        if (hasIndex && idxStr && (idxStr in this.subjectMap)) {
                            list = [this.subjectMap[idxStr]];
                        }
                        else if (hasIndex && idx >= 0 && params.length > 0) {
                            list = params;
                        }
                        else {
                            list = this.canvas ? this.canvas.getElements() : builder.bodyInstance.getContentElements();
                        }
                        for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
                            var elem = list_1[_i];
                            var id = elem.getClassType();
                            if (pathParts[2] === id) {
                                if (mappingId)
                                    this.subjectMap[mappingId] = elem;
                                if (trackElemSubject)
                                    this.currElemSubject = elem;
                                if (pathParts.length > 4) {
                                    var sub_3 = (pathParts[3] + '-' + pathParts[4]);
                                    if (sub_3 === 'edit-cmd') {
                                        var telm = elem.getToolbarElem(pathParts[5]);
                                        if (!telm)
                                            telm = elem.getToolbarElem();
                                        return new Tooltip_1.ScenarioStepSubject(telm, 'left', 0, 0, true, true);
                                    }
                                    else if (sub_3 === 'edit-btn') {
                                        elem.setControlsVisible(true);
                                        return new Tooltip_1.ScenarioStepSubject(elem.editBtn, 'left');
                                    }
                                    else if (sub_3 === 'move-btn') {
                                        elem.setControlsVisible(true);
                                        return new Tooltip_1.ScenarioStepSubject(elem.moveBtn, 'right');
                                    }
                                    else if (pathParts[3] === 'prop' || pathParts[3] === 'menu') {
                                        var prop = pathParts[4] + ((pathParts.length > 5) ? ('-' + pathParts[5]) : '');
                                        if (pathParts[3] !== 'prop')
                                            prop = pathParts[3] + '-' + prop;
                                        var field = elem.comPropertiesField(prop);
                                        if (field) {
                                            if (pathParts[4] === 'apply') {
                                                return new Tooltip_1.ScenarioStepSubject(field.getElem(), 'left', 0, 0, true, true);
                                            }
                                            else if (pathParts[4] === 'tab') {
                                                return new Tooltip_1.ScenarioStepSubject(field.getElem(), 'bottom', 0, 0, true, true);
                                            }
                                            else if (pathParts[4] === 'sizeW' || pathParts[4] === 'sizeH' || pathParts[4] === 'locX' || pathParts[4] === 'locY') {
                                                return new Tooltip_1.ScenarioStepSubject(field.getElem(), 'right');
                                            }
                                            else if (pathParts[4] === 'galleryType' && pathParts[2] === 'Gallery') {
                                                return new Tooltip_1.ScenarioStepSubject(field.getElem(), 'left', 0, 0, true, true);
                                            }
                                            else {
                                                return new Tooltip_1.ScenarioStepSubject(field.getElem(), 'left');
                                            }
                                        }
                                    }
                                }
                                else {
                                    return new Tooltip_1.ScenarioStepSubject(elem.elem);
                                }
                            }
                        }
                    }
                    break;
                case 'config':
                    if (pathParts[1] === 'background') {
                        var autoId = pathParts[0] + '-' + pathParts[1];
                        var dialog = this.subjectMap[autoId];
                        if (dialog) {
                            if (pathParts[2] === 'prop') {
                                var prop = dialog.propertyDialogField(pathParts[3]);
                                if (prop)
                                    return new Tooltip_1.ScenarioStepSubject(prop.getElem());
                            }
                        }
                    }
                    break;
            }
            return null;
        };
        HelpSystemPlayer.prototype.load = function (scenario) {
            this.end();
            this.scenario = scenario;
            if (!('animDuration' in this.scenario) || !this.scenario.animDuration || isNaN(this.scenario.animDuration)) {
                this.scenario.animDuration = HelpSystemPlayer.ANIM_DURATION;
            }
            if (!('stepDelay' in this.scenario) || !this.scenario.stepDelay || isNaN(this.scenario.stepDelay)) {
                this.scenario.stepDelay = HelpSystemPlayer.STEP_DELAY;
            }
            if (builder.isTouchDevice) {
                if (this.scenario.audio)
                    this.scenario.audio = null;
                if (this.scenario.steps)
                    for (var _i = 0, _a = this.scenario.steps; _i < _a.length; _i++) {
                        var step = _a[_i];
                        if (step.audio)
                            step.audio = undefined;
                    }
            }
        };
        HelpSystemPlayer.prototype.getTargetCanvas = function (step, defaultBlock) {
            if (step === void 0) { step = null; }
            if (defaultBlock === void 0) { defaultBlock = null; }
            var blockId = (step && step.block) ? step.block : (defaultBlock ? defaultBlock : 'wb_main');
            return this.canvas ? this.canvas : builder.bodyInstance.getContentBlock(blockId);
        };
        HelpSystemPlayer.prototype.cursorGoElem = function (step, subject, type) {
            var _this = this;
            if (type === void 0) { type = ''; }
            if (!step.cursorReady && this.cursor && subject) {
                var cursorPos = subject.elem.offset();
                if (type == 'prop') {
                    cursorPos.left += subject.getWidth() - 10;
                    cursorPos.top += 10;
                }
                else if (type == 'move') {
                    cursorPos.left += 10;
                    cursorPos.top += 10;
                }
                else if (type == 'resize') {
                    if (subject.getClassType() == 'TextArea') {
                        cursorPos.left += subject.elem.outerWidth(false) - 3;
                        cursorPos.top += Math.round(subject.elem.outerHeight(false) * 0.3);
                    }
                    else {
                        cursorPos.left += subject.elem.outerWidth(false) - 8;
                        cursorPos.top += subject.elem.outerHeight(false) - 8;
                    }
                }
                else {
                    cursorPos.left += Math.round(subject.elem.outerWidth(false) / 2.0);
                    cursorPos.top += Math.round(subject.elem.outerHeight(false) / 2.0);
                }
                this.cursor.moveTo(cursorPos, function () {
                    if (_this.cursor)
                        _this.cursor.animClick(function () {
                            step.cursorReady = true;
                            _this.perform(_this.autoAdvance);
                        });
                });
                return true;
            }
            return false;
        };
        HelpSystemPlayer.prototype.cursorGoControl = function (step, control, type, multi) {
            var _this = this;
            if (multi === void 0) { multi = false; }
            if ((!step.cursorReadyControl || !step.cursorReadyControl[type]) && this.cursor && control) {
                var elem = (control instanceof Tooltip_1.ScenarioStepSubject) ? control.elem : control;
                var cursorPos = elem.offset();
                var size = Tooltip_1.ScenarioStepSubject.calcActualSize(elem);
                cursorPos.left += Math.round(size.width / 2.0);
                cursorPos.top += Math.round(size.height / 2.0);
                this.cursor.moveTo(cursorPos, function () {
                    if (_this.cursor)
                        _this.cursor.animClick(function () {
                            if (!step.cursorReadyControl)
                                step.cursorReadyControl = {};
                            step.cursorReadyControl[type] = true;
                            _this.perform(_this.autoAdvance);
                        }, multi);
                });
                return true;
            }
            return false;
        };
        HelpSystemPlayer.prototype.perform = function (autoAdvance) {
            var _this = this;
            if (autoAdvance === void 0) { autoAdvance = false; }
            if (!this.scenario || this.stepIndex < 0)
                return;
            this.performInProgress = true;
            this.autoAdvance = autoAdvance;
            var step = this.scenario.steps[this.stepIndex];
            if (this.debug)
                console.log('performing step', autoAdvance, JSON.stringify(step));
            if (step.objectives.length > 0) {
                var _loop_6 = function (i) {
                    var parts = step.objectives[i].split('-');
                    if (parts[0] === 'add') {
                        if (parts[1] === 'plugin') {
                            var subject = this_4.resolveTargetPath(step.subject, this_4.stepParams);
                            if (this_4.cursorGoControl(step, subject, step.objectives[i]))
                                return { value: void 0 };
                            var manager_1 = UIManager_1.getManager();
                            var pluginId_1 = parts[2];
                            var addPlugin_1 = function () {
                                var ElemType = ElementRegister_5["default"].getClassByName(pluginId_1);
                                var elDef = { content: (step.defaultContent ? step.defaultContent : {}) };
                                if (pluginId_1 === 'Picture') {
                                    if (elDef.content.src)
                                        elDef.content.src = _this.updateUrl(elDef.content.src, _this.scenario);
                                }
                                else if (pluginId_1 === 'Gallery') {
                                    if (elDef.content.images && elDef.content.images instanceof Array) {
                                        elDef.content.images = elDef.content.images.map(function (img) { return _this.updateUrl(img, _this.scenario); });
                                    }
                                }
                                var el = new ElemType(elDef, true);
                                var block = _this.getTargetCanvas(step);
                                block.addElement(el);
                                if (step.forceBounds)
                                    Scenario_2.applyBounds(el, step.forceBounds);
                                _this.performStack.push(el);
                                if (el.getClassType() === 'Picture' || el.getClassType() === 'Gallery') {
                                    _this.handleEvent('item-plugin-' + pluginId_1 + '-edit-start', el);
                                    _this.handleEvent('item-plugin-' + pluginId_1 + '-edit-end', el);
                                }
                                if (el.getClassType() === 'Picture') {
                                    el.loadImage(el.getSrc());
                                }
                            };
                            if (subject) {
                                var thisSubject_1 = subject, subjectEl_1, difW_1 = 0, difH_1 = 0, animDurr_1 = this_4.scenario.animDuration;
                                if (this_4.timerHandles.resizeTween)
                                    this_4.timerHandles.resizeTween.dispose();
                                this_4.timerHandles.resizeTween = new AnimTween_3.AnimTween(animDurr_1, 24, function () {
                                    var coff = subjectEl_1.offset();
                                    subjectEl_1.css({ left: coff.left + difW_1, top: coff.top - window.scrollY + difH_1 });
                                    manager_1.closeAll();
                                }, function (tween) {
                                    var off = thisSubject_1.elem.offset();
                                    off.top -= window.scrollY;
                                    subjectEl_1 = thisSubject_1.elem.clone().detach()
                                        .css({ left: off.left, top: off.top, position: 'fixed' })
                                        .addClass('ui-draggable-dragging')
                                        .attr({ id: '' });
                                    var targetPos = new Scenario_2.BoundableElement(pluginId_1, _this.getTargetCanvas(step));
                                    targetPos.left = $(window).width() / 2.0;
                                    targetPos.top = $(window).height() / 2.0;
                                    if (step.forceBounds)
                                        Scenario_2.applyBounds(targetPos, step.forceBounds);
                                    targetPos.makePageRelative();
                                    if (_this.cursor)
                                        _this.cursor.moveTo(targetPos, null, animDurr_1, 24);
                                    targetPos.top -= window.scrollY;
                                    $(document.body).append(subjectEl_1);
                                    difW_1 = (targetPos.left - off.left) / tween.numKeyframes;
                                    difH_1 = (targetPos.top - off.top) / tween.numKeyframes;
                                }, function () {
                                    subjectEl_1.remove();
                                    addPlugin_1();
                                    _this.performInProgress = false;
                                    _this.handleAutoAdvance();
                                }, function () {
                                    subjectEl_1.remove();
                                }).start();
                                return { value: void 0 };
                            }
                            else {
                                manager_1.closeAll();
                                addPlugin_1();
                            }
                        }
                    }
                    else if (parts[0] === 'item') {
                        if (parts[1] === 'plugin') {
                            if (parts[3] === 'resize') {
                                var subject = (this_4.performStack.length > 0) ? this_4.performStack[this_4.performStack.length - 1] : null;
                                if (this_4.cursorGoElem(step, subject, 'resize'))
                                    return { value: void 0 };
                                this_4.handleEvent('item-plugin-' + parts[2] + '-resize-start', subject);
                                if (step.forceBounds && subject) {
                                    var targetBounds_1 = step.forceBounds, thisSubject_2 = subject, difW_2 = 0, difH_2 = 0, animDurr_2 = this_4.scenario.animDuration;
                                    if (this_4.timerHandles.resizeTween)
                                        this_4.timerHandles.resizeTween.dispose();
                                    this_4.timerHandles.resizeTween = new AnimTween_3.AnimTween(animDurr_2, 24, function () {
                                        thisSubject_2.setSize(thisSubject_2.getWidth() + difW_2, thisSubject_2.getHeight() + difH_2);
                                        thisSubject_2.onResize();
                                    }, function (tween) {
                                        if (_this.cursor && targetBounds_1.width) {
                                            var cursorPos = _this.cursor.getElem().offset();
                                            cursorPos.top += targetBounds_1.height - thisSubject_2.getHeight();
                                            cursorPos.left += targetBounds_1.width - thisSubject_2.getWidth();
                                            _this.cursor.moveTo(cursorPos, null, animDurr_2, 24);
                                        }
                                        difW_2 = (targetBounds_1.width ? (targetBounds_1.width - thisSubject_2.getWidth()) : 0) / tween.numKeyframes;
                                        difH_2 = (targetBounds_1.height ? (targetBounds_1.height - thisSubject_2.getHeight()) : 0) / tween.numKeyframes;
                                    }, function () {
                                        thisSubject_2.elem.trigger('resize');
                                        _this.handleEvent('item-plugin-' + parts[2] + '-resize-end', thisSubject_2);
                                        _this.performInProgress = false;
                                        _this.handleAutoAdvance();
                                    }).start();
                                    return { value: void 0 };
                                }
                            }
                            else if (parts[3] === 'move') {
                                var subject = (this_4.performStack.length > 0) ? this_4.performStack[this_4.performStack.length - 1] : null;
                                if (this_4.cursorGoElem(step, subject, 'move'))
                                    return { value: void 0 };
                                this_4.handleEvent('item-plugin-' + parts[2] + '-move-start', subject);
                                if (step.forceBounds && subject) {
                                    var targetBounds_2 = step.forceBounds, thisSubject_3 = subject, difX_1 = 0, difY_1 = 0, animDurr_3 = this_4.scenario.animDuration;
                                    if (this_4.timerHandles.moveTween)
                                        this_4.timerHandles.moveTween.dispose();
                                    this_4.timerHandles.moveTween = new AnimTween_3.AnimTween(animDurr_3, 24, function () {
                                        var subjectPos = thisSubject_3.getLocation();
                                        thisSubject_3.setLocation(subjectPos.left + difX_1, subjectPos.top + difY_1);
                                    }, function (tween) {
                                        var parent = thisSubject_3.getParent();
                                        var cursorPos = new Scenario_2.BoundableElement('', _this.getTargetCanvas(step, (parent ? parent.id : null)), targetBounds_2, true);
                                        cursorPos.left += 10;
                                        cursorPos.top += 10;
                                        if (_this.cursor)
                                            _this.cursor.moveTo(cursorPos, null, animDurr_3, 24);
                                        var subjectPos = thisSubject_3.getLocation();
                                        difX_1 = ((targetBounds_2.left && typeof targetBounds_2.left === 'number')
                                            ? (targetBounds_2.left - subjectPos.left)
                                            : 0) / tween.numKeyframes;
                                        difY_1 = ((targetBounds_2.top && typeof targetBounds_2.top === 'number')
                                            ? (targetBounds_2.top - subjectPos.top)
                                            : 0) / tween.numKeyframes;
                                    }, function () {
                                        _this.handleEvent('item-plugin-' + parts[2] + '-move-end', thisSubject_3);
                                        _this.performInProgress = false;
                                        _this.handleAutoAdvance();
                                    }).start();
                                    return { value: void 0 };
                                }
                            }
                            else if (parts[3] === 'edit') {
                                var act = (parts.length > 4) ? parts[4] : '';
                                var subject = this_4.currElemSubject;
                                if (subject) {
                                    var defValue = (step.defaultContent && ('value' in step.defaultContent) ? step.defaultContent.value : '1234');
                                    if (parts[2] == 'TextArea') {
                                        if (act === 'select') {
                                            if (this_4.cursorGoElem(step, subject))
                                                return { value: void 0 };
                                            subject.selectAll();
                                        }
                                        else if (act === 'text') {
                                            subject.insertText(defValue, true);
                                        }
                                        else if (act === 'cmd') {
                                            if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, step.objectives[i]))
                                                return { value: void 0 };
                                            subject.execCommand(parts[5]);
                                        }
                                        else {
                                            if (parts[4] == 'start') {
                                                if (this_4.cursorGoElem(step, subject))
                                                    return { value: void 0 };
                                                subject.showEditor(0, 0);
                                            }
                                            if (parts[4] == 'end') {
                                                if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, step.objectives[i]))
                                                    return { value: void 0 };
                                                subject.hideEditor();
                                            }
                                        }
                                    }
                                }
                            }
                            else if (parts[3] === 'prop' || parts[3] === 'menu') {
                                var subject = this_4.currElemSubject;
                                if (subject) {
                                    var defValue = (step.defaultContent && ('value' in step.defaultContent) ? step.defaultContent.value : '1234');
                                    if (parts[4] === 'open') {
                                        if (this_4.cursorGoElem(step, subject, 'prop'))
                                            return { value: void 0 };
                                        subject.comProperties();
                                    }
                                    else if (parts[4] === 'close') {
                                        if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, step.objectives[i]))
                                            return { value: void 0 };
                                        subject.closeComProperties();
                                    }
                                    else if (parts[4] === 'apply') {
                                        if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, step.objectives[i]))
                                            return { value: void 0 };
                                        subject.applyComProperties();
                                    }
                                    else if (parts[4] === 'tab') {
                                        if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, step.objectives[i]))
                                            return { value: void 0 };
                                        var field = subject.comPropertiesField(parts[4] + '-' + parts[5]);
                                        if (field) {
                                            field.select();
                                            HelpSystemPlayer.notify('item-plugin-' + parts[2] + '-prop-' + parts[4] + '-' + parts[5], subject);
                                        }
                                    }
                                    else if (parts[4] === 'urlLink' && parts[2] == 'Picture') {
                                        if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, step.objectives[i]))
                                            return { value: void 0 };
                                        var field = subject.comPropertiesField(parts[4]);
                                        if (field) {
                                            field.setValue({ type: 'url', url: defValue });
                                            HelpSystemPlayer.notify('item-plugin-' + parts[2] + '-prop-' + parts[4] + '-change', subject);
                                        }
                                    }
                                    else if (parts[4] === 'linkTypeEnlarge' && parts[2] == 'Picture') {
                                        if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, step.objectives[i]))
                                            return { value: void 0 };
                                        var field = subject.comPropertiesField(parts[4]);
                                        if (field) {
                                            field.setValue(true);
                                            HelpSystemPlayer.notify('item-plugin-' + parts[2] + '-prop-' + parts[4] + '-change', subject);
                                        }
                                    }
                                    else {
                                        var propName = void 0, actName = void 0;
                                        if (parts[3] !== 'prop') {
                                            propName = parts[3] + '-' + parts[4] + ((parts[3] === 'menu') ? ((parts.length > 5) ? ('-' + parts[5]) : '') : '');
                                            actName = ((parts[3] === 'menu') ? parts[6] : parts[5]);
                                        }
                                        else {
                                            propName = parts[4];
                                            actName = parts[5];
                                        }
                                        if (parts[2] == 'Menu') {
                                            if (propName === 'menu-new-apply' || propName === 'menu-edit-apply' || propName.match(/^menu\-edit\-select\:[0-9]+$/)) {
                                                if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, propName))
                                                    return { value: void 0 };
                                                subject.applyComProperties(parts[3] + '-' + parts[4] + ((parts.length > 5) ? ('-' + parts[5]) : ''));
                                                return "continue";
                                            }
                                            else if (propName === 'menu-new') {
                                                if (this_4.cursorGoElem(step, subject, 'prop'))
                                                    return { value: void 0 };
                                                subject.openEditMenuItems(true);
                                                return "continue";
                                            }
                                            else if (propName === 'menu-edit') {
                                                if (this_4.cursorGoElem(step, subject, 'prop'))
                                                    return { value: void 0 };
                                                subject.openEditMenuItems(false);
                                                return "continue";
                                            }
                                        }
                                        var multi = step.objectives[i].match(/^.+\-bg[^\-]+\-change$/) ? true : false;
                                        if (this_4.selfTip && this_4.cursorGoControl(step, this_4.selfTip.subject, propName, multi))
                                            return { value: void 0 };
                                        var field = subject.comPropertiesField(propName);
                                        if (field && actName === 'click') {
                                            field.trigger('click');
                                        }
                                        else if (field) {
                                            if (parts[2] == 'Shape' && propName === 'borderRadius' && typeof defValue !== 'object') {
                                                field.setValue({ lt: defValue, rt: defValue, rb: defValue, lb: defValue });
                                            }
                                            else {
                                                field.setValue(defValue);
                                            }
                                            if (parts[2] == 'Picture' && (propName === 'sizeW' || propName === 'sizeH')) {
                                                field.trigger('change');
                                            }
                                            else if (parts[2] == 'GoogleMaps' && propName === 'gmapAddress') {
                                                var gmap = subject.comPropertiesField('gmap');
                                                if (gmap && step.defaultContent && ('ll' in step.defaultContent)) {
                                                    gmap.setLatLng(step.defaultContent.ll);
                                                }
                                            }
                                            else if (parts[2] == 'GoogleMaps' && propName === 'gmapZoomLevel') {
                                                field.trigger('change');
                                            }
                                            else if (parts[2] == 'Youtube' && propName === 'videoId') {
                                                field.trigger('paste');
                                            }
                                            else if (parts[2] == 'Form') {
                                                field.trigger('change');
                                            }
                                            HelpSystemPlayer.notify('item-plugin-' + parts[2]
                                                + ((parts[3] === 'prop') ? ('-' + parts[3]) : '')
                                                + '-' + propName + '-' + actName, subject);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (parts[0] === 'toolbar') {
                        if (parts[1] === 'plugin') {
                            var subject = this_4.resolveTargetPath(step.subject, []);
                            if (parts[3] == 'open') {
                                if (subject) {
                                    if (this_4.cursorGoControl(step, subject, step.objectives[i]))
                                        return { value: void 0 };
                                    var buttons = subject.elem.children('a, button, .btn');
                                    if (buttons.length > 0) {
                                        buttons.first().trigger('mouseover');
                                    }
                                    else {
                                        subject.elem.trigger('mouseover');
                                    }
                                }
                            }
                        }
                        else if (parts[1] === 'ctrl') {
                            var subject = this_4.resolveTargetPath(step.subject, []);
                            if (parts[3] == 'click') {
                                if (subject) {
                                    if (this_4.cursorGoControl(step, subject, step.objectives[i]))
                                        return { value: void 0 };
                                    var buttons = subject.elem.children('a, button, .btn');
                                    if (buttons.length > 0) {
                                        buttons.first().trigger('click');
                                    }
                                    else {
                                        subject.elem.trigger('click');
                                    }
                                    if (this_4.autoAdvance)
                                        this_4.handleEvent(step.objectives[i]);
                                }
                            }
                        }
                    }
                    else if (parts[0] === 'config') {
                        if (parts[1] === 'background') {
                            var subject = this_4.resolveTargetPath(step.subject, []);
                            var multi = step.objectives[i].match(/^.+\-bgPage\-change$/) ? true : false;
                            if (subject && this_4.cursorGoControl(step, subject, step.objectives[i], multi))
                                return { value: void 0 };
                            var autoId = parts[0] + '-' + parts[1];
                            if (parts[2] === 'open') {
                                this_4.subjectMap[autoId] = builder.site.changeBackground();
                            }
                            else if (parts[2] === 'apply') {
                                var dialog = this_4.subjectMap[autoId];
                                if (dialog)
                                    dialog.propertyDialogApply(true);
                            }
                            else if (parts[2] === 'prop') {
                                var dialog = this_4.subjectMap[autoId];
                                if (dialog) {
                                    var prop = dialog.propertyDialogField(parts[3]);
                                    if (parts[4] === 'change') {
                                        if (prop) {
                                            var val = prop.getValue();
                                            if (step.defaultContent && ('value' in step.defaultContent)) {
                                                val = step.defaultContent.value;
                                            }
                                            prop.setValue(val);
                                            if (parts[3] === 'bgPage' && this_4.canvas && val && val.css) {
                                                this_4.canvas.elem.css(val.css);
                                                if (this_4.canvas.elem.get(0).style.backgroundColor === 'transparent') {
                                                    this_4.canvas.elem.css({ backgroundColor: '#ffffff' });
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                };
                var this_4 = this;
                for (var i = (step.objectives.length - 1); i >= 0; i--) {
                    var state_1 = _loop_6(i);
                    if (typeof state_1 === "object")
                        return state_1.value;
                }
            }
            else {
                this.next();
            }
            this.performInProgress = false;
            if (this.debug)
                console.log('performing step done');
            this.handleAutoAdvance();
        };
        HelpSystemPlayer.prototype.handleAutoAdvance = function () {
            var _this = this;
            if (!this.scenario)
                return;
            if (this.debug)
                console.log('try auto advance', this.autoAdvance, this.performInProgress);
            if (this.autoAdvance && !this.performInProgress) {
                if (this.debug)
                    console.log('auto advance', this.audio);
                if (this.waitForAudio && this.audio && !this.audio.ended) {
                    if (this.debug)
                        console.log('wait for audio', this.audio);
                    this.audio.addEventListener('ended', function () {
                        if (!_this.scenario)
                            return;
                        if (_this.debug)
                            console.log('wait for audio done - advance');
                        if (_this.timerHandles.stepDelay)
                            clearTimeout(_this.timerHandles.stepDelay);
                        _this.timerHandles.stepDelay = setTimeout(function () { return _this.perform(_this.autoAdvance); }, _this.scenario.stepDelay);
                    });
                }
                else {
                    if (this.debug)
                        console.log('advance');
                    if (this.timerHandles.stepDelay)
                        clearTimeout(this.timerHandles.stepDelay);
                    this.timerHandles.stepDelay = setTimeout(function () { return _this.perform(_this.autoAdvance); }, this.scenario.stepDelay);
                }
            }
        };
        HelpSystemPlayer.prototype.next = function () {
            if (!this.scenario || this.stepIndex < 0)
                return;
            if ((this.scenario.steps.length - 1) <= this.stepIndex) {
                this.controls.setEndState(true, true);
                this.clearStep();
                this.autoAdvance = false;
            }
            else {
                this.clearStep();
                this.stepIndex++;
                this.currElemSubject = null;
                this.controls.setStep(this.stepIndex + 1, this.scenario.steps.length);
                this.handleEvent('scenario-next-step');
                this.handleAutoAdvance();
            }
        };
        HelpSystemPlayer.prototype.setStyle = function (style) {
            if (style === void 0) { style = null; }
            var scenarioStyle, normalStyle;
            for (var _i = 0, _a = builder.site.styles; _i < _a.length; _i++) {
                var style_1 = _a[_i];
                if (style_1.selector === '.wb-stl-scenario') {
                    scenarioStyle = style_1;
                }
                else if (style_1.selector === '.wb-stl-normal') {
                    normalStyle = style_1;
                }
            }
            if (scenarioStyle) {
                var idx = builder.site.styles.indexOf(scenarioStyle);
                builder.site.styles.splice(idx, 1);
            }
            if (!style || !normalStyle || !this.scenario || !this.scenario.style) {
                builder.site.updateStyle();
                return;
            }
            scenarioStyle = new Site_1["default"].Style(normalStyle.serialize());
            scenarioStyle.name = 'Scenario';
            scenarioStyle.selector = '.wb-stl-scenario';
            if (this.scenario.style.color) {
                scenarioStyle.rules.color = this.scenario.style.color;
                if (!scenarioStyle.sys.text)
                    scenarioStyle.sys.text = {};
                scenarioStyle.sys.text.color = this.scenario.style.color;
            }
            builder.site.styles.push(scenarioStyle);
            builder.site.updateStyle();
        };
        HelpSystemPlayer.prototype.start = function (doNotCallEnd, autoPlay, useCanvas, useMoreCanvas, doneCallback) {
            var _this = this;
            if (doNotCallEnd === void 0) { doNotCallEnd = false; }
            if (autoPlay === void 0) { autoPlay = false; }
            if (useCanvas === void 0) { useCanvas = false; }
            if (useMoreCanvas === void 0) { useMoreCanvas = false; }
            if (doneCallback === void 0) { doneCallback = null; }
            this.playToggleLock = false;
            if (!this.scenario || this.scenario.steps.length === 0)
                return;
            if (!doNotCallEnd)
                this.end();
            this.doneCallback = doneCallback;
            if (autoPlay) {
                this.autoAdvance = true;
                this.controls.getFields().nextBtn.setEnabled(false);
                this.controls.getFields().playBtn.getElem().attr({ attr: __('Stop') });
                this.controls.getFields().playBtn.setIcon('fa fa-pause');
            }
            if (useCanvas) {
                this.canvas = new PlayerCanvas_1.PlayerCanvas(useMoreCanvas);
                var step_2, opacity_2 = 0, thisCanvas_1 = this.canvas;
                new AnimTween_3.AnimTween(300, 24, function () { opacity_2 += step_2; thisCanvas_1.elem.css({ opacity: opacity_2 }); }, function (tween) { thisCanvas_1.elem.css({ opacity: opacity_2 }); step_2 = 1.0 / tween.numKeyframes; }, function (tween) { tween.dispose(); }).start();
            }
            else if (this.canvas) {
                this.canvas.dispose();
                this.canvas = null;
            }
            if (this.scenario.requireSpace && this.scenario.requireSpace > 0) {
                var clBlocks = {};
                for (var _i = 0, _a = this.scenario.steps; _i < _a.length; _i++) {
                    var step = _a[_i];
                    if (!this.canvas) {
                        if (step.subject == 'config-background-prop-bgPage') {
                            var p = builder.site.getPage(builder.pageId);
                            if (p && p.background && ((p.background.image && p.background.image !== 'none') ||
                                (p.background.color && p.background.color !== 'transparent'))) {
                                p.background = { css: { background: '' } };
                            }
                            builder.bodyInstance.bgSite = { css: { background: '' } };
                            builder.bodyInstance.updateStyle();
                        }
                    }
                    var block = this.getTargetCanvas(step);
                    if (block.id in clBlocks)
                        continue;
                    clBlocks[block.id] = true;
                    for (var _b = 0, _c = block.getElements(); _b < _c.length; _b++) {
                        var elem = _c[_b];
                        block.removeElement(elem, true);
                    }
                    if (!this.canvas) {
                        if (block.isFlexible) {
                            var ElemType = ElementRegister_5["default"].getClassByName('Shape');
                            var el = new ElemType({ content: { opacity: 0.1 } }, true);
                            el.setSize(10, 10);
                            el.setLocation(0, this.scenario.requireSpace);
                            block.addElement(el);
                        }
                    }
                    else {
                        break;
                    }
                }
            }
            this.stepIndex = 0;
            this.stepParams = [];
            this.forceList = [];
            this.performStack = [];
            this.vDesktop = $('<div>')
                .css({
                position: 'fixed',
                left: -1,
                top: ($(window).height() / 2),
                width: 1,
                height: 1,
                zIndex: 999,
                overflow: 'visible'
            })
                .appendTo(document.body);
            this.cursor = new VirtualCursor_1.VirtualCursor();
            $(document.body).append(this.cursor.getElem());
            this.hotkeysEnabled = true;
            this.subjectMap = {};
            this.currElemSubject = null;
            this.controls.setEndState(false);
            this.controls.setSpeed(3);
            this.controls.setStep(this.stepIndex + 1, this.scenario.steps.length);
            this.controls.setVisible(true);
            if (this.scenario.audio) {
                if (this.bgAudio)
                    this.bgAudio.pause();
                this.bgAudio = new Audio((this.scenario.baseUrl ? this.scenario.baseUrl : '') + this.scenario.audio);
                this.bgAudio.loop = true;
                this.bgAudio.onload = function () {
                    if (_this.bgAudio)
                        _this.bgAudio.play();
                };
                this.bgAudio.onerror = function () {
                    if (!_this.scenario)
                        return;
                    console.error("Failed to load audio: " + _this.scenario.audio);
                };
                this.bgAudio.load();
                this.bgAudio.play();
            }
            if (this.scenario.style)
                this.setStyle(this.scenario.style);
            this.handleEvent('scenario-start');
            var ea = new BuilderEvent_9.VisibilityChangedBuilderEvent(true);
            BuilderEvent_9.GlobalEvents.triggerEvent("help.playershow", ea);
        };
        HelpSystemPlayer.prototype.end = function () {
            if (!this.scenario)
                return;
            if (this.doneCallback) {
                this.doneCallback.call(this);
                this.doneCallback = null;
            }
            this.clearStep();
            this.stepIndex = -1;
            this.forceList = [];
            this.performInProgress = false;
            if (this.vDesktop) {
                this.vDesktop.remove();
                this.vDesktop = null;
            }
            this.subjectMap = {};
            this.currElemSubject = null;
            this.controls.setVisible(false);
            if (this.bgAudio)
                this.bgAudio.pause();
            this.bgAudio = null;
            if (this.canvas) {
                this.canvas.dispose();
                this.canvas = null;
            }
            if (this.cursor) {
                this.cursor.dispose();
                this.cursor = null;
            }
            this.hotkeysEnabled = false;
            this.handleEvent('scenario-end');
            this.setStyle(null);
            Dialog_11["default"].closeAll();
            if (this.timerHandles.eventDelay)
                clearTimeout(this.timerHandles.eventDelay);
            if (this.timerHandles.stepDelay)
                clearTimeout(this.timerHandles.stepDelay);
            if (this.timerHandles.resizeTween)
                this.timerHandles.resizeTween.dispose();
            if (this.timerHandles.moveTween)
                this.timerHandles.moveTween.dispose();
            var ea = new BuilderEvent_9.VisibilityChangedBuilderEvent(false);
            BuilderEvent_9.GlobalEvents.triggerEvent("help.playerhide", ea);
        };
        HelpSystemPlayer.ANIM_DURATION = 400;
        HelpSystemPlayer.STEP_DELAY = 500;
        return HelpSystemPlayer;
    }());
    exports["default"] = HelpSystemPlayer;
});
define("PreviewToolbar", ["require", "exports", "jquery", "HelpSystem/HelpSystemPlayer", "BuilderEvent"], function (require, exports, $, HelpSystemPlayer_2, BuilderEvent_10) {
    "use strict";
    exports.__esModule = true;
    var PreviewToolbar = (function () {
        function PreviewToolbar(builder) {
            var _this = this;
            this.isOpen = false;
            this.isDebugMode = false;
            this.builder = builder;
            this.body = $('<div>').addClass('wb-preview-body').hide();
            this.bodyCover = $('<div>').addClass('wb-preview-cover').appendTo(this.body).hide();
            this.loaderOverlay = $('<div><div class="ico-spin icon-wb-spinner"></div></div>').addClass('wb-preview-loader-overlay').hide();
            this.iframe = document.createElement('iframe');
            $(this.iframe)
                .attr({ frameborder: '0', scrolling: 'yes' })
                .on('load', function () {
                _this.loaderOverlay.hide();
                _this.updateFramHeight();
                _this.toggleDebugMode(true);
                HelpSystemPlayer_2["default"].notify('preview-loaded', _this);
            });
            this.body.append(this.iframe);
            $(window).on('resize', function () { return _this.updateFramHeight(); });
            var mouse = null, mouseMoved = false;
            this.resizerRight = $('<div>').addClass('wb-preview-sizer-r')
                .on('mousedown', function (e) {
                mouse = { v: _this.body.width(), t: 6, x: e.pageX, y: e.pageY };
                mouseMoved = false;
                _this.bodyCover.show();
            })
                .appendTo(this.body);
            this.resizerLeft = $('<div>').addClass('wb-preview-sizer-l')
                .on('mousedown', function (e) {
                mouse = { v: _this.body.width(), t: 4, x: e.pageX, y: e.pageY };
                mouseMoved = false;
                _this.bodyCover.show();
            })
                .appendTo(this.body);
            $(window)
                .on('mousemove', function (e) {
                if (mouse) {
                    if (mouse.t === 6)
                        _this.body.width(Math.max(mouse.v + (e.pageX - mouse.x) * 2.0, 320));
                    if (mouse.t === 4)
                        _this.body.width(Math.max(mouse.v + (mouse.x - e.pageX) * 2.0, 320));
                    if (!mouseMoved) {
                        mouseMoved = true;
                        HelpSystemPlayer_2["default"].notify('preview-resize-start', _this);
                    }
                    _this.setPreviewWidth(_this.body.width());
                }
            })
                .on('mouseup', function () {
                if (mouseMoved)
                    HelpSystemPlayer_2["default"].notify('preview-resize-end', _this);
                mouse = null;
                mouseMoved = false;
                _this.bodyCover.hide();
            });
            this.builder.body.before(this.body);
            this.builder.body.before(this.loaderOverlay);
            this.bodySize = { width: 320, height: 200 };
            this.setVisible(false);
        }
        PreviewToolbar.prototype.toggleDebugMode = function (keep) {
            if (keep === void 0) { keep = false; }
            if (!keep)
                this.isDebugMode = !this.isDebugMode;
            if (!this.iframe.contentDocument)
                return;
            if (this.isDebugMode) {
                $(this.iframe.contentDocument.body).addClass('wb-site-debug');
            }
            else {
                $(this.iframe.contentDocument.body).removeClass('wb-site-debug');
            }
        };
        PreviewToolbar.prototype.updateFramHeight = function () {
            if (!this.bodySize || !this.body)
                return;
            this.bodySize.height = $(window).height() - this.body.position().top;
            if (!this.iframe || (typeof this.iframe.contentDocument !== 'object')
                || (!this.iframe.contentDocument || typeof this.iframe.contentDocument.body !== 'object'))
                return;
            var h = this.iframe.contentDocument ? $(this.iframe.contentDocument.body).height() : 0;
            if (h > 0) {
                if (this.bodySize.height > h)
                    this.bodySize.height = h;
                this.updateBody();
            }
        };
        PreviewToolbar.prototype.updateBody = function () {
            this.body.css({
                width: this.bodySize.width,
                height: this.bodySize.height
            });
        };
        PreviewToolbar.prototype.setVisible = function (visible) {
            var ea = new BuilderEvent_10.VisibilityChangedBuilderEvent(visible);
            BuilderEvent_10.GlobalEvents.triggerEvent(visible ? "preview.show" : "preview.hide", ea);
            if (visible && this.builder && this.builder.bodyInstance) {
                this.setPreviewWidth(this.builder.bodyInstance.getSiteSize().width);
            }
            return this;
        };
        PreviewToolbar.prototype.open = function () {
            if (!this.isOpen) {
                this.isOpen = true;
                this.builder.body.hide();
                this.setVisible(true);
                this.loaderOverlay.show();
                this.body.show();
                this.updateBody();
                $(document.body).css({ backgroundColor: '#aaaaaa' });
                this.builder.bodyInstance.elementBoxSetVisible(false);
                HelpSystemPlayer_2["default"].notify('preview-open', this);
            }
            return this.iframe.contentWindow;
        };
        PreviewToolbar.prototype.close = function () {
            if (this.isOpen) {
                this.isOpen = false;
                this.setVisible(false);
                this.body.hide();
                this.loaderOverlay.hide();
                this.builder.body.show();
                $(document.body).css({ backgroundColor: '#ffffff' });
                this.builder.bodyInstance.elementBoxSetVisible(true);
                HelpSystemPlayer_2["default"].notify('preview-close', this);
            }
        };
        PreviewToolbar.prototype.getResizerElement = function (left) {
            if (left === void 0) { left = false; }
            return left ? this.resizerLeft : this.resizerRight;
        };
        PreviewToolbar.prototype.setPreviewWidth = function (width) {
            if (!this.bodySize)
                return;
            this.bodySize.width = width;
            this.updateBody();
            this.updateFramHeight();
            BuilderEvent_10.GlobalEvents.triggerEvent('preview.size.changed', new BuilderEvent_10.PreviewSizeChangedEvent(width));
        };
        PreviewToolbar.init = function (builder) {
            var tb = new PreviewToolbar(builder);
            return tb;
        };
        return PreviewToolbar;
    }());
    exports["default"] = PreviewToolbar;
});
define("PreloaderMonitorUrl", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var PreloaderMonitorUrl = (function () {
        function PreloaderMonitorUrl(url, method) {
            this.url = "";
            this.method = "get";
            this.opts = {};
            if (url)
                this.url = url;
            if (method)
                this.method = method;
        }
        return PreloaderMonitorUrl;
    }());
    exports.PreloaderMonitorUrl = PreloaderMonitorUrl;
});
define("ProgressBar", ["require", "exports", "UIComponent", "jquery"], function (require, exports, UIComponent_18, $) {
    "use strict";
    exports.__esModule = true;
    var ProgressBarType;
    (function (ProgressBarType) {
        ProgressBarType["Default"] = "default";
        ProgressBarType["Info"] = "info";
        ProgressBarType["Success"] = "success";
        ProgressBarType["Warning"] = "warning";
        ProgressBarType["Danger"] = "danger";
    })(ProgressBarType = exports.ProgressBarType || (exports.ProgressBarType = {}));
    var ProgressBar = (function (_super) {
        __extends(ProgressBar, _super);
        function ProgressBar() {
            var _this = _super.call(this) || this;
            _this.parts = {};
            return _this;
        }
        ProgressBar.prototype._createElem = function () {
            var elem = $('<div class="progress wb-progress-bar">');
            this.container = $('<div class="wb-progress-bar-cont">').css({
                "white-space": "nowrap",
                overflow: "hidden"
            });
            elem.append(this.container);
            return elem;
        };
        ProgressBar.prototype.setValue = function (value) {
            this.setProgress(ProgressBarType.Default, value);
        };
        ProgressBar.prototype.setText = function (text) {
            if (!this.textOver) {
                this.textOver = $('<div class="wb-progress-bar-text wb-pbt-over">');
                this.textUnder = $('<div class="wb-progress-bar-text wb-pbt-under">');
                this.container.append(this.textOver);
                this.getElem().append(this.textUnder);
            }
            this.textOver.text(text);
            this.textUnder.text(text);
        };
        ProgressBar.prototype.setProgress = function (type, percent) {
            var key = type;
            var $bar;
            var total = 0;
            if (this.parts.hasOwnProperty(key)) {
                $bar = this.parts[key];
            }
            else {
                $bar = $('<div class="wb-progress-bar-part progress-bar progress-bar-' + type + ' progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">');
                this.container.append($bar);
                this.parts[key] = $bar;
            }
            $bar.attr("aria-valuenow", percent).data("value", percent);
            for (key in this.parts) {
                if (this.parts.hasOwnProperty(key))
                    total += this.parts[key].data("value");
            }
            this.container.css({ width: total + "%" });
            if (total > 0) {
                for (key in this.parts) {
                    if (this.parts.hasOwnProperty(key))
                        this.parts[key].css({ width: (total ? (100 * this.parts[key].data("value") / total) : 0) + "%" });
                }
            }
        };
        return ProgressBar;
    }(UIComponent_18.UIComponent));
    exports.ProgressBar = ProgressBar;
});
define("TaskProgressDialog", ["require", "exports", "Dialog", "Service", "ProgressBar", "VerticalLayout", "FlowLayout"], function (require, exports, Dialog_12, Service_25, ProgressBar_1, VerticalLayout_14, FlowLayout_7) {
    "use strict";
    exports.__esModule = true;
    var TaskProgressStepState;
    (function (TaskProgressStepState) {
        TaskProgressStepState["Pending"] = "pending";
        TaskProgressStepState["Active"] = "active";
        TaskProgressStepState["Done"] = "done";
    })(TaskProgressStepState || (TaskProgressStepState = {}));
    var TaskProgressFields = (function () {
        function TaskProgressFields() {
        }
        return TaskProgressFields;
    }());
    var MonitoringInterval = 3000;
    var TaskProgressDialog = (function (_super) {
        __extends(TaskProgressDialog, _super);
        function TaskProgressDialog(title) {
            var _this = _super.call(this, title, true) || this;
            _this.monitorOptions = null;
            _this.monitorTimer = null;
            _this.monitorXHR = null;
            _this.monitorResult = null;
            _this.tasks = {};
            _this.retryTimer = null;
            _this.isActivatedManually = false;
            var uiDef = { type: VerticalLayout_14.VerticalLayout, children: [
                    { type: 'CustomContainer', id: "preloader", styleClass: "fa fa-spinner fa-spin" },
                    { type: VerticalLayout_14.VerticalLayout, id: "container", children: [] },
                    { type: 'CustomContainer', id: "errorMessage", visible: false, styleClass: 'alert alert-danger', tag: 'div', content: '' },
                    { type: 'CustomContainer', id: "retryCountdown", visible: false, styleClass: "text-center", tag: "div", content: "" }
                ] };
            var ui = {};
            _this.content.empty();
            Service_25["default"].UIBuilder.buildLayout(uiDef, _this.content, ui);
            _this.preloader = ui.preloader;
            _this.container = ui.container;
            _this.errorMessage = ui.errorMessage;
            _this.retryCountdown = ui.retryCountdown;
            var thisClass = _this;
            _this.addButton(__("Close"), function () {
                if ($(this).is(".disabled"))
                    return;
                thisClass.reset();
                thisClass.setVisible(false);
                if (!thisClass.isActivatedManually && !thisClass.monitorResult)
                    wb_builder.initPage();
            });
            return _this;
        }
        TaskProgressDialog.prototype.reset = function () {
            this.preloader.setVisible(true);
            this.container.removeAllChildren();
            this.tasks = {};
            this.monitorResult = null;
            this.errorMessage.getElem().text("");
            this.errorMessage.setVisible(false);
            this.retryCountdown.setVisible(false);
            if (this.retryTimer !== null)
                clearTimeout(this.retryTimer);
            this.retryTimer = null;
        };
        TaskProgressDialog.prototype.monitor = function (options) {
            this.reset();
            this.monitorOptions = options;
            this.xButton.addClass("hidden");
            this.buttons.find("button").addClass("disabled");
            this.doMonitorLoop();
        };
        TaskProgressDialog.prototype.doMonitorLoop = function () {
            if (!this.monitorOptions)
                return;
            this.monitorTimer = null;
            this.monitorXHR = $.ajax({
                url: this.monitorOptions.url,
                data: this.monitorOptions.data ? this.monitorOptions.data : {},
                type: "post",
                dataType: "json",
                async: true,
                success: (function (data) {
                    this.monitorXHR = null;
                    this.preloader.setVisible(false);
                    this.onSuccess(data);
                }).bind(this),
                error: (function (jqXHR, textStatus, errorThrown) {
                    this.monitorXHR = null;
                    this.preloader.setVisible(false);
                    if (textStatus !== "abort")
                        this.onError(errorThrown, true);
                }).bind(this)
            });
        };
        TaskProgressDialog.prototype.onSuccess = function (response) {
            if (!this.monitorOptions)
                return;
            if (typeof response.complete !== "boolean") {
                this.onError("Bad response received", true);
                return;
            }
            if (response.error) {
                this.onError(response.error, false);
                return;
            }
            if (response.steps) {
                for (var key in response.steps) {
                    this.updateStep(key, response.steps[key]);
                }
            }
            if (response.complete)
                this.onComplete();
            else
                this.monitorTimer = setTimeout(this.doMonitorLoop.bind(this), MonitoringInterval);
        };
        TaskProgressDialog.prototype.onComplete = function () {
            if (!this.monitorOptions)
                return;
            this.monitorResult = true;
            if (typeof this.monitorOptions.onComplete === "function")
                this.monitorOptions.onComplete();
            this.stopMonitoring();
        };
        TaskProgressDialog.prototype.onError = function (error, isNetworkError) {
            if (!this.monitorOptions)
                return;
            if (isNetworkError)
                this.monitorTimer = setTimeout(this.doMonitorLoop.bind(this), 30000);
            else {
                this.monitorResult = false;
                if (typeof this.monitorOptions.onError === "function")
                    this.monitorOptions.onError(error);
                else
                    this.setError(error);
                this.stopMonitoring();
            }
        };
        TaskProgressDialog.prototype.isMonitoring = function () {
            return this.monitorOptions !== null;
        };
        TaskProgressDialog.prototype.stopMonitoring = function () {
            if (this.monitorTimer) {
                clearTimeout(this.monitorTimer);
                this.monitorTimer = null;
            }
            if (this.monitorXHR) {
                this.monitorXHR.abort();
                this.monitorXHR = null;
            }
            this.monitorOptions = null;
            this.xButton.removeClass("hidden");
            this.buttons.find("button").removeClass("disabled");
        };
        TaskProgressDialog.prototype.updateStep = function (key, data) {
            var fields;
            if (!this.tasks.hasOwnProperty(key)) {
                fields = new TaskProgressFields();
                Service_25["default"].UIBuilder.buildLayout({ type: "HorizontalLayout", styleClass: "wb-lay-no-mb", columnWeights: [6, 6], columnWeightsSmall: [12, 12], css: { marginBottom: 15 }, children: [
                        { type: FlowLayout_7.FlowLayout, styleClass: "wb-lay-no-mb", children: [
                                { type: "CustomContainer", id: "icon", styleClass: "fa fa-hourglass", tag: "i", width: 30 },
                                { type: "Label", id: "text", css: { "font-weight": "normal" }, text: data.text },
                            ] },
                        { type: "HorizontalLayout", styleClass: "wb-lay-no-mb", css: { minHeight: 20 }, children: [
                                { type: "ProgressBar", id: "progress" }
                            ] }
                    ] }, this.container, fields);
                this.tasks[key] = fields;
            }
            else
                fields = this.tasks[key];
            fields.text.setText(data.text);
            if (data.state == TaskProgressStepState.Pending) {
                fields.icon.getElem().attr("class", "fa fa-hourglass-half").css({ color: "#AAA" });
                fields.progress.setVisible(false);
            }
            else {
                fields.progress.setVisible(true);
                if (data.progressText)
                    fields.progress.setText(data.progressText);
                if (data.state == TaskProgressStepState.Active) {
                    fields.icon.addClass("fa-play-circle");
                    fields.icon.getElem().attr("class", "fa fa-spinner fa-spin").css({ color: "#377BB5" });
                    fields.progress.setProgress(ProgressBar_1.ProgressBarType.Default, data.progress);
                    fields.progress.setProgress(ProgressBar_1.ProgressBarType.Success, 0);
                }
                else {
                    fields.icon.addClass("fa-check-circle");
                    fields.icon.getElem().attr("class", "fa fa-check-circle").css({ color: "#0A0" });
                    fields.progress.setProgress(ProgressBar_1.ProgressBarType.Default, 0);
                    fields.progress.setProgress(ProgressBar_1.ProgressBarType.Success, data.progress);
                }
            }
        };
        TaskProgressDialog.prototype.setError = function (message) {
            this.preloader.setVisible(false);
            this.errorMessage.getElem().text(message);
            this.errorMessage.setVisible(true);
        };
        TaskProgressDialog.prototype.retry = function (timeout, data, retriesLeft) {
            var _this = this;
            if (this.retryTimer !== null)
                return;
            this.retryCountdown.setVisible(true);
            var seconds = timeout;
            var importData = data;
            var retries = retriesLeft;
            var countdown = function () {
                if (seconds > 0) {
                    _this.retryCountdown.getElem().text(__("Retrying in %s seconds").replace("%s", seconds.toString()));
                    seconds--;
                    _this.retryTimer = setTimeout(countdown, 1000);
                }
                else {
                    Service_25["default"].websiteImporter.importWebsite(importData, retries, false);
                    _this.retryTimer = null;
                }
            };
            countdown();
        };
        return TaskProgressDialog;
    }(Dialog_12["default"]));
    exports.TaskProgressDialog = TaskProgressDialog;
});
define("WebsiteImporter", ["require", "exports", "TaskProgressDialog", "Service", "Confirm"], function (require, exports, TaskProgressDialog_1, Service_26, Confirm_4) {
    "use strict";
    exports.__esModule = true;
    var IMPORT_RETRY_TIMEOUT = 15;
    var WebsiteImportOptions = (function () {
        function WebsiteImportOptions() {
        }
        return WebsiteImportOptions;
    }());
    exports.WebsiteImportOptions = WebsiteImportOptions;
    var WebsiteImporterModule = (function () {
        function WebsiteImporterModule() {
        }
        WebsiteImporterModule.prototype.resetProgress = function () {
            this.taskProgressDialog.reset();
            this.taskProgressDialog.setVisible(true);
        };
        WebsiteImporterModule.prototype.openPreloader = function () {
            if (!this.taskProgressDialog) {
                this.taskProgressDialog = new TaskProgressDialog_1.TaskProgressDialog(__("Import website"));
                this.resetProgress();
            }
        };
        WebsiteImporterModule.prototype.checkUrl = function (url) {
            return (/^https?:\/\/[a-zA-Z0-9\u0080-\uFFFF]([a-zA-Z0-9\u0080-\uFFFF\-]*[a-zA-Z0-9\u0080-\uFFFF])?(\.[a-zA-Z0-9\u0080-\uFFFF]([a-zA-Z0-9\u0080-\uFFFF\-]*[a-zA-Z0-9\u0080-\uFFFF])?)+(:[0-9]+)?(\/|\?|#|$)/.test(url));
        };
        WebsiteImporterModule.prototype.importWebsite = function (data, allowRetryCount, isManual) {
            var thisImporter = this;
            this.lastImportData = data;
            this.retriesLeft = Math.max(allowRetryCount, 0);
            this.openPreloader();
            this.resetProgress();
            if (isManual)
                this.taskProgressDialog.isActivatedManually = isManual;
            $.ajax({
                url: WB_IMPORT_URL + '?sess=' + wb_builder.sessUniqKey,
                data: data,
                type: 'post',
                dataType: 'json',
                async: true,
                success: function (resp) {
                    if (("success" in resp) && resp.success) {
                        thisImporter.showProgress();
                    }
                    else if (("error" in resp)) {
                        thisImporter.showError({ allowRetry: false, message: resp.error });
                    }
                    else {
                        thisImporter.showError({ allowRetry: true, message: __("Import service is currently unavailable. Please try again later.") });
                    }
                },
                error: function () {
                    thisImporter.showError({ allowRetry: true, message: __("Import service is currently unavailable. Please try again later.") });
                }
            });
        };
        WebsiteImporterModule.prototype.showProgress = function () {
            this.openPreloader();
            if (!this.taskProgressDialog.isMonitoring()) {
                this.taskProgressDialog.monitor({
                    url: WB_IMPORT_STATUS_URL + '?sess=' + wb_builder.sessUniqKey,
                    onComplete: this.onImportDone.bind(this),
                    onError: this.showError.bind(this)
                });
            }
        };
        WebsiteImporterModule.prototype.showError = function (error) {
            this.openPreloader();
            this.taskProgressDialog.setError(error.message);
            if (error.allowRetry && this.lastImportData && this.retriesLeft > 0)
                this.taskProgressDialog.retry(IMPORT_RETRY_TIMEOUT, this.lastImportData, this.retriesLeft - 1);
        };
        WebsiteImporterModule.prototype.onImportDone = function () {
            var _this = this;
            setTimeout(function () {
                _this.taskProgressDialog.setVisible(false);
                wb_builder.loadPage(1, true);
            }, 500);
        };
        WebsiteImporterModule.prototype.onBuilderInit = function (status) {
            if (!status)
                return false;
            if (status.importing) {
                if (status.importData) {
                    this.lastImportData = status.importData;
                    this.retriesLeft = 1;
                }
                this.showProgress();
            }
            else if (status.error)
                this.showError(status.error);
            return true;
        };
        WebsiteImporterModule.prototype.showImportDialog = function () {
            var importFields = {};
            var thisImporter = this;
            var $dlg = $('<div class="wb_change_template_dlg">' +
                '<div class="website-import-form"></div>' +
                '<div class="red">' + __("Your current information will be lost once import is completed.") + '</div>' +
                '</div>');
            Service_26["default"].UIBuilder.buildLayout({ type: "VerticalLayout", css: { margin: "10px 0", textAlign: "left" }, children: [
                    { type: "Label", text: __("URL of a website to import") },
                    { type: "TextField", id: "importUrl", attr: { placeholder: "http://..." } },
                    { type: "HorizontalLayout", ignore: !wb_builder.devTestMode, css: { marginTop: 5 }, children: [
                            { type: "Label", text: "Max Pages" },
                            { type: "TextField", value: 10, id: "maxPages" }
                        ] },
                    { type: "HorizontalLayout", ignore: !wb_builder.devTestMode, css: { marginTop: 5 }, children: [
                            { type: "Label", text: "Max Files" },
                            { type: "TextField", value: 1000, id: "maxFiles" }
                        ] },
                    { type: "HorizontalLayout", ignore: !wb_builder.devTestMode, css: { marginTop: 5 }, children: [
                            { type: "Label", text: "Max Gallery Size (MB)" },
                            { type: "TextField", value: 50, id: "maxGallerySize" }
                        ] },
                    { type: "HorizontalLayout", ignore: !wb_builder.devTestMode, css: { marginTop: 5 }, children: [
                            { type: "Label", text: "Max Image Size (MB)" },
                            { type: "TextField", value: 3, id: "maxImageSize" }
                        ] },
                    { type: "HorizontalLayout", ignore: !wb_builder.devTestMode, css: { marginTop: 5 }, children: [
                            { type: "Label", text: "Max Document Size (MB)" },
                            { type: "TextField", value: 20, id: "maxDocumentSize" }
                        ] }
                ] }, $dlg.find(".website-import-form"), importFields);
            Confirm_4["default"].showDialog(__("Import"), $dlg, [
                {
                    title: __("No, keep current website")
                },
                {
                    title: __("Yes, import website"),
                    cssClass: "btn-danger",
                    validateFunc: (function () {
                        var url = this.importUrl.getValue();
                        this.importUrl.getElem().removeClass("has-error");
                        if (url === "") {
                            this.importUrl.getElem().addClass("has-error");
                            return false;
                        }
                        if (!/^https?:\/\//.test(url))
                            url = "http://" + url;
                        if (!thisImporter.checkUrl(url)) {
                            this.importUrl.getElem().addClass("has-error");
                            return false;
                        }
                        this.importUrl.setValue(url);
                        return true;
                    }).bind(importFields),
                    func: (function ($dlg) {
                        var data = new WebsiteImportOptions();
                        data.url = this.importUrl.getValue();
                        if (wb_builder.devTestMode) {
                            var val = void 0;
                            val = Math.floor(parseFloat(this.maxPages.getValue()));
                            if (!isNaN(val) && val > 0)
                                data.maxPages = val;
                            val = Math.floor(parseFloat(this.maxFiles.getValue()));
                            if (!isNaN(val) && val >= 0)
                                data.maxFiles = val;
                            val = Math.floor(parseFloat(this.maxGallerySize.getValue()) * 1024 * 1024);
                            if (!isNaN(val) && val >= 0)
                                data.maxGallerySize = val;
                            val = Math.floor(parseFloat(this.maxImageSize.getValue()) * 1024 * 1024);
                            if (!isNaN(val) && val >= 0)
                                data.maxImageSize = val;
                            val = Math.floor(parseFloat(this.maxDocumentSize.getValue()) * 1024 * 1024);
                            if (!isNaN(val) && val >= 0)
                                data.maxDocumentSize = val;
                        }
                        thisImporter.importWebsite(data, 1, true);
                    }).bind(importFields, $dlg)
                }
            ], 480);
            if (Confirm_4["default"].dialog)
                Confirm_4["default"].dialog.setCenterButtons(true);
        };
        return WebsiteImporterModule;
    }());
    exports.WebsiteImporterModule = WebsiteImporterModule;
    exports.WebsiteImporter = new WebsiteImporterModule();
    Service_26["default"].websiteImporter = exports.WebsiteImporter;
});
define("PointerTracker", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var defaultOptions = {
        trackMouse: true,
        trackTouches: true,
        allowMultiplePointers: true,
        preventDefaults: true,
        minDragDistance: 1
    };
    var PointerTracker = (function () {
        function PointerTracker(element, options) {
            var _this = this;
            this.pointers = {};
            this.activePointers = 0;
            this.isMultiTouch = null;
            this.options = $.extend({}, defaultOptions, options);
            if (!this.options.trackMouse && !this.options.trackTouches)
                throw new Error("At least trackMouse or trackTouches option must be set to true.");
            if (this.options.trackMouse) {
                element.on("mousedown", function (e) {
                    if (_this.onPointerStart("mouse" + e.which, true, e.target, PointerTracker.getEventPosition(e, e))) {
                        if (_this.options.preventDefaults) {
                            e.stopImmediatePropagation();
                            e.preventDefault();
                        }
                    }
                });
                $(window).on("mousemove", function (e) {
                    for (var i in _this.pointers) {
                        if (_this.pointers.hasOwnProperty(i) && _this.pointers[i].isMouse)
                            _this.onPointerMove(_this.pointers[i].identifier, e.target, PointerTracker.getEventPosition(e, e));
                    }
                });
                $(window).on("mouseup", function (e) {
                    _this.onPointerEnd("mouse" + e.which, e.target, PointerTracker.getEventPosition(e, e));
                });
            }
            if (this.options.trackTouches) {
                element.on("touchstart", function (e) {
                    var oe = e.originalEvent;
                    if (_this.isMultiTouch === null)
                        _this.isMultiTouch = ("identifier" in oe.touches[0]);
                    var touch, touchId, pos, pointerRegistered = false;
                    for (var i = oe.changedTouches.length - 1; i >= 0; i--) {
                        touch = oe.changedTouches[i];
                        touchId = "touch" + (_this.isMultiTouch ? touch.identifier : 0);
                        pos = PointerTracker.getEventPosition(e, touch);
                        if (_this.onPointerStart(touchId, false, e.target, pos))
                            pointerRegistered = true;
                    }
                    if (pointerRegistered && _this.options.preventDefaults) {
                        e.stopImmediatePropagation();
                        e.preventDefault();
                    }
                });
                $(window).on("touchmove", function (e) {
                    var oe = e.originalEvent;
                    var touch, touchId, pos;
                    for (var i = oe.changedTouches.length - 1; i >= 0; i--) {
                        touch = oe.changedTouches[i];
                        touchId = "touch" + (_this.isMultiTouch ? touch.identifier : 0);
                        pos = PointerTracker.getEventPosition(e, touch);
                        _this.onPointerMove(touchId, e.target, pos);
                    }
                });
                $(window).on("touchend touchcancel", function (e) {
                    var oe = e.originalEvent;
                    var touch, touchId, pos;
                    for (var i = oe.changedTouches.length - 1; i >= 0; i--) {
                        touch = oe.changedTouches[i];
                        touchId = "touch" + (_this.isMultiTouch ? touch.identifier : 0);
                        pos = PointerTracker.getEventPosition(e, touch);
                        _this.onPointerEnd(touchId, e.target, pos);
                    }
                });
            }
        }
        PointerTracker.getEventPosition = function (e, obj) {
            var position = {
                clientX: obj.clientX,
                clientY: obj.clientY,
                pageX: obj.pageX,
                pageY: obj.pageY
            };
            if (obj.pageX === null && obj.clientX !== null) {
                var target = e.target;
                var evDoc = (target && ("ownerDocument" in target) && target.ownerDocument) || document;
                var doc = evDoc.documentElement;
                var body = evDoc.body;
                position.pageX = position.clientX +
                    (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
                    (doc && doc.clientLeft || body && body.clientLeft || 0);
                position.pageY = position.clientY +
                    (doc && doc.scrollTop || body && body.scrollTop || 0) -
                    (doc && doc.clientTop || body && body.clientTop || 0);
            }
            return position;
        };
        PointerTracker.prototype.onPointerStart = function (id, isMouse, target, position) {
            if (!this.options.allowMultiplePointers && this.activePointers > 0 && !this.pointers.hasOwnProperty(id))
                return false;
            if (this.pointers.hasOwnProperty(id))
                this.onPointerEnd(id, target, position);
            var initialPosition = $.extend({}, position);
            var pointer = {
                identifier: id,
                isMouse: isMouse,
                isDragging: !this.options.minDragDistance,
                initialTarget: target,
                overTarget: target,
                data: null,
                initialPosition: initialPosition,
                position: position,
                positionDelta: { x: 0, y: 0 }
            };
            this.pointers[id] = pointer;
            this.activePointers++;
            if (this.options.onPointerStart) {
                if (this.options.onPointerStart.call(this, pointer) === false) {
                    this.activePointers--;
                    delete this.pointers[id];
                    return false;
                }
            }
            if (pointer.isDragging && this.options.onDragStart)
                this.options.onDragStart.call(this, pointer);
            return true;
        };
        PointerTracker.prototype.onPointerMove = function (id, target, position) {
            if (!this.pointers.hasOwnProperty(id))
                return;
            var pointer = this.pointers[id];
            pointer.position = position;
            pointer.positionDelta = {
                x: pointer.position.clientX - pointer.initialPosition.clientX,
                y: pointer.position.clientY - pointer.initialPosition.clientY
            };
            if (this.options.onPointerMove)
                this.options.onPointerMove.call(this, pointer);
            if (!pointer.isDragging) {
                if (!this.options.minDragDistance || Math.abs(pointer.position.clientX - pointer.initialPosition.clientX) + Math.abs(pointer.position.clientY - pointer.initialPosition.clientY) >= this.options.minDragDistance) {
                    pointer.isDragging = true;
                    if (this.options.onDragStart)
                        this.options.onDragStart.call(this, pointer);
                }
            }
            if (pointer.isDragging && this.options.onDragMove)
                this.options.onDragMove.call(this, pointer);
        };
        PointerTracker.prototype.onPointerEnd = function (id, target, position) {
            if (!this.pointers.hasOwnProperty(id))
                return;
            var pointer = this.pointers[id];
            delete this.pointers[id];
            this.activePointers--;
            pointer.position = position;
            pointer.positionDelta = {
                x: pointer.position.clientX - pointer.initialPosition.clientX,
                y: pointer.position.clientY - pointer.initialPosition.clientY
            };
            if (pointer.isDragging && this.options.onDragEnd)
                this.options.onDragEnd.call(this, pointer);
            if (this.options.onPointerEnd)
                this.options.onPointerEnd.call(this, pointer);
            if (!pointer.isDragging && this.options.onClick)
                this.options.onClick.call(this, pointer);
        };
        return PointerTracker;
    }());
    exports.PointerTracker = PointerTracker;
});
define("GalleryPictureManager", ["require", "exports", "Dialog", "Service", "jquery", "VerticalLayout", "CustomContainer", "HorizontalLayout", "Label", "PointerTracker"], function (require, exports, Dialog_13, Service_27, $, VerticalLayout_15, CustomContainer_2, HorizontalLayout_7, Label_9, PointerTracker_1) {
    "use strict";
    exports.__esModule = true;
    var GalleryPictureManagerType = (function (_super) {
        __extends(GalleryPictureManagerType, _super);
        function GalleryPictureManagerType() {
            var _this = _super.call(this, '%inherit%') || this;
            _this.images = [];
            _this.mediaDialog = null;
            _this.selectedImage = null;
            _this.timestamp = 0;
            _this.fullyInitialized = false;
            _this.metaChangeEventHandler = _this.onMetaChange.bind(_this);
            _this.setMediaLibraryOptions(GalleryPictureManagerType.defaultMediaLibraryOptions);
            _this.updateTimestamp();
            return _this;
        }
        GalleryPictureManagerType.prototype.updateTimestamp = function () {
            this.timestamp = (new Date()).getTime();
        };
        GalleryPictureManagerType.prototype.setMediaLibraryOptions = function (options) {
            this.mediaLibraryOptions = options;
        };
        GalleryPictureManagerType.prototype.setVisible = function (visible, noAction, ignoreEvent) {
            _super.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
            this.updateTimestamp();
            if (visible && !this.fullyInitialized) {
                this.fullyInitialized = true;
                this.fields.imageDescription.setHeight(166);
                this.fields.imageTitle.on("change", this.metaChangeEventHandler);
                this.fields.imageDescription.on("change", this.metaChangeEventHandler);
            }
            if (this.selectedImage === null)
                this.clearSelection();
        };
        GalleryPictureManagerType.prototype.init = function () {
            var _this = this;
            _super.prototype.__construct.call(this, '', false);
            this.thumb = $('<li class="thumb-li active-or-hover-visible-parent">' +
                '<div class="wb-touch-handle-placeholder">' +
                '<div class="wb-touch-handle"><i class="fa fa-bars" style="color: #FFF;"></i></div>' +
                '<a href="javascript:void(0)" class="btn btn-default btn-xs active-or-hover-visible"><i class="glyphicon glyphicon-remove"></i></a>' +
                '<a href="javascript:void(0)" class="thumbnail">' +
                '<img src="" alt="" />' +
                '</a>' +
                '</div>' +
                '<span class="wb_thumb_name"></span>' +
                '</li>');
            this.setSizeClass("modal-lg");
            this.setTitle(__('Gallery picture manager'));
            var thisManager = this;
            this.setContent(new Service_27["default"].UIBuilder({
                type: VerticalLayout_15.VerticalLayout,
                children: [
                    { type: HorizontalLayout_7.HorizontalLayout, columnWeights: [8, 4], columnWeightsSmall: [8, 4], children: [
                            { type: VerticalLayout_15.VerticalLayout, children: [
                                    { type: CustomContainer_2.CustomContainer, css: { marginTop: -10, "font-size": "12px" }, content: '<i class="fa fa-info-circle"></i> ' + __('Use Drag and Drop to reorder pictures') },
                                    { type: CustomContainer_2.CustomContainer, id: 'images', tag: 'ul',
                                        styleClass: 'thumbnails wb_media_library',
                                        css: { marginTop: '15px', 'overflow-y': 'auto' },
                                        attr: { id: 'wb_picture_manager_thumbs' },
                                        init: function () {
                                            var thisElem = this;
                                            var cont = this.getElem();
                                            cont.on("click touchend", ".thumb-li:not(.no-dd) .btn", function (e) {
                                                var item = $(this).closest(".thumb-li");
                                                var image = item.data('image');
                                                var idx = thisManager.images.indexOf(image);
                                                if (idx >= 0) {
                                                    thisManager.images.splice(idx, 1);
                                                    if (image === thisManager.selectedImage)
                                                        thisManager.clearSelection();
                                                    thisManager.render();
                                                    e.stopImmediatePropagation();
                                                    e.preventDefault();
                                                }
                                            }).on("click touchend", ".thumb-li:not(.no-dd)", function () {
                                                thisManager.setSelection($(this).data("image"));
                                            });
                                            cont.droppable({
                                                accept: '.thumb-li',
                                            });
                                        }
                                    }
                                ] },
                            { type: VerticalLayout_15.VerticalLayout, children: [
                                    { type: Label_9.Label, text: __('Title') },
                                    { type: 'MultilangTextField', id: 'imageTitle' },
                                    { type: Label_9.Label, text: __('Link'), css: { marginTop: 15 } },
                                    { type: 'LinkSelector', id: 'imageLink', multilang: true, change: this.metaChangeEventHandler },
                                    { type: Label_9.Label, text: __('Description'), css: { marginTop: 15 } },
                                    { type: 'MultilangTextField', id: 'imageDescription', textArea: true, height: 166 }
                                ] }
                        ] }
                ]
            }, this.fields), true);
            this.addButton(__("Add pictures"), function () {
                _this.openMediaLibrary();
            }, false, "pull-left btn-success");
            this.addButton(__("Close"));
            this.addButton(__("Apply"), function () {
                if (_this.applyCallback)
                    _this.applyCallback();
            }, true);
            this.clearSelection();
        };
        GalleryPictureManagerType.prototype.onMetaChange = function () {
            if (this.selectedImage === null)
                return;
            Service_27["default"].mediaLibrary.setPathMeta(this.selectedImage, {
                title: this.fields.imageTitle.getValue(),
                link: this.fields.imageLink.getValue(),
                description: this.fields.imageDescription.getValue()
            });
        };
        GalleryPictureManagerType.prototype.openMediaLibrary = function () {
            var _this = this;
            this.mediaDialog = Service_27["default"].mediaLibrary.open(__("Add pictures"), true, "image", !!this.mediaLibraryOptions.showMediaTabs, false, this.mediaLibraryOptions.customContentCallback);
            this.mediaDialog.addButton(__("Close"));
            this.mediaDialog.addButton(__("Apply"), function () {
                if (!_this.mediaDialog)
                    return;
                _this.updateTimestamp();
                var images = _this.mediaDialog.getSelectedFiles();
                _this.mediaDialog.hide();
                for (var _i = 0, images_1 = images; _i < images_1.length; _i++) {
                    var image = images_1[_i];
                    var idx = _this.images.indexOf(image);
                    if (idx < 0)
                        _this.images.push(image);
                }
                _this.render();
            }, true);
            this.mediaDialog.clearFileSelection();
            this.mediaDialog.setVisible(true);
        };
        GalleryPictureManagerType.prototype.render = function () {
            var _this = this;
            var thumbs = [], thumb;
            for (var _i = 0, _a = this.images; _i < _a.length; _i++) {
                var imageUrl = _a[_i];
                thumb = this.thumb.clone();
                thumb.find('.thumbnail img').attr('src', imageUrl);
                var nameParts = imageUrl.split("/");
                var name_3 = nameParts[nameParts.length - 1];
                var title = name_3.replace(/-ts\d+/gi, "");
                var thumbUrl = imageUrl;
                var extParts = thumbUrl.split(".");
                var ext = (extParts.length > 1) ? extParts[(extParts.length - 1)] : "";
                if (ext === "swf") {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_flash.png";
                }
                else if ("mp3,aac,wav".indexOf(ext) >= 0) {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_audio.png";
                }
                else if (ext === "pdf") {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_pdf.png";
                }
                else if ("docx,doc,xls,xlsx,rtf,ppt,pptx,odt".indexOf(ext) >= 0) {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_doc.png";
                }
                else if (ext === "rar") {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_rar.png";
                }
                else if (ext === "zip") {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_zip.png";
                }
                else if ("mp4,mpeg,avi,flv,mkv,mov".indexOf(ext) >= 0) {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_video.png";
                }
                else if ("psd,csv,html,xml,yml,txt".indexOf(ext) >= 0) {
                    thumbUrl = wb_builder.modBaseUrl + "img/file_doc.png";
                }
                else {
                    if (/^gallery\//.test(thumbUrl) && !/^gallery\/thumbs\//.test(thumbUrl))
                        thumbUrl = 'gallery/thumbs/' + thumbUrl.substring(8);
                    if (!/^https?:/i.test(thumbUrl))
                        thumbUrl = wb_builder.userBaseUrl + thumbUrl;
                }
                thumb.data("image", imageUrl);
                $("img", thumb).attr("src", thumbUrl + "?ts=" + this.timestamp);
                $("a.thumbnail", thumb).attr("title", title);
                $("span", thumb).text(name_3);
                thumbs.push(thumb);
            }
            var name = __('Add New');
            thumb = this.thumb.clone();
            thumb.on('click', function (e) {
                _this.openMediaLibrary();
            });
            thumb.addClass('no-dd');
            $("a.thumbnail", thumb).attr({ "title": name }).append('<span class="empty"><i class="glyphicon glyphicon-plus"></i><span class="name"></span></span>');
            $(".wb-touch-handle-placeholder", thumb).removeClass("wb-touch-handle-placeholder");
            $(".wb-touch-handle", thumb).remove();
            $(".btn", thumb).remove();
            $("span.name", thumb).text(name);
            thumbs.push(thumb);
            this.fields.images.setContent(thumbs);
            var thisManager = this;
            var cont = thisManager.fields.images.getElem();
            var gridSize = [wb_builder.isTouchDevice ? 110 : 80, 86];
            if (wb_builder.isTouchDevice) {
                cont.addClass('wb-touch-enabled');
                if (!this.touchTracker) {
                    var triggerJQueryUIEvent_1 = function (eventType, callback, pointer) {
                        var element = pointer.data.elem[0];
                        var ui = {
                            draggable: pointer.data.elem,
                            helper: pointer.data.helper,
                            position: {
                                left: pointer.data.pos.left + pointer.positionDelta.x,
                                top: pointer.data.pos.top + pointer.positionDelta.y
                            },
                            offset: {
                                left: pointer.data.offs.left + pointer.positionDelta.x,
                                top: pointer.data.offs.top + pointer.positionDelta.y
                            }
                        };
                        if (typeof callback === "function") {
                            var e = {
                                type: eventType,
                                target: element,
                                clientX: pointer.position.clientX,
                                clientY: pointer.position.clientY,
                                pageX: pointer.position.pageX,
                                pageY: pointer.position.pageY,
                                stopPropagation: function () { },
                                preventDefault: function () { }
                            };
                            callback.call(element, e, ui);
                        }
                        pointer.data.helper.css({ left: Math.round(ui.position.left), top: Math.round(ui.position.top) });
                        return ui;
                    };
                    this.touchTracker = new PointerTracker_1.PointerTracker(cont, {
                        trackTouches: true,
                        trackMouse: false,
                        preventDefaults: true,
                        allowMultiplePointers: false,
                        onPointerStart: function (pointer) {
                            if (!pointer.initialTarget)
                                return false;
                            var handle = $(pointer.initialTarget).closest(".wb-touch-handle");
                            if (!handle.length)
                                return false;
                            var item = handle.closest(".ui-draggable");
                            pointer.data = {
                                draggableOptions: item.data("draggable").options,
                                elem: item,
                                helper: item.clone(),
                                pos: item.position(),
                                offs: item.offset()
                            };
                            return true;
                        },
                        onDragStart: function (pointer) {
                            if (!pointer.data || !pointer.data.draggableOptions)
                                return;
                            cont.append(pointer.data.helper);
                            pointer.data.helper.css({ position: 'absolute', 'z-index': 1000 });
                            pointer.data.helper.addClass("ui-draggable-dragging");
                            if (typeof pointer.data.draggableOptions.start === "function")
                                triggerJQueryUIEvent_1("dragstart", pointer.data.draggableOptions.start, pointer);
                        },
                        onDragMove: function (pointer) {
                            if (!pointer.data || !pointer.data.draggableOptions)
                                return;
                            if (typeof pointer.data.draggableOptions.drag === "function")
                                triggerJQueryUIEvent_1("drag", pointer.data.draggableOptions.drag, pointer);
                        },
                        onDragEnd: function (pointer) {
                            if (!pointer.data || !pointer.data.draggableOptions)
                                return;
                            pointer.data.helper.removeClass("ui-draggable-dragging");
                            if (typeof pointer.data.draggableOptions.stop === "function")
                                triggerJQueryUIEvent_1("dragstop", pointer.data.draggableOptions.stop, pointer);
                            pointer.data.helper.remove();
                        }
                    });
                }
            }
            for (var _b = 0, thumbs_1 = thumbs; _b < thumbs_1.length; _b++) {
                thumb = thumbs_1[_b];
                if (thumb.is('.no-dd'))
                    continue;
                thumb.draggable({
                    helper: "clone",
                    revert: false,
                    start: function (e, ui) {
                        ui.helper.removeClass("active").css("opacity", 0.5).find(".btn").remove();
                        $(this).css('visibility', 'hidden').addClass('ui-draggable-helper');
                    },
                    stop: function () {
                        var $item = $(this);
                        $item.css('visibility', '').removeClass('ui-draggable-helper');
                        var image = $item.data("image");
                        var idx = thisManager.images.indexOf(image);
                        if (idx >= 0) {
                            thisManager.images.splice(idx, 1);
                            var newIdx = $item.data("newIdx");
                            thisManager.images.splice(newIdx, 0, image);
                        }
                    },
                    drag: function (e, ui) {
                        var contOffs = cont.offset();
                        var itemX = ui.offset.left - contOffs.left;
                        var itemY = ui.offset.top - contOffs.top + cont[0].scrollTop;
                        var w = Math.floor(cont[0].scrollWidth / gridSize[0]);
                        var h = Math.ceil(thisManager.images.length / w);
                        var x = Math.min(Math.max(Math.floor((itemX + gridSize[0] / 2) / gridSize[0]), 0), w - 1);
                        var y = Math.min(Math.max(Math.floor((itemY + gridSize[1] / 2) / gridSize[1]), 0), h - 1);
                        var idx = Math.max(Math.min(x + y * w, thisManager.images.length - 1), 0);
                        var $item = $(this);
                        $item.data("newIdx", idx);
                        var child = cont.children(":not(.ui-draggable-helper)").eq(idx);
                        if (child.length)
                            child.before($item);
                        else
                            cont.append($item);
                    }
                });
            }
            this.setSelection(this.selectedImage);
        };
        GalleryPictureManagerType.prototype.setValue = function (images) {
            this.images = [];
            for (var _i = 0, images_2 = images; _i < images_2.length; _i++) {
                var image = images_2[_i];
                this.images.push(image);
            }
            this.render();
        };
        GalleryPictureManagerType.prototype.getValue = function () {
            return this.images;
        };
        GalleryPictureManagerType.prototype.setApplyCallback = function (applyCallback) {
            this.applyCallback = applyCallback;
        };
        GalleryPictureManagerType.prototype.clearSelection = function () {
            this.setSelection((this.images.length > 0) ? this.images[0] : null);
        };
        GalleryPictureManagerType.prototype.setSelection = function (image) {
            $(":focus").blur();
            this.selectedImage = null;
            this.fields.imageTitle.setValue("");
            this.fields.imageTitle.setEnabled(false);
            this.fields.imageLink.setValue(null);
            this.fields.imageLink.setEnabled(false);
            this.fields.imageDescription.setValue("");
            this.fields.imageDescription.setEnabled(false);
            var thumbs = this.fields.images.getElem().find('.thumb-li.ui-draggable');
            var thisManager = this;
            thumbs.each(function () {
                var $item = $(this);
                if ($item.data("image") == image)
                    $item.addClass('active');
                else
                    $item.removeClass('active');
            });
            thisManager.selectedImage = image;
            if (thisManager.selectedImage) {
                Service_27["default"].mediaLibrary.getPathMeta(thisManager.selectedImage, function (meta) {
                    if (this !== thisManager.selectedImage)
                        return;
                    thisManager.fields.imageTitle.setEnabled(true);
                    thisManager.fields.imageTitle.setValue(meta.title);
                    thisManager.fields.imageLink.setEnabled(true);
                    thisManager.fields.imageLink.setValue(meta.link);
                    thisManager.fields.imageDescription.setEnabled(true);
                    thisManager.fields.imageDescription.setValue(meta.description);
                    thisManager.fields.imageTitle.focus();
                }.bind(thisManager.selectedImage));
            }
        };
        GalleryPictureManagerType.defaultMediaLibraryOptions = {
            showMediaTabs: true,
            customContentCallback: null
        };
        return GalleryPictureManagerType;
    }(Dialog_13["default"]));
    exports.GalleryPictureManagerType = GalleryPictureManagerType;
    var GalleryPictureManager = new GalleryPictureManagerType();
    Service_27["default"].GalleryPictureManager = GalleryPictureManager;
    exports["default"] = GalleryPictureManager;
});
define("util/BlockPacker", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var BlockPacker = (function () {
        function BlockPacker(maxWidth, maxHeight, spacing) {
            if (maxWidth === void 0) { maxWidth = 870; }
            if (maxHeight === void 0) { maxHeight = null; }
            if (spacing === void 0) { spacing = 0; }
            this.minPackingWidth = 1;
            this.minPackingHeight = 1;
            this.blocks = [];
            this.packingSpacing = spacing;
            this.maxWidth = maxWidth;
            this.maxHeight = maxHeight;
        }
        BlockPacker.prototype.clear = function () {
            this.blocks = [];
        };
        BlockPacker.prototype.addBlock = function (data, width, height) {
            var block = {
                widthFunc: width,
                heightFunc: height,
                width: (typeof width === "number") ? width : 0,
                height: (typeof height === "number") ? height : 0,
                data: data
            };
            this.blocks.push(block);
            return block;
        };
        BlockPacker.prototype.defaultSortFunc = function (blockA, blockB) {
            if (blockA.height == blockB.height) {
                if (blockA.width == blockB.width)
                    return 0;
                return (blockA.width > blockB.width) ? -1 : 1;
            }
            return (blockA.height > blockB.height) ? -1 : 1;
        };
        BlockPacker.prototype.pack = function (sortFunction) {
            if (this.blocks.length === 0)
                return this.blocks;
            if (typeof sortFunction !== "function")
                sortFunction = this.defaultSortFunc;
            var minSpaceWidth = null;
            var minSpaceHeight = null;
            for (var _i = 0, _a = this.blocks; _i < _a.length; _i++) {
                var block = _a[_i];
                if (typeof block.widthFunc === "function")
                    block.width = block.widthFunc();
                if (typeof block.heightFunc === "function")
                    block.height = block.heightFunc();
                if (minSpaceWidth === null || minSpaceWidth > block.width)
                    minSpaceWidth = block.width;
                if (minSpaceHeight === null || minSpaceHeight > block.height)
                    minSpaceHeight = block.height;
            }
            this.minPackingWidth = Math.max(1, minSpaceWidth || 1);
            this.minPackingHeight = Math.max(1, minSpaceHeight || 1);
            this.blocks.sort(sortFunction);
            this.packingRoot = { left: 0, top: 0, width: this.maxWidth, height: this.maxHeight, used: false, right: null, down: null, splitDir: false };
            var node;
            for (var _b = 0, _c = this.blocks; _b < _c.length; _b++) {
                var block = _c[_b];
                if (node = this.findPackingNode(this.packingRoot, block.width, block.height)) {
                    this.splitPackingNode(node, block.width, block.height);
                    block.left = node.left;
                    block.top = node.top;
                }
            }
            return this.blocks;
        };
        BlockPacker.prototype.findPackingNode = function (node, width, height) {
            if (node) {
                if (node.used) {
                    if (node.splitDir)
                        return this.findPackingNode(node.down, width, height) || this.findPackingNode(node.right, width, height);
                    return this.findPackingNode(node.right, width, height) || this.findPackingNode(node.down, width, height);
                }
                if ((width <= node.width) && (node.height === null || height <= node.height))
                    return node;
            }
            return null;
        };
        BlockPacker.prototype.splitPackingNode = function (node, width, height) {
            node.used = true;
            if (!node.splitDir) {
                node.down = (node.height !== null && node.height - height - this.packingSpacing < this.minPackingHeight) ? null : {
                    left: node.left,
                    top: node.top + height + this.packingSpacing,
                    width: node.width,
                    height: (node.height === null) ? null : (node.height - height - this.packingSpacing),
                    used: false,
                    right: null,
                    down: null,
                    splitDir: false
                };
                node.right = (node.width - width - this.packingSpacing < this.minPackingWidth || height <= 0) ? null : {
                    left: node.left + width + this.packingSpacing,
                    top: node.top,
                    width: node.width - width - this.packingSpacing,
                    height: height,
                    used: false,
                    right: null,
                    down: null,
                    splitDir: true
                };
            }
            else {
                node.down = (node.height !== null && node.height - height - this.packingSpacing < this.minPackingHeight || width <= 0) ? null : {
                    left: node.left,
                    top: node.top + height + this.packingSpacing,
                    width: width,
                    height: (node.height === null) ? null : (node.height - height - this.packingSpacing),
                    used: false,
                    right: null,
                    down: null,
                    splitDir: false
                };
                node.right = (node.width - width - this.packingSpacing < this.minPackingWidth) ? null : {
                    left: node.left + width + this.packingSpacing,
                    top: node.top,
                    width: node.width - width - this.packingSpacing,
                    height: node.height,
                    used: false,
                    right: null,
                    down: null,
                    splitDir: true
                };
            }
            return node;
        };
        return BlockPacker;
    }());
    exports.BlockPacker = BlockPacker;
});
define("ElementStyles", ["require", "exports", "Service", "ElementRegister", "Dialog", "Serializable", "UIComponent", "ColorPicker", "util/BlockPacker"], function (require, exports, Service_28, ElementRegister_6, Dialog_14, Serializable_10, UIComponent_19, ColorPicker_1, BlockPacker_1) {
    "use strict";
    exports.__esModule = true;
    var ElementStyle = (function (_super) {
        __extends(ElementStyle, _super);
        function ElementStyle(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.element = null;
            _this.itemElem = null;
            _this.scale = 1;
            _this.deserialize(data);
            return _this;
        }
        return ElementStyle;
    }(Serializable_10.Serializable));
    var ElementStyleSelector = (function (_super) {
        __extends(ElementStyleSelector, _super);
        function ElementStyleSelector() {
            var _this = _super.call(this) || this;
            _this._value = null;
            _this._selected = null;
            _this.showLabels = false;
            _this.dataDefaults = { content: {} };
            _this.parentIsVisible = true;
            _this.lastClickTime = [0, 0];
            _this.layoutUpdateTimeout = 0;
            _this._container = $('<div>').css({
                position: "relative"
            });
            _this._elem.append(_this._container);
            var resizeTimer = 0;
            _this._container.on("elementresize load error", function () {
                if (!resizeTimer) {
                    resizeTimer = setTimeout(function () {
                        resizeTimer = 0;
                        _this.updateLayout();
                    }, 0);
                }
            });
            return _this;
        }
        ElementStyleSelector.prototype.buildInit = function (data, fields) {
            var _this = this;
            this.showLabels = !!data.showLabels;
            $(window).on("resize orientationchange", this.updateLayout.bind(this));
            this.onChange = function () {
                var elem = _this.getElem();
                _this.trigger("change");
                if (typeof data.change === "function")
                    data.change.call(_this, elem, fields);
            };
            this.onClickEdit = data.onClickEdit;
            this.onClickDelete = data.onClickDelete;
            this.onClickHide = data.onClickHide;
            this.onClickShow = data.onClickShow;
        };
        ElementStyleSelector.prototype.setValue = function (value) {
            var sel = this.getSelected();
            this._value = value;
            this.updateList();
            if (sel) {
                for (var _i = 0, _a = this._value; _i < _a.length; _i++) {
                    var item = _a[_i];
                    if (item.className == sel.className && item.id == sel.id) {
                        this.setSelected(item);
                        break;
                    }
                }
            }
        };
        ElementStyleSelector.prototype.getSelected = function () {
            return this._selected;
        };
        ElementStyleSelector.prototype.addItemToList = function (item) {
            var _this = this;
            ElementRegister_6["default"].createElement(item.className, function (elem, styleInfo) {
                item.element = elem;
                item.itemElem = $('<div class="wb-element-style-item">').css({});
                var inner = $('<div class="wb-esi-inner">').css({
                    position: 'relative'
                });
                elem.elem.find(".wb_controls").children(":not(.wb_cover)").remove();
                elem.elem.off("mousedown mouseup mouseover mouseout hover out focus blur click dblclick contextmenu touchstart touchend touchcancel keydown keyup keypress");
                elem.elem.find('.wb_controls').off("mousedown mouseup mouseover mouseout hover out focus blur click dblclick contextmenu touchstart touchend touchcancel keydown keyup keypress");
                elem.elem.css({
                    position: 'relative',
                    left: 0,
                    top: 0
                });
                elem.elem.attr("style", elem.elem.attr("style").replace("relative;", "relative!important;") + ';position:relative!important;');
                if (item.className == "Gallery") {
                    item.scale = 0.25;
                    elem.elem.css({
                        transformOrigin: "left top",
                        transform: "scale(" + item.scale + ")"
                    });
                    inner.css({
                        width: item.scale * elem.getWidth(),
                        height: item.scale * elem.getHeight(),
                    });
                    _this._elem.closest(".modal").one("shown.bs.modal", (function () {
                        this.onResize();
                    }).bind(elem));
                }
                var bgColor = _this.getPreviewBackgroundColor(elem);
                if (bgColor !== null)
                    item.itemElem.css("background-color", bgColor);
                inner.append(elem.elem);
                item.itemElem.append(inner);
                if (_this.showLabels) {
                    var itemControls = $('<div class="wb-esi-controls">').append($('<span class="wb-esi-id">').text(item.id ? item.id : "Default"));
                    if (item.id && styleInfo) {
                        itemControls.append($('<button class="btn btn-xs btn-default">')
                            .attr("title", __('Rename'))
                            .append('<i class="fa fa-pencil"></i>')
                            .on('click', function () {
                            if (typeof _this.onClickEdit === "function")
                                _this.onClickEdit.call(_this, item);
                        }));
                        itemControls.append($('<button class="btn btn-xs btn-default">')
                            .attr("title", __('Delete'))
                            .append('<i class="fa fa-trash-o"></i>')
                            .on('click', function () {
                            if (typeof _this.onClickDelete === "function")
                                _this.onClickDelete.call(_this, item);
                        }));
                        if (styleInfo.visible)
                            itemControls.append($('<button class="btn btn-xs btn-default">')
                                .attr("title", __('Hide element style from users'))
                                .append('<i class="fa fa-eye-slash"></i>')
                                .on('click', function () {
                                if (typeof _this.onClickHide === "function")
                                    _this.onClickHide.call(_this, item);
                            }));
                        else {
                            itemControls.append($('<button class="btn btn-xs btn-default">')
                                .attr("title", __('Show element style to users'))
                                .append('<i class="fa fa-eye"></i>')
                                .on('click', function () {
                                if (typeof _this.onClickShow === "function")
                                    _this.onClickShow.call(_this, item);
                            }));
                            item.itemElem.append($('<div class="wb-esi-hidden"><i class="fa fa-eye-slash blink-slow-infinite"></i></div>'));
                        }
                    }
                    item.itemElem.append(itemControls);
                }
                item.itemElem.on('click touchstart', function (e) {
                    var sel = _this.getSelected();
                    _this.setSelected(item);
                    var time = (new Date()).getTime();
                    var eIdx = (e.type === "click") ? 0 : 1;
                    if (item !== sel)
                        _this.lastClickTime = [0, 0];
                    else {
                        if (time - _this.lastClickTime[eIdx] < 500) {
                            _this.lastClickTime = [0, 0];
                            if (item.itemElem)
                                item.itemElem.trigger("dblclickitem");
                        }
                    }
                    _this.lastClickTime[eIdx] = time;
                });
                _this._container.append(item.itemElem);
            }, null, this.dataDefaults, true, true, item.id);
        };
        ElementStyleSelector.prototype.getPreviewBackgroundColor = function (elem) {
            var styleClassName = null;
            switch (elem.getClassType()) {
                case "TextArea": {
                    var html = elem.getHtml();
                    var matches = html.match(/class="[^"]*\b(wb-stl-[^"\s]+)/);
                    if (matches)
                        styleClassName = matches[1];
                    break;
                }
                case "Form": {
                    styleClassName = elem.labelStyle;
                    break;
                }
            }
            if (styleClassName === null)
                return null;
            for (var _i = 0, _a = wb_builder.site.styles; _i < _a.length; _i++) {
                var style = _a[_i];
                if (style.selector === '.' + styleClassName) {
                    if (style.rules.hasOwnProperty("color"))
                        return ColorPicker_1["default"].readableColor(style.rules.color);
                    return null;
                }
            }
            return null;
        };
        ElementStyleSelector.prototype.setSelected = function (item) {
            if (item && item.itemElem) {
                item.itemElem.parent().children().removeClass('active');
                item.itemElem.addClass('active');
            }
            var prevSel = this._selected;
            this._selected = item;
            if (prevSel !== item)
                this.onChange();
        };
        ElementStyleSelector.prototype.updateList = function () {
            this._container.empty();
            if (this._value) {
                for (var i = 0, c = this._value.length; i < c; i++) {
                    this.addItemToList(this._value[i]);
                }
                this.setSelected(null);
                this.updateLayout();
            }
        };
        ElementStyleSelector.prototype.setDataDefaults = function (dataDefaults) {
            this.dataDefaults = $.extend(true, { isElementPreview: true, content: {} }, dataDefaults);
        };
        ElementStyleSelector.prototype.setParentVisible = function (visible) {
            this.parentIsVisible = visible;
            this.updateLayout();
        };
        ElementStyleSelector.prototype.updateLayout = function () {
            var _this = this;
            if (!this._value || !this._value.length || !this.parentIsVisible)
                return;
            if (this.layoutUpdateTimeout)
                clearTimeout(this.layoutUpdateTimeout);
            var cw = this._container.closest('.modal-body').outerWidth() - 28;
            if (!document.body.contains(this._container[0]) || !this._container.is(":visible") || cw <= 0) {
                setTimeout(function () {
                    _this.layoutUpdateTimeout = 0;
                    _this.updateLayout();
                }, 10);
                return;
            }
            var packer = new BlockPacker_1.BlockPacker(cw, null, 10);
            for (var _i = 0, _a = this._value; _i < _a.length; _i++) {
                var item = _a[_i];
                if (!item.element)
                    continue;
                packer.addBlock(item, item.element.getWidth() * item.scale, item.element.getHeight() * item.scale);
            }
            var numeric = /^[0-9]+$/;
            var blocks = packer.pack(function (blockA, blockB) {
                var res = packer.defaultSortFunc(blockA, blockB);
                if (res === 0) {
                    var id1 = blockA.data.id ? blockA.data.id : "Default";
                    if (numeric.test(id1))
                        for (var i = id1.length; i < 8; i++)
                            id1 = '0' + id1;
                    var id2 = blockB.data.id ? blockB.data.id : "Default";
                    if (numeric.test(id2))
                        for (var i = id2.length; i < 8; i++)
                            id2 = '0' + id2;
                    return (id1.toLowerCase() < id2.toLowerCase()) ? -1 : 1;
                }
                return res;
            });
            var bottom = 0;
            for (var _b = 0, blocks_1 = blocks; _b < blocks_1.length; _b++) {
                var block = blocks_1[_b];
                if (!block.data.itemElem || typeof block.left !== "number" || typeof block.top !== "number")
                    continue;
                block.data.itemElem.css({
                    display: "",
                    left: block.left,
                    top: block.top
                });
                bottom = Math.max(bottom, block.top + block.height);
            }
            this._container.css("height", bottom);
        };
        return ElementStyleSelector;
    }(UIComponent_19.UIComponent));
    var ElementStylesDialog = (function (_super) {
        __extends(ElementStylesDialog, _super);
        function ElementStylesDialog() {
            var _this = _super.call(this, __('Choose Style'), false) || this;
            _this.applyCallback = null;
            _this.cancelCallback = null;
            _this.elementClass = null;
            _this.setSizeClass("modal-lg");
            _this.setContent(new Service_28["default"].UIBuilder({
                type: "VerticalLayout", children: [
                    { type: ElementStyleSelector, id: 'styles', showLabels: wb_builder.adminMode,
                        onClickEdit: function (item) {
                            if (!item.id)
                                return;
                            var val = prompt("Enter new ID of for element style.");
                            if (val !== null && val !== "") {
                                Service_28["default"].ElementStyles.renameStyle(item.className, item.id, val, function () {
                                    _this.updateList();
                                }, function (err) {
                                    alert(err.message);
                                });
                            }
                        },
                        onClickDelete: function (item) {
                            if (!item.id || !confirm(__('Are you sure?')))
                                return;
                            Service_28["default"].ElementStyles.removeStyle(item.className, item.id, function () {
                                _this.updateList();
                            }, function (err) {
                                alert(err.message);
                            });
                        },
                        onClickHide: function (item) {
                            if (!item.id)
                                return;
                            Service_28["default"].ElementStyles.setStyleVisibility(item.className, item.id, false, function () {
                                _this.updateList();
                            }, function (err) {
                                alert(err.message);
                            });
                        },
                        onClickShow: function (item) {
                            if (!item.id)
                                return;
                            Service_28["default"].ElementStyles.setStyleVisibility(item.className, item.id, true, function () {
                                _this.updateList();
                            }, function (err) {
                                alert(err.message);
                            });
                        },
                        change: function () {
                            _this.updateButtons();
                        },
                        on: {
                            dblclickitem: function () {
                                var elementStyle = _this.fields.styles.getSelected();
                                if (elementStyle) {
                                    _this.onApply(elementStyle);
                                    _this.setVisible(false);
                                }
                            }
                        }
                    }
                ]
            }, _this.fields), true);
            _this.addButton(__('Cancel'), function () {
                _this.onCancel();
                _this.setVisible(false);
            });
            _this.addButton(__('Add'), function () {
                var elementStyle = _this.fields.styles.getSelected();
                if (elementStyle)
                    _this.onApply(elementStyle);
                else
                    _this.onCancel();
                _this.setVisible(false);
            }, true, 'wb-es-apply');
            _this.updateButtons();
            return _this;
        }
        ElementStylesDialog.prototype.updateButtons = function () {
            var btn = this.buttons.find(".wb-es-apply");
            if (this.fields.styles.getSelected())
                btn.removeAttr("disabled");
            else
                btn.attr("disabled", "disabled");
        };
        ElementStylesDialog.prototype.onShow = function () {
            this.fields.styles.setParentVisible(true);
        };
        ElementStylesDialog.prototype.onClose = function () {
            this.onCancel();
        };
        ElementStylesDialog.prototype.onApply = function (elementStyle) {
            this.fields.styles.setParentVisible(false);
            if (typeof this.applyCallback === "function")
                this.applyCallback(elementStyle.id);
            this.applyCallback = null;
            this.cancelCallback = null;
        };
        ElementStylesDialog.prototype.onCancel = function () {
            this.fields.styles.setParentVisible(false);
            if (typeof this.cancelCallback === "function")
                this.cancelCallback();
            this.applyCallback = null;
            this.cancelCallback = null;
        };
        ElementStylesDialog.prototype.setCallbacks = function (applyCallback, cancelCallback) {
            this.applyCallback = applyCallback;
            this.cancelCallback = cancelCallback;
        };
        ElementStylesDialog.prototype.setElementClass = function (className, dataDefaults) {
            this.elementClass = className;
            this.fields.styles.setDataDefaults(dataDefaults);
            this.updateList();
        };
        ElementStylesDialog.prototype.updateList = function () {
            if (!this.elementClass)
                return;
            var styles = [];
            for (var _i = 0, _a = Service_28["default"].ElementStyles.getAvailableStyles(this.elementClass); _i < _a.length; _i++) {
                var id = _a[_i];
                styles.push(new ElementStyle({ className: this.elementClass, id: id }));
            }
            this.fields.styles.setValue(styles);
        };
        return ElementStylesDialog;
    }(Dialog_14["default"]));
    var ElementStylesModule = (function () {
        function ElementStylesModule() {
            this.dialog = null;
        }
        ElementStylesModule.prototype.init = function () {
        };
        ElementStylesModule.prototype.open = function (elementClass, dataDefaults, applyCallback, cancelCallback) {
            if (cancelCallback === void 0) { cancelCallback = null; }
            if (!this.dialog)
                this.dialog = new ElementStylesDialog();
            this.dialog.setCallbacks(applyCallback, cancelCallback);
            this.dialog.setElementClass(elementClass, dataDefaults);
            this.dialog.setVisible(true);
        };
        ElementStylesModule.prototype.getAvailableStyles = function (className) {
            var list = [];
            var classId = className.replace(/[^a-z0-9_\-]+/ig, "");
            if (wb_builder.predefinedElementStyles.hasOwnProperty(classId)) {
                if (wb_builder.adminMode)
                    list = Object.keys(wb_builder.predefinedElementStyles[classId]);
                else {
                    var collection = wb_builder.predefinedElementStyles[classId];
                    for (var styleId in collection) {
                        if (!collection.hasOwnProperty(styleId))
                            continue;
                        if (!collection[styleId].visible)
                            continue;
                        list.push(styleId);
                    }
                }
            }
            return list;
        };
        ElementStylesModule.prototype.getStyleInfo = function (className, styleId) {
            if (styleId !== null && styleId !== false) {
                var classId = this.classNameToClassId(className);
                if (wb_builder.predefinedElementStyles.hasOwnProperty(classId) && wb_builder.predefinedElementStyles[classId].hasOwnProperty(styleId)) {
                    var styleInfo = wb_builder.predefinedElementStyles[classId][styleId];
                    if (!styleInfo.galleryUrlsReplaced) {
                        styleInfo.previewData = $.extend(true, {}, styleInfo.data);
                        if (styleId) {
                            this.replaceGalleryUrls(className, styleId, styleInfo.previewData);
                            this.replaceGalleryUrls(null, null, styleInfo.data);
                        }
                        styleInfo.galleryUrlsReplaced = true;
                    }
                    return styleInfo;
                }
            }
            return null;
        };
        ElementStylesModule.prototype.mergeGallery = function (className, styleId, doneCallback) {
            var styleInfo = this.getStyleInfo(className, styleId);
            if (styleInfo && styleInfo.hasGallery) {
                $.ajax({
                    url: wb_builder.lnBaseUrl + 'element-styles/merge-gallery',
                    type: 'post',
                    data: {
                        className: className,
                        id: styleId
                    },
                    complete: doneCallback
                });
            }
            else if (typeof doneCallback === "function")
                doneCallback();
        };
        ElementStylesModule.prototype.renameStyle = function (className, styleId, newStyleId, successCallback, errorCallback, doneCallback) {
            $.ajax({
                url: wb_builder.lnBaseUrl + 'element-styles/rename',
                type: 'post',
                data: {
                    className: className,
                    id: styleId,
                    newId: newStyleId
                },
                dataType: "json",
                success: function (data) {
                    if (data && data.success && data.styles) {
                        wb_builder.predefinedElementStyles = data.styles;
                        if (typeof successCallback === "function")
                            successCallback();
                    }
                    else if (typeof errorCallback === "function")
                        errorCallback((data && data.error) ? data.error : {
                            code: -1,
                            message: "Network error: invalid response"
                        });
                },
                error: function () {
                    if (typeof errorCallback === "function")
                        errorCallback({
                            code: -1,
                            message: "Network connection error"
                        });
                },
                complete: doneCallback
            });
        };
        ElementStylesModule.prototype.removeStyle = function (className, styleId, successCallback, errorCallback, doneCallback) {
            $.ajax({
                url: wb_builder.lnBaseUrl + 'element-styles/remove',
                type: 'post',
                data: {
                    className: className,
                    id: styleId
                },
                dataType: "json",
                success: function (data) {
                    if (data && data.success && data.styles) {
                        wb_builder.predefinedElementStyles = data.styles;
                        if (typeof successCallback === "function")
                            successCallback();
                    }
                    else if (typeof errorCallback === "function")
                        errorCallback((data && data.error) ? data.error : {
                            code: -1,
                            message: "Network error: invalid response"
                        });
                },
                error: function () {
                    if (typeof errorCallback === "function")
                        errorCallback({
                            code: -1,
                            message: "Network connection error"
                        });
                },
                complete: doneCallback
            });
        };
        ElementStylesModule.prototype.setStyleVisibility = function (className, styleId, visible, successCallback, errorCallback, doneCallback) {
            $.ajax({
                url: wb_builder.lnBaseUrl + 'element-styles/set-visible',
                type: 'post',
                data: {
                    className: className,
                    id: styleId,
                    visible: visible ? 1 : 0
                },
                dataType: "json",
                success: function (data) {
                    if (data && data.success && data.styles) {
                        wb_builder.predefinedElementStyles = data.styles;
                        if (typeof successCallback === "function")
                            successCallback();
                    }
                    else if (typeof errorCallback === "function")
                        errorCallback((data && data.error) ? data.error : {
                            code: -1,
                            message: "Network error: invalid response"
                        });
                },
                error: function () {
                    if (typeof errorCallback === "function")
                        errorCallback({
                            code: -1,
                            message: "Network connection error"
                        });
                },
                complete: doneCallback
            });
        };
        ElementStylesModule.prototype.classNameToClassId = function (className) {
            return className.replace(/[^a-z0-9_\-]+/ig, "");
        };
        ElementStylesModule.prototype.getElementStyleUrl = function (className, styleId) {
            if (className === null || styleId === null)
                return "";
            return wb_builder.baseUrl + 'element_styles/' + this.classNameToClassId(className) + '/' + styleId + '/';
        };
        ElementStylesModule.prototype.replaceGalleryUrls = function (className, styleId, data) {
            var styleUrl = this.getElementStyleUrl(className, styleId);
            for (var i in data) {
                if (!data.hasOwnProperty(i))
                    continue;
                if (typeof data[i] === "string")
                    data[i] = data[i].replace("{{predefinedElementStyleUrl}}", styleUrl);
                else if (typeof data[i] === "object")
                    this.replaceGalleryUrls(className, styleId, data[i]);
            }
        };
        return ElementStylesModule;
    }());
    exports.ElementStylesModule = ElementStylesModule;
    Service_28["default"].ElementStyles = new ElementStylesModule();
});
define("Blocks", ["require", "exports", "Service", "ElementRegister", "Element", "Dialog", "List", "Serializable", "ModeManager", "UIComponent"], function (require, exports, Service_29, ElementRegister_7, Element_3, Dialog_15, List_7, Serializable_11, ModeManager_2, UIComponent_20) {
    "use strict";
    exports.__esModule = true;
    var Block = (function (_super) {
        __extends(Block, _super);
        function Block(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.deserialize(data);
            return _this;
        }
        return Block;
    }(Serializable_11.Serializable));
    var Category = (function (_super) {
        __extends(Category, _super);
        function Category(data) {
            if (data === void 0) { data = null; }
            var _this = _super.call(this) || this;
            _this.blocks = [];
            _this.deserialize(data);
            return _this;
        }
        return Category;
    }(Serializable_11.Serializable));
    var BlocksElement = (function (_super) {
        __extends(BlocksElement, _super);
        function BlocksElement(data) {
            var _this = _super.call(this, data) || this;
            setTimeout(function () {
                var mode = ModeManager_2["default"].getMode();
                _this.setLocation(0);
                _this.setSize(ModeManager_2["default"].getModeWidth(mode), 100);
                _this.setSelected(true);
            }, 20);
            Module.open(_this);
            return _this;
        }
        return BlocksElement;
    }(Element_3["default"]));
    exports.BlocksElement = BlocksElement;
    var BlocksModule = (function () {
        function BlocksModule() {
            this.categoriesLoaded = false;
            this.blocksLoaded = {};
            this.applying = false;
        }
        BlocksModule.prototype.init = function (builder) {
            this.builder = builder;
        };
        BlocksModule.prototype.open = function (elem) {
            this.elem = elem;
            if (!this.dialog)
                this.dialog = new BlocksDialog();
            this.dialog.setVisible(true);
        };
        BlocksModule.prototype.apply = function (block) {
            var _this = this;
            if (this.elem) {
                this.elem.container.append(__('loading...'));
                this.applying = true;
                this.loadBlockData(block, function (data) {
                    var elem;
                    var elems = _this.elem.getParent().getElements();
                    var offsetTop = _this.elem.getBounds().top;
                    var maxZIndex = 0;
                    for (var i = 0, c = elems.length; i < c; i++) {
                        var zIndex = elems[i].getZIndex();
                        if (zIndex && (!maxZIndex || maxZIndex < zIndex)) {
                            maxZIndex = zIndex;
                        }
                    }
                    var _loop_7 = function (i, c) {
                        var elemData = $.extend(true, {}, data[i]);
                        var isTextArea = (elemData["class"] === 'TextArea');
                        elemData.y = (elemData.y ? elemData.y : 0) + offsetTop;
                        if (elemData.modes) {
                            for (var j in elemData.modes) {
                                var y = parseInt(elemData.modes[j].y);
                                elemData.modes[j].y = (y ? y : 0) + offsetTop;
                            }
                        }
                        if (elemData.zIndex)
                            elemData.zIndex += maxZIndex;
                        var cls = ElementRegister_7["default"].getClassByName(elemData["class"]);
                        if (!cls)
                            return "continue";
                        if (isTextArea) {
                            elemData.content.__noInitCleanupWbTrOk = true;
                        }
                        elem = new cls(elemData);
                        if (isTextArea) {
                            elem.elem.css('visibility', 'hidden');
                        }
                        var currMode = ModeManager_2["default"].getMode();
                        _this.builder.bodyInstance.addElement(_this.elem.getParent().id, elem, true);
                        elem.switchMode(currMode, currMode, true);
                        if (isTextArea) {
                            (function (elem) {
                                setTimeout(function () {
                                    var plot1 = elemData.width * elemData.height;
                                    var plot2 = elem.getWidth() * elem.getHeight();
                                    var c = plot2 / plot1;
                                    var tmpElem = $(__tr(elem.textDivValue));
                                    if (!tmpElem.find('.wb_tr_ok').length) {
                                        var tmpText = tmpElem.text();
                                        tmpText = tmpText.substring(0, (tmpText.length / c) - 3).replace(/[\s\.,\!\?\(\[\-+=\/\*:;]+$/, '') + '...';
                                        tmpElem.text(tmpText);
                                        tmpText = tmpElem.wrap('<div>').parent().html();
                                        elem.setValue(tmpText);
                                        elem.setHtml(tmpText);
                                    }
                                    elem.cleanupWbTrOk(true);
                                    setTimeout(function () { return elem.elem.css('visibility', ''); }, 250);
                                }, 250);
                            })(elem);
                        }
                    };
                    for (var i = 0, c = data.length; i < c; i++) {
                        _loop_7(i, c);
                    }
                    _this.builder.bodyInstance.getContentBlock('wb_main').updateSize();
                    _this.applying = false;
                    _this.close();
                }, function (error) {
                    alert(error);
                    _this.close();
                });
            }
        };
        BlocksModule.prototype.close = function () {
            if (this.elem && !this.applying)
                this.elem.remove(true);
        };
        BlocksModule.prototype.reload = function () {
            this.categoriesLoaded = false;
            this.blocksLoaded = {};
        };
        BlocksModule.prototype.findCategoryById = function (id) {
            for (var i = 0, c = this.categories.length; i < c; i++) {
                if (this.categories[i].id === id) {
                    return this.categories[i];
                }
            }
            return null;
        };
        BlocksModule.prototype.loadBlockData = function (block, callback, error) {
            var ts = (new Date()).getTime();
            var url = (this.builder ? this.builder.lnBaseUrl : '') + 'blocks/load-block-data/?id=' + encodeURIComponent(block.id) + '&ts=' + ts;
            $.get(url).done(function (data) {
                if (data.error && data.error.message) {
                    if (typeof error === 'function')
                        error(data.error.message);
                }
                else {
                    if (typeof callback === 'function')
                        callback(data);
                }
            });
        };
        BlocksModule.prototype.loadCategories = function (callback, forceLoad) {
            var _this = this;
            if (forceLoad || !this.categoriesLoaded) {
                var ts = (new Date()).getTime();
                var url = (this.builder ? this.builder.lnBaseUrl : '') + 'blocks/load-categories/ts=' + ts;
                $.get(url).done(function (data) {
                    _this.categories = [];
                    for (var i = 0, c = data.length; i < c; i++) {
                        var category = new Category({ id: data[i].id, name: data[i].name });
                        if (data[i].blocks) {
                            for (var j = 0, c2 = data[i].blocks.length; j < c2; j++) {
                                category.blocks.push((new Block(data[i].blocks[j])));
                            }
                        }
                        _this.categories.push(category);
                    }
                    _this.categoriesLoaded = true;
                    if (typeof callback === 'function')
                        callback.call(_this);
                });
            }
            else {
                if (typeof callback === 'function')
                    callback.call(this);
            }
        };
        return BlocksModule;
    }());
    var CategoryList = (function (_super) {
        __extends(CategoryList, _super);
        function CategoryList() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CategoryList.prototype.buildInit = function (data, fields) {
            data.itemType = Category;
            data.sortable = false;
            data.select = this.onSelect;
            _super.prototype.buildInit.call(this, data, fields);
        };
        CategoryList.prototype.onSelect = function (fields, item) {
            var category = Module.findCategoryById(item.id);
            if (category) {
                fields.blocks.setValue(category.blocks);
            }
        };
        return CategoryList;
    }(List_7.List));
    var BlockSelector = (function (_super) {
        __extends(BlockSelector, _super);
        function BlockSelector() {
            var _this = _super.call(this) || this;
            _this._value = null;
            _this._selected = null;
            _this.showLabels = false;
            _this._container = $('<div>').addClass('row wb-block-selector-row');
            _this._elem.append(_this._container);
            return _this;
        }
        BlockSelector.prototype.buildInit = function (data, fields) {
            this.showLabels = !!data.showLabels;
        };
        BlockSelector.prototype.setValue = function (value) {
            this._value = [];
            for (var i = 0, c = value.length; i < c; i++) {
                var item = {
                    icon: value[i].icon,
                    inst: value[i]
                };
                this._value.push(item);
            }
            this.updateList();
        };
        BlockSelector.prototype.getSelected = function () {
            return this._selected;
        };
        BlockSelector.prototype.addItemToList = function (item) {
            var _this = this;
            var cont = $('<div>').addClass('col-md-4 wb-block-selector-item');
            var inner = $('<div>');
            if (item.inst.icon) {
                inner.append($('<img src=""/>').attr('src', item.icon));
            }
            if (this.showLabels && item.inst.id) {
                inner.append($('<span>').text(item.inst.id));
            }
            cont.append(inner);
            item.elem = cont;
            item.elem.on('click', function () { return _this.setSelected(item); });
            this._container.append(cont);
        };
        BlockSelector.prototype.setSelected = function (item) {
            if (item.elem) {
                item.elem.parent().children().removeClass('active');
                item.elem.addClass('active');
                this._selected = item.inst;
            }
        };
        BlockSelector.prototype.updateList = function () {
            this._container.empty();
            if (this._value) {
                for (var i = 0, c = this._value.length; i < c; i++) {
                    this.addItemToList(this._value[i]);
                }
                if (this._value.length)
                    this.setSelected(this._value[0]);
            }
        };
        return BlockSelector;
    }(UIComponent_20.UIComponent));
    var BlocksDialog = (function (_super) {
        __extends(BlocksDialog, _super);
        function BlocksDialog() {
            var _this = _super.call(this, __('Blocks'), false) || this;
            _this.setSize(900, null);
            _this.setContent(new Service_29["default"].UIBuilder({
                type: 'HorizontalLayout',
                columnWeights: [3, 9],
                children: [
                    { type: CategoryList, id: 'list' },
                    { type: 'VerticalLayout', children: [
                            { type: BlockSelector, id: 'blocks', showLabels: wb_builder.adminMode }
                        ] }
                ]
            }, _this.fields), true);
            _this.addButton(__('Cancel'), function () {
                _this.setVisible(false);
            });
            _this.addButton(__('Add'), function () {
                var block = _this.fields.blocks.getSelected();
                if (block)
                    Module.apply(block);
                _this.setVisible(false);
            }, true);
            return _this;
        }
        BlocksDialog.prototype.onShow = function () {
            var _this = this;
            Module.loadCategories(function () {
                _this.fields.list.setValue(Module.categories);
            });
        };
        BlocksDialog.prototype.onClose = function () {
            Module.close();
        };
        return BlocksDialog;
    }(Dialog_15["default"]));
    exports.BlocksDialog = BlocksDialog;
    ElementRegister_7["default"].registerClass('Blocks', BlocksElement);
    var Module = new BlocksModule();
    Service_29["default"].Blocks = { Module: Module };
});
define("EditFontsDialog", ["require", "exports", "Dialog", "Service", "FontManager", "DropdownBox", "BuilderEvent"], function (require, exports, Dialog_16, Service_30, FontManager_2, DropdownBox_9, BuilderEvent_11) {
    "use strict";
    exports.__esModule = true;
    var GoogleFontListItem = (function () {
        function GoogleFontListItem(data) {
            if (data) {
                this.name = data.name;
                this.title = data.title;
                this.fontId = data.fontId;
                this.usage = FontManager_2.GoogleFontUsage.fromJson(data.usage);
            }
        }
        GoogleFontListItem.prototype.serialize = function () {
            return {
                name: this.name,
                title: this.title,
                fontId: this.fontId,
                usage: this.usage.serialize()
            };
        };
        return GoogleFontListItem;
    }());
    var EditFontsErrorDialog = (function (_super) {
        __extends(EditFontsErrorDialog, _super);
        function EditFontsErrorDialog(title) {
            var _this = _super.call(this, title) || this;
            var ui = {};
            _this.content.empty();
            Service_30["default"].UIBuilder.buildLayout({ type: 'CustomContainer', init: function () {
                    this.getElem().append('<div class="alert alert-danger">' + FontManager_2.FontManager.error + '</div>');
                } }, _this.content, ui);
            return _this;
        }
        return EditFontsErrorDialog;
    }(Dialog_16["default"]));
    exports.EditFontsErrorDialog = EditFontsErrorDialog;
    var EditFontsDialog = (function (_super) {
        __extends(EditFontsDialog, _super);
        function EditFontsDialog(title) {
            var _this = _super.call(this, title) || this;
            _this.variants = {};
            _this.subsets = {};
            _this.selectedFont = null;
            var ui = {};
            var i, j;
            var font;
            var variants = [];
            var subsets = [];
            for (i in FontManager_2.FontManager.availableFonts) {
                var font_2 = FontManager_2.FontManager.availableFonts[i];
                for (var _i = 0, _a = font_2.variants; _i < _a.length; _i++) {
                    j = _a[_i];
                    if (variants.indexOf(j) < 0)
                        variants.push(j);
                }
                for (var _b = 0, _c = font_2.subsets; _b < _c.length; _b++) {
                    j = _c[_b];
                    if (subsets.indexOf(j) < 0)
                        subsets.push(j);
                }
            }
            for (i in wb_builder.site.usedCustomFonts) {
                var font_3 = wb_builder.site.usedCustomFonts[i].font;
                for (var _d = 0, _e = font_3.variants; _d < _e.length; _d++) {
                    j = _e[_d];
                    if (variants.indexOf(j) < 0)
                        variants.push(j);
                }
                for (var _f = 0, _g = font_3.subsets; _f < _g.length; _f++) {
                    j = _g[_f];
                    if (subsets.indexOf(j) < 0)
                        subsets.push(j);
                }
            }
            variants.sort();
            subsets.sort();
            var styleCheckboxes = [
                { type: 'Label', text: __('Style') }
            ];
            for (var _h = 0, variants_1 = variants; _h < variants_1.length; _h++) {
                i = variants_1[_h];
                styleCheckboxes.push({
                    type: "CheckBox",
                    id: "variant_" + i,
                    label: FontManager_2.GoogleFont.getVariantName(i),
                    value: i,
                    change: _this.updateItemOptions.bind(_this)
                });
            }
            var langCheckboxes = [
                { type: 'Label', text: __('Languages') }
            ];
            for (var _j = 0, subsets_1 = subsets; _j < subsets_1.length; _j++) {
                i = subsets_1[_j];
                langCheckboxes.push({
                    type: "CheckBox",
                    id: "subset_" + i,
                    label: FontManager_2.GoogleFont.getSubsetName(i),
                    value: i,
                    change: _this.updateItemOptions.bind(_this)
                });
            }
            _this.content.empty();
            Service_30["default"].UIBuilder.buildLayout({ type: 'VerticalLayout', children: [
                    { type: 'CustomContainer', id: "loader", visible: true, content: '<div class="text-center"><i class="fa fa-spinner fa-spin" style="font-size: 50px;"></i></div>' },
                    { type: 'HorizontalLayout', id: "interface", visible: false, columnWeightsSmall: [4, 8], columnWeights: [4, 8], children: [
                            { type: 'VerticalLayout', children: [
                                    { type: 'List', id: 'fonts',
                                        newItemButtonText: __("Add font"),
                                        editable: true,
                                        sortable: false,
                                        listHeight: 200,
                                        itemType: GoogleFontListItem,
                                        select: _this.onSelectFont.bind(_this),
                                        remove: _this.onRemoveFont.bind(_this),
                                        css: { height: "auto" }
                                    }
                                ] },
                            { type: 'VerticalLayout', children: [
                                    { type: 'Label', text: __('Preview') },
                                    { type: 'CustomContainer', id: 'preview', styleClass: "panel panel-default", css: { "margin-bottom": "15px", padding: "5px", fontFamily: "Arial", fontStyle: "italic", fontSize: "14px", color: "#AAA" }, content: __("Select and add a font") },
                                    { type: 'HorizontalLayout', id: "rightPane", visible: false, children: [
                                            { type: 'VerticalLayout', children: styleCheckboxes },
                                            { type: 'VerticalLayout', children: langCheckboxes }
                                        ] }
                                ] }
                        ] }
                ] }, _this.content, ui);
            _this.rightPane = ui.rightPane;
            _this.fonts = ui.fonts._control;
            _this.preview = ui.preview;
            for (var _k = 0, variants_2 = variants; _k < variants_2.length; _k++) {
                i = variants_2[_k];
                var vd = FontManager_2.GoogleFont.parseVariantCode(i);
                _this.variants[i] = ui["variant_" + i];
                _this.variants[i]._labelText.css({
                    "font-weight": vd.weight,
                    "font-style": vd.italic ? "italic" : "none"
                });
            }
            for (var _l = 0, subsets_2 = subsets; _l < subsets_2.length; _l++) {
                i = subsets_2[_l];
                _this.subsets[i] = ui["subset_" + i];
            }
            if ('latin' in _this.subsets)
                _this.subsets["latin"].setEnabled(false);
            _this.fonts.addBtn.unbind("click").bind("click", _this.onAddFont.bind(_this));
            _this.addFontForm = $('<div class="hidden" />');
            _this.fonts.addBtn.after(_this.addFontForm);
            Service_30["default"].UIBuilder.buildLayout({ type: 'VerticalLayout', children: [
                    { type: 'DropdownBox', id: 'newFontList' },
                    { type: 'FlowLayout', spacing: 0, children: [
                            { type: 'Button', text: __("Cancel"), click: _this.cancelAddFont.bind(_this), styleClass: "btn btn-link" },
                            { type: 'Button', text: __("Add"), click: _this.addFont.bind(_this), styleClass: "btn btn-link" }
                        ] }
                ] }, _this.addFontForm, ui);
            _this.newFontList = ui.newFontList;
            _this.dialog.children(".modal-dialog").addClass("modal-lg");
            _this.addButton(__("Cancel"), _this.onCancelButtonClick.bind(_this), false);
            setTimeout(function () {
                FontManager_2.FontManager.loadFontThumbs(function () {
                    _this.addButton(__("Apply"), _this.onApplyButtonClick.bind(_this), true);
                    _this.updateList();
                    ui.loader.setVisible(false);
                    ui.interface.setVisible(true);
                });
            }, 10);
            BuilderEvent_11.GlobalEvents.on("fonts.changed", function () {
                console.log("change2");
                _this.updateList();
            });
            return _this;
        }
        EditFontsDialog.prototype.addFontToList = function (fontId, uf, noStyleUpdate) {
            return this.fonts.addItem(new GoogleFontListItem({
                name: '<span style="font: 20px \'' + uf.font.family + '\';">' + uf.font.family + '</span>',
                title: uf.font.family,
                fontId: fontId,
                usage: uf.serialize()
            }), noStyleUpdate, " ");
        };
        EditFontsDialog.prototype.updateList = function () {
            if (!FontManager_2.FontManager.ready || !FontManager_2.FontManager.fontThumbs)
                return;
            this.rightPane.setVisible(false);
            this.fonts.removeAllItems();
            var forcedFonts = {};
            for (var _i = 0, _a = FontManager_2.FontManagerModule.getForcedCustomFonts(); _i < _a.length; _i++) {
                var i = _a[_i];
                forcedFonts[i] = true;
            }
            var isEmpty = true;
            for (var i in wb_builder.site.usedCustomFonts) {
                var uf = wb_builder.site.usedCustomFonts[i];
                if (forcedFonts.hasOwnProperty(uf.font.family))
                    continue;
                isEmpty = false;
                this.addFontToList(i, uf, true);
            }
            this.fonts.updateStyle();
            this.onSelectFont(null, null);
            this.fonts.selectFirst();
            if (isEmpty)
                this.onAddFont();
        };
        EditFontsDialog.prototype.onAddFont = function () {
            this.newFontList.removeAllItems();
            var i;
            var added = {};
            var li;
            for (var _i = 0, _a = this.fonts.getValue(); _i < _a.length; _i++) {
                li = _a[_i];
                added[li.fontId] = true;
            }
            for (var _b = 0, _c = FontManager_2.FontManagerModule.getHardcodedFontList(); _b < _c.length; _b++) {
                i = _c[_b];
                added[i] = true;
            }
            for (var _d = 0, _e = FontManager_2.FontManagerModule.getForcedCustomFonts(); _d < _e.length; _d++) {
                i = _e[_d];
                added[i] = true;
            }
            for (i in FontManager_2.FontManager.availableFonts) {
                if (added.hasOwnProperty(i))
                    continue;
                var font = FontManager_2.FontManager.availableFonts[i];
                this.newFontList.addItem(new DropdownBox_9.Item(font.family, i, null, FontManager_2.FontManager.getFontThumbnail(font).get(0).outerHTML));
            }
            this.fonts.addBtn.addClass("hidden");
            this.addFontForm.removeClass("hidden");
        };
        EditFontsDialog.prototype.cancelAddFont = function () {
            this.fonts.addBtn.removeClass("hidden");
            this.addFontForm.addClass("hidden");
        };
        EditFontsDialog.prototype.addFont = function () {
            var item = this.newFontList.getSelectedItem();
            var fontId = item ? item.getId() : "";
            if (!fontId) {
                alert(__("Please select a font to add"));
                return;
            }
            this.cancelAddFont();
            var fu = new FontManager_2.GoogleFontUsage();
            fu.font = FontManager_2.FontManager.availableFonts[fontId].clone();
            if (fu.font.variants.indexOf("400") >= 0)
                fu.variants = ["400"];
            else if (fu.font.variants.indexOf("400i") >= 0)
                fu.variants = ["400i"];
            else
                fu.variants = [fu.font.variants[0]];
            if (fu.font.subsets.indexOf("latin") >= 0)
                fu.subsets = ["latin"];
            else if (fu.font.subsets.indexOf("latin-ext") >= 0)
                fu.subsets = ["latin-ext"];
            else
                fu.subsets = [fu.font.subsets[0]];
            FontManager_2.FontManager.createFontLinkElement(fontId);
            this.fonts.selectItemLi(this.addFontToList(fontId, fu, false));
        };
        EditFontsDialog.prototype.onSelectFont = function (fields, item) {
            var i;
            var fu = item ? item.usage : null;
            if (item) {
                var css = { fontFamily: fu ? fu.font.getCssFontFamily() : "Arial", fontStyle: "" };
                this.rightPane.setVisible(true);
                this.preview.setContent('ABCDEFGHIJKLMNOPQRSTUVWXYZ<br />abcdefghijklmnopqrstuvwxyz<br />0123456789 !@#$%^&amp;*()');
                this.preview.css($.extend({ fontSize: "16px", color: "" }, css));
                FontManager_2.FontManager.createFontLinkElement(item.fontId);
                for (i in this.variants) {
                    this.variants[i].setVisible(fu != null && fu.font.variants.indexOf(i) >= 0).setValue(fu != null && fu.variants.indexOf(i) >= 0);
                    this.variants[i].getElem().css(css);
                }
                for (i in this.subsets)
                    this.subsets[i].setVisible(fu != null && fu.font.subsets.indexOf(i) >= 0).setValue(fu != null && fu.subsets.indexOf(i) >= 0);
            }
            else {
                this.preview.setContent(__("Select and add a font"));
                this.preview.css({ fontFamily: "Arial", fontStyle: "italic", fontSize: "14px", color: "#AAA" });
            }
            this.selectedFont = item;
        };
        EditFontsDialog.prototype.onRemoveFont = function (fields, item) {
            if (this.fonts.getValue().length == 1) {
                this.preview.setContent(__("Select and add a font"));
                this.preview.css({ fontFamily: "Arial", fontStyle: "italic", fontSize: "14px", color: "#AAA" });
                this.rightPane.setVisible(false);
                this.onAddFont();
            }
            else {
                if (this.fonts.lastSelected === item)
                    this.fonts.selectFirst();
            }
        };
        EditFontsDialog.prototype.updateItemOptions = function () {
            if (!this.selectedFont)
                return;
            var uf = this.selectedFont.usage;
            var i;
            uf.variants = [];
            for (var _i = 0, _a = uf.font.variants; _i < _a.length; _i++) {
                i = _a[_i];
                if (this.variants[i].getValue())
                    uf.variants.push(i);
            }
            uf.subsets = [];
            for (var _b = 0, _c = uf.font.subsets; _b < _c.length; _b++) {
                i = _c[_b];
                if (this.subsets[i].getValue())
                    uf.subsets.push(i);
            }
        };
        EditFontsDialog.prototype.onCancelButtonClick = function () {
            this.setVisible(false);
        };
        EditFontsDialog.prototype.onApplyButtonClick = function () {
            wb_builder.site.usedCustomFonts = {};
            FontManager_2.FontManager.forceCustomFontsUsage();
            for (var _i = 0, _a = this.fonts.getValue(); _i < _a.length; _i++) {
                var item = _a[_i];
                wb_builder.site.usedCustomFonts[item.fontId] = item.usage.clone();
            }
            this.fontsControl.updateOptions();
            if (this.selectedFont)
                this.fontsControl.setValue(this.selectedFont.usage.font.family);
            this.setVisible(false);
        };
        return EditFontsDialog;
    }(Dialog_16["default"]));
    exports.EditFontsDialog = EditFontsDialog;
});
define("RangeList", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var RangeList = (function () {
        function RangeList() {
            this.ranges = [];
        }
        RangeList.prototype.add = function (newRange, checkIntersections, priorityCheckCallback) {
            if (checkIntersections === void 0) { checkIntersections = true; }
            var addRange = true;
            if (checkIntersections) {
                if (priorityCheckCallback && typeof priorityCheckCallback !== "function")
                    throw new Error("priorityCheckCallback must be a callable function when specified.");
                var range = void 0, prioritizedRange = void 0, secondaryRange = void 0, secondaryRanges = [];
                for (var idx = this.ranges.length - 1; idx >= 0; idx--) {
                    range = this.ranges[idx];
                    if (newRange.to < range.from || newRange.from > range.to)
                        continue;
                    prioritizedRange = priorityCheckCallback ? priorityCheckCallback(newRange, range) : newRange;
                    if (prioritizedRange === range) {
                        if (newRange.from < range.from) {
                            if (newRange.to > range.to) {
                                secondaryRange = $.extend({}, newRange);
                                secondaryRange.from = range.to;
                                secondaryRanges.push(secondaryRange);
                            }
                            newRange.to = range.from;
                        }
                        else {
                            if (newRange.to <= range.to) {
                                addRange = false;
                                break;
                            }
                            newRange.from = range.to;
                        }
                    }
                    else {
                        if (range.from < newRange.from) {
                            if (range.to > newRange.to) {
                                secondaryRange = $.extend({}, range);
                                secondaryRange.from = newRange.to;
                                secondaryRanges.push(secondaryRange);
                            }
                            range.to = newRange.from;
                        }
                        else {
                            if (range.to <= newRange.to) {
                                this.ranges.splice(idx, 1);
                            }
                            else {
                                range.from = newRange.to;
                            }
                        }
                    }
                }
                if (secondaryRanges.length) {
                    for (var _i = 0, secondaryRanges_1 = secondaryRanges; _i < secondaryRanges_1.length; _i++) {
                        secondaryRange = secondaryRanges_1[_i];
                        this.add(secondaryRange, checkIntersections, priorityCheckCallback);
                    }
                }
            }
            if (addRange)
                this.ranges.push(newRange);
        };
        return RangeList;
    }());
    exports.RangeList = RangeList;
});
define("Rulers", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var RulerManager = (function () {
        function RulerManager() {
            this.invalidationTimer = null;
            this.rulers = [];
        }
        RulerManager.prototype.invalidate = function () {
            var _this = this;
            if (!this.invalidationTimer) {
                this.invalidationTimer = setTimeout(function () {
                    _this.render();
                    _this.invalidationTimer = null;
                }, 0);
            }
            return this;
        };
        RulerManager.prototype.render = function () {
            for (var _i = 0, _a = this.rulers; _i < _a.length; _i++) {
                var ruler = _a[_i];
                ruler.render();
            }
            return this;
        };
        RulerManager.prototype.addRuler = function (from, to, lineVisible) {
            if (lineVisible === void 0) { lineVisible = true; }
            var ruler = new Ruler(from, to, lineVisible);
            this.rulers.push(ruler);
            this.invalidate();
            return ruler;
        };
        RulerManager.prototype.removeRuler = function (ruler) {
            var i = this.rulers.indexOf(ruler);
            if (i >= 0) {
                this.rulers.splice(i, 1);
                ruler.onRemove();
            }
            return this;
        };
        RulerManager.prototype.clear = function () {
            for (var _i = 0, _a = this.rulers; _i < _a.length; _i++) {
                var ruler = _a[_i];
                ruler.onRemove();
            }
            this.rulers = [];
            this.invalidate();
            return this;
        };
        return RulerManager;
    }());
    var Ruler = (function () {
        function Ruler(from, to, lineVisible) {
            if (lineVisible === void 0) { lineVisible = true; }
            this.visible = true;
            this.lineVisible = true;
            this.renderedVisible = false;
            this.hElem = null;
            this.vElem = null;
            this.hMeasurement = null;
            this.vMeasurement = null;
            this.lineVisible = lineVisible;
            this.set(from, to);
        }
        Ruler.prototype.set = function (from, to) {
            this.from = from;
            this.to = to;
            exports.RulerManagerInstance.invalidate();
            return this;
        };
        Ruler.prototype.setVisible = function (visible) {
            if (this.visible != visible) {
                this.visible = visible;
                exports.RulerManagerInstance.invalidate();
            }
            return this;
        };
        Ruler.prototype.render = function () {
            if (!wb_builder.bodyInstance)
                return this;
            var delta;
            if (this.visible && (this.from.x !== this.to.x || this.from.y !== this.to.y)) {
                if (this.from.x !== this.to.x) {
                    if (!this.hElem) {
                        this.hElem = $('<div class="wb-ruler wb-ruler-horizontal">');
                        this.hMeasurement = $('<div class="wb-ruler-measurement">');
                        this.hElem.append(this.hMeasurement);
                        if (!this.lineVisible)
                            this.hElem.addClass("wb-ruler-no-line");
                        wb_builder.body.append(this.hElem);
                    }
                    delta = Math.round(Math.abs(this.to.x - this.from.x));
                    if (this.hMeasurement) {
                        this.hMeasurement.text(delta + "px");
                        if (this.from.y <= this.to.y)
                            this.hMeasurement.removeClass("wb-ruler-measurement-bottom").addClass("wb-ruler-measurement-top");
                        else
                            this.hMeasurement.removeClass("wb-ruler-measurement-top").addClass("wb-ruler-measurement-bottom");
                    }
                    this.hElem.removeClass("hidden").css({
                        left: Math.min(this.from.x, this.to.x),
                        top: this.from.y,
                        width: delta
                    });
                }
                else if (this.hElem)
                    this.hElem.addClass("hidden");
                if (this.from.y !== this.to.y) {
                    if (!this.vElem) {
                        this.vElem = $('<div class="wb-ruler wb-ruler-vertical">');
                        this.vMeasurement = $('<div class="wb-ruler-measurement">');
                        this.vElem.append(this.vMeasurement);
                        if (!this.lineVisible)
                            this.vElem.addClass("wb-ruler-no-line");
                        wb_builder.body.append(this.vElem);
                    }
                    delta = Math.round(Math.abs(this.to.y - this.from.y));
                    if (this.vMeasurement) {
                        this.vMeasurement.text(delta + "px");
                        if (this.from.x <= this.to.x)
                            this.vMeasurement.removeClass("wb-ruler-measurement-left").addClass("wb-ruler-measurement-right");
                        else
                            this.vMeasurement.removeClass("wb-ruler-measurement-right").addClass("wb-ruler-measurement-left");
                    }
                    this.vElem.removeClass("hidden").css({
                        left: this.to.x,
                        top: Math.min(this.from.y, this.to.y),
                        height: delta
                    });
                }
                else if (this.vElem)
                    this.vElem.addClass("hidden");
            }
            else {
                if (this.hElem)
                    this.hElem.addClass("hidden");
                if (this.vElem)
                    this.vElem.addClass("hidden");
            }
            this.renderedVisible = this.visible;
            return this;
        };
        Ruler.prototype.onRemove = function () {
            if (this.hElem) {
                this.hElem.remove();
                this.hElem = null;
            }
            if (this.vElem) {
                this.vElem.remove();
                this.vElem = null;
            }
        };
        return Ruler;
    }());
    exports.Ruler = Ruler;
    exports.RulerManagerInstance = new RulerManager();
});
define("ElementMeasurementHelpers", ["require", "exports", "RangeList", "Rulers", "CommonTypes"], function (require, exports, RangeList_1, Rulers_1, CommonTypes_1) {
    "use strict";
    exports.__esModule = true;
    var ElementMeasurementHelpers = (function () {
        function ElementMeasurementHelpers(element) {
            this.timeout = 0;
            this.rulers = [];
            this.element = element;
        }
        ElementMeasurementHelpers.prototype.show = function () {
            if (ElementMeasurementHelpers.disabled)
                return;
            if (this.timeout)
                this.hide();
            this.timeout = setTimeout(this.render.bind(this), 500);
        };
        ElementMeasurementHelpers.prototype.hide = function () {
            if (this.timeout) {
                clearTimeout(this.timeout);
                this.timeout = 0;
            }
            if (this.rulers.length)
                Rulers_1.RulerManagerInstance.clear();
        };
        ElementMeasurementHelpers.prototype.update = function () {
            if (ElementMeasurementHelpers.disabled || this.timeout)
                return;
            this.render();
        };
        ElementMeasurementHelpers.prototype.render = function () {
            this.timeout = 0;
            var otherLeft, otherTop, otherRight, otherBottom, distance;
            var leftRanges = new RangeList_1.RangeList();
            var topRanges = new RangeList_1.RangeList();
            var rightRanges = new RangeList_1.RangeList();
            var bottomRanges = new RangeList_1.RangeList();
            var otherBounds, bounds = this.element.getBounds();
            var left = Math.floor(bounds.pageLeft);
            var top = Math.floor(bounds.pageTop);
            var right = left + Math.floor(bounds.width);
            var bottom = top + Math.floor(bounds.height);
            var containerLeft = left - bounds.left;
            var containerTop = top - bounds.top;
            var containerRight = left + (this.element.getParent().getWidth() - bounds.left);
            var containerBottom = top + (this.element.getParent().getHeight() - bounds.top);
            if (left > containerLeft && left - containerLeft <= ElementMeasurementHelpers.MAX_HORIZONTAL_DISTANCE) {
                leftRanges.add({
                    from: Math.max(top, containerTop),
                    to: Math.min(bottom, containerBottom),
                    offset: containerLeft,
                    distance: left - containerLeft
                }, true, ElementMeasurementHelpers.checkRangePriority);
            }
            if (top > containerTop && top - containerTop <= ElementMeasurementHelpers.MAX_VERTICAL_DISTANCE) {
                topRanges.add({
                    from: Math.max(left, containerLeft),
                    to: Math.min(right, containerRight),
                    offset: containerTop,
                    distance: top - containerTop
                }, true, ElementMeasurementHelpers.checkRangePriority);
            }
            if (right < containerRight && containerRight - right <= ElementMeasurementHelpers.MAX_HORIZONTAL_DISTANCE) {
                rightRanges.add({
                    from: Math.max(top, containerTop),
                    to: Math.min(bottom, containerBottom),
                    offset: containerRight,
                    distance: containerRight - right
                }, true, ElementMeasurementHelpers.checkRangePriority);
            }
            if (bottom < containerBottom && containerBottom - bottom <= ElementMeasurementHelpers.MAX_VERTICAL_DISTANCE) {
                bottomRanges.add({
                    from: Math.max(left, containerLeft),
                    to: Math.min(right, containerRight),
                    offset: containerBottom,
                    distance: containerBottom - bottom
                }, true, ElementMeasurementHelpers.checkRangePriority);
            }
            var otherElements = this.element.getParent().getElements();
            for (var _i = 0, otherElements_1 = otherElements; _i < otherElements_1.length; _i++) {
                var otherElement = otherElements_1[_i];
                if (otherElement === this.element || otherElement.isHidden() || otherElement.isHidden(true))
                    continue;
                otherBounds = otherElement.getBounds();
                otherLeft = Math.floor(otherBounds.pageLeft);
                otherTop = Math.floor(otherBounds.pageTop);
                otherRight = otherLeft + Math.floor(otherBounds.width);
                otherBottom = otherTop + Math.floor(otherBounds.height);
                if (otherRight < left) {
                    if (otherTop < bottom && otherBottom > top) {
                        distance = left - otherRight;
                        if (distance <= ElementMeasurementHelpers.MAX_HORIZONTAL_DISTANCE) {
                            leftRanges.add({
                                from: Math.max(top, otherTop),
                                to: Math.min(bottom, otherBottom),
                                offset: otherRight,
                                distance: distance,
                            }, true, ElementMeasurementHelpers.checkRangePriority);
                        }
                    }
                }
                if (otherBottom < top) {
                    if (otherLeft < right && otherRight > left) {
                        distance = top - otherBottom;
                        if (distance <= ElementMeasurementHelpers.MAX_VERTICAL_DISTANCE) {
                            topRanges.add({
                                from: Math.max(left, otherLeft),
                                to: Math.min(right, otherRight),
                                offset: otherBottom,
                                distance: distance,
                            }, true, ElementMeasurementHelpers.checkRangePriority);
                        }
                    }
                }
                if (otherLeft > right) {
                    if (otherTop < bottom && otherBottom > top) {
                        distance = otherLeft - right;
                        if (distance <= ElementMeasurementHelpers.MAX_HORIZONTAL_DISTANCE) {
                            rightRanges.add({
                                from: Math.max(top, otherTop),
                                to: Math.min(bottom, otherBottom),
                                offset: otherLeft,
                                distance: distance,
                            }, true, ElementMeasurementHelpers.checkRangePriority);
                        }
                    }
                }
                if (otherTop > bottom) {
                    if (otherLeft < right && otherRight > left) {
                        distance = otherTop - bottom;
                        if (distance <= ElementMeasurementHelpers.MAX_VERTICAL_DISTANCE) {
                            bottomRanges.add({
                                from: Math.max(left, otherLeft),
                                to: Math.min(right, otherRight),
                                offset: otherTop,
                                distance: distance,
                            }, true, ElementMeasurementHelpers.checkRangePriority);
                        }
                    }
                }
            }
            ElementMeasurementHelpers.normalizeRangeList(leftRanges);
            ElementMeasurementHelpers.normalizeRangeList(topRanges);
            ElementMeasurementHelpers.normalizeRangeList(rightRanges);
            ElementMeasurementHelpers.normalizeRangeList(bottomRanges);
            Rulers_1.RulerManagerInstance.clear();
            this.renderRangeList("horizontal", left, leftRanges);
            this.renderRangeList("vertical", top, topRanges);
            this.renderRangeList("horizontal", right, rightRanges);
            this.renderRangeList("vertical", bottom, bottomRanges);
        };
        ElementMeasurementHelpers.checkRangePriority = function (newRange, storedRange) {
            if (storedRange.distance <= newRange.distance)
                return storedRange;
            return newRange;
        };
        ElementMeasurementHelpers.normalizeRangeList = function (rangeList) {
            rangeList.ranges.sort(function (a, b) {
                return (a.from < b.from) ? -1 : 1;
            });
            for (var i = rangeList.ranges.length - 1; i > 0; i--) {
                if (rangeList.ranges[i - 1].to === rangeList.ranges[i].from && rangeList.ranges[i - 1].distance === rangeList.ranges[i].distance) {
                    rangeList.ranges[i - 1].to = rangeList.ranges[i].to;
                    rangeList.ranges.splice(i, 1);
                }
            }
            var unique = {};
            rangeList.ranges = rangeList.ranges.filter(function (range) {
                var k = "" + range.distance;
                if (unique.hasOwnProperty(k))
                    return false;
                unique[k] = 1;
                return true;
            });
        };
        ElementMeasurementHelpers.prototype.renderRangeList = function (type, base, rangeList) {
            var pos, ruler;
            var shift = wb_builder.bodyInstance.getContentBlock(CommonTypes_1.ContentBlockId.Header).elem.offset().top;
            for (var _i = 0, _a = rangeList.ranges; _i < _a.length; _i++) {
                var range = _a[_i];
                pos = Math.floor((range.from + range.to) / 2);
                if (type === "vertical") {
                    ruler = Rulers_1.RulerManagerInstance.addRuler({ x: pos, y: base - shift }, { x: pos, y: range.offset - shift });
                }
                else {
                    ruler = Rulers_1.RulerManagerInstance.addRuler({ x: base, y: pos - shift }, { x: range.offset, y: pos - shift });
                }
                this.rulers.push(ruler);
            }
        };
        ElementMeasurementHelpers.MAX_HORIZONTAL_DISTANCE = 10000;
        ElementMeasurementHelpers.MAX_VERTICAL_DISTANCE = 500;
        ElementMeasurementHelpers.disabled = false;
        return ElementMeasurementHelpers;
    }());
    exports.ElementMeasurementHelpers = ElementMeasurementHelpers;
});
define("FreeGallery", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var rand = function (from, to) {
        var choices = to - from + 1;
        return Math.floor(Math.random() * choices + from);
    };
    var makeUrl = function (baseUrl, params) {
        var qs = Object.keys(params).map(function (i) { return i + '=' + (params[i] ? encodeURIComponent(params[i]) : ''); }).join('&');
        return baseUrl + (qs ? '?' + qs : '');
    };
    var FreeGalleryDef = (function () {
        function FreeGalleryDef() {
            this.galleries = {};
            this.current = null;
        }
        FreeGalleryDef.prototype.add = function (cls) {
            this.galleries[cls.ID] = cls;
        };
        FreeGalleryDef.prototype.resetPages = function () {
            for (var i in this.galleries) {
                this.galleries[i].totalImages = 0;
                this.galleries[i].page = 0;
            }
        };
        FreeGalleryDef.prototype.takeAnyFree = function () {
            var useGallery = null;
            var ids = Object.keys(this.galleries);
            while (ids.length > 0) {
                var idx = rand(0, ids.length - 1);
                var id = ids.splice(idx, 1)[0];
                var gallery = this.galleries[id];
                if (!gallery.totalPages || gallery.page < gallery.totalPages) {
                    useGallery = gallery;
                    break;
                }
            }
            return useGallery;
        };
        FreeGalleryDef.genOptionsFromArgs = function (args) {
            var res = {
                perPage: (args.perPage ? args.perPage : 25),
                forEach: ((args.forEach && (typeof args.forEach === 'function')) ? args.forEach : function (i, item) { }),
                beforeForEach: ((args.beforeForEach && (typeof args.beforeForEach === 'function')) ? args.beforeForEach : function () { }),
                afterForEach: ((args.afterForEach && (typeof args.afterForEach === 'function')) ? args.afterForEach : function () { }),
                emptyList: ((args.emptyList && (typeof args.emptyList === 'function')) ? args.emptyList : function () { })
            };
            return res;
        };
        FreeGalleryDef.prototype.init = function (args) {
            this.options = FreeGalleryDef.genOptionsFromArgs(args);
            this.resetPages();
        };
        FreeGalleryDef.prototype.load = function (searchQuery) {
            this.searchQuery = searchQuery ? searchQuery : null;
            this.current = this.takeAnyFree();
            if (this.current) {
                this.current.loadGallery(this.options, (this.current.page + 1), this.searchQuery);
                this.current.page++;
            }
        };
        return FreeGalleryDef;
    }());
    var FreeGallery = (function () {
        function FreeGallery() {
            this.page = 0;
            this.totalImages = 0;
            this.totalPages = 0;
        }
        return FreeGallery;
    }());
    var UnsplashGallery = (function (_super) {
        __extends(UnsplashGallery, _super);
        function UnsplashGallery() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.ID = 'unsplash';
            _this.KEY = 'd7d1134d5a4cb24f6aaca87fc75254aad7f6fad54750e8634e8d18c7353036c7';
            _this.IMAGES_URL = 'https://api.unsplash.com/search/photos/';
            _this.RANDOM_IMAGES_URL = 'https://api.unsplash.com/photos/';
            _this.MAX_RETRIES = 3;
            _this.retries = 0;
            return _this;
        }
        UnsplashGallery.prototype.url = function (page, query, perPage) {
            if (page === void 0) { page = 1; }
            if (query === void 0) { query = null; }
            if (perPage === void 0) { perPage = 25; }
            var url;
            var params = {};
            params['client_id'] = this.KEY;
            if (query) {
                params['query'] = query;
                url = this.IMAGES_URL;
            }
            else {
                url = this.RANDOM_IMAGES_URL;
            }
            params['per_page'] = '' + perPage;
            params['page'] = '' + page;
            return makeUrl(url, params);
        };
        UnsplashGallery.prototype.loadGallery = function (options, page, searchQuery) {
            var _this = this;
            if (page === void 0) { page = 1; }
            if (searchQuery === void 0) { searchQuery = null; }
            var url = this.url(page, searchQuery, options.perPage);
            $.ajax({
                url: url,
                success: function (data) {
                    _this.retries = 0;
                    var list = searchQuery ? data.results : data;
                    _this.totalPages = searchQuery ? data.total_pages : 1000;
                    _this.totalImages = list.length;
                    if (_this.totalImages) {
                        options.beforeForEach();
                        $.each(list, function (i, li) {
                            var item = {
                                url: li.urls.regular,
                                thumb: li.urls.thumb,
                                name: li.user.name,
                                title: li.user.name
                            };
                            options.forEach(i, item);
                        });
                        options.afterForEach();
                    }
                    else {
                        options.emptyList();
                    }
                },
                error: function () {
                    _this.retries++;
                    if (_this.retries < _this.MAX_RETRIES) {
                        _this.loadGallery(options, page, searchQuery);
                    }
                },
                dataType: 'json'
            });
        };
        return UnsplashGallery;
    }(FreeGallery));
    var PixabayGallery = (function (_super) {
        __extends(PixabayGallery, _super);
        function PixabayGallery() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.ID = 'pixabay';
            _this.KEY = '8464430-d10ea9b4543afa20b3042ab23';
            _this.IMAGES_URL = 'https://pixabay.com/api/';
            _this.MAX_RETRIES = 3;
            _this.retries = 0;
            return _this;
        }
        PixabayGallery.prototype.url = function (page, query, perPage) {
            if (page === void 0) { page = 1; }
            if (query === void 0) { query = null; }
            if (perPage === void 0) { perPage = 25; }
            var url = this.IMAGES_URL;
            var params = {};
            params['key'] = this.KEY;
            if (query)
                params['q'] = query;
            params['safesearch'] = 'true';
            params['per_page'] = '' + perPage;
            params['page'] = '' + page;
            return makeUrl(url, params);
        };
        PixabayGallery.prototype.loadGallery = function (options, page, searchQuery) {
            var _this = this;
            if (page === void 0) { page = 1; }
            if (searchQuery === void 0) { searchQuery = null; }
            var url = this.url(page, searchQuery, options.perPage);
            $.ajax({
                url: url,
                success: function (data) {
                    _this.retries = 0;
                    var list = data.hits;
                    _this.totalImages = list.length;
                    _this.totalPages = Math.ceil(data.totalHits / (options.perPage ? options.perPage : 20));
                    if (_this.totalImages) {
                        options.beforeForEach();
                        $.each(list, function (i, li) {
                            var item = {
                                url: li.largeImageURL,
                                thumb: li.previewURL,
                                name: li.user,
                                title: li.tags
                            };
                            options.forEach(i, item);
                        });
                        options.afterForEach();
                    }
                    else {
                        options.emptyList();
                    }
                },
                error: function () {
                    _this.retries++;
                    if (_this.retries < _this.MAX_RETRIES) {
                        _this.loadGallery(options, page, searchQuery);
                    }
                },
                dataType: 'json'
            });
        };
        return PixabayGallery;
    }(FreeGallery));
    exports.Module = new FreeGalleryDef();
    exports.Module.add(new PixabayGallery());
});
define("Guides", ["require", "exports", "BuilderEvent", "Service", "CommonTypes", "Rulers", "ElementMeasurementHelpers"], function (require, exports, BuilderEvent_12, Service_31, CommonTypes_2, Rulers_2, ElementMeasurementHelpers_1) {
    "use strict";
    exports.__esModule = true;
    var GuideKind;
    (function (GuideKind) {
        GuideKind["Horizontal"] = "horizontal";
        GuideKind["Vertical"] = "vertical";
    })(GuideKind = exports.GuideKind || (exports.GuideKind = {}));
    var GuideType;
    (function (GuideType) {
        GuideType["Edge"] = "edge";
        GuideType["Middle"] = "middle";
        GuideType["Custom"] = "custom";
    })(GuideType = exports.GuideType || (exports.GuideType = {}));
    var GuideManager = (function () {
        function GuideManager() {
            var _this = this;
            this.invalidationTimer = null;
            this.lastMousePosition = null;
            this.dragCounters = { horizontal: 0, vertical: 0 };
            this.helpPlayerVisible = false;
            this.documentRulerH = null;
            this.documentRulerV = null;
            this.documentRulerMeasureH = null;
            this.documentRulerMeasureV = null;
            this.modeGuides = {};
            for (var _i = 0, _a = Service_31["default"].modeManager.getModes(); _i < _a.length; _i++) {
                var mode = _a[_i];
                this.modeGuides[mode] = new GuideCollection(this, mode);
            }
            BuilderEvent_12.GlobalEvents.on("help.playershow help.playerhide", function (e) {
                _this.helpPlayerVisible = e.visible;
                _this.invalidate();
            });
            BuilderEvent_12.GlobalEvents.on("guides.show guides.hide", this.invalidate.bind(this));
            BuilderEvent_12.GlobalEvents.on("blocks.resize", this.invalidate.bind(this));
            BuilderEvent_12.GlobalEvents.on("page.load", this.onPageLoad.bind(this));
            BuilderEvent_12.GlobalEvents.on("modes.change", this.onModeChange.bind(this));
            BuilderEvent_12.GlobalEvents.on("builder.init", function () {
                $(window)
                    .on("resize", _this.invalidate.bind(_this))
                    .on("keydown", function (e) {
                    if (!_this.lastMousePosition)
                        return;
                    if (e.ctrlKey && e.shiftKey && e.key === "H") {
                        e.preventDefault();
                        e.stopImmediatePropagation();
                        _this.addGuide(GuideKind.Horizontal, _this.lastMousePosition.y - GuideManager.getPageContentOffset().y);
                    }
                    else if (e.ctrlKey && e.shiftKey && e.key === "V") {
                        e.preventDefault();
                        e.stopImmediatePropagation();
                        _this.addGuide(GuideKind.Vertical, _this.lastMousePosition.x - GuideManager.getPageContentOffset().x);
                    }
                })
                    .on("mousemove", function (e) {
                    _this.lastMousePosition = {
                        x: e.pageX,
                        y: e.pageY
                    };
                });
            });
        }
        GuideManager.prototype.getCurrentModeGuides = function () {
            return this.modeGuides[Service_31["default"].modeManager.getMode()];
        };
        GuideManager.getPageContentOffset = function () {
            if (wb_builder.bodyInstance) {
                var headerOffset = wb_builder.bodyInstance.getContentBlock("wb_header").container.offset();
                return { x: headerOffset.left, y: headerOffset.top };
            }
            return { x: 0, y: 0 };
        };
        GuideManager.prototype.invalidate = function () {
            var _this = this;
            if (!this.invalidationTimer) {
                this.invalidationTimer = setTimeout(function () {
                    _this.updateOffsets();
                    _this.render();
                    _this.invalidationTimer = null;
                }, 0);
            }
            return this;
        };
        GuideManager.prototype.reset = function () {
            for (var mode in this.modeGuides)
                this.modeGuides[mode].reset();
            return this;
        };
        GuideManager.prototype.updateOffsets = function () {
            var collection = this.getCurrentModeGuides();
            if (collection)
                collection.updateOffsets();
            return this;
        };
        GuideManager.prototype.render = function () {
            var _this = this;
            if (this.areGuidesVisible()) {
                if (!this.documentRulerH) {
                    this.documentRulerH = $('<div class="wb-document-ruler wb-document-ruler-horizontal"><div class="wb-document-ruler-corner"></div><div class="wb-drm"></div></div>');
                    this.documentRulerH.on("mousedown touchstart", function (e) {
                        var guide = _this.addGuide(GuideKind.Horizontal, 0);
                        if (guide) {
                            guide.onDragStart(e);
                            guide.onDragMove(e);
                        }
                    });
                    wb_builder.body.append(this.documentRulerH);
                }
                if (!this.documentRulerV) {
                    this.documentRulerV = $('<div class="wb-document-ruler wb-document-ruler-vertical"><div class="wb-drm"></div></div>');
                    this.documentRulerV.on("mousedown touchstart", function (e) {
                        var guide = _this.addGuide(GuideKind.Vertical, 0);
                        if (guide) {
                            guide.onDragStart(e);
                            guide.onDragMove(e);
                        }
                    });
                    wb_builder.body.append(this.documentRulerV);
                }
                if (!this.documentRulerMeasureH)
                    this.documentRulerMeasureH = this.documentRulerH.find(".wb-drm");
                if (!this.documentRulerMeasureV)
                    this.documentRulerMeasureV = this.documentRulerV.find(".wb-drm");
                this.documentRulerMeasureH.css("background-position-x", GuideManager.getPageContentOffset().x - 10);
                this.documentRulerH.removeClass("hidden");
                this.documentRulerV.removeClass("hidden");
                $(document.body).addClass("wb-rulers-enabled");
            }
            else {
                $(document.body).removeClass("wb-rulers-enabled");
                if (this.documentRulerH)
                    this.documentRulerH.addClass("hidden");
                if (this.documentRulerV)
                    this.documentRulerV.addClass("hidden");
            }
            for (var mode in this.modeGuides)
                this.modeGuides[mode].render();
            return this;
        };
        GuideManager.prototype.serialize = function () {
            var modeData = {};
            for (var mode in this.modeGuides)
                modeData[mode] = this.modeGuides[mode].serialize();
            return modeData;
        };
        GuideManager.prototype.deserialize = function (data) {
            this.reset();
            for (var mode in data) {
                if (!data.hasOwnProperty(mode))
                    continue;
                if (!this.modeGuides.hasOwnProperty(mode))
                    continue;
                this.modeGuides[mode].deserialize(data[mode]);
            }
            return this;
        };
        GuideManager.prototype.areGuidesVisible = function () {
            return wb_builder.showGuides && !this.helpPlayerVisible;
        };
        GuideManager.prototype.onPageLoad = function (e) {
            var page = wb_builder.site.getPage(e.pageId);
            if (page.guides)
                this.deserialize(page.guides);
            else
                this.reset();
        };
        GuideManager.prototype.onModeChange = function (e) {
            if (e.previousMode !== e.mode) {
                if (this.modeGuides.hasOwnProperty(e.previousMode))
                    this.modeGuides[e.previousMode].setVisible(false);
                if (this.modeGuides.hasOwnProperty(e.mode))
                    this.modeGuides[e.mode].setVisible(true);
            }
        };
        GuideManager.prototype.getActiveGuides = function () {
            var guides;
            var collection = (wb_builder.snapToGuides && !this.helpPlayerVisible) ? this.getCurrentModeGuides() : null;
            if (collection)
                guides = collection.getActiveGuides();
            else {
                guides = {};
                guides[GuideKind.Horizontal] = [];
                guides[GuideKind.Vertical] = [];
            }
            return guides;
        };
        GuideManager.prototype.addGuide = function (kind, offset) {
            return this.getCurrentModeGuides().addGuide(kind, offset);
        };
        GuideManager.prototype.removeGuide = function (guide) {
            this.getCurrentModeGuides().removeGuide(guide);
            return this;
        };
        GuideManager.prototype.onGuideDragStart = function (guide) {
            this.dragCounters[guide.getKind()]++;
        };
        GuideManager.prototype.onGuideDragMove = function (guide, pointerId, clientX, clientY) {
        };
        GuideManager.prototype.onGuideDragEnd = function (guide, pointerId, clientX, clientY) {
            this.dragCounters[guide.getKind()]--;
            return false;
        };
        return GuideManager;
    }());
    var GuideCollection = (function () {
        function GuideCollection(guideManager, mode) {
            this.visible = false;
            this.renderedVisible = { horizontal: false, vertical: false };
            this.guideManager = guideManager;
            this.mode = mode;
            this.modeWidth = Service_31["default"].modeManager.getModeWidth(this.mode);
            this.guides = {};
            this.guides[GuideKind.Horizontal] = [];
            this.guides[GuideKind.Vertical] = [];
        }
        GuideCollection.prototype.serialize = function () {
            var kind, guide, data = {};
            for (var _i = 0, _a = [GuideKind.Horizontal, GuideKind.Vertical]; _i < _a.length; _i++) {
                kind = _a[_i];
                data[kind] = [];
                for (var _b = 0, _c = this.guides[kind]; _b < _c.length; _b++) {
                    guide = _c[_b];
                    if (guide.getType() == GuideType.Custom)
                        data[kind].push(guide.serialize());
                }
            }
            return data;
        };
        GuideCollection.prototype.deserialize = function (data) {
            var kind, guideData, kindColl;
            this.reset();
            for (var _i = 0, _a = [GuideKind.Horizontal, GuideKind.Vertical]; _i < _a.length; _i++) {
                kind = _a[_i];
                if (!data.hasOwnProperty(kind))
                    continue;
                kindColl = data[kind];
                for (var _b = 0, kindColl_1 = kindColl; _b < kindColl_1.length; _b++) {
                    guideData = kindColl_1[_b];
                    this.guides[kind].push(new Guide(this, kind, GuideType.Custom, guideData));
                }
            }
            this.guideManager.invalidate();
            return this;
        };
        GuideCollection.prototype.getGuideManager = function () {
            return this.guideManager;
        };
        GuideCollection.prototype.getMode = function () {
            return this.mode;
        };
        GuideCollection.prototype.getModeWidth = function () {
            return this.modeWidth;
        };
        GuideCollection.prototype.reset = function () {
            var guide;
            for (var _i = 0, _a = this.guides[GuideKind.Horizontal]; _i < _a.length; _i++) {
                guide = _a[_i];
                guide.onRemove();
            }
            for (var _b = 0, _c = this.guides[GuideKind.Vertical]; _b < _c.length; _b++) {
                guide = _c[_b];
                guide.onRemove();
            }
            this.guides[GuideKind.Horizontal] = [
                new Guide(this, GuideKind.Horizontal, GuideType.Edge, { block: CommonTypes_2.ContentBlockId.Header }),
                new Guide(this, GuideKind.Horizontal, GuideType.Middle, { block: CommonTypes_2.ContentBlockId.Header }),
                new Guide(this, GuideKind.Horizontal, GuideType.Edge, { block: CommonTypes_2.ContentBlockId.Header }),
                new Guide(this, GuideKind.Horizontal, GuideType.Edge, { block: CommonTypes_2.ContentBlockId.Footer }),
                new Guide(this, GuideKind.Horizontal, GuideType.Middle, { block: CommonTypes_2.ContentBlockId.Footer }),
                new Guide(this, GuideKind.Horizontal, GuideType.Edge, { block: CommonTypes_2.ContentBlockId.Footer }),
            ];
            this.guides[GuideKind.Vertical] = [
                new Guide(this, GuideKind.Vertical, GuideType.Edge),
                new Guide(this, GuideKind.Vertical, GuideType.Middle),
                new Guide(this, GuideKind.Vertical, GuideType.Edge),
            ];
            this.guideManager.invalidate();
            return this;
        };
        GuideCollection.prototype.updateOffsets = function () {
            var kind, guide;
            if (wb_builder.bodyInstance) {
                var header = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header);
                var headerHeight = header.getHeight();
                var footerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Footer).getHeight();
                var contentWidth = this.modeWidth;
                if (!this.guides[GuideKind.Horizontal].length)
                    this.reset();
                this.guides[GuideKind.Horizontal][1].setRelOffset(Math.floor(headerHeight / 2));
                this.guides[GuideKind.Horizontal][2].setRelOffset(headerHeight);
                this.guides[GuideKind.Horizontal][4].setRelOffset(Math.floor(footerHeight / 2));
                this.guides[GuideKind.Horizontal][5].setRelOffset(footerHeight);
                this.guides[GuideKind.Vertical][1].setRelOffset(Math.floor(contentWidth / 2));
                this.guides[GuideKind.Vertical][2].setRelOffset(contentWidth);
                for (var _i = 0, _a = [GuideKind.Horizontal, GuideKind.Vertical]; _i < _a.length; _i++) {
                    kind = _a[_i];
                    for (var _b = 0, _c = this.guides[kind]; _b < _c.length; _b++) {
                        guide = _c[_b];
                        guide.calcOffset();
                    }
                }
            }
            return this;
        };
        GuideCollection.prototype.getMiddleGuides = function (kind) {
            if (kind === GuideKind.Vertical)
                return [this.guides[GuideKind.Vertical][1]];
            return [
                this.guides[GuideKind.Horizontal][1],
                this.guides[GuideKind.Horizontal][4]
            ];
        };
        GuideCollection.prototype.addGuide = function (kind, offset) {
            if (offset < 0)
                return null;
            var size = wb_builder.bodyInstance.getSiteSize();
            if (kind === GuideKind.Vertical) {
                if (offset > size.width)
                    return null;
            }
            else if (kind === GuideKind.Horizontal) {
                if (offset > size.height)
                    return null;
            }
            else
                throw new Error("Only horizontal and vertical guide types are supported");
            var guide = new Guide(this, kind, GuideType.Custom, { offset: offset });
            guide.calcRelOffset();
            this.guides[kind].push(guide);
            this.guideManager.invalidate();
            return guide;
        };
        GuideCollection.prototype.removeGuide = function (guide) {
            if (guide.getType() === GuideType.Custom) {
                var collection = this.guides[guide.getKind()];
                if (collection) {
                    for (var i = collection.length - 1; i >= 0; i--) {
                        if (collection[i] === guide) {
                            collection.splice(i, 1);
                            break;
                        }
                    }
                }
                guide.onRemove();
            }
            return this;
        };
        GuideCollection.prototype.setVisible = function (visible) {
            this.visible = visible;
            this.guideManager.invalidate();
            return this;
        };
        GuideCollection.prototype.render = function () {
            var visible = this.visible && this.guideManager.areGuidesVisible();
            var kind, guide, kindColl;
            for (var _i = 0, _a = [GuideKind.Horizontal, GuideKind.Vertical]; _i < _a.length; _i++) {
                kind = _a[_i];
                var showSystemGuides = this.guideManager.dragCounters[kind] > 0;
                if (visible || showSystemGuides || this.renderedVisible[kind]) {
                    kindColl = this.guides[kind];
                    for (var _b = 0, kindColl_2 = kindColl; _b < kindColl_2.length; _b++) {
                        guide = kindColl_2[_b];
                        guide.render(visible, showSystemGuides);
                    }
                }
                this.renderedVisible[kind] = visible || showSystemGuides;
            }
            return this;
        };
        GuideCollection.prototype.getActiveGuides = function () {
            var guides = {};
            var kind, guide, kindColl, outColl;
            for (var _i = 0, _a = [GuideKind.Horizontal, GuideKind.Vertical]; _i < _a.length; _i++) {
                kind = _a[_i];
                guides[kind] = outColl = [];
                kindColl = this.guides[kind];
                for (var _b = 0, kindColl_3 = kindColl; _b < kindColl_3.length; _b++) {
                    guide = kindColl_3[_b];
                    if (guide.getEnabled() && guide.getInBounds())
                        outColl.push(guide);
                }
            }
            return guides;
        };
        GuideCollection.prototype.getGuides = function () {
            return this.guides;
        };
        return GuideCollection;
    }());
    exports.GuideCollection = GuideCollection;
    var Guide = (function () {
        function Guide(collection, kind, type, data) {
            this.lineClass = "guide";
            this.block = null;
            this.offset = 0;
            this.relOffset = 0;
            this.enabled = true;
            this.elem = null;
            this.handleElem = null;
            this.renderedVisible = false;
            this.inBounds = true;
            this.dragPointerId = null;
            this.collection = collection;
            this.kind = kind;
            this.type = type;
            this.rulers = {};
            if (data)
                this.deserialize(data);
        }
        Guide.prototype.serialize = function () {
            return {
                block: this.block,
                relOffset: this.relOffset,
                enabled: this.enabled
            };
        };
        Guide.prototype.deserialize = function (data) {
            this.block = data.block ? data.block : null;
            this.enabled = data.enabled ? data.enabled : true;
            if (data.hasOwnProperty("offset")) {
                this.offset = data.offset;
                this.calcRelOffset();
            }
            else if (data.hasOwnProperty("relOffset")) {
                this.relOffset = data.relOffset;
                this.calcOffset();
            }
            return this;
        };
        Guide.prototype.getKind = function () {
            return this.kind;
        };
        Guide.prototype.getType = function () {
            return this.type;
        };
        Guide.prototype.setEnabled = function (enabled) {
            this.enabled = enabled;
            return this;
        };
        Guide.prototype.getEnabled = function () {
            return this.enabled;
        };
        Guide.prototype.getInBounds = function () {
            return this.inBounds;
        };
        Guide.prototype.getOffset = function () {
            return this.offset;
        };
        Guide.prototype.setRelOffset = function (offset) {
            this.relOffset = offset;
            this.calcOffset();
            return this;
        };
        Guide.prototype.getRelOffset = function () {
            return this.relOffset;
        };
        Guide.prototype.moveTo = function (newOffset) {
            this.offset = newOffset;
            this.calcRelOffset();
            this.collection.getGuideManager().invalidate();
            return this;
        };
        Guide.prototype.calcOffset = function () {
            this.offset = this.relOffset;
            if (wb_builder.bodyInstance) {
                if (this.kind == GuideKind.Horizontal) {
                    var headerHeight = void 0, mainHeight = void 0, footerHeight = void 0;
                    if (this.block === CommonTypes_2.ContentBlockId.Header) {
                        headerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight();
                        this.inBounds = this.relOffset >= 0 && this.relOffset <= headerHeight;
                    }
                    else if (this.block === CommonTypes_2.ContentBlockId.Main) {
                        headerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight();
                        mainHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Main).getHeight();
                        this.offset += headerHeight;
                        this.inBounds = this.relOffset > 0 && this.relOffset < mainHeight;
                    }
                    else if (this.block === CommonTypes_2.ContentBlockId.Footer) {
                        headerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight();
                        mainHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Main).getHeight();
                        footerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Footer).getHeight();
                        this.offset += headerHeight + mainHeight;
                        this.inBounds = this.relOffset >= 0 && this.relOffset <= footerHeight;
                    }
                }
                else {
                    this.inBounds = true;
                }
            }
            return this;
        };
        Guide.prototype.calcRelOffset = function () {
            this.relOffset = this.offset;
            if (wb_builder.bodyInstance) {
                if (this.kind == GuideKind.Horizontal) {
                    var headerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight();
                    var mainHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Main).getHeight();
                    var footerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Footer).getHeight();
                    if (this.offset <= headerHeight) {
                        this.block = CommonTypes_2.ContentBlockId.Header;
                    }
                    else if (this.offset < headerHeight + mainHeight) {
                        this.block = CommonTypes_2.ContentBlockId.Main;
                        this.relOffset -= headerHeight;
                    }
                    else {
                        this.block = CommonTypes_2.ContentBlockId.Footer;
                        this.relOffset -= headerHeight + mainHeight;
                    }
                    this.inBounds = this.offset >= 0 && this.offset <= headerHeight + mainHeight + footerHeight;
                }
                else {
                    this.inBounds = true;
                }
            }
            return this;
        };
        Guide.prototype.render = function (visible, showSystemGuides) {
            if (showSystemGuides === void 0) { showSystemGuides = false; }
            if (wb_builder.bodyInstance) {
                visible = visible && (showSystemGuides || this.type === GuideType.Custom);
                var hideHandle = true;
                if (visible && (this.inBounds || this.dragPointerId)) {
                    if (!this.elem) {
                        this.elem = $('<div class="hidden wb-guide wb-guide-' + this.kind + ' wb-guide-' + this.type + '">');
                        if (this.kind === GuideKind.Vertical)
                            $("#head").append(this.elem);
                        else
                            wb_builder.body.append(this.elem);
                    }
                    if (this.kind === GuideKind.Vertical)
                        this.elem.css("left", this.offset + GuideManager.getPageContentOffset().x);
                    else
                        this.elem.css("top", this.offset);
                    if (this.type === GuideType.Custom && wb_builder.showGuides) {
                        hideHandle = false;
                        if (!this.handleElem) {
                            this.handleElem = $('<div class="hidden wb-guide-handle wb-guide-handle-' + this.kind + ' wb-guide-handle-' + this.type + '">');
                            this.handleElem.data("guide", this);
                            if (this.kind === GuideKind.Vertical)
                                $("#head").append(this.handleElem);
                            else
                                wb_builder.body.append(this.handleElem);
                            this.handleElem
                                .on('mousedown touchstart', this.onDragStart.bind(this));
                        }
                        if (this.kind === GuideKind.Vertical)
                            this.handleElem.css("left", this.offset + GuideManager.getPageContentOffset().x);
                        else
                            this.handleElem.css("top", this.offset);
                    }
                    if (!this.renderedVisible) {
                        if (this.dragPointerId) {
                            this.elem.addClass("wb-guide-dragging");
                            if (this.handleElem)
                                this.handleElem.addClass("wb-guide-dragging");
                        }
                        this.elem.removeClass("hidden");
                        if (this.handleElem && !hideHandle)
                            this.handleElem.removeClass("hidden");
                        this.renderedVisible = true;
                    }
                }
                else if (this.elem && this.renderedVisible) {
                    this.elem.addClass("hidden");
                    this.renderedVisible = false;
                }
                if (hideHandle && this.handleElem) {
                    this.handleElem.addClass("hidden");
                }
            }
            return this;
        };
        Guide.prototype.renderRulers = function () {
            var from, to;
            var siteSize = wb_builder.bodyInstance.getSiteSize();
            var headOffset = GuideManager.getPageContentOffset();
            var topOffset = headOffset.y;
            var margins = Math.max(0, headOffset.x - 1);
            var viewHeight = $(window).height() - topOffset;
            var scrollTop = $(window).scrollTop();
            var middleGuide, middleGuides = this.collection.getMiddleGuides(this.kind);
            var prevGuide = null, nextGuide = null, prevGuideDistance = 0, nextGuideDistance = 0, guideDistance, otherGuideOffset;
            var otherGuides = this.collection.getGuides()[this.kind], otherGuide;
            for (var _i = 0, otherGuides_1 = otherGuides; _i < otherGuides_1.length; _i++) {
                otherGuide = otherGuides_1[_i];
                if (otherGuide.getType() != GuideType.Custom || !otherGuide.getInBounds())
                    continue;
                otherGuideOffset = otherGuide.getOffset();
                guideDistance = Math.abs(this.offset - otherGuideOffset);
                if (otherGuideOffset < this.offset) {
                    if (prevGuide === null || guideDistance < prevGuideDistance) {
                        prevGuideDistance = guideDistance;
                        prevGuide = otherGuide;
                    }
                }
                else if (otherGuideOffset > this.offset) {
                    if (nextGuide === null || guideDistance < nextGuideDistance) {
                        nextGuideDistance = guideDistance;
                        nextGuide = otherGuide;
                    }
                }
            }
            if (this.kind == GuideKind.Vertical) {
                if (this.offset >= -margins && this.offset < siteSize.width) {
                    from = { x: headOffset.x + this.offset, y: Math.floor(scrollTop + viewHeight * 3 / 4) };
                    to = { x: headOffset.x, y: from.y };
                    if (!this.rulers.minEdge)
                        this.rulers.minEdge = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.minEdge.set(from, to);
                    this.rulers.minEdge.setVisible(true);
                }
                else if (this.rulers.minEdge)
                    this.rulers.minEdge.setVisible(false);
                if (this.offset > 0 && this.offset <= siteSize.width + margins) {
                    from = { x: headOffset.x + this.offset, y: Math.floor(scrollTop + viewHeight * 3 / 4) };
                    to = { x: headOffset.x + siteSize.width, y: from.y };
                    if (!this.rulers.maxEdge)
                        this.rulers.maxEdge = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.maxEdge.set(from, to);
                    this.rulers.maxEdge.setVisible(true);
                }
                else if (this.rulers.maxEdge)
                    this.rulers.maxEdge.setVisible(false);
                middleGuide = middleGuides[0];
                if (middleGuide.getOffset() !== this.offset) {
                    from = { x: headOffset.x + this.offset, y: Math.floor(scrollTop + viewHeight * 2 / 4) };
                    to = { x: headOffset.x + middleGuide.getOffset(), y: from.y };
                    if (!this.rulers.middleGuide)
                        this.rulers.middleGuide = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.middleGuide.set(from, to);
                    this.rulers.middleGuide.setVisible(true);
                }
                else if (this.rulers.middleGuide)
                    this.rulers.middleGuide.setVisible(false);
                if (prevGuide) {
                    from = { x: headOffset.x + this.offset, y: Math.floor(scrollTop + viewHeight / 4) };
                    to = { x: headOffset.x + prevGuide.getOffset(), y: from.y };
                    if (!this.rulers.prevGuide)
                        this.rulers.prevGuide = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.prevGuide.set(from, to);
                    this.rulers.prevGuide.setVisible(true);
                }
                else if (this.rulers.prevGuide)
                    this.rulers.prevGuide.setVisible(false);
                if (nextGuide) {
                    from = { x: headOffset.x + this.offset, y: Math.floor(scrollTop + viewHeight / 4) };
                    to = { x: headOffset.x + nextGuide.getOffset(), y: from.y };
                    if (!this.rulers.nextGuide)
                        this.rulers.nextGuide = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.nextGuide.set(from, to);
                    this.rulers.nextGuide.setVisible(true);
                }
                else if (this.rulers.nextGuide)
                    this.rulers.nextGuide.setVisible(false);
            }
            if (this.kind == GuideKind.Horizontal) {
                if (this.offset > 0 && this.offset < siteSize.height) {
                    from = { x: headOffset.x + Math.floor(siteSize.width * 4 / 5), y: this.offset };
                    to = { x: from.x, y: 0 };
                    if (!this.rulers.minEdge)
                        this.rulers.minEdge = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.minEdge.set(from, to);
                    this.rulers.minEdge.setVisible(true);
                }
                else if (this.rulers.minEdge)
                    this.rulers.minEdge.setVisible(false);
                if (this.offset > 0 && this.offset < siteSize.height) {
                    from = { x: headOffset.x + Math.floor(siteSize.width * 4 / 5), y: this.offset };
                    to = { x: from.x, y: siteSize.height };
                    if (!this.rulers.maxEdge)
                        this.rulers.maxEdge = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.maxEdge.set(from, to);
                    this.rulers.maxEdge.setVisible(true);
                }
                else if (this.rulers.maxEdge)
                    this.rulers.maxEdge.setVisible(false);
                if (middleGuides.length) {
                    middleGuide = (Math.abs(middleGuides[0].getOffset() - this.offset) <= Math.abs(middleGuides[1].getOffset() - this.offset)) ? middleGuides[0] : middleGuides[1];
                    if (middleGuide.getOffset() !== this.offset) {
                        from = { x: headOffset.x + Math.floor(siteSize.width * 3 / 5), y: this.offset };
                        to = { x: from.x, y: middleGuide.getOffset() };
                        if (!this.rulers.middleGuide)
                            this.rulers.middleGuide = Rulers_2.RulerManagerInstance.addRuler(from, to);
                        else
                            this.rulers.middleGuide.set(from, to);
                        this.rulers.middleGuide.setVisible(true);
                    }
                    else if (this.rulers.middleGuide)
                        this.rulers.middleGuide.setVisible(false);
                }
                var blockTop = void 0, blockBottom = void 0;
                var headerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight();
                var mainHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Main).getHeight();
                var footerHeight = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Footer).getHeight();
                if (this.block === CommonTypes_2.ContentBlockId.Header) {
                    blockTop = 0;
                    blockBottom = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight();
                }
                else if (this.block === CommonTypes_2.ContentBlockId.Footer) {
                    blockTop = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight()
                        + wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Main).getHeight();
                    blockBottom = siteSize.height;
                }
                else {
                    blockTop = wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Header).getHeight();
                    blockBottom = blockTop + wb_builder.bodyInstance.getContentBlock(CommonTypes_2.ContentBlockId.Main).getHeight();
                }
                if (this.offset > 0 && this.offset < siteSize.height) {
                    from = { x: headOffset.x + Math.floor(siteSize.width * 2 / 5), y: this.offset };
                    to = { x: from.x, y: blockTop };
                    if (!this.rulers.minBlock)
                        this.rulers.minBlock = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.minBlock.set(from, to);
                    this.rulers.minBlock.setVisible(true);
                }
                else if (this.rulers.minBlock)
                    this.rulers.minBlock.setVisible(false);
                if (this.offset > 0 && this.offset < siteSize.height) {
                    from = { x: headOffset.x + Math.floor(siteSize.width * 2 / 5), y: this.offset };
                    to = { x: from.x, y: blockBottom };
                    if (!this.rulers.maxBlock)
                        this.rulers.maxBlock = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.maxBlock.set(from, to);
                    this.rulers.maxBlock.setVisible(true);
                }
                else if (this.rulers.maxBlock)
                    this.rulers.maxBlock.setVisible(false);
                if (prevGuide) {
                    from = { x: headOffset.x + Math.floor(siteSize.width / 5), y: this.offset };
                    to = { x: from.x, y: prevGuide.getOffset() };
                    if (!this.rulers.prevGuide)
                        this.rulers.prevGuide = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.prevGuide.set(from, to);
                    this.rulers.prevGuide.setVisible(true);
                }
                else if (this.rulers.prevGuide)
                    this.rulers.prevGuide.setVisible(false);
                if (nextGuide) {
                    from = { x: headOffset.x + Math.floor(siteSize.width / 5), y: this.offset };
                    to = { x: from.x, y: nextGuide.getOffset() };
                    if (!this.rulers.nextGuide)
                        this.rulers.nextGuide = Rulers_2.RulerManagerInstance.addRuler(from, to);
                    else
                        this.rulers.nextGuide.set(from, to);
                    this.rulers.nextGuide.setVisible(true);
                }
                else if (this.rulers.nextGuide)
                    this.rulers.nextGuide.setVisible(false);
            }
            return this;
        };
        Guide.prototype.clearRulers = function () {
            this.rulers = {};
            Rulers_2.RulerManagerInstance.clear();
            return this;
        };
        Guide.prototype.onRemove = function () {
            if (this.elem)
                this.elem.remove();
            if (this.handleElem)
                this.handleElem.remove();
            if (this.dragPointerId !== null) {
                $(window)
                    .off('mousemove touchmove', this.dragMoveEventHandler)
                    .off('mouseup touchend touchcancel', this.dragEndEventHandler);
            }
            this.handleElem = this.elem = this.dragPointerId = null;
            this.clearRulers();
        };
        Guide.prototype.onDragStart = function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            if (!this.dragMoveEventHandler)
                this.dragMoveEventHandler = this.onDragMove.bind(this);
            if (!this.dragEndEventHandler)
                this.dragEndEventHandler = this.onDragEnd.bind(this);
            $(window)
                .on('mousemove touchmove', this.dragMoveEventHandler)
                .on('mouseup touchend touchcancel', this.dragEndEventHandler);
            if (e.type == "mousedown") {
                this.dragPointerId = "mouse";
            }
            else if (e.type == "touchstart") {
                var touch = e.originalEvent.changedTouches[0];
                this.dragPointerId = touch.identifier ? touch.identifier : "unknown touch";
            }
            if (this.dragPointerId) {
                ElementMeasurementHelpers_1.ElementMeasurementHelpers.disabled = true;
                if (this.elem)
                    this.elem.addClass("wb-guide-dragging");
                if (this.handleElem)
                    this.handleElem.addClass("wb-guide-dragging");
                this.renderRulers();
                this.collection.getGuideManager().invalidate().onGuideDragStart(this);
            }
        };
        Guide.prototype.onDragMove = function (e) {
            var cursor = null;
            if (e.type == "mousemove" || e.type == "mousedown") {
                if (this.dragPointerId === "mouse") {
                    cursor = { x: e.pageX, y: e.pageY, clientX: e.clientX, clientY: e.clientY };
                }
            }
            else if (e.type == "touchmove" || e.type == "touchstart") {
                for (var _i = 0, _a = e.originalEvent.changedTouches; _i < _a.length; _i++) {
                    var touch = _a[_i];
                    if (this.dragPointerId === "unknown touch" || this.dragPointerId === touch.identifier) {
                        cursor = { x: touch.pageX, y: touch.pageY, clientX: touch.clientX, clientY: touch.clientY };
                        break;
                    }
                }
            }
            if (cursor) {
                if (this.kind == GuideKind.Vertical) {
                    this.offset = Math.round(cursor.x) - GuideManager.getPageContentOffset().x;
                }
                else {
                    this.offset = Math.round(cursor.y) - GuideManager.getPageContentOffset().y;
                }
                this.calcRelOffset();
                this.render(true);
                this.renderRulers();
                this.collection.getGuideManager().onGuideDragMove(this, this.dragPointerId, cursor.clientX, cursor.clientY);
            }
        };
        Guide.prototype.onDragEnd = function (e) {
            var cursor = null;
            if (e.type == "mouseup") {
                if (this.dragPointerId === "mouse") {
                    cursor = { x: e.pageX, y: e.pageY, clientX: e.clientX, clientY: e.clientY };
                }
            }
            else if (e.type == "touchend" || e.type == "touchcancel") {
                for (var _i = 0, _a = e.originalEvent.changedTouches; _i < _a.length; _i++) {
                    var touch = _a[_i];
                    if (this.dragPointerId === "unknown touch" || this.dragPointerId === touch.identifier) {
                        cursor = { x: touch.pageX, y: touch.pageY, clientX: touch.clientX, clientY: touch.clientY };
                        break;
                    }
                }
            }
            if (cursor) {
                ElementMeasurementHelpers_1.ElementMeasurementHelpers.disabled = false;
                $(window)
                    .off('mousemove touchmove', this.dragMoveEventHandler)
                    .off('mouseup touchend touchcancel', this.dragEndEventHandler);
                this.clearRulers();
                if (this.elem)
                    this.elem.removeClass("wb-guide-dragging");
                if (this.handleElem)
                    this.handleElem.removeClass("wb-guide-dragging");
                var remove = false;
                if ($(e.target).closest(".wb-guide-manager-remove-guide").length)
                    remove = true;
                else if (cursor) {
                    if (this.kind === GuideKind.Vertical) {
                        if (cursor.x < 0 || cursor.x > $(window).width())
                            remove = true;
                    }
                    else {
                        var size = wb_builder.bodyInstance.getSiteSize();
                        if (this.offset < 0 || this.offset > size.height)
                            remove = true;
                    }
                    remove = this.collection.getGuideManager().onGuideDragEnd(this, this.dragPointerId, cursor.clientX, cursor.clientY) || remove;
                }
                if ((this.kind === GuideKind.Vertical && cursor.clientX <= 6) || this.kind === GuideKind.Horizontal && cursor.clientY >= $(window).height() - 6)
                    remove = true;
                if (remove)
                    this.collection.getGuideManager().removeGuide(this);
                else
                    this.collection.getGuideManager().invalidate();
                this.dragPointerId = null;
            }
        };
        return Guide;
    }());
    exports.Guide = Guide;
    exports.GuideManagerInstance = new GuideManager();
});
define("MenuListControl", ["require", "exports", "ComboBox", "util/MenuList"], function (require, exports, ComboBox_1, MenuList_2) {
    "use strict";
    exports.__esModule = true;
    var MenuListControl = (function () {
        function MenuListControl(noFixedWidth, anchorMode, config) {
            if (noFixedWidth === void 0) { noFixedWidth = false; }
            if (anchorMode === void 0) { anchorMode = false; }
            this._maxNameLength = 24;
            this._elem = new ComboBox_1["default"]();
            if (config) {
                this._elem.onBeforeChange = config.onBeforeChange;
                this._elem.onChange = config.onChange;
            }
            if (!noFixedWidth) {
                this._elem.elem.css({ width: '220px' });
            }
            else {
                this._maxNameLength = 38;
            }
            this.anchorMode = !!anchorMode;
            this.input = this._elem.input;
            this.button = this._elem.button;
            this.elem = this._elem.elem;
            this.reloadMenuList();
        }
        MenuListControl.prototype.getItems = function () {
            return this._elem.getOptionsData();
        };
        MenuListControl.prototype.reloadMenuList = function () {
            this._elem.removeAllOptions();
            var pd = '&nbsp;&nbsp;&nbsp;&nbsp;';
            var menuList = MenuList_2.buildMenuStruct(this.anchorMode, false, null, true);
            var first = true;
            for (var _i = 0, menuList_1 = menuList; _i < menuList_1.length; _i++) {
                var menu = menuList_1[_i];
                if (menu.items.length == 0)
                    continue;
                if (first)
                    first = false;
                else
                    this._elem.addSeparator();
                for (var _a = 0, _b = menu.items; _a < _b.length; _a++) {
                    var mi = _b[_a];
                    var ident = '', identIdx = mi.lvl;
                    while (identIdx > 0) {
                        identIdx--;
                        ident += pd;
                    }
                    var opt = this._elem.addOption(mi.uID, ident + mi.name, mi.isCurrent(), mi);
                    opt.find('a').attr('title', mi.fullName);
                    if (!mi.anchor) {
                        opt.attr('data-type', mi.type);
                        opt.attr('data-target', $.JSON.encode(mi.isExternal() ? mi.url : mi.pageId));
                    }
                }
                if (!this.anchorMode)
                    buildEditToolbar(this._elem, menu);
            }
        };
        MenuListControl.prototype.getExtendedValue = function () {
            return this._elem.getValueData();
        };
        MenuListControl.prototype.setExtendedValue = function (value) {
            if (value.menuUID) {
                this._elem.setValue('' + value.menuUID + '_' + value.id + (value.anchor ? '_' + value.anchor : ''));
            }
            else {
                this.setValue('' + value.id);
            }
        };
        MenuListControl.prototype.getValue = function () {
            var data = this._elem.getValueData();
            return (data && data.id) ? data.id : 0;
        };
        MenuListControl.prototype.setValue = function (value) {
            for (var k in this._elem.optionsData) {
                if (this._elem.optionsData[k].data && this._elem.optionsData[k].data.id === parseInt('' + value, 10)) {
                    this._elem.setValue(k);
                }
            }
        };
        MenuListControl.prototype.open = function () {
            this._elem.menu.parent().addClass('open');
        };
        MenuListControl.prototype.close = function () {
            this._elem.menu.parent().removeClass('open');
        };
        return MenuListControl;
    }());
    exports.MenuListControl = MenuListControl;
    function buildEditToolbarLabel(text, checked) {
        return $('<span>')
            .addClass('wb-menuselector-btn wb-menuselector-label')
            .addClass((checked ? 'checked' : ''))
            .append($('<span>').addClass('wb-menuselector-text').text(text));
    }
    function buildEditToolbarButton(title, icon, func) {
        return $('<span>')
            .addClass('wb-menuselector-btn')
            .attr({ title: title })
            .append($('<span>').addClass('wb-menuselector-icon ' + icon))
            .append($('<span>').addClass('wb-menuselector-text').text(title))
            .on('click', func);
    }
    function buildEditToolbar(thisElem, menuElem) {
        var tb = $('<span>').addClass('wb-menuselector-tb');
        if (menuElem.isEditable()) {
            tb.append(buildEditToolbarButton(__('Edit'), 'glyphicon glyphicon-pencil', function () { menuElem.edit(); return false; }));
        }
        if (menuElem.isRemovable()) {
            tb.append(buildEditToolbarButton(__('Remove'), 'glyphicon glyphicon-trash', function () { menuElem.remove(); return false; }));
        }
        var landingChecked = wb_builder.site.landing;
        if (landingChecked) {
            var hasHomePage = false;
            for (var _i = 0, _a = menuElem.items; _i < _a.length; _i++) {
                var item = _a[_i];
                var p = void 0;
                if (item.type === 'page' && item.pageId
                    && (p = wb_builder.site.getPage(item.pageId)) && p.isFront) {
                    hasHomePage = true;
                    break;
                }
            }
            if (hasHomePage) {
                var landingItem = buildEditToolbarLabel(__('Landing'), landingChecked);
                landingItem.tooltip({ title: __('All pages from this menu will be published as one page with common header and footer of homepage'), placement: 'top' });
                tb.append(landingItem);
            }
        }
        thisElem.addOption(menuElem.uID + '_edit', '', false, null, true)
            .append(tb);
        return tb;
    }
});
define("PremiumButton", ["require", "exports", "MsgDialog", "MobileToolbar"], function (require, exports, MsgDialog_5, MobileToolbar_1) {
    "use strict";
    exports.__esModule = true;
    var prmDlg = null;
    function init(builder) {
        if (!builder.premiumButtonType)
            return;
        var groupsPro = $('<div></div>').addClass('wb_toolbar_groups_pro');
        $('.wb_toolbar_all').append(groupsPro);
        var sliceIndex = 0, i;
        for (i = 0; i < builder.pluginToolbar.length; i++) {
            switch (builder.pluginToolbar[i].id) {
                case 'wb-group-additional':
                    if (builder.tinyMode)
                        sliceIndex++;
                    break;
                case 'wb-group-social':
                case 'wb-group-advanced':
                case 'wb-group-complex':
                case 'wb-group-commerce':
                case 'wb-group-maps':
                    sliceIndex++;
                    break;
            }
        }
        sliceIndex += (sliceIndex - 1);
        var proTb = "";
        if ($("#wb_pro_version").length > 0) {
            $("#wb_pro_version").bind("click", function () {
                location.href = builder.buyProUrl;
                return false;
            });
            $(".wb_toolbar_pro").find(".wb_item[id^=wb__]").each(function () {
                $(this).css({ opacity: 0.3 });
                $(this).attr("title", __("Available only with PRO account"));
            }).css("cursor", "default");
        }
        else {
            proTb = ",.wb_toolbar_pro";
        }
        $(".wb_toolbar_all" + proTb).find(".wb_item_group, .wb_item_sep").slice(-sliceIndex).each(function () {
            $(this).children('.wb_item_grouper').addClass('wb_inactive');
            groupsPro.append($(this));
        });
        if (builder.premiumButtonType === 'premium') {
            groupsPro.append(buildButton(builder));
            for (var _i = 0, _a = MobileToolbar_1.Drawer.list; _i < _a.length; _i++) {
                var drawer = _a[_i];
                if (!drawer.id || !drawer.id.match(/^wb-group-.+-drawer$/))
                    continue;
                for (var i_1 = 0, c = drawer.getItemCount(); i_1 < c; i_1++) {
                    if (drawer.getItem(i_1).isEnabled())
                        continue;
                    drawer.getBodyElem().append(buildButton(builder).css({ top: '60px' }));
                    break;
                }
            }
        }
        else if (builder.premiumButtonType === 'expired') {
            groupsPro.children('.wb_item_group').each(function () {
                $(this).attr('title', __('Ask administrator to enable this feature')).tooltip({ placement: 'top' });
            });
        }
    }
    exports.init = init;
    function buildButton(builder) {
        var btn = $('<div>').addClass("wb-prm-btn").html('<div>' + __("Available in %sPremium version%s")
            .replace("%s", (builder.upgradeUrl
            ? '<a href="' + builder.upgradeUrl + '" target="_blank">'
            : '<a href="javascript:void(0)">'))
            .replace("%s", '</a>') + '</div>');
        if (!builder.upgradeUrl) {
            if (!prmDlg) {
                prmDlg = new MsgDialog_5["default"](__('Premium version'), __('Available in %sPremium version%s').replace('%s', '').replace('%s', ''), null, null, true, true);
            }
            btn.find('a').on('click', function () { if (prmDlg)
                prmDlg.setVisible(true); });
        }
        return btn;
    }
});
define("SiteLoader", ["require", "exports", "ElementRegister", "Body", "Site", "Service", "Confirm", "ModeManager", "util/MenuList", "BuilderEvent"], function (require, exports, ElementRegister_8, Body_1, Site_2, Service_32, Confirm_5, ModeManager_3, MenuList_3, BuilderEvent_13) {
    "use strict";
    exports.__esModule = true;
    var SharedState = (function () {
        function SharedState(maxElementsToLoad) {
            if (maxElementsToLoad === void 0) { maxElementsToLoad = 0; }
            this.maxElementsToLoad = 0;
            this.batchStart = -1;
            this.batchEnd = 0;
            this.batchSize = 150;
            this.bodySet = false;
            this.maxElementsToLoad = maxElementsToLoad;
        }
        SharedState.prototype.getRemaining = function () {
            return (this.maxElementsToLoad - this.batchEnd);
        };
        SharedState.prototype.hasMore = function () {
            return (this.batchEnd < this.maxElementsToLoad);
        };
        SharedState.prototype.nextBatch = function () {
            if (!this.hasMore()) {
                return false;
            }
            else if (this.batchStart < 0) {
                this.batchStart = 0;
            }
            else {
                this.batchStart = this.batchEnd;
            }
            this.batchEnd = Math.min(this.batchStart + this.batchSize, this.maxElementsToLoad);
            return true;
        };
        return SharedState;
    }());
    function loadMenuStructures(pageData) {
        MenuList_3.clearRemovedMenuList();
        if (('menu' in pageData) && pageData.menu && (typeof pageData.menu === 'object')) {
            for (var j in pageData.menu) {
                Service_32["default"].menu.storeStrangeMenu(pageData.menu[j]);
            }
        }
    }
    function initEsentialData(pageData, builder, sharedState, thisReloadSite) {
        builder.excludedElements = [];
        builder.pageId = parseInt(pageData.id, 10);
        builder.preloader.setProgress(40);
        loadMenuStructures(pageData);
        builder.preloader.setProgress(52);
        $("#site").css("height", "auto");
        $("#site").append('<div class="root">' + pageData.layout + '</div>');
        var bodyContentData = { blocks: {} };
        var bodyData = {
            "class": "Body",
            content: bodyContentData
        };
        sharedState.siteData = { 'class': 'Site', content: { pages: [] } };
        builder.preloader.setProgress(60);
        var pp = 10 / sharedState.maxElementsToLoad;
        var pp_val = 60;
        for (var i = 0; i < sharedState.maxElementsToLoad; i++) {
            var data = pageData.elemntQueue[i];
            if (data['class'] === 'Site') {
                sharedState.siteData = data;
            }
            else if (data['class'] === 'Body') {
                bodyData = data;
                if (!bodyData.content)
                    bodyData.content = { blocks: {} };
                bodyData.content.blocks = bodyContentData.blocks;
            }
            else if (data["class"] === "Content") {
                if (data.id) {
                    bodyContentData.blocks[data.id] = data;
                }
            }
            builder.preloader.setProgress(Math.floor(pp_val += pp));
        }
        if (thisReloadSite)
            builder.site.applyData(sharedState.siteData);
        builder.bodyInstance = new Body_1["default"](bodyData, builder.body);
        if (thisReloadSite)
            ModeManager_3["default"].updateEnabledModes();
        if (builder.site.renderMode == Site_2["default"].RENDER_MODE_RESPONSIVE2) {
            ModeManager_3["default"].setAutoLayoutEnabled(true, true);
            ModeManager_3["default"].setMode(sharedState.siteData.builderWidth, true, true, true);
            builder.setPageModified(false);
        }
        else {
            ModeManager_3["default"].setAutoLayoutEnabled(false, true);
            if (thisReloadSite) {
                ModeManager_3["default"].setMode(ModeManager_3["default"].getBiggestEnabledMode(), true, true, false);
            }
        }
    }
    function initElementData(pageData, builder, sharedState) {
        var pp = 30 / sharedState.maxElementsToLoad, pp_val = 70, body = builder.bodyInstance;
        builder.preloader.setProgress(pp_val);
        sharedState.bodySet = false;
        var elm;
        for (var i = sharedState.batchStart; i < sharedState.batchEnd; i++) {
            var data = pageData.elemntQueue[i];
            if (data.isCommon && data.includePages) {
                var hasPages = (Object.keys(data.includePages).length > 0);
                if (hasPages && !data.includePages[builder.pageId]) {
                    builder.excludedElements.push(data);
                    continue;
                }
            }
            if (data['class'] === 'Blocks')
                continue;
            var cls = ElementRegister_8["default"].getClassByName(data['class']);
            if (!cls)
                continue;
            elm = new cls(data, true);
            var blockId = data.parentId;
            if (!blockId)
                blockId = data.block;
            if (!elm.dontAdd || elm.className === 'Menu') {
                body.addElement(blockId, elm, true, true);
            }
            else {
                elm = null;
            }
            builder.preloader.setProgress(Math.floor(pp_val += pp));
            if (blockId === 'wb_main')
                sharedState.bodySet = true;
        }
        setTimeout(function () { return body.getContentBlock('wb_main').updateSize(); }, 0);
    }
    function initFinalisingData(pageData, builder, sharedState, thisDoneCallback) {
        var body = builder.bodyInstance;
        if (!sharedState.bodySet && ('wb_main' in body.blocks) && body.blocks.wb_main) {
            body.blocks.wb_main.updateSize();
        }
        body.zReset();
        body.updateStyle();
        var menuElems = Service_32["default"].menu.getElemList();
        if (!menuElems.length) {
            BuilderEvent_13.GlobalEvents.triggerEvent('pages.changed', new BuilderEvent_13.PagesChangedBuilderEvent());
        }
        builder.preloader.setProgress(100);
        setTimeout(function () {
            builder.preloader.setVisible(false);
            setTimeout(function () { builder.highlightLayout(builder.showLayout); }, 500);
        }, 500);
        builder.gridSetVisible(builder.showGrid, true);
        builder.highlightLayout(builder.showLayout);
        builder.setPageModified(false);
        if (builder.isTouchDevice) {
            builder.reloadScrollStyles();
        }
        builder.site.reloadPagesMiId();
        if (builder.site.renderMode == Site_2["default"].RENDER_MODE_RESPONSIVE2) {
            ModeManager_3["default"].setMode(sharedState.siteData.builderWidth, true, true, true);
            builder.setPageModified(false);
            if ('freshCopy' in sharedState.siteData) {
                var bestWidth = ModeManager_3["default"].detectBestSuitableWidth();
                if (bestWidth != sharedState.siteData.builderWidth) {
                    builder.resizeSite(bestWidth);
                    builder.setPageModified(false);
                }
                else {
                    $.ajax({
                        url: wb_builder.resizeSiteUrl,
                        data: {
                            width: bestWidth,
                            data: '[]'
                        },
                        type: 'post',
                        dataType: 'json',
                        async: true
                    });
                }
            }
        }
        else {
            var mode = ModeManager_3["default"].getMode();
            if (!mode) {
                ModeManager_3["default"].setMode(ModeManager_3["default"].getModeFromWidth(ModeManager_3["default"].detectBestSuitableWidth(true)), false, true);
            }
            else {
                ModeManager_3["default"].setMode(mode, true, true);
            }
            builder.setPageModified(false);
        }
        builder.site.setLanding(builder.site.landing, true);
        builder.site.onUpdateLanguages(true);
        if (thisDoneCallback && typeof thisDoneCallback === 'function')
            thisDoneCallback.call(builder);
    }
    function loadInitSiteData(pageData, builder, thisReloadSite, thisDoneCallback) {
        if (thisReloadSite === void 0) { thisReloadSite = false; }
        var sharedState = new SharedState(pageData.elemntQueue.length);
        initEsentialData(pageData, builder, sharedState, thisReloadSite);
        var loaderEndFunc = function () {
            initFinalisingData(pageData, builder, sharedState, thisDoneCallback);
        };
        var loaderFunc = function () {
            if (sharedState.nextBatch()) {
                initElementData(pageData, builder, sharedState);
                if (sharedState.hasMore()) {
                    Confirm_5["default"].showDialog(__('Page has lots of elements'), __('Page loaded %s of %s elements, do you want to continue loading?')
                        .replace('%s', '' + sharedState.batchEnd)
                        .replace('%s', '' + sharedState.maxElementsToLoad), [
                        { title: __('Yes'), func: function () { return setTimeout(function () { return loaderFunc(); }, 1000); } },
                        { title: __('No'), func: function () { return setTimeout(function () { return loaderEndFunc(); }, 1000); } }
                    ], 600);
                    return;
                }
            }
            loaderEndFunc();
        };
        loaderFunc();
    }
    exports.loadInitSiteData = loadInitSiteData;
});
define("DefaultUI/AdminOptions", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    function buildAdminModeMarkers(hcWrp) {
        var ami = $('<div>').css({
            fontSize: '12px',
            lineHeight: '14px',
            margin: '26px 0 0 0',
            opacity: 0.3,
            position: 'absolute',
            textTransform: 'uppercase',
            fontWeight: 'bold'
        }).text('— ' + __('Admin mode') + ' —'), ami2 = ami.clone();
        hcWrp.prepend(ami.css({ left: -240 }));
        hcWrp.append(ami2.css({ right: -240 }));
        setTimeout(function () {
            var wl = ami.outerWidth(), wr = ami2.outerWidth();
            if (wl > 0)
                ami.css({ left: -(wl + 50) });
            if (wr > 0)
                ami2.css({ right: -(wr + 50) });
        }, 40);
    }
    exports.buildAdminModeMarkers = buildAdminModeMarkers;
    function buildAdminModeMenu(builder, saveMenu) {
        if (builder.isTemplateSavingAvailable()) {
            saveMenu.push({ name: __('Save As...'), click: function (e) {
                    e.stopPropagation();
                    builder.showSaveAsTemplateDialog();
                    return false;
                }, active: builder.isTemplateSavingEnabled(), featureMessage: builder.isTemplateSavingEnabled() ? '' : 'Please switch builder to English language' });
        }
        if (builder.isBlockSavingAvailable()) {
            saveMenu.push({ name: __('Save Block...'), click: function (e) {
                    e.stopPropagation();
                    builder.showSaveBlockDialog();
                    return false;
                }, active: builder.isBlockSavingEnabled(), featureMessage: builder.isBlockSavingEnabled() ? '' : 'Please switch builder to English language' });
        }
        if (builder.isElementStyleSavingAvailable()) {
            saveMenu.push({ name: __('Save Element Style...'), click: function (e) {
                    e.stopPropagation();
                    builder.showSaveElementStyleDialog();
                    return false;
                }, active: builder.isElementStyleSavingEnabled(), featureMessage: builder.isElementStyleSavingEnabled() ? '' : 'Please switch builder to English language' });
        }
    }
    exports.buildAdminModeMenu = buildAdminModeMenu;
});
define("DefaultUI/AutoAlignButton", ["require", "exports", "ModeManager"], function (require, exports, ModeManager_4) {
    "use strict";
    exports.__esModule = true;
    var AutoAlignButton = (function () {
        function AutoAlignButton(builder) {
            this._isVisible = false;
            this.elem = $('<div>').addClass('mode-enable-toggle');
            $('<i>').addClass('glyphicon glyphicon-align-center').appendTo(this.elem);
            this.elem.on('click', function () {
                builder.sortAndAutoAlignElements();
            }).attr('title', __('Auto align elements'));
        }
        AutoAlignButton.prototype.isVisible = function () {
            return this._isVisible;
        };
        AutoAlignButton.prototype.setVisible = function (visible) {
            this._isVisible = visible ? true : false;
            if (visible) {
                this.elem.show();
            }
            else {
                this.elem.hide();
            }
        };
        AutoAlignButton.prototype.setMode = function (mode) {
            if (mode === ModeManager_4["default"].MODE_PHONE) {
                this.setVisible(true);
            }
            else {
                this.setVisible(false);
            }
        };
        return AutoAlignButton;
    }());
    exports.AutoAlignButton = AutoAlignButton;
});
define("DefaultUI/PageSelector", ["require", "exports", "MenuListControl", "MobileToolbar", "ComboBox", "BuilderEvent", "Service"], function (require, exports, MenuListControl_1, MobileToolbar_2, ComboBox_2, BuilderEvent_14, Service_33) {
    "use strict";
    exports.__esModule = true;
    var PageSelector = (function () {
        function PageSelector(builder, mobileToolbar) {
            var _this = this;
            this.builder = builder;
            this.mobileItem = null;
            this.elem = $('<div id="page_selector" class="li">');
            this.control = new MenuListControl_1.MenuListControl(false, false, {
                onBeforeChange: function (e, data) { return _this.onBeforeChange(e, data); },
                onChange: function (e) { return _this.onChange(e); }
            });
            this.control.elem.css({ width: '110px' }).appendTo(this.elem);
            if (mobileToolbar) {
                mobileToolbar.addItem(MobileToolbar_2.Toolbar.buildItem({
                    name: __('Menu'),
                    icon: 'icon-wb-page-selector',
                    drawer: { id: 'mobile-menu', type: 'list', items: [] }
                }), 2);
                this.mobileItem = MobileToolbar_2.Drawer.get('mobile-menu');
            }
            BuilderEvent_14.GlobalEvents.on('pages.changed', function () { _this.reloadPages(); });
        }
        PageSelector.prototype.reloadPages = function () {
            this.control.reloadMenuList();
            if (this.mobileItem) {
                var items = this.control.getItems(), drawer_1 = this.mobileItem;
                drawer_1.removeAllItems();
                for (var i = 0; i < items.length; i++) {
                    var itemData = items[i].data;
                    if (!itemData || !('menuUID' in itemData))
                        continue;
                    (function (item, self) {
                        drawer_1.addItem(MobileToolbar_2.Toolbar.buildDrawerItem({ name: item.name, icon: 'icon-wb-page-selector', click: function () {
                                self.onChange(null, item.data);
                            } }));
                    })(items[i], this);
                }
                drawer_1.addItem(MobileToolbar_2.Toolbar.buildDrawerItem({ name: __('Edit Menu'), icon: 'icon-wb-edit', click: function (e) {
                        ComboBox_2["default"].closeAll();
                        Service_33["default"].menu.editMenu();
                        e.stopPropagation();
                        return false;
                    } }));
            }
        };
        PageSelector.prototype.onBeforeChange = function (e, data) {
            var exData;
            if ((typeof data === 'object') && data) {
                exData = data;
            }
            else {
                exData = this.control.getExtendedValue();
            }
            return !(exData && (exData.type === 'empty' || exData.type === 'anchor'));
        };
        PageSelector.prototype.onChange = function (e, data) {
            var exData;
            if ((typeof data === 'object') && data) {
                exData = data;
            }
            else {
                exData = this.control.getExtendedValue();
            }
            if (exData)
                exData.navigate();
        };
        PageSelector.prototype.setOpen = function (open) {
            if (open) {
                this.control.open();
            }
            else {
                this.control.close();
            }
        };
        return PageSelector;
    }());
    exports.PageSelector = PageSelector;
});
define("DefaultUI/LanguageSelector", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    function flagFromLangCode(language) {
        var countryCode = language ? language.countryCode : '';
        var flagCountry;
        switch (countryCode) {
            case 'us':
                flagCountry = 'gb';
                break;
            case 'cs':
                flagCountry = 'rs';
                break;
            case 'ct':
                flagCountry = 'es-ct';
                break;
            case 'gb':
                flagCountry = 'gb-wls';
                break;
            case 'gl':
                flagCountry = 'gal';
                break;
            default: flagCountry = countryCode;
        }
        return 'flag-icon-' + flagCountry;
    }
    exports.flagFromLangCode = flagFromLangCode;
    var LanguageSelector = (function () {
        function LanguageSelector(builder, onOpen) {
            var _this = this;
            this.isOpen = false;
            var language = builder.getLanguage();
            var languages = builder.getLanguages();
            var lcCount = 0;
            for (var _i = 0, languages_1 = languages; _i < languages_1.length; _i++) {
                var li = languages_1[_i];
                if (!li.hidden)
                    lcCount++;
            }
            var selector = $('<div id="lang_selector" class="btn-group langs li">')
                .append('<button type="button" class="btn"><i class="' + flagFromLangCode(language) + '"></i></button>')
                .append("\n\t\t\t\t<button type=\"button\" class=\"btn dropdown-toggle\" data-toggle=\"dropdown\">\n\t\t\t\t\t<span class=\"caret\"></span>\n\t\t\t\t</button>\n\t\t\t");
            var contClass = 'lang-col-1';
            if (lcCount >= 4)
                contClass = 'lang-col-2';
            if (lcCount >= 9)
                contClass = 'lang-col-3';
            if (lcCount >= 16)
                contClass = 'lang-col-4';
            var langList = $('<ul class="dropdown-menu">').addClass(contClass).appendTo(selector);
            var cc = 0, baseUrl = builder.getBaseUrl();
            for (var _a = 0, languages_2 = languages; _a < languages_2.length; _a++) {
                var lang = languages_2[_a];
                if (lang.hidden)
                    continue;
                var langElem = $('<li>').appendTo(langList);
                if (language && lang.id == language.id)
                    langElem.addClass('active');
                $('<a>')
                    .attr({ href: baseUrl + lang.code + '/' })
                    .append('<i class="' + flagFromLangCode(lang) + '">')
                    .append(' ' + lang.name)
                    .appendTo(langElem);
                cc++;
            }
            var self = this;
            selector.find("a").on("click", function () {
                self.setOpen(true);
                builder.goToPage(null, $(this).attr("href"));
                return false;
            });
            selector.find('button').on('click touchend', function (e) {
                if (typeof onOpen === 'function')
                    onOpen();
                _this.setOpen(!_this.isOpen);
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
            this.elem = selector;
        }
        LanguageSelector.prototype.setOpen = function (visible) {
            if (visible) {
                this.isOpen = true;
                this.elem.addClass('open');
            }
            else {
                this.isOpen = false;
                this.elem.removeClass('open');
            }
        };
        return LanguageSelector;
    }());
    exports.LanguageSelector = LanguageSelector;
});
define("DefaultUI/ModesToolbar", ["require", "exports", "ModeManager", "BuilderEvent"], function (require, exports, ModeManager_5, BuilderEvent_15) {
    "use strict";
    exports.__esModule = true;
    function buildModesToolbar(builder, controlMenu) {
        var modeItems = [];
        var modes = ModeManager_5["default"].getModes();
        for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
            var mode = modes_1[_i];
            var modeName = ModeManager_5["default"].getModeName(mode, true);
            modeItems.push({
                name: modeName,
                title: modeName,
                icon: 'ico-tb ico-tb-mode-' + mode,
                click: (function (mode) {
                    return function () {
                        if (!this.enabled)
                            return;
                        builder.setMode(mode);
                    };
                })(mode),
                init: (function (mode) {
                    return function () {
                        var _this = this;
                        this.elem.css({ position: 'relative' });
                        var markerElem = $('<span>').addClass('checked-marker').appendTo(this.elem).hide();
                        BuilderEvent_15.GlobalEvents.on('modes.usable.change', function (e) {
                            if (e.mode != mode)
                                return;
                            _this.setEnabled(e.value);
                        });
                        BuilderEvent_15.GlobalEvents.on('modes.enabled.change', function (e) {
                            if (e.mode != mode)
                                return;
                            if (e.value) {
                                markerElem.show();
                            }
                            else {
                                markerElem.hide();
                            }
                        });
                        BuilderEvent_15.GlobalEvents.on('modes.change', function (e) {
                            if (e.mode == mode) {
                                _this.setActive(true);
                            }
                            else {
                                _this.setActive(false);
                            }
                        });
                    };
                })(mode)
            });
        }
        modeItems.push({
            name: __('Auto Layout'),
            title: __('Auto Layout'),
            icon: 'ico-tb ico-tb-auto-layout',
            featureMessage: (wb_builder.isB2C
                ? __("Available in Premium version")
                : __("Ask administrator to enable this feature")),
            beta: true,
            active: builder.isAutoLayoutEnabled(),
            click: function () {
                if (!this.enabled)
                    return;
                builder.setAutoLayoutEnabled(!builder.isAutoLayoutEnabled());
            },
            init: function () {
                this.elem.css({ position: 'relative' });
                var markerElem = $('<span>').addClass('checked-marker').appendTo(this.elem).hide();
                this.setEnabled(true);
                if (!builder.isAutoLayoutAvailable() && !builder.isAutoLayoutEnabled()) {
                    this.setEnabled(false);
                }
                else if (!builder.isAutoLayoutAvailable() && builder.isAutoLayoutEnabled()) {
                    $('<span>').addClass('fa fa-exclamation-triangle')
                        .css({ position: 'absolute', display: 'block', top: '0px', left: '8px', color: '#a94442', fontSize: '18px' })
                        .appendTo(this.elem);
                }
                BuilderEvent_15.GlobalEvents.on('modes.autolayout.changed', function (e) {
                    if (e.value) {
                        markerElem.show();
                    }
                    else {
                        markerElem.hide();
                    }
                });
            }
        });
        controlMenu.push({ type: '-' });
        controlMenu.push({
            type: 'group',
            collapsable: true,
            borderless: false,
            icon: 'ico-tb ico-tb-mode-desktop',
            name: __('Responsive'),
            items: modeItems
        });
    }
    exports.buildModesToolbar = buildModesToolbar;
    function buildModesMobileToolbar(builder, mobileMenu) {
        var modeItems = [];
        var modes = ModeManager_5["default"].getModes();
        for (var _i = 0, modes_2 = modes; _i < modes_2.length; _i++) {
            var mode = modes_2[_i];
            var modeName = ModeManager_5["default"].getModeName(mode, true);
            modeItems.push({
                name: modeName,
                icon: 'ico-tb-mode-' + mode,
                click: (function (mode) {
                    return function () {
                        if (!this.enabled)
                            return;
                        builder.setMode(mode);
                    };
                })(mode)
            });
        }
        mobileMenu.splice(1, 0, {
            name: __('Responsive'),
            icon: 'ico-tb-mode-desktop',
            drawer: {
                id: 'mobile-modes-selector',
                type: 'list',
                items: modeItems
            }
        });
    }
    exports.buildModesMobileToolbar = buildModesMobileToolbar;
});
define("DefaultUI/SettingsBox", ["require", "exports", "Service", "GridAndGuidesDialog", "MobileToolbar", "BuilderEvent"], function (require, exports, Service_34, GridAndGuidesDialog_2, MobileToolbar_3, BuilderEvent_16) {
    "use strict";
    exports.__esModule = true;
    var SettingsBox = (function () {
        function SettingsBox(builder, mobileToolbar, opts) {
            var _this = this;
            this._isOpen = false;
            if (!this._opts)
                this._opts = {};
            if (opts && (opts instanceof Object)) {
                this._opts = $.extend({}, true, opts);
            }
            var onOpen = (typeof this._opts.onOpen === 'function') ? this._opts.onOpen : null;
            var openFunc = function (e) {
                if (onOpen)
                    onOpen(e);
                _this.setOpen(!_this.isOpen());
                e.stopPropagation();
                e.preventDefault();
                if (_this._isOpen)
                    Service_34["default"].HelpSystemPlayer.notify('toolbar-ctrl-config-click');
                return true;
            };
            $(document.body).on('click', function () { _this.setOpen(false); });
            this._elem = $('<div>').addClass('btn-group li wb-config').attr({ id: 'wb_config_btn' });
            this._btn = $('<button>')
                .attr({ type: 'button' })
                .addClass('btn')
                .append($('<i>').addClass('icon-cog-big'))
                .appendTo(this._elem)
                .on('click', openFunc);
            this._btnDrop = $('<button>')
                .attr({ type: 'button' })
                .addClass('btn dropdown-toggle')
                .append($('<span>').addClass('caret'))
                .appendTo(this._elem)
                .on('click', openFunc);
            this._submenu = $('<ul>').addClass('dropdown-menu').appendTo(this._elem);
            this._items = [];
            this.addDefaultItems(builder, mobileToolbar);
            this._elem.insertAfter($('#settings-toolbar-cont').children().eq(0));
        }
        SettingsBox.prototype.setOpen = function (open) {
            if (open) {
                if (!this._elem.hasClass('open'))
                    this._elem.addClass('open');
            }
            else {
                if (this._elem.hasClass('open'))
                    this._elem.removeClass('open');
            }
            this._isOpen = open ? true : false;
        };
        SettingsBox.prototype.isOpen = function () {
            return this._isOpen;
        };
        SettingsBox.prototype.getElem = function () {
            return this._elem;
        };
        SettingsBox.prototype.addItem = function (title, icon, callback, id, initCallback, tooltip) {
            var item = new Item(title, this, icon, callback, id, tooltip);
            this._submenu.append(item.getElem());
            if (initCallback && typeof (initCallback) === 'function') {
                initCallback.call(item);
            }
            this._items.push(item);
            return item;
        };
        SettingsBox.prototype.getItem = function (id) {
            for (var _i = 0, _a = this._items; _i < _a.length; _i++) {
                var item = _a[_i];
                if (item.id == id)
                    return item;
            }
            return null;
        };
        SettingsBox.prototype.addDefaultItems = function (builder, mobileToolbar) {
            var def = {
                items: [
                    { name: __('SEO'), icon: 'ico-tb-seo', click: function () { return builder.showSiteSEODialog(); } },
                    { name: __('Background'), icon: 'ico-tb-background', click: function () { return builder.showSiteBackgroundDialog(); } },
                    { name: __('Styles'), icon: 'ico-tb-styles', click: function () { return builder.showSiteStylesDialog(); } },
                    { name: __('Favicon'), icon: 'ico-tb-favicon', click: function () { return builder.showSiteFaviconDialog(); } },
                    { name: __('Settings'), icon: 'ico-tb-settings', click: function () { return builder.showSitePropertiesDialog(); } },
                    '-',
                    {
                        name: __('Landing'),
                        icon: 'ico-tb-landing',
                        click: function () {
                            if (this.isChecked()) {
                                this.setChecked(false);
                                builder.setSiteLanding(false);
                            }
                            else {
                                this.setChecked(true);
                                builder.setSiteLanding(true);
                            }
                        },
                        tooltip: { title: __('If checked then pages of main site menu will be published as one page with common header and footer of homepage'), placement: 'left' },
                        init: function () {
                            var _this = this;
                            BuilderEvent_16.GlobalEvents.on('landing.changed', function (e) {
                                _this.setChecked(e.value);
                            });
                        },
                        checked: builder.getSiteLanding()
                    },
                    {
                        name: __('Grid and guides'),
                        icon: 'ico-tb-grid',
                        click: function () { GridAndGuidesDialog_2.GridAndGuidesDialog.open(); }
                    }
                ]
            };
            if (builder.isFullScreenSupported()) {
                def.items.push('-');
                def.items.push({ name: __('Full Screen'), icon: 'ico-tb-fullscreen', click: function () { return builder.toggleFullScreen(); } });
            }
            def.items.push('-');
            def.items.push({ name: __('Log Out'), icon: 'ico-tb-logout', click: function () { return builder.logout(); } });
            this.buildFromDefinition(def);
            if (mobileToolbar) {
                mobileToolbar.addItem(MobileToolbar_3.Toolbar.buildItem({ name: __('Settings'), icon: 'icon-cog-big', drawer: {
                        type: 'list',
                        items: def.items
                    } }), 2);
            }
        };
        SettingsBox.prototype.buildFromDefinition = function (definition) {
            var i, item, itemDef;
            if ('items' in definition && definition.items.length > 0) {
                for (i = 0; i < definition.items.length; i++) {
                    itemDef = definition.items[i];
                    if (typeof itemDef === 'string' && itemDef === '-') {
                        this.addItem('-');
                        continue;
                    }
                    if (typeof itemDef !== 'object' || itemDef === null)
                        continue;
                    item = this.addItem(itemDef.name, itemDef.icon, itemDef.click, itemDef.id, itemDef.init, itemDef.tooltip);
                    if ('checked' in itemDef) {
                        item.setChecked(itemDef.checked ? true : false);
                    }
                }
            }
        };
        return SettingsBox;
    }());
    exports.SettingsBox = SettingsBox;
    var Item = (function () {
        function Item(title, parent, icon, callback, id, tooltip) {
            this._checked = false;
            this.id = id;
            this._elem = $('<li>');
            this._parent = parent;
            if (title === '-') {
                this._elem.addClass('divider');
            }
            else {
                this._aElem = $('<a>').attr({ href: 'javascript:void(0)', title: title }).appendTo(this._elem);
                if (icon)
                    this._aElem.append($('<i>').addClass('ico-tb ' + icon));
                if (title)
                    this._aElem.append('&nbsp;' + title);
                if (typeof callback === 'function') {
                    (function (callback, thisSelf) {
                        thisSelf._aElem.on('click', function (e) {
                            if (thisSelf._parent && (typeof thisSelf._parent.setOpen === 'function')) {
                                thisSelf._parent.setOpen(false);
                            }
                            callback.call(thisSelf, e);
                        });
                    })(callback, this);
                }
                if (id)
                    this._aElem.attr({ id: id });
                if (tooltip)
                    this._elem.tooltip(tooltip);
            }
        }
        Item.prototype.getElem = function () { return this._elem; };
        Item.prototype.setChecked = function (checked) {
            if (checked) {
                if (!this._aElem.hasClass('checked'))
                    this._aElem.addClass('checked');
            }
            else {
                if (this._aElem.hasClass('checked'))
                    this._aElem.removeClass('checked');
            }
            this._checked = checked ? true : false;
        };
        Item.prototype.isChecked = function () {
            return this._checked;
        };
        return Item;
    }());
});
define("DefaultUI/HelpButton", ["require", "exports", "MobileToolbar", "BuilderEvent"], function (require, exports, MobileToolbar_4, BuilderEvent_17) {
    "use strict";
    exports.__esModule = true;
    var HelpButton = (function () {
        function HelpButton(builder, mobileToolbar) {
            var _this = this;
            this.elem = $('<div>').addClass('wb_toolbar_help');
            var helpBtnAnchor = $('<a>').addClass('wb_item');
            helpBtnAnchor.attr('title', __('Help'));
            helpBtnAnchor.append('<i class="ico-tb-help"></i>');
            helpBtnAnchor.on('click', function () { builder.showHelp(); return false; });
            this.elem.append(helpBtnAnchor);
            BuilderEvent_17.GlobalEvents.on('help.show help.hide help.playershow help.playerhide preview.show preview.hide', function (e) {
                _this.setVisible(!e.visible);
            });
            if (mobileToolbar) {
                mobileToolbar.addItem(MobileToolbar_4.Toolbar.buildItem({ name: __('Help'), icon: 'icon-wb-help', click: function () {
                        builder.showHelp();
                    } }));
            }
        }
        HelpButton.prototype.setVisible = function (visible) {
            if (!this.elem)
                return;
            if (visible) {
                this.elem.show();
            }
            else {
                this.elem.hide();
            }
        };
        return HelpButton;
    }());
    exports.HelpButton = HelpButton;
});
define("DefaultUI/NotificationRibbon", ["require", "exports", "UIComponent", "BuilderEvent"], function (require, exports, UIComponent_21, BuilderEvent_18) {
    "use strict";
    exports.__esModule = true;
    var NotificationRibbon = (function (_super) {
        __extends(NotificationRibbon, _super);
        function NotificationRibbon(builder) {
            var _this = _super.call(this) || this;
            _this.text = '';
            _this._elem.addClass('weeemsg alert alert-warning');
            _this.xElem = $('<button>').addClass('close').attr({ type: 'button', dataDismiss: 'alert' }).html('&times;').appendTo(_this._elem);
            _this.xElem.on('click', function () { _this.setVisible(false); });
            _this.setVisible(false);
            BuilderEvent_18.GlobalEvents.on('notification.changed', function (e) {
                _this.setText(e.message, e.isHtml);
                if (e.message) {
                    _this.setVisible(true);
                }
                else {
                    _this.setVisible(false);
                }
            });
            BuilderEvent_18.GlobalEvents.on('help.show help.hide help.playershow help.playerhide preview.show preview.hide', function (e) {
                _this.setVisible((_this.text && !e.visible) ? true : false);
            });
            return _this;
        }
        NotificationRibbon.prototype.setText = function (text, asHtml) {
            if (asHtml === void 0) { asHtml = false; }
            if (this.xElem)
                this.xElem.detach();
            this._elem.empty();
            this.text = text;
            if (typeof text !== 'string') {
                this._elem.append(text);
            }
            else if (asHtml) {
                this._elem.html(text);
            }
            else {
                this._elem.text(text);
            }
            if (this.xElem)
                this._elem.prepend(this.xElem);
        };
        return NotificationRibbon;
    }(UIComponent_21.UIComponent));
    exports.NotificationRibbon = NotificationRibbon;
});
define("modes/RenderModeSwitchToolbarItem", ["require", "exports", "WidgetToolbar"], function (require, exports, WidgetToolbar_2) {
    "use strict";
    exports.__esModule = true;
    exports.RenderModeSwitchToolbarItem = $.extend(Object.create(WidgetToolbar_2["default"].ToolbarItem), {
        _markerElem: null,
        init: function (icon, name) {
            WidgetToolbar_2["default"].ToolbarItem.init.call(this, icon, name);
            this._markerElem = $('<span>').addClass('checked-marker').appendTo(this.elem).hide();
            this.setBeta(true);
            return this;
        },
        setActive: function (active) {
            WidgetToolbar_2["default"].ToolbarItem.setActive.call(this, active);
            this.setMarked(active);
        },
        setMarked: function (marked) {
            if (marked) {
                this._markerElem.show();
            }
            else {
                this._markerElem.hide();
            }
        }
    });
});
define("DefaultUI/PreviewToolbar", ["require", "exports", "UIComponent", "Service", "DropdownBox", "WidgetToolbar", "ModeManager", "modes/RenderModeSwitchToolbarItem", "BuilderEvent"], function (require, exports, UIComponent_22, Service_35, DropdownBox_10, WidgetToolbar_3, ModeManager_6, RenderModeSwitchToolbarItem_1, BuilderEvent_19) {
    "use strict";
    exports.__esModule = true;
    var FieldsDef = (function () {
        function FieldsDef() {
        }
        return FieldsDef;
    }());
    var PreviewToolbar = (function (_super) {
        __extends(PreviewToolbar, _super);
        function PreviewToolbar(builder) {
            var _this = _super.call(this) || this;
            _this.builder = builder;
            _this.customItem = new DropdownBox_10.Item('', '_', { id: '', name: '', size: 0 });
            _this.modeButtons = {};
            _this._elem.addClass('wb-preview-toolbar wb_toolbar');
            wb_builder.addCSSRule('.wb-preview-body', 'top: 65px;');
            var group = Object.create(WidgetToolbar_3["default"].ToolbarItemGroup).init();
            var separator = Object.create(WidgetToolbar_3["default"].ToolbarItemSeparator).init();
            separator.elem.addClass('hidden-xs');
            group.addItem(separator);
            var mm = Service_35["default"].modeManager;
            var modes = mm.getModes();
            var _loop_8 = function (i) {
                var mode = modes[i];
                var button_1 = Object.create(mm.ToolbarItem).init('ico-tb ico-tb-mode-' + mode, mm.getModeName(mode, true));
                button_1.elem.tooltip({ placement: 'bottom', title: mm.getModeName(mode, true) });
                button_1.elem.addClass('wb-preview-mode-btn');
                button_1.mode = mode;
                button_1.setEnabled(true);
                button_1.elem.on('click touchstart', function () {
                    _this.selectSize(ModeManager_6["default"].getModeWidth(mode), true);
                });
                group.addItem(button_1);
                this_5.modeButtons[mode] = button_1;
            };
            var this_5 = this;
            for (var i in modes) {
                _loop_8(i);
            }
            var button = Object.create(RenderModeSwitchToolbarItem_1.RenderModeSwitchToolbarItem).init('ico-tb ico-tb-auto-layout', __('Auto Layout'));
            button.setTitle(__('Auto Layout'));
            button.setFeatureMessage(wb_builder.isB2C ? __("Available in Premium version") : __("Ask administrator to enable this feature"));
            button.elem.addClass('wb-preview-auto-layout-btn');
            button.setEnabled(false);
            group.addItem(button);
            _this.modeButtons['auto'] = button;
            var debug = (builder.getSiteDomain() === 'ftp.marius.dev' || builder.getSiteDomain() === 'test.realmdev.lt');
            _this.fields = new FieldsDef();
            var sizeIdx = {}, sizeOptions = [
                { id: '320', name: 'Phone (320)', size: 320 },
                { id: '360', name: 'U Phone (360)', size: 360 },
                { id: '768', name: 'Tablet (768)', size: 768 },
                { id: '992', name: 'Desktop (992)', size: 992 },
                { id: '1200', name: 'Wide (1200)', size: 1200 },
                { id: '1920', name: 'U Wide (1920)', size: 1920 }
            ];
            for (var _i = 0, sizeOptions_1 = sizeOptions; _i < sizeOptions_1.length; _i++) {
                var size = sizeOptions_1[_i];
                sizeIdx['#' + size.id] = size.size;
            }
            Service_35["default"].UIBuilder.buildLayout({
                type: 'FlowLayout',
                align: 'center',
                styleClass: 'wb-preview-toolbar-items',
                css: { width: (debug ? 760 : 720), margin: '0 auto' },
                children: [
                    { type: 'Button', id: 'closeBtn',
                        styleClass: 'hidden-xs',
                        css: { margin: '4px 0 0 0' },
                        text: __('Close'),
                        click: function () { return builder.hidePreview(); }
                    },
                    { type: 'DropdownBox', id: 'res',
                        styleClass: 'hidden-xs',
                        css: { width: 200, margin: '4px 0 0 0' },
                        change: function (fields) {
                            var selItem = fields.res.getSelectedItem();
                            var option = selItem ? selItem.getOriginal() : null;
                            builder.setPreviewWidth(option ? option.size : 100);
                        },
                        options: sizeOptions
                    },
                    { type: 'Button', text: __('Reload'), css: { marginTop: 4 }, click: function () { return builder.reloadPreview(); }, ignore: !debug },
                    { type: 'CustomContainer', content: group.elem }
                ]
            }, _this._elem, _this.fields);
            var closeBtn = $('<div style="position: absolute; right: 15px; top: 15px; font-weight: bold; font-size: 24px; color: #AAA; cursor: pointer; text-align: center; width: 34px; line-height: 34px;">&times;</div>');
            closeBtn.on('click touchstart', function () { return builder.hidePreview(); });
            _this._elem.append(closeBtn);
            BuilderEvent_19.GlobalEvents.on('preview.show preview.hide', function (e) {
                _this.setVisible(e.visible);
            });
            BuilderEvent_19.GlobalEvents.on('preview.size.changed', function (e) {
                if (('#' + e.width) in sizeIdx) {
                    _this.updateModeButtons(false, e.width);
                    _this.selectSize(e.width);
                }
                else {
                    _this.setCustom(e.width);
                }
            });
            return _this;
        }
        PreviewToolbar.prototype.updateModeButtons = function (initial, width) {
            var modes = ModeManager_6["default"].getModes();
            var enabledModes = ModeManager_6["default"].getEnabledModes();
            var bestMode = ModeManager_6["default"].MODE_PHONE;
            var bestWidth = 0;
            var autoLayout = initial ? false : this.builder.isAutoLayoutEnabled();
            for (var i in modes) {
                var mode = modes[i];
                var button = this.modeButtons[mode];
                var enabled_1 = initial
                    ? false
                    : (((mode in enabledModes) && enabledModes[mode]) || autoLayout);
                button.elem.attr('data-original-title', (initial || autoLayout)
                    ? ModeManager_6["default"].getModeName(mode, true)
                    : (ModeManager_6["default"].getModeName(mode, true, true) + ' ' + (enabled_1 ? __('ON') : __('OFF'))));
                button.setMarked(enabled_1);
                button.setActive(false);
                button.setEnabled(!autoLayout);
                if (width > bestWidth && width >= ModeManager_6["default"].getModeWidth(mode)) {
                    bestWidth = width;
                    bestMode = mode;
                }
            }
            this.modeButtons[bestMode].setActive(true);
            var enabled = !initial && autoLayout;
            this.modeButtons['auto'].setEnabled(enabled);
            this.modeButtons['auto'].setMarked(enabled);
            this.modeButtons['auto'].elem.attr('data-original-title', __('Auto Layout') + ' ' + (enabled ? __('ON') : __('OFF')));
        };
        PreviewToolbar.prototype.setCustom = function (width) {
            var res = this.fields.res;
            this.customItem.setTitle('Custom (' + width + ')');
            var ori = this.customItem.getOriginal();
            if (ori)
                ori.size = width;
            res.addItem(this.customItem);
            res.selectItem(this.customItem);
        };
        PreviewToolbar.prototype.selectSize = function (selectWidth, triggerEvent) {
            if (triggerEvent === void 0) { triggerEvent = false; }
            var res = this.fields.res, items = res.getItems(), ssw, sdw = -1, itm = null;
            for (var i = 0; i < items.length; i++) {
                ssw = parseInt(items[i].getId().split('x')[0], 10);
                if (Math.abs(selectWidth - ssw) < sdw || sdw < 0) {
                    sdw = Math.abs(selectWidth - ssw);
                    itm = items[i];
                }
            }
            if (itm) {
                res.selectItem(itm);
                if (triggerEvent)
                    res.trigger('change');
            }
        };
        PreviewToolbar.prototype.getCloseButton = function () {
            return this.fields.closeBtn;
        };
        return PreviewToolbar;
    }(UIComponent_22.UIComponent));
    exports.PreviewToolbar = PreviewToolbar;
});
define("DefaultUI/Toolbar", ["require", "exports", "DefaultUI/PageSelector", "DefaultUI/LanguageSelector", "WidgetToolbar", "Service", "HelpSystem/HelpSystemPlayer", "RemoteLoginDialog", "WebsiteImporter", "MobileToolbar", "DefaultUI/AdminOptions", "DefaultUI/PluginToolbar", "DefaultUI/ModesToolbar", "BuilderEvent", "DefaultUI/SettingsBox", "DefaultUI/HelpButton", "DefaultUI/NotificationRibbon", "DefaultUI/PreviewToolbar"], function (require, exports, PageSelector_1, LanguageSelector_1, WidgetToolbar_4, Service_36, HelpSystemPlayer_3, RemoteLoginDialog_2, WebsiteImporter_1, MobileToolbar, AdminOptions_1, PluginToolbar_2, ModesToolbar_1, BuilderEvent_20, SettingsBox_1, HelpButton_1, NotificationRibbon_2, PreviewToolbar_1) {
    "use strict";
    exports.__esModule = true;
    var Toolbar = (function () {
        function Toolbar(builder) {
            var widgetContainer = $('<div class="wrp">');
            var language = builder.getLanguage();
            var toolbar = $('<div id="head" class="' + (language ? 'lang-' + language.code : '') + '" data-spy="affix">');
            toolbar
                .append(this.buildToolbarControl(builder, toolbar, widgetContainer))
                .append($('<div id="head-tools">').append(widgetContainer))
                .append('<div class="sh">')
                .append((new NotificationRibbon_2.NotificationRibbon(builder)).getElem());
            this.elem = toolbar;
        }
        Toolbar.prototype.adjustSize = function () {
            this.controlToolbar.ajustSize();
        };
        Toolbar.prototype.closeAll = function () {
            this.pageSelector.setOpen(false);
            this.languageSelector.setOpen(false);
            this.settingsSelector.setOpen(false);
        };
        Toolbar.prototype.buildToolbarControl = function (builder, toolbar, widgetContainer) {
            var toolbarControl = $('<div id="head-control">');
            var wrapper = $('<div class="wrp">').appendTo(toolbarControl);
            var logo = $('<div class="logo">').appendTo(wrapper);
            var logoUrl = builder.getLogoUrl();
            if (logoUrl) {
                logo.css({
                    backgroundImage: "url('" + logoUrl + "')",
                    backgroundPosition: (builder.isRtl() ? 'right' : 'left') + ' center',
                });
            }
            if (builder.isAdminMode())
                AdminOptions_1.buildAdminModeMarkers(wrapper);
            var pageSelector;
            var settingsSelector;
            var languageSelector = new LanguageSelector_1.LanguageSelector(builder, function () {
                settingsSelector.setOpen(false);
                pageSelector.setOpen(false);
                Service_36["default"].contextMenu.hideAll();
            });
            var ctrlRight = $('<div class="wrp2 ctrl-right" id="settings-toolbar-cont">')
                .appendTo(wrapper);
            var signUpInfo = builder.getSignUpInfo();
            var signUpFunc = function () { if (signUpInfo)
                window.open(signUpInfo.url); };
            if (signUpInfo) {
                var signUpBtn = $('<button type="button" class="btn btn-default" id="test-sign-up-btn"></button>')
                    .css({ position: 'absolute', right: -100, opacity: 0 })
                    .text(signUpInfo.title)
                    .append('<span class="icon-wb-play-green" style="margin-left: 10px;"></span>')
                    .on('click', signUpFunc)
                    .appendTo(ctrlRight);
                signUpBtn.css({ right: -(signUpBtn.outerWidth(true) + 10), opacity: 1 });
            }
            var content = $('<div class="wrp2 ctrl-left" id="control-toolbar-cont">')
                .appendTo(wrapper);
            var saveFunc, backupRestoreFunc, importWebsiteFunc;
            var publishBtnActive = builder.isPublishAvailable();
            var publishFunc = function (e) {
                HelpSystemPlayer_3["default"].notify('toolbar-ctrl-save-click');
                if (builder.isTestMode()) {
                    if (RemoteLoginDialog_2["default"].available())
                        RemoteLoginDialog_2["default"].setVisible(true);
                    else if (signUpInfo)
                        signUpFunc();
                    return false;
                }
                builder.publish();
                e.stopPropagation();
                return false;
            };
            var previewFunc = function (e) {
                HelpSystemPlayer_3["default"].notify('toolbar-ctrl-preview-click');
                builder.preview();
                e.stopPropagation();
                return false;
            };
            var newTplFunc = function (e) {
                HelpSystemPlayer_3["default"].notify('toolbar-ctrl-change-click');
                builder.showTemplateChooser();
                e.stopPropagation();
                return false;
            };
            var resetTplFunc = function (e) {
                builder.resetSite(true);
                e.stopPropagation();
                return false;
            };
            var collapseCallback = function (collapse, elem) {
            };
            var saveMenu = [];
            if (!RemoteLoginDialog_2["default"].isPlainPublish()) {
                saveMenu = [
                    { id: 'wb_fn_save_publish', name: __('Save and publish'), active: (publishBtnActive ? true : false),
                        help: (publishBtnActive ? __('Save site and Publish it to the internet') : __('Unavailable in test mode')),
                        helpPlacement: "right",
                        click: publishFunc
                    },
                    { type: '-' },
                    { id: 'wb_fn_save_save', name: __('Save'), help: __('Save site without Publishing it'), helpPlacement: "right", click: (saveFunc = function (e) {
                            HelpSystemPlayer_3["default"].notify('toolbar-ctrl-save-click');
                            builder.save(true);
                            e.stopPropagation();
                            return false;
                        }) },
                    { id: 'wb_fn_save_backup', name: __('Backup/Restore'), click: (backupRestoreFunc = function (e) {
                            builder.showBackupRestoreDialog();
                            e.stopPropagation();
                            return false;
                        }) }
                ];
                if (builder.isAdminMode())
                    AdminOptions_1.buildAdminModeMenu(builder, saveMenu);
            }
            var controlDef = [{
                    type: 'group',
                    id: 'wb_save_group',
                    collapsable: true,
                    collapseCallback: collapseCallback,
                    icon: 'ico-tb ico-tb-save',
                    borderless: false,
                    name: __('Save'),
                    items: [
                        { id: 'wb_fn_save', icon: 'ico-tb ico-tb-save', name: __('Save and publish'), submenu: saveMenu,
                            click: (builder.isTouchDevice() ? null : publishFunc) },
                        { id: 'wb_fn_preview', icon: 'ico-tb ico-tb-preview', name: __('Preview'), title: __('Preview site'),
                            submenu: (builder.getPanelUrl() ? [
                                { id: 'wb_fn_preview_preview', name: __('Preview'), click: previewFunc },
                                { id: 'wb_fn_preview_website', name: __('Go to my website'),
                                    click: function (e) { window.open(builder.getSiteUrl()); e.stopPropagation(); } }
                            ] : []),
                            click: previewFunc
                        },
                        { type: '-' },
                        { id: 'wb_fn_undo', icon: 'ico-tb ico-tb-undo', name: __('Undo'), click: function () { builder.historyUndo(); return false; } },
                        { id: 'wb_fn_redo', icon: 'ico-tb ico-tb-redo', name: __('Redo'), click: function () { builder.historyRedo(); return false; } },
                        { type: '-' },
                        { id: 'wb_fn_change', icon: 'ico-tb ico-tb-reset', name: __('New/Reset'), submenu: [
                                { id: 'wb_fn_change_new', name: __('Change template'), click: newTplFunc },
                                { id: 'wb_fn_change_reset', name: __('Reset'), click: resetTplFunc },
                                { id: 'wb_fn_change_import', name: __('Import'),
                                    active: builder.isImportAvailable(),
                                    hidden: !builder.isImportVisible(),
                                    beta: true,
                                    featureMessage: wb_builder.isB2C ? __("Available in Premium version") : __("Ask administrator to enable this feature"),
                                    click: (importWebsiteFunc = function (e) {
                                        WebsiteImporter_1.WebsiteImporter.showImportDialog();
                                        e.stopPropagation();
                                        return false;
                                    })
                                }
                            ], click: (builder.isTouchDevice() ? null : newTplFunc) }
                    ]
                }];
            ModesToolbar_1.buildModesToolbar(builder, controlDef);
            var controlToolbar = Object.create(WidgetToolbar_4["default"]).init(controlDef);
            controlToolbar.setId('wb_toolbar_ext');
            controlToolbar.elem
                .css('margin-right', '6px')
                .appendTo(content);
            var undoItem = controlToolbar.getItemByIdRe('wb_fn_undo');
            var redoItem = controlToolbar.getItemByIdRe('wb_fn_redo');
            BuilderEvent_20.GlobalEvents.on('history.changed', function () {
                if (builder.isHistoryUndoAvailable()) {
                    if (undoItem)
                        undoItem.elem.css({ opacity: 1 });
                }
                else {
                    if (undoItem)
                        undoItem.elem.css({ opacity: 0.3 });
                }
                if (builder.isHistoryRedoAvailable()) {
                    if (redoItem)
                        redoItem.elem.css({ opacity: 1 });
                }
                else {
                    if (redoItem)
                        redoItem.elem.css({ opacity: 0.3 });
                }
            });
            $.getJSON(builder.getBaseUrl() + 'get_ui/', { prop: 'toolbars', ts: (new Date()).getTime() }).done(function (data) {
                if (!('control-toolbar-cont' in data) || !data['control-toolbar-cont'] || !data['control-toolbar-cont'].items)
                    return;
                var items = data['control-toolbar-cont'].items;
                for (var _i = 0, items_3 = items; _i < items_3.length; _i++) {
                    var item = items_3[_i];
                    if (item.name) {
                        item = $.extend({ img: null, url: null, order: null }, item);
                        var toolbarItem = Object.create(WidgetToolbar_4["default"].ToolbarItem).init(item.img, __trr(item.name), true);
                        if (item.url) {
                            item.url = __trr(item.url).replace('{{siteDomain}}', builder.getSiteDomain());
                            toolbarItem.setLink(item.url);
                        }
                        controlToolbar.addItem(toolbarItem, item.order);
                    }
                }
                controlToolbar.ajustSize();
            });
            this.controlToolbar = controlToolbar;
            var widgetToolbarDef = PluginToolbar_2.constructPluginToolbar(builder, collapseCallback);
            var widgetToolbar = Object.create(WidgetToolbar_4["default"]).init(widgetToolbarDef, 'wb_toolbar_all');
            widgetToolbar.setId('wb_toolbar');
            widgetContainer.append(widgetToolbar.elem);
            widgetToolbar.ajustSize();
            var fItem = widgetToolbar.getToolbarItem(0);
            if (fItem && $(window).width() > 485) {
                setTimeout(function () { fItem.elem.tooltip('show'); }, 5000);
                if (builder.isTouchDevice()) {
                    setTimeout(function () { fItem.elem.tooltip('hide'); }, 10000);
                }
                fItem.elem.one('hover touchstart', function () { fItem.elem.tooltip('hide'); });
                $(document.body).on('show.bs.modal', function () { fItem.elem.tooltip('hide'); });
            }
            $(window).on("scroll resize orientationchange", function () {
                $('.tooltip').each(function () {
                    var tooltip = $(this).data('bs.tooltip');
                    if (tooltip)
                        tooltip.show();
                });
            });
            this.widgetToolbar = widgetToolbar;
            var mobilePublishMenuItems = [
                { name: __('Publish'), icon: 'ico-tb-save', click: publishFunc },
                { name: __('Save'), icon: 'ico-tb-savedraft', click: saveFunc },
                { name: __('Preview'), icon: 'ico-tb-preview', click: previewFunc },
                { name: __('Backup'), icon: 'ico-tb-backup', click: backupRestoreFunc },
                { name: __('Change template'), icon: 'ico-tb-changetpl', click: newTplFunc },
                { name: __('Reset'), icon: 'ico-tb-resettpl', click: resetTplFunc }
            ];
            if (builder.isImportAvailable()) {
                mobilePublishMenuItems.push({ name: __('Import'), icon: 'ico-tb-import', click: importWebsiteFunc });
            }
            var mobileDef = {
                items: [
                    { name: __('Publish'), icon: 'ico-tb-save', drawer: {
                            type: 'list',
                            items: mobilePublishMenuItems
                        } },
                    {
                        name: __('Language'),
                        icon: LanguageSelector_1.flagFromLangCode(builder.getLanguage()),
                        drawer: {
                            type: 'lang-grid',
                            items: (function () {
                                var languages = builder.getLanguages();
                                var baseUrl = builder.getBaseUrl();
                                var list = [];
                                var _loop_9 = function (lang) {
                                    if (!lang.active || lang.hidden)
                                        return "continue";
                                    list.push({ name: lang.name, icon: LanguageSelector_1.flagFromLangCode(lang), click: function (e) {
                                            e.stopPropagation();
                                            location.href = baseUrl + lang.code;
                                        } });
                                };
                                for (var _i = 0, languages_3 = languages; _i < languages_3.length; _i++) {
                                    var lang = languages_3[_i];
                                    _loop_9(lang);
                                }
                                return list;
                            })()
                        }
                    },
                    { name: __('Add'), icon: 'icon-wb-add', drawer: {
                            type: 'list',
                            items: widgetToolbarDef
                        } }
                ]
            };
            var mobileToolbar = new MobileToolbar.Toolbar(mobileDef);
            toolbar.append(mobileToolbar.getElem());
            pageSelector = new PageSelector_1.PageSelector(builder, mobileToolbar);
            settingsSelector = new SettingsBox_1.SettingsBox(builder, mobileToolbar, {
                onOpen: function () {
                    languageSelector.setOpen(false);
                    pageSelector.setOpen(false);
                    Service_36["default"].contextMenu.hideAll();
                }
            });
            ctrlRight
                .append(pageSelector.elem)
                .append(settingsSelector.getElem())
                .append(languageSelector.elem);
            (new HelpButton_1.HelpButton(builder, mobileToolbar)).elem.appendTo(document.body);
            (this.previewToolbar = new PreviewToolbar_1.PreviewToolbar(builder)).getElem().appendTo(document.body);
            this.pageSelector = pageSelector;
            this.languageSelector = languageSelector;
            this.settingsSelector = settingsSelector;
            return toolbarControl;
        };
        return Toolbar;
    }());
    exports.Toolbar = Toolbar;
});
define("DefaultUI/ModeEnableToggle", ["require", "exports", "ToolTipControl", "ModeManager"], function (require, exports, ToolTipControl_3, ModeManager_7) {
    "use strict";
    exports.__esModule = true;
    var ModeEnableToggle = (function () {
        function ModeEnableToggle(builder) {
            var _this = this;
            this.builder = builder;
            this.elem = $('<div>').addClass('mode-enable-toggle');
            this.labelElem = $('<span>').text(__('version')).appendTo(this.elem);
            this.valueElem = $('<span>').addClass('mode-enable-value-on').text(__('ON')).appendTo(this.elem);
            this.markerElem = $('<span>').addClass('mode-enable-marker-on').appendTo(this.elem);
            this.tipElem = {
                on: new ToolTipControl_3["default"]('?', __('Publish my %s version of website'), 'bottom'),
                off: new ToolTipControl_3["default"]('?', __('I will modify my website for %s version'), 'bottom')
            };
            this.elem.on('click', function () {
                var currMode = ModeManager_7["default"].getMode();
                var value = !ModeManager_7["default"].getModeEnabled(currMode);
                ModeManager_7["default"].setModeEnabled(currMode, value);
                _this.setValue(value);
            });
        }
        ModeEnableToggle.prototype.setMode = function (mode) {
            var isEnabled = ModeManager_7["default"].getModeEnabled(mode);
            var modes = ModeManager_7["default"].getModes();
            var enabledCount = 0;
            for (var _i = 0, modes_3 = modes; _i < modes_3.length; _i++) {
                var li = modes_3[_i];
                if (ModeManager_7["default"].getModeEnabled(li))
                    enabledCount++;
            }
            this.labelElem.text(ModeManager_7["default"].getModeName(mode, false, true));
            this.setValue(isEnabled, mode);
            if (this.builder.isAutoLayoutEnabled() || (isEnabled && enabledCount < 2)) {
                this.elem.hide();
            }
            else {
                this.elem.show();
            }
        };
        ModeEnableToggle.prototype.setValue = function (value, mode) {
            var currMode = ModeManager_7["default"].getMode();
            var modeName = ModeManager_7["default"].getModeName(mode ? mode : (currMode ? currMode : ModeManager_7["default"].MODE_DESKTOP), true);
            this.tipElem.on.elem.attr('data-original-title', __('Publish my %s version of website').replace('%s', modeName));
            this.tipElem.off.elem.attr('data-original-title', __('I will modify my website for %s version').replace('%s', modeName));
            if (value) {
                this.valueElem.text(__('ON')).removeClass('mode-enable-value-off').addClass('mode-enable-value-on');
                this.markerElem.removeClass('mode-enable-marker-off').addClass('mode-enable-marker-on');
                this.tipElem.on.elem.appendTo(this.elem);
                this.tipElem.off.elem.detach();
            }
            else {
                this.valueElem.text(__('OFF')).removeClass('mode-enable-value-on').addClass('mode-enable-value-off');
                this.markerElem.removeClass('mode-enable-marker-on').addClass('mode-enable-marker-off');
                this.tipElem.on.elem.detach();
                this.tipElem.off.elem.appendTo(this.elem);
            }
        };
        return ModeEnableToggle;
    }());
    exports.ModeEnableToggle = ModeEnableToggle;
});
define("DefaultUI/SubBar", ["require", "exports", "DefaultUI/ModeEnableToggle", "DefaultUI/AutoAlignButton", "BuilderEvent", "ModeManager"], function (require, exports, ModeEnableToggle_1, AutoAlignButton_1, BuilderEvent_21, ModeManager_8) {
    "use strict";
    exports.__esModule = true;
    var SubBar = (function () {
        function SubBar(builder) {
            var _this = this;
            this.modeToggle = new ModeEnableToggle_1.ModeEnableToggle(builder);
            this.alignButton = new AutoAlignButton_1.AutoAlignButton(builder);
            this.elem = $('<div>')
                .append(this.modeToggle.elem)
                .append(this.alignButton.elem);
            BuilderEvent_21.GlobalEvents.on('modes.change', function (e) {
                _this.modeToggle.setMode(e.mode);
                _this.alignButton.setMode(e.mode);
                _this.handleResize(e.mode);
            });
            $(window).on('resize', function () { _this.handleResize(ModeManager_8["default"].getMode()); });
        }
        SubBar.prototype.handleResize = function (mode) {
            var ww = $(window).width(), sw = ModeManager_8["default"].getModeWidth(mode), w = this.modeToggle.elem.outerWidth(true) + (this.alignButton.isVisible() ? (this.alignButton.elem.outerWidth(true) + 10) : 0), right = Math.round(((ww - sw) / 2) - w - 2), finalRight = ((right < 20) ? 20 : right);
            this.modeToggle.elem.css({ right: finalRight });
            if (this.alignButton.isVisible())
                this.alignButton.elem.css({ right: finalRight + this.modeToggle.elem.outerWidth(true) + 10 });
        };
        return SubBar;
    }());
    exports.SubBar = SubBar;
});
define("DefaultUI/DefaultUI", ["require", "exports", "PluginApi/UIManager", "DefaultUI/Toolbar", "DefaultUI/SubBar", "BuilderEvent", "HelpSystem/Tooltip", "Service"], function (require, exports, UIManager_2, Toolbar_1, SubBar_1, BuilderEvent_22, Tooltip_2, Service_37) {
    "use strict";
    exports.__esModule = true;
    var DefaultUI = (function (_super) {
        __extends(DefaultUI, _super);
        function DefaultUI(builder) {
            var _this = _super.call(this, builder) || this;
            var body = $(document.body);
            var toolbar = new Toolbar_1.Toolbar(builder);
            var subBar = new SubBar_1.SubBar(builder);
            subBar.elem.appendTo(body);
            var headSpacer = $('<div class="head-spacer">');
            BuilderEvent_22.GlobalEvents.on('preview.show preview.hide', function (e) {
                if (e.visible) {
                    toolbar.elem.hide();
                    subBar.elem.hide();
                    headSpacer.hide();
                }
                else {
                    toolbar.elem.show();
                    subBar.elem.show();
                    headSpacer.show();
                }
            });
            BuilderEvent_22.GlobalEvents.on('contextmenu.show', function () { return _this.closeAll(); });
            var editor = $('<div id="body">')
                .on('click', function () {
                toolbar.closeAll();
                Service_37["default"].contextMenu.hideAll();
            });
            body
                .prepend(editor)
                .prepend(headSpacer)
                .prepend('<div class="clear">')
                .prepend(toolbar.elem);
            builder.init(editor);
            toolbar.adjustSize();
            _this.toolbar = toolbar;
            return _this;
        }
        DefaultUI.prototype.lookupUIElement = function (type, elementId) {
            if (type == 'control') {
                var m = void 0;
                if (elementId == 'config') {
                    return new Tooltip_2.ScenarioStepSubject($('#wb_config_btn').eq(0), 'left');
                }
                else if ((m = elementId.match(/^config-(.+)$/))) {
                    var mi = $('#wb_config_btn').eq(0).find('.ico-tb-' + m[1]);
                    if (mi.length > 0)
                        return new Tooltip_2.ScenarioStepSubject(mi.eq(0).parent().parent(), 'left');
                }
                for (var _i = 0, _a = this.toolbar.controlToolbar.tbItems; _i < _a.length; _i++) {
                    var item = _a[_i];
                    var id = item.getId();
                    if (id)
                        id = id.replace(/^wb_fn_/i, '');
                    if (elementId === id) {
                        return new Tooltip_2.ScenarioStepSubject(item.elem, 'left');
                    }
                }
            }
            else if (type === 'plugin') {
                for (var _b = 0, _c = this.toolbar.widgetToolbar.tbItems; _b < _c.length; _b++) {
                    var item = _c[_b];
                    var id = item.getId();
                    if (id)
                        id = id.replace(/^wb__/i, '');
                    if (elementId === id) {
                        return new Tooltip_2.ScenarioStepSubject(item.elem, null, 10);
                    }
                }
                for (var _d = 0, _e = this.toolbar.widgetToolbar.collapsableGroups; _d < _e.length; _d++) {
                    var item = _e[_d];
                    var id = item.getId();
                    if (id)
                        id = id.replace(/^wb-group-/i, '');
                    if (elementId === id) {
                        return new Tooltip_2.ScenarioStepSubject(item.expander.elem, 'left', 0, 0, true);
                    }
                }
            }
            else if (type === 'preview') {
                if (elementId === 'close' && this.toolbar.previewToolbar) {
                    return new Tooltip_2.ScenarioStepSubject(this.toolbar.previewToolbar.getCloseButton().getElem());
                }
            }
            return null;
        };
        DefaultUI.prototype.closeAll = function () {
            this.toolbar.widgetToolbar.closeAllGroups();
            this.toolbar.closeAll();
        };
        return DefaultUI;
    }(UIManager_2.UIManager));
    UIManager_2.registerUI('default', DefaultUI);
});
define("DefaultUI/SwitchDialog", ["require", "exports", "Dialog", "ModeManager"], function (require, exports, Dialog_17, ModeManager_9) {
    "use strict";
    exports.__esModule = true;
    var SwitchDialog = (function (_super) {
        __extends(SwitchDialog, _super);
        function SwitchDialog() {
            var _this = _super.call(this, '', true) || this;
            _this.setTitleVisible(false);
            _this.setFooterVisible(false);
            _this.setSize(400, null);
            var dlgCont = $('<div>').addClass('mode-switcher-dlg');
            _this._onElem = $('<div>').addClass('mode-switcher-dlg-on').appendTo(dlgCont)
                .append(_this._onInpElem = $('<input>').attr('type', 'radio').attr('name', 'mode_switcher_value_inp'))
                .append($('<div>').addClass('mode-switcher-dlg-label')
                .append(_this._onNameElem = $('<span>').text(__('version')))
                .append($('<span>').addClass('mode-switcher-dlg-value').text(__('ON')))
                .append($('<span>').addClass('mode-switcher-dlg-marker'))
                .append(_this._onTextElem = $('<div>').addClass('mode-switcher-dlg-text'))).on('click', function () {
                ModeManager_9["default"].setModeEnabled(ModeManager_9["default"].getMode(), true);
                _this.setVisible(false);
            });
            _this._offElem = $('<div>').addClass('mode-switcher-dlg-off').appendTo(dlgCont)
                .append(_this._offInpElem = $('<input>').attr('type', 'radio').attr('name', 'mode_switcher_value_inp'))
                .append($('<div>').addClass('mode-switcher-dlg-label')
                .append(_this._offNameElem = $('<span>').text(__('version')))
                .append($('<span>').addClass('mode-switcher-dlg-value').text(__('OFF')))
                .append($('<span>').addClass('mode-switcher-dlg-marker'))
                .append(_this._offTextElem = $('<div>').addClass('mode-switcher-dlg-text'))).on('click', function () {
                ModeManager_9["default"].setModeEnabled(ModeManager_9["default"].getMode(), false);
                _this.setVisible(false);
            });
            _this.setContent(dlgCont);
            return _this;
        }
        SwitchDialog.prototype.setMode = function (mode) {
            var modeName = ModeManager_9["default"].getModeName(mode, true);
            var modeNameShort = ModeManager_9["default"].getModeName(mode, false, true);
            this._onNameElem.text(modeNameShort);
            this._offNameElem.text(modeNameShort);
            this._onTextElem.text(__('I will modify my website for %s version').replace('%s', modeName));
            this._offTextElem.text(__('Publish my %s version of website').replace('%s', modeName));
            if (ModeManager_9["default"].getModeEnabled(mode) && ModeManager_9["default"].isAutoLayoutEnabled()) {
                this._onInpElem.get(0).checked = true;
                this._offInpElem.get(0).checked = false;
            }
            else {
                this._onInpElem.get(0).checked = false;
                this._offInpElem.get(0).checked = true;
            }
        };
        return SwitchDialog;
    }(Dialog_17["default"]));
    exports.SwitchDialog = SwitchDialog;
});
define("PluginApi/DataWrapper", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var wrapMapping = {};
    var wrapIdx = 0;
    var DataWrapper = (function () {
        function DataWrapper() {
        }
        DataWrapper.wrap = function (wrappedInst, dataType) {
            var elem = new dataType();
            elem.wrapId = 'wrap_elem_' + wrapIdx;
            wrapIdx++;
            wrapMapping[elem.wrapId] = wrappedInst;
            return elem;
        };
        DataWrapper.uwrap = function (elem, dataType) {
            var val = wrapMapping[elem.wrapId];
            return val;
        };
        return DataWrapper;
    }());
    exports.DataWrapper = DataWrapper;
});
define("PluginApi/PluginContent", ["require", "exports", "Content", "Element", "PluginApi/DataWrapper", "PluginApi/PluginBody"], function (require, exports, Content_2, Element_4, DataWrapper_1, PluginBody_1) {
    "use strict";
    exports.__esModule = true;
    var PluginContent = (function () {
        function PluginContent() {
            this.wrapId = '';
        }
        PluginContent.prototype.getType = function () {
            return 'Content';
        };
        PluginContent.prototype.getX = function () {
            return DataWrapper_1.DataWrapper.uwrap(this, Content_2["default"]).container.offset().left;
        };
        PluginContent.prototype.getY = function () {
            return DataWrapper_1.DataWrapper.uwrap(this, Content_2["default"]).elem.offset().top;
        };
        PluginContent.prototype.getWidth = function () {
            return DataWrapper_1.DataWrapper.uwrap(this, Content_2["default"]).getWidth();
        };
        PluginContent.prototype.getHeight = function () {
            return DataWrapper_1.DataWrapper.uwrap(this, Content_2["default"]).getHeight();
        };
        PluginContent.prototype.getParent = function () {
            var body = DataWrapper_1.DataWrapper.uwrap(this, Content_2["default"]).bodyInstance;
            return DataWrapper_1.DataWrapper.wrap(body, PluginBody_1.PluginBody);
        };
        PluginContent.prototype.addElement = function (element) {
            if (!element)
                throw 'Bad argument';
            wb_builder.setPageModified(true);
            var wElement = DataWrapper_1.DataWrapper.uwrap(element, Element_4["default"]);
            DataWrapper_1.DataWrapper.uwrap(this, Content_2["default"]).addElement(wElement);
        };
        return PluginContent;
    }());
    exports.PluginContent = PluginContent;
});
define("PluginApi/PluginElement", ["require", "exports", "Element", "ElementRegister", "PluginApi/PluginContent", "PluginApi/DataWrapper"], function (require, exports, Element_5, ElementRegister_9, PluginContent_1, DataWrapper_2) {
    "use strict";
    exports.__esModule = true;
    var PluginElement = (function () {
        function PluginElement() {
            this.wrapId = '';
            this.x = 0;
            this.y = 0;
        }
        PluginElement.prototype.getType = function () {
            return DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).className;
        };
        PluginElement.prototype.getId = function () {
            return DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).id;
        };
        PluginElement.prototype.getX = function () {
            var elem = DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]);
            return elem.getParent() ? elem.getLocation().left : this.x;
        };
        PluginElement.prototype.getY = function () {
            var elem = DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]);
            return elem.getParent() ? elem.getLocation().top : this.y;
        };
        PluginElement.prototype.getWidth = function () {
            return DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).getWidth();
        };
        PluginElement.prototype.getHeight = function () {
            return DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).getHeight();
        };
        PluginElement.prototype.setX = function (x) {
            DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).setLocation(x);
        };
        PluginElement.prototype.setY = function (y) {
            DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).setLocation(null, y);
        };
        PluginElement.prototype.getParent = function () {
            var parent = DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).getParent();
            return (parent ? DataWrapper_2.DataWrapper.wrap(parent, PluginContent_1.PluginContent) : null);
        };
        PluginElement.prototype.toData = function () {
            return DataWrapper_2.DataWrapper.uwrap(this, Element_5["default"]).serialize();
        };
        PluginElement.fromData = function (data) {
            var cls = data["class"] ? ElementRegister_9["default"].getClassByName(data["class"]) : null;
            if (!cls)
                return null;
            var elem = DataWrapper_2.DataWrapper.wrap(new cls(data), PluginElement);
            elem.x = data.x ? data.x : 0;
            elem.y = data.y ? data.y : 0;
            return elem;
        };
        return PluginElement;
    }());
    exports.PluginElement = PluginElement;
});
define("PluginApi/PluginBody", ["require", "exports", "Element", "Service", "PluginApi/DataWrapper"], function (require, exports, Element_6, Service_38, DataWrapper_3) {
    "use strict";
    exports.__esModule = true;
    var PluginBody = (function () {
        function PluginBody() {
            this.wrapId = '';
        }
        PluginBody.prototype.getType = function () {
            return 'Body';
        };
        PluginBody.prototype.setElementSelection = function (elements) {
            Service_38["default"].element.unselectAll();
            for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
                var elem = elements_2[_i];
                var relem = DataWrapper_3.DataWrapper.uwrap(elem, Element_6["default"]);
                relem.setSelected(true);
            }
        };
        return PluginBody;
    }());
    exports.PluginBody = PluginBody;
});
define("PluginApi/PluginContextMenu", ["require", "exports", "ContextMenu", "PluginApi/DataWrapper"], function (require, exports, ContextMenu_1, DataWrapper_4) {
    "use strict";
    exports.__esModule = true;
    var idPrefix = 'plugin_ctx_menu_';
    var itemIdPrefix = 'plugin_ctx_menu_item_';
    var idIdx = 0;
    var PluginContextMenu = (function () {
        function PluginContextMenu() {
            this.wrapId = '';
            this.id = '';
        }
        PluginContextMenu.prototype.getId = function () {
            return this.id;
        };
        PluginContextMenu.prototype.setVisible = function (visible) {
            var rmenu = DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]);
            rmenu.setVisible(itemIdPrefix + this.id, visible);
        };
        PluginContextMenu.prototype.addItem = function (id, name, func, icon, index) {
            if (icon === void 0) { icon = 'glyphicon glyphicon-link'; }
            if (index === void 0) { index = -1; }
            if (!id) {
                id = 'auto' + idIdx;
                idIdx++;
            }
            var item = new PluginContextMenuItem(id, this);
            DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]).insertItemAt(index, itemIdPrefix + id, name, func, false, false, null, icon);
            return item;
        };
        PluginContextMenu.prototype.addMenu = function (id, name, icon, index) {
            if (icon === void 0) { icon = 'glyphicon glyphicon-list'; }
            if (index === void 0) { index = -1; }
            if (!id) {
                id = 'auto' + idIdx;
                idIdx++;
            }
            var menu = new ContextMenu_1["default"](idPrefix + id);
            var wmenu = DataWrapper_4.DataWrapper.wrap(menu, PluginContextMenu);
            wmenu.id = id;
            var item = new PluginContextMenuItem(id, wmenu);
            DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]).insertItemAt(index, itemIdPrefix + id, name, menu, false, false, null, icon);
            return wmenu;
        };
        PluginContextMenu.prototype.addSeparator = function (index) {
            DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]).addSeparator(index);
        };
        PluginContextMenu.prototype.getItem = function (id) {
            var rmenu = DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]);
            var li = rmenu.getItem(itemIdPrefix + id);
            if (!li)
                return null;
            var menu = rmenu.getSubmenu(itemIdPrefix + id);
            if (menu) {
                var wmenu = DataWrapper_4.DataWrapper.wrap(menu, PluginContextMenu);
                wmenu.id = id;
                return wmenu;
            }
            else {
                var item = new PluginContextMenuItem(id, this);
                return item;
            }
        };
        PluginContextMenu.prototype.hasItemById = function (id) {
            var rmenu = DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]);
            var li = rmenu.getItem(itemIdPrefix + id);
            return (li ? true : false);
        };
        PluginContextMenu.prototype.removeItem = function (item) {
            DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]).removeItem(itemIdPrefix + item.getId());
        };
        PluginContextMenu.prototype.removeAllItems = function () {
            DataWrapper_4.DataWrapper.uwrap(this, ContextMenu_1["default"]).removeAllItems();
        };
        return PluginContextMenu;
    }());
    exports.PluginContextMenu = PluginContextMenu;
    var PluginContextMenuItem = (function () {
        function PluginContextMenuItem(id, menu) {
            this.id = id;
            this.menu = menu;
        }
        PluginContextMenuItem.prototype.getId = function () {
            return this.id;
        };
        PluginContextMenuItem.prototype.getParent = function () {
            return this.menu;
        };
        PluginContextMenuItem.prototype.setName = function (name) {
            DataWrapper_4.DataWrapper.uwrap(this.menu, ContextMenu_1["default"]).setName(itemIdPrefix + this.id, name);
        };
        PluginContextMenuItem.prototype.setSelected = function (selected) {
            DataWrapper_4.DataWrapper.uwrap(this.menu, ContextMenu_1["default"]).setSelected(itemIdPrefix + this.id, selected);
        };
        PluginContextMenuItem.prototype.setEnabled = function (enabled) {
            DataWrapper_4.DataWrapper.uwrap(this.menu, ContextMenu_1["default"]).setDisabled(itemIdPrefix + this.id, !enabled);
        };
        PluginContextMenuItem.prototype.setVisible = function (visible) {
            DataWrapper_4.DataWrapper.uwrap(this.menu, ContextMenu_1["default"]).setVisible(itemIdPrefix + this.id, visible);
        };
        return PluginContextMenuItem;
    }());
});
define("PluginApi/PluginResourceLoader", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var PluginResourceLoader = (function () {
        function PluginResourceLoader(pluginId) {
            this.pluginId = pluginId;
        }
        PluginResourceLoader.prototype.getResourceUrl = function (relPath) {
            return wb_builder.baseUrl + 'plugins/' + this.pluginId + '/' + relPath.replace(/^\/+/, '');
        };
        PluginResourceLoader.prototype.loadStyles = function (styles) {
            var head = $('head');
            for (var _i = 0, styles_1 = styles; _i < styles_1.length; _i++) {
                var styleFile = styles_1[_i];
                head.append($('<link rel="stylesheet prefetch" type="text/css" />').attr("href", this.getResourceUrl(styleFile)));
            }
        };
        PluginResourceLoader.prototype.addRawStyleSheet = function (styleSheet) {
            var _this = this;
            var style = document.createElement("STYLE");
            style.setAttribute("type", "text/css");
            styleSheet = styleSheet.replace(/(url\(\s*['"]?)(.*?['"]?\s*\))/ig, function (match0, match1, match2) {
                if (/^(https?:\/\/|\/)/i.test(match2))
                    return match0;
                return match1 + _this.getResourceUrl(match2);
            });
            style.append(document.createTextNode(styleSheet));
            document.body.append(style);
        };
        PluginResourceLoader.prototype.loadResources = function (relativeResourcesPaths, onDone) {
            var resources = {};
            var counter = relativeResourcesPaths.length;
            var countdown = function () {
                if (--counter <= 0)
                    onDone(resources);
            };
            for (var _i = 0, relativeResourcesPaths_1 = relativeResourcesPaths; _i < relativeResourcesPaths_1.length; _i++) {
                var relPath = relativeResourcesPaths_1[_i];
                var resource = new PluginResource(relPath, this.getResourceUrl(relPath));
                resources[relPath] = resource;
                resource.load(countdown);
            }
            return resources;
        };
        return PluginResourceLoader;
    }());
    exports.PluginResourceLoader = PluginResourceLoader;
    var PluginResource = (function () {
        function PluginResource(name, url) {
            this.xhr = null;
            this.data = null;
            this.status = null;
            this.error = null;
            this.name = name;
            this.url = url;
        }
        PluginResource.prototype.load = function (callback) {
            var _this = this;
            this.status = null;
            this.error = null;
            this.data = null;
            this.xhr = $.ajax({
                url: this.url,
                type: "GET",
                success: function (data, textStatus) {
                    _this.data = data;
                    _this.status = textStatus;
                },
                error: function (xhr, textStatus, errorThrown) {
                    _this.status = textStatus;
                    _this.error = errorThrown;
                },
                complete: function () {
                    callback();
                }
            });
        };
        PluginResource.prototype.abort = function () {
            if (this.xhr)
                this.xhr.abort();
        };
        return PluginResource;
    }());
    exports.PluginResource = PluginResource;
});
define("PluginApi/PluginSite", ["require", "exports", "PluginApi/DataWrapper", "Site"], function (require, exports, DataWrapper_5, Site_3) {
    "use strict";
    exports.__esModule = true;
    var PluginSite = (function () {
        function PluginSite() {
            this.wrapId = '';
        }
        PluginSite.prototype.getType = function () {
            return 'Site';
        };
        PluginSite.prototype.getSiteMetaHtml = function () {
            var value = DataWrapper_5.DataWrapper.uwrap(this, Site_3["default"]).metaHtml;
            return value ? value : '';
        };
        PluginSite.prototype.setSiteMetaHtml = function (value) {
            DataWrapper_5.DataWrapper.uwrap(this, Site_3["default"]).metaHtml = (typeof value === 'string') ? value : '';
        };
        PluginSite.prototype.getSiteHeadEndHtml = function () {
            var value = DataWrapper_5.DataWrapper.uwrap(this, Site_3["default"]).headSnippetsHtml;
            return value ? value : '';
        };
        PluginSite.prototype.setSiteHeadEndHtml = function (value) {
            DataWrapper_5.DataWrapper.uwrap(this, Site_3["default"]).headSnippetsHtml = (typeof value === 'string') ? value : '';
        };
        PluginSite.prototype.getSiteBodyEndHtml = function () {
            var value = DataWrapper_5.DataWrapper.uwrap(this, Site_3["default"]).bodySnippetsHtml;
            return value ? value : '';
        };
        PluginSite.prototype.setSiteBodyEndHtml = function (value) {
            DataWrapper_5.DataWrapper.uwrap(this, Site_3["default"]).bodySnippetsHtml = (typeof value === 'string') ? value : '';
        };
        return PluginSite;
    }());
    exports.PluginSite = PluginSite;
});
define("PluginApi/PluginTranslation", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var translationExtensions = {};
    function extendTranslations(translations) {
        $.extend(translationExtensions, translations);
    }
    exports.extendTranslations = extendTranslations;
    function __(msg) {
        if (translationExtensions.hasOwnProperty(msg))
            return translationExtensions[msg];
        return window.__(msg);
    }
    exports.__ = __;
});
define("PluginApi/Types", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var PluginEvent = (function () {
        function PluginEvent() {
            this.x = 0;
            this.y = 0;
            this.ctxMenu = null;
            this.target = null;
        }
        return PluginEvent;
    }());
    exports.PluginEvent = PluginEvent;
    var PluginMetaData = (function () {
        function PluginMetaData() {
            this.id = null;
            this.icon = null;
            this.name = null;
            this.isBorderless = false;
            this.template = '';
            this.serviceUrl = null;
            this.def = new PluginDefinition();
        }
        return PluginMetaData;
    }());
    exports.PluginMetaData = PluginMetaData;
    var PluginWrapperConfig = (function () {
        function PluginWrapperConfig(id, icon, template, active, serviceUrl) {
            if (id === void 0) { id = null; }
            if (icon === void 0) { icon = null; }
            if (template === void 0) { template = null; }
            if (active === void 0) { active = false; }
            if (serviceUrl === void 0) { serviceUrl = null; }
            this.id = id;
            this.icon = icon;
            this.template = template;
            this.active = active;
            this.serviceUrl = serviceUrl;
        }
        return PluginWrapperConfig;
    }());
    exports.PluginWrapperConfig = PluginWrapperConfig;
    var PluginDefinition = (function () {
        function PluginDefinition() {
            this.name = null;
            this.borderless = false;
            this.element = new ElementDefinition();
            this.serviceUrl = null;
        }
        return PluginDefinition;
    }());
    exports.PluginDefinition = PluginDefinition;
    var ElementDefinition = (function () {
        function ElementDefinition() {
            this.resizable = false;
            this.renderOnce = false;
            this.supportsFullWidth = true;
            this.initialFullWidth = false;
            this.isolatedRendering = false;
        }
        return ElementDefinition;
    }());
    exports.ElementDefinition = ElementDefinition;
});
define("PluginApi/PluginWrapper", ["require", "exports", "Element", "ElementRegister", "Service", "URLControl", "PluginApi/Types", "BuilderEvent", "Body", "Content", "PluginApi/PluginElement", "PluginApi/DataWrapper", "PluginApi/PluginContextMenu", "PluginApi/PluginContent", "PluginApi/PluginBody", "PluginApi/PluginSite"], function (require, exports, Element_7, ElementRegister_10, Service_39, URLControl_1, Types_1, BuilderEvent_23, Body_2, Content_3, PluginElement_1, DataWrapper_6, PluginContextMenu_1, PluginContent_2, PluginBody_2, PluginSite_1) {
    "use strict";
    exports.__esModule = true;
    var eventHandlersIdx = 0;
    var eventHandlers = {};
    var PluginWrapper = (function (_super) {
        __extends(PluginWrapper, _super);
        function PluginWrapper(data, def) {
            var _this = _super.call(this, data) || this;
            _this._rendered = false;
            _this._isolatorElem = null;
            _this._isolatorElemWnd = null;
            _this._isolatorElemReady = false;
            _this._isolatorElemListeners = [];
            _this._callbackApplied = false;
            _this._supportsFullWidth = true;
            if (!data)
                return _this;
            _this._def = def;
            var elDef = (_this._def && _this._def.element) ? _this._def.element : new Types_1.ElementDefinition();
            _this._supportsFullWidth = !!elDef.supportsFullWidth;
            if (typeof elDef.minSize === 'object' && elDef.minSize) {
                if (elDef.minSize.width)
                    _this.setMinSize(elDef.minSize.width, null);
                if (elDef.minSize.height)
                    _this.setMinSize(null, elDef.minSize.height);
            }
            if (typeof elDef.defaultSize === 'object' && elDef.defaultSize && !data.id) {
                if (elDef.defaultSize.width)
                    _this.setSize(elDef.defaultSize.width, null);
                if (elDef.defaultSize.height)
                    _this.setSize(null, elDef.defaultSize.height);
            }
            if ('resizable' in elDef && !elDef.resizable)
                _this.setResizingEnabled(false, true);
            _this.displayEmtyMessage(true);
            if (_this.elem.hasClass('ui-resizable')) {
                var resizeStopHandler_1 = _this.elem.resizable('option', 'stop');
                _this.elem.resizable('option', 'stop', function (e, ui) {
                    resizeStopHandler_1(e, ui);
                    if (typeof _this._def.resizeStopAction === 'function')
                        _this._def.resizeStopAction(_this._data, _this.container);
                });
            }
            _this._data = data;
            _this._data.id = _this.id;
            _this._data.width = _this.getWidth();
            _this._data.height = _this.getHeight();
            if (wb_builder.pluginData) {
                for (var k in wb_builder.pluginData) {
                    _this._data[k] = wb_builder.pluginData[k];
                }
            }
            _this.updateStyle(true);
            _this._def.notifyHelpSystemPlayer = function (eventName, target) {
                if (!target)
                    target = _this;
                Service_39["default"].HelpSystemPlayer.notify('item-plugin-' + _this.getClassType() + '-' + eventName, target);
            };
            _this._def.updateElement = function () { _this.updateStyle(); };
            _this._def.setSize = function (width, height) { _this.setSize(width, height); };
            _this._def.setLocation = function (left, top) { _this.setLocation(left, top); };
            _this._def.openProperties = function () { _this.comProperties(); };
            _this._def.bringToFront = function () {
                if (!_this.parent)
                    return;
                _this.parent.changeElementLayer(_this, 'top');
            };
            _this._def.sendToBack = function () {
                if (!_this.parent)
                    return;
                _this.parent.changeElementLayer(_this, 'bottom');
            };
            _this._def.bringForward = function () {
                if (!_this.parent)
                    return;
                _this.parent.changeElementLayer(_this, 'up');
            };
            _this._def.sendBackwards = function () {
                if (!_this.parent)
                    return;
                _this.parent.changeElementLayer(_this, 'down');
            };
            _this._def.moveToHeader = function () {
                if (!_this.parent)
                    return;
                wb_builder.bodyInstance.addElement('wb_header', _this);
            };
            _this._def.moveToBody = function () {
                if (!_this.parent)
                    return;
                wb_builder.bodyInstance.addElement('wb_main', _this);
            };
            _this._def.moveToFooter = function () {
                if (!_this.parent)
                    return;
                wb_builder.bodyInstance.addElement('wb_footer', _this);
            };
            _this.container.css({ overflow: 'hidden' });
            if (typeof _this._def.loadedAction === 'function') {
                setTimeout(function () { if (_this._def.loadedAction)
                    _this._def.loadedAction(data, _this.container); }, 0);
            }
            _this.controls.bind('dblclick', function () { _this.comProperties(); });
            return _this;
        }
        PluginWrapper.mutateData = function (meta, data, out) {
            if (!data)
                return data;
            if (!data.content || typeof data.content !== 'object' || typeof data.content.pop === 'function')
                data.content = {};
            data.isPublished = false;
            data.isPreview = false;
            data.requireService = null;
            var def = meta.def ? PluginWrapper._extendDef(meta.def) : new Types_1.PluginDefinition();
            def.serviceUrl = meta.serviceUrl;
            if (typeof def.loadAction === 'function')
                def.loadAction(data);
            def.element = (typeof def.element === 'object' && def.element) ? def.element : new Types_1.ElementDefinition();
            def.element.supportsFullWidth = (!('supportsFullWidth' in def.element) || def.element.supportsFullWidth);
            if (def.element.supportsFullWidth && def.element.initialFullWidth) {
                data.isFullWidth = true;
            }
            out.def = def;
            return data;
        };
        PluginWrapper.registerPlugin = function (id, def) {
            var _a;
            if (!('propertyDialog' in def) || (typeof def.propertyDialog !== 'object') || def.propertyDialog === null) {
                def.propertyDialog = {};
            }
            var meta = new Types_1.PluginMetaData();
            meta.id = PluginWrapper._config.id;
            PluginWrapper._config.id = null;
            meta.icon = PluginWrapper._config.icon;
            PluginWrapper._config.icon = null;
            meta.name = def.name;
            meta.isBorderless = def.borderless;
            meta.template = PluginWrapper._config.template || '';
            PluginWrapper._config.template = null;
            meta.serviceUrl = PluginWrapper._config.serviceUrl;
            PluginWrapper._config.serviceUrl = null;
            meta.def = def;
            var out = { def: def };
            var plugin = (_a = (function (_super) {
                    __extends(class_1, _super);
                    function class_1(data) {
                        var _this = _super.call(this, PluginWrapper.mutateData(meta, data ? data : null, out), out.def) || this;
                        _this.className = id;
                        return _this;
                    }
                    class_1.prototype.meta = function () {
                        return meta;
                    };
                    return class_1;
                }(PluginWrapper)),
                _a._metaData_ = meta,
                _a);
            def.pluginScoped = plugin.pluginScoped = (typeof def.pluginScoped === 'object') ? def.pluginScoped : {};
            ElementRegister_10["default"].registerClass(id, plugin, true, PluginWrapper._config.active);
        };
        PluginWrapper.isDataImageSelector = function (data, _checkPattern) {
            if (_checkPattern === void 0) { _checkPattern = false; }
            if (!data)
                return false;
            if (_checkPattern) {
                return (/^gallery\//.test(data));
            }
            else {
                var res = true;
                if (typeof data === 'object' && ('length' in data)) {
                    for (var i in data) {
                        if (!PluginWrapper.isDataImageSelector(data[i], true)) {
                            res = false;
                            break;
                        }
                    }
                }
                else if (!PluginWrapper.isDataImageSelector(data, true)) {
                    res = false;
                }
                return res;
            }
        };
        PluginWrapper.imageSelectorMakeLocalUrl = function (data) {
            if (data) {
                if (typeof data === 'object' && ('length' in data)) {
                    var _data = [];
                    for (var i in data) {
                        _data.push(wb_builder.makeLocalUrl(data[i]));
                    }
                    return _data;
                }
                else {
                    return wb_builder.makeLocalUrl(data);
                }
            }
            return data;
        };
        PluginWrapper.updateImageSelectorData = function (data) {
            if (!data)
                return;
            for (var i in data) {
                if (data[i] instanceof HTMLElement || data[i] instanceof $)
                    continue;
                if (PluginWrapper.isDataImageSelector(data[i])) {
                    data[i] = PluginWrapper.imageSelectorMakeLocalUrl(data[i]);
                }
                else if (data[i] && typeof data[i] === 'object') {
                    PluginWrapper.updateImageSelectorData(data[i]);
                }
            }
        };
        PluginWrapper.isMultilangValue = function (value) {
            if (value && typeof (value) === 'object') {
                for (var i in value) {
                    if (!(i in wb_builder.getLanguageCodeIndex())) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        };
        PluginWrapper.updateMultilangData = function (data) {
            if (!data)
                return;
            for (var i in data) {
                if (data[i] instanceof HTMLElement || data[i] instanceof $)
                    continue;
                if (PluginWrapper.isMultilangValue(data[i])) {
                    data[i] = __tr(data[i], null, __tr(data[i], wb_builder.site.getLastDefLang()));
                }
                else if (typeof data[i] === 'object') {
                    PluginWrapper.updateMultilangData(data[i]);
                }
            }
        };
        PluginWrapper.isLinkSelectorValue = function (value) {
            return !!(value && typeof (value) === 'object' && ('name' in value)
                && ('type' in value) && ('url' in value) && ('target' in value)
                && ('title' in value) && ('menuUID' in value) && ('anchor' in value));
        };
        PluginWrapper.updateLinkSelectorData = function (data) {
            if (!data)
                return;
            for (var i in data) {
                if (data[i] instanceof HTMLElement || data[i] instanceof $)
                    continue;
                if (PluginWrapper.isLinkSelectorValue(data[i])) {
                    if (!('name' && data[i]) || !data[i].name)
                        data[i].name = URLControl_1["default"].getName(data[i]);
                    if (!('finalUrl' && data[i]) || !data[i].finalUrl)
                        data[i].finalUrl = URLControl_1["default"].getUrl(data[i]);
                }
                else if (typeof data[i] === 'object') {
                    PluginWrapper.updateLinkSelectorData(data[i]);
                }
            }
        };
        PluginWrapper.addEventListener = function (event, func) {
            if (!event || typeof event !== 'string' || !func || typeof func !== 'function')
                return;
            var funcAny = func;
            if (!funcAny.eventHandlerId) {
                funcAny.eventHandlerId = 'plEventId' + eventHandlersIdx;
                eventHandlersIdx++;
            }
            if (!(funcAny.eventHandlerId in eventHandlers)) {
                eventHandlers[funcAny.eventHandlerId] = function (e) {
                    var plEvent = new Types_1.PluginEvent();
                    if (e instanceof BuilderEvent_23.ContextMenuEvent) {
                        plEvent.x = e.x;
                        plEvent.y = e.y;
                        plEvent.ctxMenu = DataWrapper_6.DataWrapper.wrap(e.menu, PluginContextMenu_1.PluginContextMenu);
                        if (e.target instanceof Element_7["default"]) {
                            plEvent.target = DataWrapper_6.DataWrapper.wrap(e.target, PluginElement_1.PluginElement);
                            plEvent.targets = [];
                            var selection = Service_39["default"].element.getSelected();
                            for (var k in selection) {
                                plEvent.targets.push(DataWrapper_6.DataWrapper.wrap(selection[k], PluginElement_1.PluginElement));
                            }
                        }
                        else if (e.target instanceof Content_3["default"]) {
                            plEvent.target = DataWrapper_6.DataWrapper.wrap(e.target, PluginContent_2.PluginContent);
                        }
                        else if (e.target instanceof Body_2["default"]) {
                            plEvent.target = DataWrapper_6.DataWrapper.wrap(e.target, PluginBody_2.PluginBody);
                        }
                    }
                    else if (e instanceof BuilderEvent_23.SaveEvent) {
                        plEvent.target = DataWrapper_6.DataWrapper.wrap(wb_builder.site, PluginSite_1.PluginSite);
                    }
                    func(plEvent);
                };
            }
            BuilderEvent_23.GlobalEvents.on(event, eventHandlers[funcAny.eventHandlerId]);
        };
        PluginWrapper.removeEventListener = function (event, func) {
            if (!event || typeof event !== 'string' || !func || typeof func !== 'function')
                return;
            var funcAny = func;
            if (!funcAny.eventHandlerId || !(funcAny.eventHandlerId in eventHandlers))
                return;
            BuilderEvent_23.GlobalEvents.off(event, eventHandlers[funcAny.eventHandlerId]);
        };
        PluginWrapper._extendDef = function (def) {
            var newDef = {};
            for (var k in def) {
                newDef[k] = def[k];
            }
            return newDef;
        };
        PluginWrapper.prototype.supportsFullWidth = function () {
            return this._supportsFullWidth;
        };
        PluginWrapper.prototype.serialize = function () {
            var data = _super.prototype.serialize.call(this);
            var typeClass = data['class'];
            if ((typeClass in ElementRegister_10["default"].pluginRegistry) && ElementRegister_10["default"].pluginRegistry[typeClass].textId) {
                data['class'] = ElementRegister_10["default"].pluginRegistry[typeClass].textId;
            }
            data.content = (this._data.content && typeof this._data.content === 'object' && typeof this._data.content.pop !== 'function') ? this._data.content : {};
            if (typeof this._def.saveAction === 'function')
                this._def.saveAction(data, this.container);
            return data;
        };
        PluginWrapper.prototype.updateContentSize = function () {
            _super.prototype.updateContentSize.call(this);
            if (this._data) {
                this._data.width = this.getWidth();
                this._data.height = this.getHeight();
                if (typeof this._def.resizeAction === 'function')
                    this._def.resizeAction(this._data, this.container);
            }
            var parent = this.getParent();
            if (parent)
                parent.updateSize();
        };
        PluginWrapper.prototype.onSwitchLanguage = function (langCode) {
            _super.prototype.onSwitchLanguage.call(this, langCode);
            if (typeof this._def.switchLanguageAction === 'function')
                this._def.switchLanguageAction(this._data, this.container, langCode);
            this.updateStyle(false, langCode);
        };
        PluginWrapper.prototype.switchMode = function (fromMode, toMode, initial, manual) {
            _super.prototype.switchMode.call(this, fromMode, toMode, initial, manual);
            if (manual && typeof this._def.switchModeAction === 'function')
                this._def.switchModeAction(this._data, this.container);
        };
        PluginWrapper.prototype.updateStyle = function (initial, langCode) {
            var _this = this;
            _super.prototype.updateStyle.call(this, initial, langCode);
            if (!this._rendered || !this._def.element.renderOnce) {
                this._rendered = true;
                PluginWrapper.updateLinkSelectorData(this._data.content);
                var _data = $.extend(true, {}, this._data);
                PluginWrapper.updateImageSelectorData(_data.content);
                PluginWrapper.updateMultilangData(_data.content);
                var html_1 = window.Mustache.render(this.meta().template, _data);
                if (this._def.element.isolatedRendering) {
                    if (!this._isolatorElem) {
                        this._isolatorElemWnd = null;
                        this._isolatorElemReady = false;
                        this._isolatorElemListeners = [];
                        this._isolatorElem = $('<iframe>').css({
                            border: 'none',
                            background: 'transparent',
                            padding: '0',
                            margin: '0',
                            width: '100%',
                            height: '100%'
                        }).attr({ src: 'modules/builder/tpl/blank.html' }).on('load', function () {
                            if (!_this._isolatorElem)
                                return;
                            _this._isolatorElemWnd = (_this._isolatorElem.get(0).contentWindow || _this._isolatorElem.get(0).contentDocument);
                            _this._isolatorElemWnd.xnextStickRight = function () { };
                            _this._isolatorElemReady = true;
                            for (var i = 0; i < _this._isolatorElemListeners.length; i++) {
                                if (typeof _this._isolatorElemListeners[i].func === 'function') {
                                    _this._isolatorElemListeners[i].func.call(_this._isolatorElemListeners[i].inst);
                                }
                            }
                        });
                        this.container.empty();
                        this.container.append(this._isolatorElem);
                    }
                    var isoBody_1 = null;
                    if (this._isolatorElemWnd instanceof Window) {
                        isoBody_1 = $(this._isolatorElemWnd.document.body);
                    }
                    else if (this._isolatorElemWnd instanceof Document) {
                        isoBody_1 = $(this._isolatorElemWnd.body);
                    }
                    if (this._isolatorElemReady) {
                        if (isoBody_1)
                            isoBody_1.html(html_1);
                    }
                    else {
                        this._isolatorElemListeners.push({ inst: this, func: function () { if (isoBody_1)
                                isoBody_1.html(html_1); } });
                    }
                }
                else {
                    this.container.html(html_1);
                }
                this.displayEmtyMessage(!html_1);
            }
        };
        PluginWrapper.prototype.comProperties = function (uiDef) {
            var _this = this;
            if (!this._def.propertyDialog)
                return {};
            var thisClass = this;
            if (!this._callbackApplied) {
                this._callbackApplied = true;
                this._def.propertyDialog.callbackFunc = function (fields) {
                    if (typeof thisClass._def.applyAction === 'function')
                        thisClass._def.applyAction(fields, thisClass._data, thisClass.container);
                    _this.updateStyle();
                };
            }
            var res = _super.prototype.comProperties.call(this, this._def.propertyDialog);
            if (this.comDialog) {
                if (this._callbackApplied)
                    delete this._def.propertyDialog.callbackFunc;
                var fields = this.comDialog.fields;
                if (!fields._initiated) {
                    fields._initiated = true;
                }
                if (typeof this._def.openAction === 'function')
                    this._def.openAction(fields, this._data, this.container);
            }
            return res;
        };
        PluginWrapper.prototype.updateComPropertiesInterface = function () {
            _super.prototype.updateComPropertiesInterface.call(this);
            if (!this.comDialog)
                return;
            if (typeof this._def.updateAction === 'function')
                this._def.updateAction(this.comDialog.fields, this._data, this.container);
        };
        PluginWrapper.prototype.onFullWidthChanged = function () {
            _super.prototype.onFullWidthChanged.call(this);
            if (typeof this._def.fullWidthChangeAction === 'function')
                this._def.fullWidthChangeAction(this.isFullWidth, this._data, this.container);
        };
        PluginWrapper.prototype.applyAction = function (fields, data, elem) {
        };
        PluginWrapper.prototype.meta = function () {
            return PluginWrapper._metaData_;
        };
        PluginWrapper.PluginElement = PluginElement_1.PluginElement;
        PluginWrapper._config = new Types_1.PluginWrapperConfig();
        PluginWrapper._metaData_ = new Types_1.PluginMetaData();
        return PluginWrapper;
    }(Element_7["default"]));
    exports["default"] = PluginWrapper;
});
define("modes/ChangeRenderModePromptDialog", ["require", "exports", "Service", "Dialog"], function (require, exports, Service_40, Dialog_18) {
    "use strict";
    exports.__esModule = true;
    var ChangeRenderModePromptDialog = (function (_super) {
        __extends(ChangeRenderModePromptDialog, _super);
        function ChangeRenderModePromptDialog(onApplyCallback) {
            var _this = _super.call(this, __('Turn automatic layout off')) || this;
            _this.onApplyCallback = onApplyCallback;
            _this.setContent(new Service_40["default"].UIBuilder({
                type: 'VerticalLayout',
                children: [
                    { type: 'RadioBox', id: 'modeConvert', group: 'manualModeSwitchType',
                        label: __('Convert your current design to mode-specific (we advise to make a backup)'),
                        styleClass: 'mode-change-type-selector'
                    },
                    { type: 'RadioBox', id: 'modeReturn', group: 'manualModeSwitchType',
                        label: __('Return to previous design you had before switching to auto layout'),
                        styleClass: 'mode-change-type-selector'
                    }
                ]
            }, _this.fields), true);
            _this.applyButton = _this.addButton(__('Apply'), function () { _this.onApply(); }, false, 'btn-success apply-mode-change-btn');
            _this.addButton(__('Cancel'));
            _this.setValue(0);
            return _this;
        }
        ChangeRenderModePromptDialog.prototype.onApply = function () {
            if (this.applyButton.is('disabled'))
                return;
            var rebuild = (this.getValue() == 1);
            this.hide();
            if (typeof this.onApplyCallback === 'function')
                this.onApplyCallback(rebuild);
        };
        ChangeRenderModePromptDialog.prototype.getValue = function () {
            if (this.fields.modeConvert.getValue()) {
                return 1;
            }
            else {
                return 0;
            }
        };
        ChangeRenderModePromptDialog.prototype.setValue = function (mode) {
            if (mode == 1) {
                this.fields.modeConvert.setValue(true);
                this.fields.modeReturn.setValue(false);
            }
            else {
                this.fields.modeConvert.setValue(false);
                this.fields.modeReturn.setValue(true);
            }
        };
        return ChangeRenderModePromptDialog;
    }(Dialog_18["default"]));
    exports.ChangeRenderModePromptDialog = ChangeRenderModePromptDialog;
});
;

/** LayoutManager **/
(window.defineModule = (window.defineModule || {})).name = 'LayoutManager';

define('LayoutManager', ['Content', 'Service', 'ModeManager'], function(Content, Service, ModeManager) {
	'use strict';
	
	var _visible = false, _builder = null, elem = {
		top: null, right: null, bottom: null, left: null, leftGuide: null, rightGuide: null
	}, showGuides = function(show) {
		if (show) {
			elem.leftGuide.elem.removeClass('hide');
			elem.rightGuide.elem.removeClass('hide');
		} else {
			elem.leftGuide.elem.addClass('hide');
			elem.rightGuide.elem.addClass('hide');
		}
	}, docMoveEvent = null, docUpEvent = null, dragTarget = null, noWidthResize = true,
	Line = {
		elem: null,
		type: null,
		refBlock: null,
		reflector: null,
		tPos: null,
		init: function(type) {
			this.type = type;
			var style = '', hasEvent = true;
			if (type === 'top' || type === 'bottom') {
				style = 'layout_border_h';
				if (type === 'top') this.refBlock = 'wb_header';
				if (type === 'bottom') this.refBlock = 'wb_footer';
			} else if (type === 'left' || type === 'right') {
				style = 'layout_border_v';
				if (type === 'left') this.reflector = 'right';
				if (type === 'right') this.reflector = 'left';
				if (noWidthResize) hasEvent = false;
			} else if (type === 'leftGuide' || type === 'rightGuide') {
				style = 'layout_border_v2 hide';
				hasEvent = false;
			}
			this.elem = $('<div>').addClass('layout_border').addClass(style);
			var thisSelf = this;
			if (hasEvent) {
				this.elem.on('mousedown', function(e) {
					var pos2 = (thisSelf.reflector && (thisSelf.reflector in elem)) ? elem[thisSelf.reflector].elem.position() : null;
					if (thisSelf.refBlock) {
						var refBlock = _builder.bodyInstance.getContentBlock(thisSelf.refBlock);
						thisSelf.logPos({height: (refBlock ? refBlock.elem.height() : 0)}, e, pos2);
					} else {
						thisSelf.logPos({width: parseInt(_builder.bodyInstance.siteWidth, 10)}, e, pos2);
						showGuides(true);
					}
					dragTarget = thisSelf;
					e.stopPropagation();
					e.preventDefault();
					return false;
				});
			} else {
				if (type === 'left' || type === 'right') {
					this.elem.on('mousedown', function(e) {
						e.stopPropagation();
						e.preventDefault();
						return false;
					});
				}
				this.elem.css('cursor', 'default');
			}
			
			return this;
		},
		logPos: function(size, e, pos2) {
			this.tPos = {
				size: size,
				offset: this.elem.offset(),
				position: this.elem.position(),
				position2: pos2
			};
			var val = Math.round((('height' in size) ? size.height : (('width' in size) ? size.width : 0)));
			if (isNaN(val)) val = 0;
			Content.locTip.html(val);
			Content.locTip.css({
				display: 'block',
				left: (e.pageX - 90) + 'px',
				top: e.pageY + 'px'
			});
		}
	};
	
	return {
		/** @param {Builder} builder */
		init: function(builder) {
			var self = this;
			_builder = builder;
			
			for (var k in elem) { elem[k] = Object.create(Line).init(k); }
			
			docMoveEvent = function(e) {
				if (dragTarget) {
					var refBlock = dragTarget.refBlock ? _builder.bodyInstance.getContentBlock(dragTarget.refBlock) : null;
					var d = 0, dr = 0;
					if (dragTarget.type === 'top' || dragTarget.type === 'bottom') {
						d = Math.round(e.pageY - dragTarget.tPos.offset.top);
					} else if (dragTarget.type === 'left' || dragTarget.type === 'right') {
						d = Math.round(e.pageX - dragTarget.tPos.offset.left);
					}
					if (dragTarget.type === 'bottom' || dragTarget.type === 'left') dr = -d; else dr = d;
					if (dragTarget.type === 'top' || dragTarget.type === 'bottom') {
						dragTarget.elem.css('top', dragTarget.tPos.position.top + d);
					} else if (dragTarget.type === 'left' || dragTarget.type === 'right') {
						dragTarget.elem.css('left', dragTarget.tPos.position.left + d);
					}
					if (dragTarget.reflector && (dragTarget.reflector in elem)) {
						elem[dragTarget.reflector].elem.css('left', dragTarget.tPos.position2.left - d);
					}
					if (refBlock) refBlock.setSize(null, dragTarget.tPos.size.height + dr);
					if (dragTarget.type === 'left' || dragTarget.type === 'right') _builder.bodyInstance.setWidth(dragTarget.tPos.size.width + dr*2);
					//if (dragTarget.type === 'top' && refBlock) refBlock.updateSize();
					var val = ('height' in dragTarget.tPos.size) ? Math.round(dragTarget.tPos.size.height + dr) : Math.round(dragTarget.tPos.size.width + dr*2);
					Content.locTip.html(val);
					Content.locTip.css({ left: (e.pageX - 90), top: e.pageY });
					_builder.setPageModified(true);
					e.stopPropagation();
					e.preventDefault();
					return false;
				}
				return true;
			};
			
			docUpEvent = function(e) {
				if (dragTarget) {
					Content.locTip.css({ display: 'none', left: 0, top: 0 });
					var refBlock = dragTarget.refBlock ? _builder.bodyInstance.getContentBlock(dragTarget.refBlock) : null;
					if (refBlock) {
						self._updateCurrentBlockHeight(refBlock);
						refBlock.fitElements();
						refBlock.updateSize();
					} else {
						showGuides(false);
						_builder.bodyInstance.fitElements();
					}
					if (dragTarget.type === 'bottom') $('html, body').scrollTop($(document).height()); //move down
					dragTarget.tPos = null;
					dragTarget = null;
					e.stopPropagation();
					e.preventDefault();
					return false;
				}
				return true;
			};
			
		},
		
		_updateCurrentBlockHeight: function(refBlock) {
			var currMode = ModeManager.getMode();
			var height = refBlock.getHeight();
			var defData = (wb_builder.bodyInstance.blocksData && wb_builder.bodyInstance.blocksData[refBlock.id]) ? wb_builder.bodyInstance.blocksData[refBlock.id] : null;
			if (defData && defData.useDefault) {
				if (!defData.modes) defData.modes = {};
				if (!(currMode in defData.modes)) defData.modes[currMode] = new Content.Mode();
				defData.modes[currMode].height = height;
				defData.height = height;
			} else {
				if (!(currMode in refBlock.modes)) refBlock.modes[currMode] = new Content.Mode();
				refBlock.modes[currMode].height = height;
				refBlock.height = height;
			}
			var pageBlock = wb_builder.site.pages['#' + wb_builder.pageId].blocks[refBlock.id];
			pageBlock.height = height;
			if (!pageBlock.modes) pageBlock.modes = {};
			if (!(currMode in pageBlock.modes)) pageBlock.modes[currMode] = new Content.Mode();
			pageBlock.modes[currMode].height = height;
		},
		
		setPageSwitchesEnabled: function(enabled) {
			var landingMenu = Service.menu.getLandingMenu();
			var prevItem, nextItem;
			if (landingMenu && enabled) {
				var i, menuItems = [];
				for (i in landingMenu.items) {
					var item = landingMenu.items[i];
					if (item.type === 'page' || item.type === 'internal') {
						menuItems.push(item);
					}
				}
				for (i = 0; i < menuItems.length; i++) {
					var menuItem = menuItems[i];
					if (parseInt(menuItem.targetId, 10) === _builder.pageId) {
						prevItem = (i-1 >= 0) ? menuItems[i-1] : null;
						nextItem = (i+1 < menuItems.length) ? menuItems[i+1] : null;
						break;
					}
				}
			}
			var items = { bottom: nextItem, top: prevItem };
			for (var k in elem) {
				var line = elem[k];
				if (line.pageSwitch) {
					line.pageSwitch.detach();
					line.pageSwitch.remove();
					line.pageSwitch = null;
				}
				if ((line.type === 'top' || line.type === 'bottom') && items[line.type] && items[line.type].targetId) {
					line.pageSwitch = $('<div class="layout_border_page_switch"></div>');
					if (line.type === 'top')
						line.pageSwitch.addClass('page_switch_top').tooltip({ title: __('Go to upper landing page'), placement: 'bottom' });
					else if (line.type === 'bottom')
						line.pageSwitch.addClass('page_switch_bottom').tooltip({ title: __('Go to lower landing page'), placement: 'top' });
					line.pageSwitch.on('mousedown', function(e) { e.stopPropagation(); });
					(function(item) {
						line.pageSwitch.on('click', function() {
							_builder.goToPage(item.targetId*1);
						});
					})(items[line.type]);
					
					line.elem.append(line.pageSwitch);
				}
			}
		},
		
		setVisible: function(visible) {
			_visible = visible ? true : false;
			var k, docBody = $(document.body);
			if (_visible) {
				if (!_builder.bodyInstance) return;
				var container = _builder.bodyInstance.elem,
					mainBlock = _builder.bodyInstance.getContentBlock('wb_main');
				if (mainBlock) {
					var mainPos = {left: mainBlock.container.offset().left, top: mainBlock.elem.position().top},
						mainWidth = mainBlock.container.width(),
						siteWidth = _builder.bodyInstance.siteWidth + 4,
						siteHeight = _builder.bodyInstance.site.outerHeight(true),
						obw = (_builder.oriSiteWidth ? _builder.oriSiteWidth : mainWidth),
						obl = Math.round(mainPos.left + (mainWidth / 2) - (obw / 2));

					elem.top.elem.css({ top: (mainPos.top - 1), minWidth: siteWidth });
					elem.right.elem.css({ left: (mainPos.left + mainWidth - 1), height: siteHeight });
					elem.bottom.elem.css({ top: (mainPos.top + mainBlock.elem.outerHeight(true) - 1), minWidth: siteWidth});
					elem.left.elem.css({ left: (mainPos.left - 3), height: siteHeight });
					elem.leftGuide.elem.css({ left: (obl - 3), height: siteHeight });
					elem.rightGuide.elem.css({ left: (obl + obw - 1), height: siteHeight });

					if( docMoveEvent && docUpEvent ) {
						docBody.off('mousemove', docMoveEvent).off('mouseup', docUpEvent);
						docBody.on('mousemove', docMoveEvent).on('mouseup', docUpEvent);
					}
					for (k in elem) { elem[k].elem.appendTo(container); }
				}
			} else {
				if( docMoveEvent && docUpEvent )
					docBody.off('mousemove', docMoveEvent).off('mouseup', docUpEvent);
				for (k in elem) { elem[k].elem.detach(); }
			}
		}
		
	};
});
;

/** ModeManager **/
(window.defineModule = (window.defineModule || {})).name = 'ModeManager';

define('ModeManager', [
	'Dialog',
	'WidgetToolbar',
	'Service',
	'Preloader',
	'SwitchDialog',
	'modes/ChangeRenderModePromptDialog',
	'BuilderEvent'
], function(Dialog, WidgetToolbar, Service, Preloader, SwitchDialog, ChangeRenderModePromptDialog, BuilderEvent) {
	'use strict';
	
	var self = {}, currMode = null, prevMode = null, useModes = true, buttons = {}, modeListeners = [],
		modesEnabled = {}, switchDlg = null, layoutSwitchDlg = null;
	/** @type {Builder} */
	var builder;

	self.MODE_TV = 'tv';
	self.MODE_DESKTOP = 'desktop';
	self.MODE_TABLET = 'tablet';
	self.MODE_PHONE = 'phone';
	
	/** @return {Array} */
	self.getModes = function() {
		return [
			self.MODE_TV,
			self.MODE_DESKTOP,
			self.MODE_TABLET,
			self.MODE_PHONE
		];
	};
	
	/**
	 * @param {String} mode one of MODE_* constants
	 * @param {Boolean} title
	 * @param {Boolean} version
	 * @returns {String}
	 */
	self.getModeName = function(mode, title, version) {
		if (mode === self.MODE_TV) return (version ? __('Wide version') : (title ? __('Wide') : __('Wide')));
		if (mode === self.MODE_DESKTOP) return (version ? __('Desktop version') : (title ? __('Desktop') : __('Desktop')));
		if (mode === self.MODE_TABLET) return (version ? __('Tablet version') : (title ? __('Tablet') : __('Tablet')));
		if (mode === self.MODE_PHONE) return (version ? __('Phone version') : (title ? __('Phone') : __('Phone')));
		return null;
	};
	
	/**
	 * @param {String} mode one of MODE_* constants
	 * @returns {Number}
	 */
	self.getModeWidth = function(mode) {
		if (mode === self.MODE_TV) return 1200;
		if (mode === self.MODE_DESKTOP) return 992;
		if (mode === self.MODE_TABLET) return 768;
		if (mode === self.MODE_PHONE) return 320;
		return null;
	};
	
	self.ToolbarItem = $.extend(Object.create(WidgetToolbar.ToolbarItem), {
		_markerElem: null,
		mobileItem: null,
		mode: null,
		
		init: function(icon, name, external) {
			WidgetToolbar.ToolbarItem.init.call(this, icon, name, external);
			this.elem.css({position: 'relative'});
			this._markerElem = $('<span>').addClass('checked-marker').appendTo(this.elem).hide();
			return this;
		},
		
		setMarked: function(marked) {
			if (marked && builder.site.renderMode === Service.site.RENDER_MODE_RESPONSIVE2) {
				marked = false;
			}
			if (marked) {
				this._markerElem.show();
			} else {
				this._markerElem.hide();
			}
			if (this.mobileItem) this.mobileItem.setChecked(marked);
		}
	});

	var sortAndAutoAlignElements = function() {
		var elementList = builder ? builder.bodyInstance.getContentElements() : [];
		var i, strHash = {}, hashIdx = 0, strVal = function(str) { if (str in strHash) return strHash[str]; else { hashIdx++; strHash[str] = hashIdx; return hashIdx; } };
		elementList.sort(function(a, b) {
			if (strVal(a.getParent().id) === strVal(b.getParent().id)) {
				if (a.getLocation().top === b.getLocation().top) return 0;
				return (a.getLocation().top - b.getLocation().top);
			}
			return (strVal(a.getParent().id) - strVal(b.getParent().id));
		});
		var parentId = null, parent = null, lastTop = 0, left, mw = self.getModeWidth(currMode);
		for (i = 0; i < elementList.length; i++) {
			if (elementList[i].isHidden() || elementList[i].isHidden(true)) continue;
			if (parentId !== elementList[i].getParent().id) {
				if (parent && parentId === 'wb_main') parent.updateSize();
				parentId = elementList[i].getParent().id;
				parent = elementList[i].getParent();
				lastTop = 0;
			}
			if (mw > elementList[i].getSize().width) {
				left = Math.round((mw - elementList[i].getSize().width) / 2);
			} else {
				left = 0;
				if (parentId === 'wb_main') {
					elementList[i].setSize(mw, null);
					elementList[i].onResize();
				}
			}
			if (parentId === 'wb_main') elementList[i].setLocation(left, lastTop);
			lastTop += elementList[i].getSize().height + 20;
		}
		if (parent && parentId === 'wb_main') parent.updateSize();
	};
	self.sortAndAutoAlignElements = sortAndAutoAlignElements;

	var ResizePromptDialog = null;
	var ResizePreloader = null;
	
	/**
	 * @param {string} mode
	 * @return {boolean}
	 */
	function getModeEnabled(mode) {
		return (mode && modesEnabled[mode]) ? true : false;
	}
	
	/**
	 * @param {string} mode
	 * @param {boolean} value
	 * @return {void}
	 */
	function setModeEnabled(mode, value) {
		var prevValue = (mode && modesEnabled[mode]) ? true : false;
		// Note: mode in chack is required to make sure it will be set on initial setup
		if (!mode || ((mode in modesEnabled) && prevValue === value)) return;
		modesEnabled[mode] = value;
		var event = new BuilderEvent.ModesEnabledChangeBuilderEvent(mode, value);
		BuilderEvent.GlobalEvents.triggerEvent('modes.enabled.change', event);
	}
	
	/**
	 * @param {string} mode
	 * @return {boolean}
	 */
	function isModeEnabledSet(mode) {
		return (mode in modesEnabled);
	}
	
	/**
	 * @param {bollean} enabled
	 * @param {bollean} rebuild
	 * @return {void}
	 */
	function setAutoLayoutEnabled(enabled, rebuild, initial) {
		if (!initial && (!builder || enabled === self.isAutoLayoutEnabled()
			|| (enabled && !builder.enableAutoLayout))) return;
		
		var changed = false;
		
		if (enabled) {
			builder.setAutoLayout(true);
			if (!initial) {
				builder.historyAdd('autoLayoutEnable', null, function () {
					builder.setAutoLayout(false, false);
				}, function() {
					builder.setAutoLayout(true);
				});
			}
			changed = true;
		}
		else {
			builder.setAutoLayout(false, !initial && rebuild);
			if (!initial) {
				builder.historyAdd('autoLayoutDisable', rebuild, function() {
					builder.setAutoLayout(true);
				}, function(data) {
					builder.setAutoLayout(false, data);
				});
			}
			changed = true;
		}
		if (changed) {
			self.setUseModes(!enabled);
			builder.bodyInstance.elementBoxSetVisible(!enabled);
			
			BuilderEvent.GlobalEvents.triggerEvent(
				"modes.autolayout.changed",
				new BuilderEvent.AutoLayoutChangedBuilderEvent(enabled)
			);
		}
	}
	
	/* exports */
	self.getModeEnabled = getModeEnabled;
	self.setModeEnabled = setModeEnabled;
	self.isAutoLayoutEnabled = function() {
		return builder && builder.site && builder.site.renderMode === Service.site.RENDER_MODE_RESPONSIVE2;
	};
	
	/**
	 * Set if modes should be used.
	 * @param {Boolean} use if true them use modes else not.
	 */
	self.setUseModes = function(use) {
		useModes = (use ? true : false);
		var modes = self.getModes();
		for (var i = 0; i < modes.length; i++) {
			var event = new BuilderEvent.ModesEnabledChangeBuilderEvent(modes[i], useModes);
			BuilderEvent.GlobalEvents.triggerEvent('modes.usable.change', event);
		}
	};

	/**
	 * Get if modes should be used.
	 * @returns {Boolean} if true then modes should be used else not.
	 */
	self.getUseModes = function() {
		return useModes;
	};

	self.setModeWithPrompt = function(mode) {
		if (builder.site.renderMode === Service.site.RENDER_MODE_RESPONSIVE2) {
			ResizePromptDialog.activate(mode);
		} else {
			self.setMode(mode, false, false, false, true);
		}
	};

	/**
	 * Initialise mode manager/chooser
	 * @param {Builder} builderInstance
	 */
	self.init = function(builderInstance) {
		builder = builderInstance;
		this.setUseModes(self.isAutoLayoutEnabled());
		ResizePreloader = new Preloader(__("Change builder area"));
		ResizePreloader.setMessage(__("Calculating new element positions and sizes."), '', 'warning');

		ResizePromptDialog = new Dialog(
			__('Change builder area'),
			null,
			$('<div class="wb_change_template_dlg">' +
				'<div class="qq">' + __('Do you want to reposition and/or resize elements in your design automatically?') + '</div>' +
				'<div class="desc">' + __('Clicking "yes" will save your current changes and resize all pages.') + '</div>' +
				'<div class="desc">' + __('Clicking "no" will change the editable builder area. In this case you will have to move and resize elements manually.') + '</div>' +
				'<div class="red">' + __('We recommend to save a backup of your design before resizing since this operation is irrecoverable.') + '</div>' +
				'<div class="hint">' + __('Please use the preview function in case you just want to see how the website will look on other devices.') + '</div>' +
			'</div>')
		);

		ResizePromptDialog.activate = function(mode, force, initial) {
			ResizePromptDialog._mode = mode;
			ResizePromptDialog._force = force;
			ResizePromptDialog._initial = initial;
			ResizePromptDialog.show();
		};
		ResizePromptDialog.addButton(__('Yes, resize automatically'), function() {
			self.setMode(ResizePromptDialog._mode, ResizePromptDialog._force, ResizePromptDialog._initial, true);
			ResizePromptDialog.hide();
		}, true);
		ResizePromptDialog.addButton(__('No, just change the builder area'), function() {
			self.setMode(ResizePromptDialog._mode, ResizePromptDialog._force, ResizePromptDialog._initial, false);
			ResizePromptDialog.hide();
		}, false, 'btn-danger');
		ResizePromptDialog.addButton(__('Cancel'));

		this.updateEnabledModes();
	};

	/**
	 * Detect best suitable mode width from current browser window size.
	 * @param {boolean} strict if true then prefer enabled modes when selecting width.
	 * @return {Number}
	 */
	self.detectBestSuitableWidth = function(strict) {
		var mw, mode, sizeBest = 0, modeBest = null, windowWidth = $(window).width(), modes = self.getModes();
		for (var i = 0; i < modes.length; i++) {
			mode = modes[i];
			if (strict && useModes && modesEnabled[mode]) modeBest = mode;
			if (windowWidth >= (mw = self.getModeWidth(mode))) {
				if (strict && useModes && !modesEnabled[mode]) {
					if (sizeBest === 0) sizeBest = mw;
				} else {
					return mw;
				}
			}
		}
		if (strict && useModes && modeBest) return self.getModeWidth(modeBest);
		if (strict && useModes && sizeBest !== 0) return mw;
		return self.getModeWidth(mode);
	};

	self.getModeFromWidth = function(width) {
		switch(width) {
			case 320: return self.MODE_PHONE;
			case 768: return self.MODE_TABLET;
			case 992: return self.MODE_DESKTOP;
			case 1200: return self.MODE_TV;
			default: console.error('Unknown resolution', width);
		}
		return self.MODE_DESKTOP;
	};

	/**
	 * Set mode (one of MODE_* constants)
	 * @param {String} mode
	 * @param {Boolean} force
	 * @param {object} initial
	 * @param {Boolean} autoResize
	 */
	self.setMode = function(mode, force, initial, autoResize, manual) {
		if (typeof mode === 'number') mode = self.getModeFromWidth(mode);
		if (currMode !== mode || force) {
			var ea = new BuilderEvent.ModesChangeBuilderEvent(currMode, mode, manual);
			BuilderEvent.GlobalEvents.triggerEvent("modes.change", ea);
			if( force || !ea.defaultPrevented ) {
				if (!initial && (typeof autoResize === 'boolean') && autoResize) {
					var newWidth = this.getModeWidth(mode);
					builder.resizeSite(newWidth);
					return;
				}
				if (!isModeEnabledSet(mode) && mode !== self.MODE_DESKTOP) {
					if (!switchDlg) switchDlg = new SwitchDialog.SwitchDialog();
					switchDlg.setMode(mode);
					switchDlg.setVisible(true);
				}
				prevMode = currMode;
				currMode = mode;
				prevMode = prevMode || currMode;
				var i, k, btn;
				for (k in buttons) {
					buttons[k].setActive(k === currMode);
				}
				if (builder.bodyInstance) {
					var elementList = builder.bodyInstance.getContentElements();
					for (i = 0; i < elementList.length; i++) {
						elementList[i].switchMode(prevMode, mode, initial, manual);
					}

					var first = !(mode in builder.bodyInstance.modes);

					builder.bodyInstance.switchMode(prevMode, mode, initial, manual);
					builder.site.switchMode(prevMode, mode, initial, manual);

					builder.bodyInstance.siteWidth = this.getModeWidth(mode);

					if (first && mode === self.MODE_TV) {
						for (i = 0; i < elementList.length; i++) {
							elementList[i].setLocation(elementList[i].getLocation().left + 104, null);
						}
					} else if (first && mode === self.MODE_PHONE) {
						sortAndAutoAlignElements();
					}

					builder.bodyInstance.updateStyle(true, initial);
	//				builder.bodyInstance.fitElements((mode === self.MODE_TABLET || mode === self.MODE_PHONE));

					for (var n = 0; n < modeListeners.length; n++) { modeListeners[n].call(this, mode); }

					for (i = 0; i < elementList.length; i++) {
						elementList[i].updateStyle(initial);
						elementList[i].onResize(initial);
					}

					if (builder.showLayout) builder.highlightLayout(builder.showLayout);
					Service.contextMenu.hideAll();
				}
			}
		}
	};

	self.setAutoLayoutEnabled = function(enabled, initial) {
		if (!initial) {
			if (!builder || enabled === self.isAutoLayoutEnabled()) return;

			var enableRec = builder.historyGetLatestRecord('autoLayoutEnable');
			var prevRec = builder.historyGetLatestRecord();
			if (!enabled && (!enableRec || enableRec !== prevRec)) {
				if (!layoutSwitchDlg) {
					layoutSwitchDlg = new ChangeRenderModePromptDialog.ChangeRenderModePromptDialog(function(rebuild) {
						setAutoLayoutEnabled(false, rebuild);
					});
				}
				layoutSwitchDlg.setValue(0);
				layoutSwitchDlg.show();
				return;
			}
		}
		setAutoLayoutEnabled(enabled, false, initial);
	};

	self.getBiggestEnabledMode = function() {
		var i, modes = this.getModes(), mode;
//		for (i = modes.length - 1; i >= 0; i--) {
		for (i = 0; i < modes.length; i++) {
			mode = modes[i];
			if( modesEnabled[mode] )
				return mode;
		}
		return null;
	};

	self.updateEnabledModes = function() {
		var modes = this.getModes(), mode, bestMode = self.getModeFromWidth(self.detectBestSuitableWidth());
		for (var i = 0; i < modes.length; i++) {
			mode = modes[i];
			setModeEnabled(mode, (mode in builder.site.modesEnabled) ? builder.site.modesEnabled[mode] : (mode === bestMode));
		}
	};

	self.getEnabledModes = function() {
		return modesEnabled;
	};

	/**
	 * Get mode (one of MODE_* constants)
	 * @returns {String}
	 */
	self.getMode = function() {
		return currMode;
	};
	
	/** @return {Object} */
	self.serialize = function() {
		return $.extend({}, modesEnabled);
	};
	
	/** @param {Function} l */
	self.addModeListener = function(l) {
		var idx = modeListeners.indexOf(l);
		if (idx < 0) modeListeners.push(l);
	};
	
	/** @param {Function} l */
	self.removeModeListener = function(l) {
		var idx = modeListeners.indexOf(l);
		if (idx >= 0) modeListeners.splice(idx, 1);
	};
	
	Service.modeManager = self;
	
	window.ModeManager = self;
	
	return self;
});
;

/** ElementBox **/
(window.defineModule = (window.defineModule || {})).name = 'ElementBox';

define('ElementBox', ["Service", "BuilderEvent", "ModeManager", "ElementRegister"], function(Service, BuilderEvent, ModeManager, ElementRegister) {
	'use strict';
	
	var tplLi = $('<div>').addClass('wb-element-box-li');
	
	return {
		/** @type Element[] */
		_elements: null,
		/** @type Builder */
		_builder: null,
		/** @type jQuery */
		elem: null,
		/** @type jQuery */
		_container: null,
		
		/**
		 * @param {Builder} builder
		 * @return ElementBox
		 */
		init: function(builder) {
			this._elements = [];
			this._builder = builder;
			this.elem = $('<div>').addClass('wb-element-box');
			var header = $('<div>').addClass('wb-element-box-header').text(__('Hidden items')).prepend($('<i>').addClass('glyphicon glyphicon-trash')).appendTo(this.elem);
			this._container = $('<div>').addClass('wb-element-box-list').appendTo(this.elem);
			this.elem.hide();
			this.elem.appendTo(document.body);
			var thisSelf = this;
			this._container.droppable({
				tolerance: 'pointer',
				hoverClass: 'wb-state-highlight',
				accept: '.wb_element',
				greedy: true,
				drop: function(e, ui) {
					var itm = ui.draggable.wbGetClassInstance();
					if (!itm || itm.removed || itm.dropAccepted) return false;
					itm.dropAccepted = true;
					var selected = Service.element.getSelected();
					for( var i in selected ) {
						if( !selected.hasOwnProperty(i) )
							continue;
						var el = selected[i];
						el.hide(true, true);
						thisSelf.addElement(el, (function() {
							thisSelf.removeElement(this);
							this.show(true, true);
						}).bind(el), el.boxItemOptions());
						if( el.dragStartPos )
							el.setLocation(el.dragStartPos.left, el.dragStartPos.top);
					}
					e.stopPropagation();
					e.preventDefault();
					return false;
				}
			});
			
			this.elem.draggable({handle: header, distance: 3});

			BuilderEvent.GlobalEvents.on("help.playershow help.playerhide", function(e) {
				if( e.visible )
					thisSelf.elem.addClass("hidden");
				else
					thisSelf.elem.removeClass("hidden");
				// thisSelf._container.droppable(e.visible ? "disable" : "enable");
			});

			return this;
		},
		/**
		 * @param {Element} elem
		 * @param {Function} callback
		 * @param {Object} options
		 * @return {Element}
		 */
		addElement: function(elem, callback, options) {
			var idx = this._elements.indexOf(elem), li, opts;
			if (idx < 0) {
				opts = $.extend({title: elem.getClassType(), text: ('#' + elem.id), thumb: null}, ((options && (typeof options === 'object') && !('length' in options)) ? options : {}));
				this._elements.push(elem);
				li = tplLi.clone();
				li.html('<span>' + opts.title + '</span>' + opts.text);
				if (opts.thumb) {
					if (typeof opts.thumb === 'string') {
						$('<img>').attr('src', opts.thumb).attr('alt', '').appendTo(li);
					} else {
						$('<span>').addClass('wb-element-box-thumb').append(opts.thumb).appendTo(li);
					}
				}
				li.on('click', callback);
				this._container.append(li);
				this.setVisible(true);
			}
		},
		/**
		 * @param {Element} elem
		 * @return {Element}
		 */
		removeElement: function(elem) {
			var idx = this._elements.indexOf(elem), remElem;
			if (idx >= 0) {
				this._container.children().eq(idx).remove();
				remElem = this._elements.splice(idx, 1)[0];
				if (!this._container.children().length) {
					this.setVisible(false);
				}
			}
			return remElem;
		},
		removeAllElements: function() {
			this._elements.splice(0, this._elements.length);
			this._container.empty();
			this.setVisible(false);
		},
		/**
		 * @param {Element} elem
		 * @return {Boolean}
		 */
		hasElement: function(elem) {
			var idx = this._elements.indexOf(elem);
			return (idx >= 0);
		},
		/** @param {Boolean} visible */
		setVisible: function(visible, force) {
			if (!this.elem) return;
			if (visible && (force || this._elements.length)) {
				this.elem.show();
			} else {
				this.elem.hide();
			}
		},
		/**
		 * @param {String} fromMode
		 * @param {String} toMode
		 * @param {Boolean} initial
		 */
		switchMode: function(fromMode, toMode, initial) {
			if (!toMode) return;
			var modeName = ModeManager.getModeName(toMode, true);
			this.elem.children('.wb-element-box-header').text(__('Hidden items') + (modeName ? ' (' + modeName + ')' : ''));
		}
	};
});
;

/** UIBuilder **/
(window.defineModule = (window.defineModule || {})).name = 'UIBuilder';

define('UIBuilder', [
	'Service',
	'UIComponent',
	'UIContainer',
	'VerticalLayout',
	'HorizontalLayout',
	'FlowLayout',
	'CustomContainer',
	'UIButton',
	'Label',
	'TextField',
	'MultilangTextField',
	'WYSIWYGControl',
	'RadioBox',
	'CheckBox',
	'URLControl',
	'List',
	'StyleControl',
	'TextControl',
	'ToolTipControl',
	'BackgroundControl',
	'BorderControl',
	'ColorPicker',
	'SpacingControl',
	'RoundCornersControl',
	'FontControl',
	'FontTransformControl',
	'MenuListControl',
	'ContactFormControl',
	'SizeSelector',
	'TabbedPane',
	'AlertBox',
	'DropdownBox',
	'ProgressBar'
], function(
	Service,
	UIComponent,
	UIContainer,
	VerticalLayout,
	HorizontalLayout,
	FlowLayout,
	CustomContainer,
	UIButton,
	Label,
	TextField,
	MultilangTextField,
	WYSIWYGControl,
	RadioBox,
	CheckBox,
	URLControl,
	List,
	StyleControl,
	TextControl,
	ToolTipControl,
	BackgroundControl,
	BorderControl,
	ColorPicker,
	SpacingControl,
	RoundCornersControl,
	FontControl,
	FontTransformControl,
	MenuListControl,
	ContactFormControl,
	SizeSelector,
	TabbedPane,
	AlertBox,
	DropdownBox,
	ProgressBar) {
	'use strict';
	
	/**
	 * Build UI layout from UI definition object
	 * @param {Object} data UI definition object
	 * @param {Object=} exFields external fields object
	 * @constructor
	 */
	var UIBuilder = function(data, exFields) {
		if (data !== '%inherit%') {
			UIContainer.UIContainer.prototype.constructor.call(this);
			this.fields = ((exFields && typeof exFields === 'object') ? exFields : {});
			UIBuilder.buildLayout(data, this, this.fields);
		}
	};
	UIBuilder.prototype = new UIContainer.UIContainer('%inherit%');
	UIBuilder.prototype.constructor = UIBuilder;
	
	/**
	 * Object to reference fields by id to
	 * @type {Object}
	 */
	UIBuilder.prototype.fields = null;
	
	/**
	 * Extend base UI definition with UI definition extension
	 * @param {Object} baseUiDef
	 * @param {Object} uiDef
	 * @returns {Object}
	 */
	UIBuilder.extendDefinition = function(baseUiDef, uiDef) {
		var i, k, k1, ex;
		if (typeof uiDef === 'object' && uiDef) {
			for (k in uiDef) {
				ex = (k in baseUiDef);
				if (ex && typeof baseUiDef[k] === 'object' && 'length' in baseUiDef[k] && typeof baseUiDef[k].length === 'number') {
					for (i = 0; i < uiDef[k].length; i++) {
						baseUiDef[k].push(uiDef[k][i]);
					}
				} else if (ex && typeof baseUiDef[k] === 'object') {
					for (k1 in uiDef[k]) {
						baseUiDef[k][k1] = uiDef[k][k1];
					}
				} else {
					baseUiDef[k] = uiDef[k];
				}
			}
		}
		return baseUiDef;
	};
	
	/**
	 * Build UI layout from UI definition object
	 * @param {Object} data UI definition object
	 * @param {UIComponent.UIComponent|jQuery} parent element to attach UI elements to
	 * @param {Object} fields object to reference fields by id to
	 */
	UIBuilder.buildLayout = function(data, parent, fields) {
		if (typeof data !== 'object' || !parent) return;
		var i, n, type, el, elItem, elItemDef, children = (typeof data.length === 'number') ? data : [data];
		for (i = 0; i < children.length; i++) {
			type = children[i].type ? children[i].type : null;
			if (type && children[i].ignore) continue;
			el = null;
			if (type === 'VerticalLayout') type = VerticalLayout.VerticalLayout;
			if (type === 'HorizontalLayout') type = HorizontalLayout.HorizontalLayout;
			if (type === 'FlowLayout') type = FlowLayout.FlowLayout;
			if (type === 'Label') type = Label.Label;
			if (type === 'List') type = List.List;
			if (type === 'Button') type = UIButton.UIButton;
			if (type === 'TextField') type = TextField;
			if (type === 'WYSIWYGControl') type = WYSIWYGControl.WYSIWYGControl;
			if (type === 'DropdownBox') type = DropdownBox;
			if (type === 'CustomContainer') type = CustomContainer.CustomContainer;
			if (typeof type === 'function' && type.prototype instanceof UIComponent.UIComponent/* && type.prototype instanceof UIBuildable */) {
				el = new type();
				el.buildInit(children[i], fields);
			} else if (type === 'Form') {
				el = new UIContainer.UIContainer('form');
				elItem = el.getElem();
				if ('action' in children[i]) elItem.attr({action: children[i].action});
				if ('method' in children[i]) elItem.attr({method: children[i].method});
				if ('enctype' in children[i]) elItem.attr({enctype: children[i].enctype});
				if (('submit' in children[i]) && (typeof children[i].submit === 'function')) {
					(function(el, func) {
						el.getElem().on('submit', function() {
							var funcRes = func.call(el, fields);
							if (funcRes === false) return false;
						});
					})(el, children[i].submit);
				}
			} else if (type === 'Tooltip') {
				el = UIComponent.UIComponent.wrapControl(new ToolTipControl(
						(children[i].label ? children[i].label : '?'),
						children[i].text,
						(children[i].placement ? children[i].placement : 'right')
					));
			} else if (type === 'Image') {
				el = UIComponent.UIComponent.wrapControl((function() {
					return {
						elem: $(new Image()),
						getValue: function() { return this.elem.get(0).src; },
						setValue: function(src) { this.elem.get(0).src = src; }
					};
				})());
				if (children[i].value) el.setValue(children[i].value);
				if (children[i].src) el.setValue(children[i].src);
			} else if (type === 'MultilangTextField') {
				el = new MultilangTextField(
						null,
						(children[i].textArea ? true : false),
						(children[i].resizable ? children[i].resizable : undefined),
						(children[i].onReload ? children[i].onReload : null)
					);
				if (children[i].value) el.setText(children[i].value);
				if (children[i].onChange) el.setOnChange(children[i].onChange);
				else if (children[i].text) el.setText(children[i].text);
				if (children[i].placeholder) el.setPlaceholder(children[i].placeholder);
				if (children[i].height) el.setHeight(children[i].height);
			} else if (type === 'FileField') {
				el = UIComponent.UIComponent.wrapControl(new WB_UploadFieldControl(
						(children[i].name ? children[i].name : 'fileupload'),
						(children[i].accept ? children[i].accept : null)
					));
				if (children[i].change) el._control.onChange = children[i].change;
			} else if (type === 'RadioBox') {
				var label = 'Radio Box';
				if (children[i].label && typeof children[i].label === 'object') {
					label = new UIBuilder(children[i].label, fields);
				} else {
					label = children[i].label;
				}
				el = new RadioBox(label, null,
						(children[i].group ? children[i].group : null),
						(children[i].inline ? true : false),
						(children[i].inputValue ? children[i].inputValue : null)
					);
				if (children[i].value) el.setValue(children[i].value);
				if (children[i].title) el.setTitle(children[i].title);
				if (children[i].html) el.setLabelHtml(children[i].html);
				if (children[i].helpText) {
					el.getElem().append((new ToolTipControl('?', children[i].helpText, (children[i].helpPlacement ? children[i].helpPlacement : 'right'))).elem);
				}
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el.on('change', function() { func.call(el, fields); }); })(el, children[i].change);
				}
			} else if (type === 'CheckBox') {
				var cbLabel = 'Check Box';
				if (children[i].label && typeof children[i].label === 'object') {
					cbLabel = new UIBuilder(children[i].label, fields);
				} else {
					cbLabel = children[i].label;
				}
				el = new CheckBox(cbLabel, null, (children[i].inline ? true : false));
				if (children[i].value) el.setValue(children[i].value);
				if (children[i].helpText) {
					el.getElem().append((new ToolTipControl('?', children[i].helpText, (children[i].helpPlacement ? children[i].helpPlacement : 'right'))).elem);
				}
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el.on('change', function() { func.call(el, fields); }); })(el, children[i].change);
				}
			} else if (type === 'MenuItemSelector') {
				el = UIComponent.UIComponent.wrapControl(new MenuListControl.MenuListControl(true, (children[i].anchorMode ? true : false)));
				if (children[i].value) el.setValue(children[i].value);
				el.reloadMenuList = function() { this._control.reloadMenuList(); };
				el.getExtendedValue = function() { return this._control.getExtendedValue(); };
				el.setExtendedValue = function(value) { this._control.setExtendedValue(value); };
			} else if (type === 'LinkEditSelector') {
				el = UIComponent.UIComponent.wrapControl(new WB_LinkEditControl(null, (children[i].emptyMsg ? children[i].emptyMsg : null)));
				if (children[i].value) el.setValue(children[i].value);
				el.clearValue = function() { this._control.clearValue(); };
			} else if (type === 'ColorSelector') {
				el = UIComponent.UIComponent.wrapControl(new ColorPicker(
						(children[i].noTransparent ? true : false),
						(children[i].noAlpha ? true : false),
						(children[i].big ? true : false),
						(children[i].noFidexWidth ? true : false)
					));
				if (children[i].value) el.setValue(children[i].value);
				if (children[i].colorSelectorClass) el._control.setColorSelectorClass(children[i].colorSelectorClass);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.onChange = function() { func.call(el, fields); }; })(el, children[i].change);
				}
			} else if (type === 'SizeSelector') {
				el = UIComponent.UIComponent.wrapControl(new SizeSelector(
						(children[i].units ? false : true),
						(('min' in children[i]) ? children[i].min : null),
						(('max' in children[i]) ? children[i].max : null),
						(('step' in children[i]) ? children[i].step : null),
						(children[i].repeat ? false : true),
						(children[i].noFixedWidth ? true : false)
					));
				if (children[i].value) el.setValue(children[i].value);
				if (children[i].units) el._control.setUnit(children[i].units);
				if (children[i].precision) el._control.setPrecision(children[i].precision);
				if (children[i].hasOwnProperty("clearTrailingZeroes")) el._control.setClearTrailingZeroes(children[i].clearTrailingZeroes);

				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.bind('change', function() { func.call(el, fields); }); })(el, children[i].change);
				}
				el.getEnabled = function() { return this._control.getEnabled(); };
				el.setEnabled = function(enabled) { this._control.setEnabled(enabled); };
				el.setMaxValue = function(maxValue) { this._control.setMaxValue(maxValue); };
			} else if (type === 'ImageSelector') {
				el = UIComponent.UIComponent.wrapControl(new WB_ImagePicker(
						(children[i].mode ? children[i].mode : null),
						(children[i].thumbSize ? children[i].thumbSize : 60),
						(children[i].multiselect ? true : false),
						(('mediatabs' in children[i]) ? (children[i].mediatabs ? true : false) : true),
						(('fontAwesomeTab' in children[i]) ? !!children[i].fontAwesomeTab : false),
						(('usePictureManager' in children[i]) ? !!children[i].usePictureManager : false)
					));
				if (children[i].value) el.setValue(children[i].value);
				el.getValues = function(asObject) { return this._control.getValues(asObject); };
				el.setValues = function(list) { this._control.setValues(list); };
				if (('select' in children[i]) && (typeof children[i].select === 'function')) {
					(function(el, func) { el._control.callback = function() { func.call(el, fields); }; })(el, children[i].select);
				}
				if (children[i].customContent) el._control.customContent = children[i].customContent;
			} else if (type === 'LinkSelector') {
				el = UIComponent.UIComponent.wrapControl(new URLControl((children[i].multilang ? true : false)));
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.onChange = function() { func.call(el, fields); }; })(el, children[i].change);
				}
			} else if (type === 'StyleSelector') {
				el = UIComponent.UIComponent.wrapControl(new StyleControl((children[i].emptyChoice ? true : false)));
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.onChange = function() { func.call(el, fields); }; })(el, children[i].change);
				}
			} else if (type === 'FontSelector') {
				el = UIComponent.UIComponent.wrapControl(new TextControl(
						(children[i].needLineHeight ? true : false),
						(children[i].ttPlacement ? children[i].ttPlacement : 'left'),
						(children[i].needPreview ? true : false),
						(children[i].noStyle ? true : false),
						(children[i].noAlign ? true : false),
						(children[i].horizontal ? true : false)
					));
				if (children[i].value) el.setValue(children[i].value);
				el.setPreviewTag = function(tag) { this._control.setPreviewTag(tag); };
			} else if (type === 'FontFamilySelector') {
				el = UIComponent.UIComponent.wrapControl(new FontControl((children[i].noFixedWidth ? true : false)));
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.onChange = function() { func.call(el, fields); }; })(el, children[i].change);
				}
			} else if (type === 'FontStyleSelector') {
				el = UIComponent.UIComponent.wrapControl(new WB_FontStyleControl());
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.elem.find('.btn').on('click', function() { func.call(el, fields); }); })(el, children[i].change);
				}
			} else if (type === 'FontTransformSelector') {
				el = UIComponent.UIComponent.wrapControl(new FontTransformControl());
				if (children[i].value) el.setValue(children[i].value);
			} else if (type === 'SpacingSelector') {
				el = UIComponent.UIComponent.wrapControl(new SpacingControl());
				if (children[i].value) el.setValue(children[i].value);
			} else if (type === 'HAlignSelector') {
				el = UIComponent.UIComponent.wrapControl(new WB_HAlignSelector((children[i].justify ? true : false)));
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.elem.find('.btn').on('click', function() { func.call(el, fields); }); })(el, children[i].change);
				}
			} else if (type === 'BorderSelector') {
				el = UIComponent.UIComponent.wrapControl(new BorderControl(
						(children[i].placement ? children[i].placement : 'bottom'),
						(children[i].showRadius ? true : false),
						(('noTransparent' in children[i]) ? (children[i].noTransparent ? true : false) : true)
					));
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.onChange = function() { func.call(el, fields); }; })(el, children[i].change);
				}
			} else if (type === 'AlignSelector') {
				el = UIComponent.UIComponent.wrapControl(new WB_AlignSelector());
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.callback = function() { func.call(el, fields); }; })(el, children[i].change);
				}
			} else if (type === 'BackgroundSelector') {
				el = UIComponent.UIComponent.wrapControl(new BackgroundControl({
					useColor: (("useColor" in children[i]) ? !!children[i].useColor : true),
					useImage: (("useImage" in children[i]) ? !!children[i].useImage : true),
					usePosition: (("usePosition" in children[i]) ? !!children[i].usePosition : true),
					useRepeat: (("useRepeat" in children[i]) ? !!children[i].useRepeat : true),
					useAttachment: (("useAttachment" in children[i]) ? !!children[i].useAttachment : false),
					useSize: (("useSize" in children[i]) ? !!children[i].useSize : false),
					useFullWidth: (("useFullWidth" in children[i]) ? !!children[i].useFullWidth : false)
				}));
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.onChange = function() { func.call(el, fields); }; })(el, children[i].change);
				}
				el.isSet = function() { return this._control.isSet(); };
				el.setOption = function(name, value) { this._control.setOption(name, value); };
			} else if (type === 'RoundCornersSelector') {
				el = UIComponent.UIComponent.wrapControl(new RoundCornersControl());
				if (children[i].value) el.setValue(children[i].value);
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el._control.onChange = function() { func.call(el, fields); }; })(el, children[i].change);
				}
			} else if (type === 'LayoutBlocksControl') {
				el = UIComponent.UIComponent.wrapControl(new WB_LayoutblocksControl());
				if (children[i].value) el.setValue(children[i].value);
				if (typeof children[i].change === 'function') {
					(function(el, func) {
						el._control.onChange = function() { return func.call(el, fields); };
					})(el, children[i].change);
				}
				el.getBlocks = function() { return this._control.getBlocks(); };
				el.setIsSet = function(isSet, block) { this._control.setIsSet(isSet, block); };
				el.setActive = function(active) { this._control.setActive(active); };
				el.onChange = function() { this._control.onChange(); };
			} else if (type === 'AlertBox') {
				el = new AlertBox();
				if (children[i].text) el.setText(children[i].text);
				if (children[i].html) el.setHtml(children[i].html);
				if (children[i].style) el.setBoxStyle(children[i].style);
			} else if (type === 'ContactForm') {
				el = new ContactFormControl();
			} else if (type === 'TabbedPane') {
				el = new TabbedPane();
				if (children[i].fixedHeight) el.setFixedHeight(children[i].fixedHeight);
				if (children[i].noScroll) el.setNoScroll();
				if (typeof children[i].tabs === 'object' && children[i].tabs && children[i].tabs.length > 0) {
					children[i].tabs.sort(function(a, b) {
						return (('priority' in a) ? a.priority : 0) - (('priority' in b) ? b.priority : 0);
					});
					var hasTabs = false;
					for (n = 0; n < children[i].tabs.length; n++) {
						if (children[i].tabs[n].ignore) continue;
						elItemDef = children[i].tabs[n];
						elItem = el.addTab(elItemDef.name ? elItemDef.name : __('General'), n);
						hasTabs = true;
						if (elItemDef.type) elItem.type = elItemDef.type;
						if (elItemDef.children) UIBuilder.buildLayout(elItemDef.children, elItem.contentElem, fields);
						if (elItemDef.init && typeof elItemDef.init === 'function') {
							elItemDef.init.call(elItem.contentElem, elItemDef, fields);
						}
					}
					if (hasTabs) el.selectTab(0);
				}
				if (('change' in children[i]) && (typeof children[i].change === 'function')) {
					(function(el, func) { el.onChange = function(tab, prevTab, tabDef) { func.call(el, fields, tab, prevTab, tabDef); }; })(el, children[i].change);
				}
			} else if (type === 'ProgressBar') {
				el = new ProgressBar.ProgressBar();
				if (children[i].progress) el.setProgress(("type" in children[i]) ? children[i].progress : "default", children[i].progress, ("text" in children[i]) ? children[i].text : "");
			} else {
				console.error("TypeError: unknown UI Builder type '" + type + "'");
			}
			if (el) {
				if (children[i].fixedWidth) {
					var fw = Math.max(Math.min(children[i].fixedWidth, 12), 1);
					el.addClass('span' + fw);
					if (fw === 12) el.css({float: 'none'});
				}
				if (children[i].styleClass) el.addClass(children[i].styleClass);
				if ('visible' in children[i]) el.setVisible(children[i].visible ? true : false);
				if ('enabled' in children[i]) el.setEnabled(children[i].enabled ? true : false);
				if (children[i].on && (typeof children[i].on === 'object')) {
					for (var k in children[i].on) {
						if (typeof children[i].on[k] === 'function') {
							(function(el, event, func) { el.on(event, function(e) { func.call(el, e, fields); }); })(el, k, children[i].on[k]);
						}
					}
				}
				if (children[i].click && (typeof children[i].click === 'function')) {
					(function(el, func) { el.on('click' + ((type !== 'Button') ? ' touchstart' : ''), function(e) { func.call(el, e, fields); }); })(el, children[i].click);
				}
				if (children[i].css && typeof children[i].css === 'object') el.css(children[i].css);
				if (children[i].attr && typeof children[i].attr === 'object') el.getElem().attr(children[i].attr);
				if (children[i].init && typeof children[i].init === 'function') {
					children[i].init.call(el, children[i], fields);
				}
				if (el instanceof UIContainer.UIContainer && children[i].children) UIBuilder.buildLayout(children[i].children, el, fields);
				if (children[i].id && typeof children[i].id === 'string') fields[children[i].id] = el;
				if (parent instanceof UIContainer.UIContainer) {
					parent.addChild(el);
				} else {
					parent.append(el.getElem());
				}
				if (children[i].afterInit && typeof children[i].afterInit === 'function') {
					children[i].afterInit.call(el, children[i], fields);
				}
			}
		}
	};
	
	Service.UIBuilder = UIBuilder;
	
	return UIBuilder;
});
;

/** MultilangTextField **/
(window.defineModule = (window.defineModule || {})).name = 'MultilangTextField';

define('MultilangTextField', ['UIComponent', 'LangInputControl'], function(UIComponent, LangInputControl) {
	
	var self = function() { if (arguments.length !== 1 || arguments[0] !== '%inherit%') this.__construct.apply(this, arguments); };
	self.prototype = new UIComponent.UIComponent('%inherit%');
	self.prototype.constructor = self;
	$.extend(self.prototype, {
		
		_wbField: null,
		
		__construct: function(value, isTextarea, resizable, onReload) {
			this._wbField = new LangInputControl(null, value, isTextarea, resizable, onReload);
			UIComponent.UIComponent.prototype.constructor.call(this);
		},
		
		_createElem: function() { return this._wbField.elem; },
		
		setText: function(text, langCode) {
			var noReset = false;
			if (langCode) noReset = true;
			this._wbField.setValue(text, langCode, noReset);
		},
		
		setValue: function(text) {
			this._wbField.setValue(text);
		},
		
		getText: function() {
			return this._wbField.getValue();
		},
		
		getValue: function() {
			return this._wbField.getValue();
		},
		
		focus: function() {
			this._wbField.focus();
		},
		
		setEnabled: function(enabled) {
			UIComponent.UIComponent.prototype.setEnabled.call(this, enabled);
			this._wbField.setDisabled(!enabled);
		},
		
		setModified: function(modified) {
			this._wbField.modified = modified ? true : false;
		},
		
		setPlaceholder: function(placeholder, toAll) {
			this._wbField.setPlaceholder(placeholder, toAll);
		},
		
		setHeight: function(height) {
			if (this._wbField.isTextarea) {
				this._wbField.getInputs().each(function() {
					if (height == parseInt(height)) height += 'px';
					$(this).css('height', height);
				});
			}
		},
		
		addClass: function(cls) {
			UIComponent.UIComponent.prototype.addClass.call(this, cls);
			if (('' + cls).match(/^span[0-9]+$/)) {
				this._wbField.getMainInput().addClass(cls);
			}
			return this;
		},
		
		removeClass: function(cls) {
			UIComponent.UIComponent.prototype.removeClass.call(this, cls);
			if (('' + cls).match(/^span[0-9]+$/)) {
				this._wbField.getMainInput().removeClass(cls);
			}
			return this;
		},

		setOnChange: function(callback) {
			this._wbField.onChange = callback;
		},
		
		setOnReload: function(callback) {
			this._wbField.onReload = callback;
		},
		
		getInputs: function() {
			return this._wbField.getInputs();
		}
		
	});
	
	return self;
});
;

/** CheckBox **/
(window.defineModule = (window.defineModule || {})).name = 'CheckBox';

define('CheckBox', ['UIComponent'], function(UIComponent) {
	
	var self = function() { this.__construct.apply(this, arguments); };
	self.prototype = new UIComponent.UIComponent('%inherit%');
	self.prototype.constructor = self;
	$.extend(self, {
		_elemIndex: 0
	});
	$.extend(self.prototype, {
		
		_label: null,
		_labelText: null,
		_labelComp: null,
		_input: null,
		_inline: null,
		
		/**
		 * Construct Checkbox
		 * @param {string|UIComponent} label
		 * @param {boolean} value
		 * @param {boolean} inline
		 */
		__construct: function(label, value, inline) {
			this._inline = (inline && !(label instanceof UIComponent.UIComponent)) ? true : false;
			UIComponent.UIComponent.prototype.constructor.call(this);
			var id = 'ui_checkbox_id' + self._elemIndex;
			self._elemIndex++;
			this._elem.attr({'for': id});
			this._input = $('<input>').attr({type: 'checkbox', id: id});
			if (label instanceof UIComponent.UIComponent) {
				this._elem.addClass('wb-compo-cbr');
				this._elem.append($('<label>').append(this._input));
				this._labelComp = label;
				this._labelComp.addClass('wb-compo-cbr-label');
				this._labelComp.getElem().appendTo(this._elem);
			} else {
				this._labelText = $('<span>');
				if (this._inline) {
					this._elem.append(this._input).append(this._labelText);
				} else {
					this._elem.append($('<label>').append(this._input).append(this._labelText));
				}
				this.setLabel(label);
			}
			this.setValue(value);
		},
		
		_createElem: function() { return (this._inline ? $('<label>').addClass('checkbox-inline') : $('<div>').addClass('checkbox')); },
		
		setLabel: function(label) {
			this._label = label;
			if (this._labelText) this._labelText.text(label);
		},
		
		getLabel: function() {
			return this._label;
		},
		
		setValue: function(value) {
			this._input.prop("checked", !!value);
		},
		
		getValue: function() {
			return this._input.is(':checked');
		},
		
		setEnabled: function(enabled) {
			UIComponent.UIComponent.prototype.setEnabled.call(this, enabled);
			if (enabled) {
				this._input.removeClass('disabled');
				this._input.removeAttr('disabled');
			} else {
				this._input.addClass('disabled');
				this._input.attr('disabled', 'disabled');
			}
		},
		
		on: function(event, func) {
			if (event === 'change') {
				this._input.on(event, func);
			} else {
				UIComponent.UIComponent.prototype.on.call(this, event, func);
			}
			return this;
		},
		
		off: function(event, func) {
			if (event === 'change') {
				this._input.off(event, func);
			} else {
				UIComponent.UIComponent.prototype.off.call(this, event, func);
			}
			return this;
		},
		
		trigger: function(event, extraParameters) {
			if (event === 'change') {
				this._input.trigger(event, extraParameters);
			} else {
				UIComponent.UIComponent.prototype.trigger.call(this, event, extraParameters);
			}
			return this;
		}
		
	});
	
	
	return self;
});
;

/** RadioBox **/
(window.defineModule = (window.defineModule || {})).name = 'RadioBox';

define('RadioBox', ['UIComponent'], function(UIComponent) {
	
	var self = function() { this.__construct.apply(this, arguments); };
	self.prototype = new UIComponent.UIComponent('%inherit%');
	self.prototype.constructor = self;
	$.extend(self, {
		_elemIndex: 0
	});
	$.extend(self.prototype, {
		
		_label: null,
		_group: null,
		_labelText: null,
		_labelComp: null,
		_input: null,
		_inline: null,
		
		/**
		 * Construct Radiobox
		 * @param {string|UIComponent.UIComponent} label
		 * @param {boolean} value
		 * @param {string} group
		 * @param {boolean} inline
		 * @param {string} inputValue
		 */
		__construct: function(label, value, group, inline, inputValue) {
			this._inline = (inline && !(label instanceof UIComponent.UIComponent)) ? true : false;
			UIComponent.UIComponent.prototype.constructor.call(this);
			var id = 'ui_radiobox_id' + self._elemIndex;
			self._elemIndex++;
			this._elem.attr({'for': id});
			this._input = $('<input>').attr({type: 'radio', id: id});
			if (label instanceof UIComponent.UIComponent) {
				this._elem.addClass('wb-compo-cbr');
				this._elem.append($('<label>').append(this._input));
				this._labelComp = label;
				this._labelComp.addClass('wb-compo-cbr-label');
				this._labelComp.getElem().appendTo(this._elem);
			} else {
				this._labelText = $('<span>');
				if (this._inline) {
					this._elem.append(this._input).append(this._labelText);
				} else {
					this._elem.append($('<label>').append(this._input).append(this._labelText));
				}
				this.setLabel(label);
			}
			this.setValue(value);
			if (group) this.setGroup(group);
			if (inputValue) this._input.attr({value: inputValue});
		},
		
		_createElem: function() { return (this._inline ? $('<label>').addClass('radio-inline') : $('<div>').addClass('radio')); },
		
		setGroup: function(group) {
			this._group = group;
			if (this._group) {
				this._input.attr({name: this._group});
			} else {
				this._input.removeAttr('name');
			}
		},
		
		getGroup: function() {
			return this._group;
		},
		
		setLabel: function(label) {
			this._label = label;
			if (this._labelText) this._labelText.text(label);
		},

		setLabelHtml: function(label) {
			this._label = label;
			if (this._labelText) this._labelText.html(label);
		},

		getLabel: function() {
			return this._label;
		},
		
		setValue: function(value) {
			this._input.prop("checked", !!value);
		},

		getValue: function() {
			return this._input.is(':checked');
		},
		
		setEnabled: function(enabled) {
			UIComponent.UIComponent.prototype.setEnabled.call(this, enabled);
			if (enabled) {
				this._input.removeClass('disabled');
				this._input.removeAttr('disabled');
			} else {
				this._input.addClass('disabled');
				this._input.attr('disabled', 'disabled');
			}
		},
		
		on: function(event, func) {
			if (event === 'change') {
				this._input.on(event, func);
			} else {
				UIComponent.UIComponent.prototype.on.call(this, event, func);
			}
			return this;
		},
		
		off: function(event, func) {
			if (event === 'change') {
				this._input.off(event, func);
			} else {
				UIComponent.UIComponent.prototype.off.call(this, event, func);
			}
			return this;
		},
		
		trigger: function(event, extraParameters) {
			if (event === 'change') {
				this._input.trigger(event, extraParameters);
			} else {
				UIComponent.UIComponent.prototype.trigger.call(this, event, extraParameters);
			}
			return this;
		}
		
	});
	
	
	return self;
});
;

/** AlertBox **/
(window.defineModule = (window.defineModule || {})).name = 'AlertBox';

define('AlertBox', ['UIComponent'], function(UIComponent) {
	
	var self = function(text) {
		if (text !== '%inherit%') {
			UIComponent.UIComponent.prototype.constructor.call(this);
			this.setText(text);
		}
	};
	self.STYLE_SUCCESS = 'success';
	self.STYLE_INFO = 'info';
	self.STYLE_DANGER = 'danger';
	self.STYLE_WARNING = 'warning';
	self.STYLE_PRIMARY = 'primary';
	self.STYLE_DEFAULT = 'default';
	self.prototype = new UIComponent.UIComponent('%inherit%');
	self.prototype.constructor = self;
	
	self.prototype._createElem = function() { return $('<div>').addClass('alert alert-default'); };
	self.prototype.setText = function(text) {
		this._elem.text(text);
		return this;
	};
	self.prototype.getText = function() {
		return this._elem.text();
	};
	self.prototype.setHtml = function(html) {
		this._elem.html(html);
		return this;
	};
	self.prototype.getHtml = function() {
		return this._elem.html();
	};
	self.prototype.setBoxStyle = function(style) {
		this._elem.removeClass('alert-success alert-danger alert-info alert-warning alert-primary alert-default');
		if (style === self.STYLE_DANGER) {
			this._elem.addClass('alert-danger');
		} else if (style === self.STYLE_SUCCESS) {
			this._elem.addClass('alert-success');
		} else if (style === self.STYLE_INFO) {
			this._elem.addClass('alert-info');
		} else if (style === self.STYLE_WARNING) {
			this._elem.addClass('alert-warning');
		} else if (style === self.STYLE_PRIMARY) {
			this._elem.addClass('alert-primary');
		} else if (style === self.STYLE_DEFAULT) {
			this._elem.addClass('alert-default');
		}
		return this;
	};
	
	return self;
});
;

/** TreeListControl **/
(window.defineModule = (window.defineModule || {})).name = 'TreeListControl';

define('TreeListControl', ['UIComponent'], function(UIComponent) {
	
	var self = function() { this.__construct.apply(this, arguments); };
	self.prototype = new UIComponent.UIComponent('%inherit%');
	self.prototype.constructor = self;
	$.extend(self.prototype, {
		
		_elem: null,
		_tree: null,
		_btnRemove: null,
		_eventMouseEnter: null,
		_eventMouseLeave: null,
		_treeLoaded: false,
		_selectedItem: null,
		_selectWhenReady: null,
		items: null,
		moveValidateFunc: null,
		selectFunc: null,
		deleteFunc: null,
		onItemsCountChanged: null,
		
		/**
		 * @class TreeListControl
		 */
		__construct: function() {
			UIComponent.UIComponent.prototype.constructor.call(this);
			var thisSelf = this;
			this.items = new self.Item('root');
			this.items._tree = this;
			this.items._isRoot = true;
			this._tree = this._elem;
			this._tree.addClass('wb_menu_list');
			this._tree.jstree({
				plugins: [ 'core', 'themes', 'json_data', 'ui', 'crrm', 'dnd' ],
				ui: { select_limit: 1 },
				core: { 'load_open': true, rtl: wb_builder.rtl },
				crrm: {
					move: {
						check_move: function(m) { return thisSelf._validateMove(m); }
					}
				},
				json_data: {
					data: function (n, callback) { callback(thisSelf._loadData(n)); }
				}
			}).bind('create.jstree', function(e, data) { thisSelf._createItem(data); })
				.bind('remove.jstree', function(e, data) { thisSelf._removeItem(data);	})
				.bind('rename.jstree', function(e, data) { thisSelf._renameItem(data); })
				.bind('move_node.jstree', function(e, data) { thisSelf._moveItem(data); })
				.bind('select_node.jstree', function(e, data) { thisSelf._selectItem(data); })
				.bind('loaded.jstree', function (e, data) { thisSelf._treeReady(data); });
			
			this._btnRemove = $('<button>')
				.addClass('btn btn-xs btn-link jstree-x-btn')
				.append($('<i>').addClass('glyphicon glyphicon-remove'))
				.on('click', function() {
					var del = true, item = self.Item.fromElem($(this).parent());
					if (typeof thisSelf.deleteFunc === 'function') {
						del = thisSelf.deleteFunc(item);
					}
					if (del !== false) thisSelf.removeItem(item);
				});
		
			this._eventMouseEnter = function(e) {
				e.stopPropagation();
				$(this).parent().append(thisSelf._btnRemove);
				thisSelf._btnRemove.show();
			};
			this._eventMouseLeave = function(e) {
				e.stopPropagation();
				if (thisSelf._selectedItem) {
					thisSelf._tree.find('li > a.jstree-clicked').eq(0).parent().append(thisSelf._btnRemove);
				} else {
					thisSelf._btnRemove.hide();
				}
			};
		},
		
		/** UIBuildable implementation. */
		buildInit: function(data, fields) {},
		
		newItem: function() {
			var item = new self.Item(__('New Item'));
			this._tree.jstree('create', -1, 'last', item, null, true);
		},
		
		removeItem: function(item, fadeOut) {
			var thisSelf = this;
			if (fadeOut) {
				item._elem.fadeOut(400, function() {
					thisSelf._tree.jstree('remove', item._elem);
				});
			} else {
				this._tree.jstree('remove', item._elem);
			}
		},
		
		/**
		 * @param {TreeListControl~Item} item
		 */
		selectItem: function(item, triggerClick) {
			if (!this._treeLoaded) {
				this._selectWhenReady = item;
				return;
			}
			var thisSelf = this;
			this._tree.find('li').each(function() {
				var eLi = $(this), li = self.Item.fromElem(eLi);
				if (li && li === item) {
					if (triggerClick) {
						eLi.children('a').trigger('click');
					} else {
						thisSelf._tree.jstree('select_node', eLi);
						eLi.children('a').trigger('mouseleave');
					}
					return false;
				}
			});
		},
		
		updateTree: function() {
			if (this._treeLoaded) {
				this._btnRemove.detach();
				this._tree.jstree('refresh', -1);
			}
			this._tree.find('li > a')
				.off('mouseenter', this._eventMouseEnter)
				.on('mouseenter', this._eventMouseEnter);
			this._tree.find('li')
				.off('mouseleave', this._eventMouseLeave)
				.on('mouseleave', this._eventMouseLeave)
				.each(function() {
					var li = $(this),
						item = self.Item.fromElem(li);
					item._elem = li;
				});
		},
		
		_validateMove: function(m) {
			if (typeof this.moveValidateFunc === 'function') {
				var fromIndex = m.cop,
					toIndex = m.cp,
					item = self.Item.fromElem(m.o),
					target = self.Item.fromElem(m.np);
				if (!target) target = this.items;
				return this.moveValidateFunc(item, target, fromIndex, toIndex);
			}
			return true;
		},
		
		_treeReady: function() {
			this._treeLoaded = false;
			this.updateTree();
			this._treeLoaded = true;
			if (this._selectWhenReady) {
				this.selectItem(this._selectWhenReady);
				this._selectWhenReady = null;
			}
		},
		
		_loadData: function(n) {
			if (n === -1) {
				if (this.items._items.length <= 0) {
					this.items.addItem(new self.Item('---'));
				}
				return this.items._items;					
			} else {
				var parent = self.Item.fromElem(n);
				if (parent) return parent._items;
			}
			return [];
		},
		
		_selectItem: function(data) {
			var item = self.Item.fromElem(data.rslt.obj);
			this._selectedItem = item ? item : null;
			if (typeof this.selectFunc === 'function') {
				this.selectFunc.call(this, this._selectedItem);
			}
		},
		
		_moveItem: function(data) {
			var parent = self.Item.fromElem(data.rslt.np);
			if (!parent) parent = this.items;
			var item = self.Item.fromElem(data.rslt.o.eq(0));
			if (item) {
				var idx = data.rslt.cp;
				if (parent === item.getParent() && idx > data.rslt.cop) {
					idx--;
				}
				parent.addItem(item, idx);
			}
			// fix strange jstree bug - it duplicates new menu items
			// when they are moved to a parent item
			this._tree.find('li').each(function() {
				var item = self.Item.fromElem($(this));
				if (!item) $(this).remove();
			});
		},
		
		_createItem: function(data) {
			var item = new self.Item(data.rslt.name),
				target = ((data.rslt.parent && data.rslt.parent !== -1) ? self.Item.fromElem(data.rslt.parent) : null);
			if (!target) target = this.items;
			target.addItem(item);
		},
		
		_removeItem: function(data) {
			var item = self.Item.fromElem(data.rslt.obj.eq(0));
			if (item && item.getParent()) item.getParent().removeItem(item);
			if (item && this._selectedItem === item) this._selectedItem = null;
		},
		
		_renameItem: function(data) {
			var item = self.Item.fromElem(data.rslt.obj);
			if (item) item.setTitle(data.rslt.new_name);
		}
		
	});
	
	self.Item = function() { this.__construct.apply(this, arguments); };
	$.extend(self.Item, {
		fromElem: function(elem) {
			// Use wrapper object for storing instances to jQuery data,
			// because jQuery do not keep original object.
			var wrp = elem.data('__META_INST__');
			return (wrp ? wrp.rqw : null);
		}
	});
	$.extend(self.Item.prototype, {
		
		_isHome: false,
		_isLink: false,
		_icon: null,
		_iconHome: 'glyphicon glyphicon-home',
		_iconItem: 'glyphicon glyphicon-folder-open',
		_iconLink: 'glyphicon glyphicon-share-alt',
		_original: null,
		_parent: null,
		_items: null,
		_title: null,
		_isRoot: false,
		_elem: null,
		_tree: null,
		data: null,
		metadata: null,
		state: null,
		
		/**
		 * Create new item
		 * @param {String} title
		 * @param {String=} icon
		 * @param {Object=} original
		 * @param {Number=} truncateTitle
		 * @class TreeListControl~Item
		 */
		__construct: function(title, icon, original, truncateTitle) {
			this.data = {
				title: null,
				icon: null,
				attr: {}
			};
			// Use wrapper object for storing instances to jQuery data,
			// because jQuery do not keep original object.
			this.metadata = { __META_INST__: {rqw: this} };
			this.setTitle(title, truncateTitle);
			this.setIcon(icon);
			this._original = original;
			this._items = [];
		},
		
		/** @return {Boolean} */
		isRoot: function() {
			return this._isRoot;
		},
		
		getItemCount: function() {
			return this._items.length;
		},
		
		getItem: function(index) {
			return ((index >= 0 && index < this._items.length) ? this._items[index] : null);
		},
		
		getItems: function() {
			return this._items;
		},
		
		/**
		 * @param {TreeListControl~Item} item
		 * @param {Number=} atIndex
		 */
		addItem: function(item, atIndex) {
			var idx = this._items.indexOf(item);
			if (idx < 0 || (typeof atIndex === 'number')) {
				if (item._parent) { item._parent.removeItem(item, true); }
				if (typeof atIndex === 'number') {
					this._items.splice(atIndex, 0, item);
				} else {
					this._items.push(item);
				}
				item._parent = this;
				item._tree = this._tree;
				this.state = 'open';
				this._itemsCountChanged(item);
			}
		},
		
		/**
		 * @param {TreeListControl~Item} item
		 */
		removeItem: function(item, soft) {
			var idx = this._items.indexOf(item);
			if (idx >= 0) {
				this._items.splice(idx, 1);
				this._itemsCountChanged(item);
				if (!soft) {
					item._parent = null;
					item._tree = null;
					item._elem = null;
				}
				if (this._items.length <= 0) this.state = null;
			}
		},
		
		removeAllItems: function() {
			if (this._items.length > 0) this._itemsCountChanged(this._items[0]);
			for (var i = 0; i < this._items.length; i++) {
				this._items[i]._parent = null;
				this._items[i]._tree = null;
				this._items[i]._elem = null;
			}
			this._items.splice(0, this._items.length);
			this.state = null;
		},
		
		getParent: function() {
			return this._parent;
		},
		
		getTitle: function() {
			return this._title;
		},
		
		/** jQuery Tree plugin does stuff to data object so we use this function to account for that. */
		_jsTreeDataModel: function() {
			if (this.data instanceof Array && this.data.length > 0) {
				return this.data[0];
			}
			return this.data;
		},
		
		_itemsCountChanged: function(item) {
			if (item && item._tree && (typeof item._tree.onItemsCountChanged === 'function')) {
				item._tree.onItemsCountChanged(item);
			}
		},
		
		setTitle: function(title, truncateTitle) {
			var ltitle = this._title, dataModel = this._jsTreeDataModel();
			this._title = title;
			dataModel.title = this._title;
			if (truncateTitle && truncateTitle > 0 && dataModel.title && dataModel.title.length > truncateTitle) {
				dataModel.title = dataModel.title.substring(0, truncateTitle) + '...';
			}
			if (this._tree && this._elem && ltitle !== this._title) {
				this._tree._tree.jstree('set_text', this._elem, dataModel.title);
			}
		},
		
		setIcon: function(icon) {
			var dataModel = this._jsTreeDataModel(), licon = dataModel.icon;
			this._icon = icon ? icon : null;
			dataModel.icon = this._isLink ? this._iconLink :
					(this._isHome ? this._iconHome : (this._icon ? this._icon : this._iconItem));
			if (this._tree && this._elem && licon !== dataModel.icon) {
				if (licon) this._elem.children('a').find('ins').removeClass(licon);
				if (this._icon) this._elem.children('a').find('ins').removeClass(this._icon);
				if (this._iconItem) this._elem.children('a').find('ins').removeClass(this._iconItem);
				if (dataModel.icon) this._elem.children('a').find('ins').addClass(dataModel.icon);
			}
		},
		
		setHome: function(isHome) {
			this._isHome = isHome ? true : false;
			this.setIcon(this._icon);
		},
		
		setLink: function(isLink) {
			this._isLink = isLink ? true : false;
			this.setIcon(this._icon);
		},
		
		isHome: function() {
			return this._isHome;
		},
		
		isLink: function() {
			return this._isLink;
		},
		
		getOriginal: function() {
			return this._original;
		}
		
	});
	
	return self;
});
;

/** EditMenuItemsDialog **/
(window.defineModule = (window.defineModule || {})).name = 'EditMenuItemsDialog';

define('EditMenuItemsDialog', [
	'Dialog',
	'UIComponent',
	'VerticalLayout',
	'HorizontalLayout',
	'TreeListControl',
	'Label',
	'TextField',
	'MultilangTextField',
	'RadioBox',
	'CheckBox',
	'DropdownBox',
	'UIButton',
	'IdIndexedList',
	'BuilderEvent',
	'util/MenuList',
	'Service'
], function(Dialog, UIComponent, VerticalLayout, HorizontalLayout, TreeListControl, Label, TextField, MultilangTextField, RadioBox, CheckBox, DropdownBox, UIButton, IdIndexedList, BuilderEvent, MenuList, Service) {
	'use strict';
	
	var greyBoxStyle = {background: '#F5F5F5', border: '1px solid #E3E3E3', padding: '8px 2px'}, win = window;
	
	var self = function() { this.__construct.apply(this, arguments); };
	self.prototype = new Dialog('%inherit%');
	self.prototype.constructor = self;
	$.extend(self, {
		MODE_EDIT: 'edit',
		MODE_NEW: 'new'
	});
	$.extend(self.prototype, {
		
		_base: null,
		_tree: null,
		_leftPane: null,
		_panel: null,
		_currMenu: null,
		_mode: null,
		_newDialog: null,
		applyFunc: null,
		_newApplyFunc: null,
		_fromApplyAction: false,
		_waitingToReturn: false,
		_visible: false,
		_pages: null,
		_menuItems: null,
		_liteVersionMessage: null,
		_liteVersionPopup: null,
		
		__construct: function(mode) {
			this._mode = mode ? mode : self.MODE_EDIT;
			Dialog.prototype.__construct.call(this, ((this._mode === self.MODE_NEW) ? __('Add Menu Item') : __('Edit Menu Items')), false);
			this.setNoScroll();
			var thisSelf = this;
			
			this._base = new HorizontalLayout.HorizontalLayout();
			
			if (this._mode === self.MODE_EDIT) {
				this._leftPane = new VerticalLayout.VerticalLayout();
				this._leftPane.css(greyBoxStyle);

				this._tree = new TreeListControl();
				this._tree.moveValidateFunc = function(item, target) {
					if (target && target.getParent() && target.getParent().getParent() && !target.getParent().getParent().isRoot()) {
						return false;
					}
					return true;
				};
				this._tree.selectFunc = function(selItem) {
					thisSelf._panel.selectItem(selItem, !thisSelf._visible);
					var i, c, item, page, orig;
					for (i = 0, c = thisSelf._tree.items.getItemCount(); i < c; i++) {
						item = thisSelf._tree.items.getItem(i);
						orig = item.getOriginal();
						page = (orig.targetId && (orig.type === 'page' || orig.type === 'internal')) ? thisSelf._pages.getItemById(orig.targetId) : null;
						item.setHome(page && page.isFront);
						item.setLink(page && orig.type === 'internal' || orig.type === 'external' || orig.type === 'anchor' || orig.type === 'empty');
					}
				};
				this._tree.deleteFunc = function(delItem) {
					if (delItem.getOriginal().type === 'page') {
						var name = __tr(delItem.getOriginal().name, '__DEFAULT__', null, true, true);
						var page = win.wb_builder.site.getPage(delItem.getOriginal().targetId);
						if (name && page && page.saved
								&& !confirm(__('You are about to delete page %s entirely from your website.').replace('%s', '"' + name + '"')
									+ ' ' + __('Do you really want to remove it?'))) return false;
						var updateItems = function(tree) {
							for (var i = 0, c = tree.getItemCount(); i < c; i++) {
								var item = tree.getItem(i);
								if (item.getOriginal().type === 'internal' && item.getOriginal().targetId == delItem.getOriginal().targetId) {
									item.getOriginal().targetId = null;
									item.getOriginal().type = 'empty';
								}
								updateItems(item);
							}
						};
						updateItems(thisSelf._tree.items);
						
						for (var i = 0, c = thisSelf._pages.getItemCount(); i < c; i++) {
							var p = thisSelf._pages.getItem(i);
							if (p && p.id == delItem.getOriginal().targetId) {
								thisSelf._pages.removeItem(p);
								thisSelf._panel.loadData(thisSelf._pages);
								break;
							}
						}
					}
				};
				this._tree.onItemsCountChanged = function(chnItem) {
					if (thisSelf._tree.items.getItemCount() > 0) {
						thisSelf.buttons.find('.btn-success').removeAttr('disabled');
					} else {
						thisSelf.buttons.find('.btn-success').attr('disabled', 'disabled');
					}
				};
				window.testVal = this._tree.items;
				this._leftPane.addChild(this._tree);
				this._leftPane.applyLayoutCellCss(0, {height: 306, overflowY: 'auto'});

				var newItemButton = new UIButton.UIButton(__('New Item'), UIButton.UIButton.STYLE_LINK, 'glyphicon glyphicon-plus');
				newItemButton.css({marginTop: '10px'});
				newItemButton.on('click', function() {
					var canAdd = (win.wb_builder.maxMenuItems <= 0 || thisSelf._tree.items.getItemCount() + win.WB_Menu.getTotalPages(thisSelf._currMenu) < win.wb_builder.maxMenuItems);
					thisSelf.setDisabled(!canAdd);
					if (!canAdd) return;
					thisSelf.getNewDialog().setMenu(thisSelf._currMenu, thisSelf._pages);
					thisSelf.getNewDialog().applyFunc = thisSelf._newApplyFunc;
					thisSelf._waitingToReturn = true;
					thisSelf.getNewDialog().setDisabled(!canAdd);
					thisSelf.getNewDialog().setVisible(true);
					Service.HelpSystemPlayer.notify('item-plugin-' + thisSelf._currMenu.getClassType()
						+ '-menu-edit-newItemButton-click', thisSelf._currMenu);
				});
				this.fields.newItemButton = newItemButton;
				this._newApplyFunc = function(item) {
					thisSelf._menuItems.newItem(item.getOriginal(), true);
					item.getOriginal()._ignoreId = true;
					thisSelf._handleItemCopying(item);
					thisSelf._tree.items.addItem(item);
					thisSelf._tree.updateTree();
					thisSelf._tree.selectItem(item);
				};
				this._leftPane.addChild(newItemButton);

				var note = new self.Note(__('Use Drag and Drop to sort and categorize items'));
				this._leftPane.addChild(note);

				if (!wb_builder.rtl) this._base.addChild(this._leftPane);
				this._menuItems = new IdIndexedList();
			}
			this._pages = new IdIndexedList();
			
			this._panel = new self.EditPanel(this.fields, this._mode);
			this.fields.fldName.onChange = function() {
				Service.HelpSystemPlayer.notify('item-plugin-' + thisSelf._currMenu.getClassType() + '-menu-'
						+ ((thisSelf._mode === self.MODE_EDIT) ? 'edit' : 'new')
						+ '-fldName-change', thisSelf._currMenu);
			};
			this._base.addChild(this._panel);
			if (this._mode === self.MODE_EDIT) {
				if (wb_builder.rtl) {
					this._base.addChild(this._leftPane);
					this._base.setColWeight(0, 7);
					this._base.setColWeight(1, 5);
					this._panel.css({marginRight: '10px'});
				} else {
					this._base.setColWeight(0, 5);
					this._base.setColWeight(1, 7);
					this._panel.css({marginLeft: '10px'});
				}
			}
			
			if (this._mode === self.MODE_NEW) {
				this.setSize(385, null);
				this._panel.css({marginLeft: '10px', marginRight: '10px'});
			} else if (this._mode === self.MODE_EDIT) {
				this.setSize(685, null);
			}
			
			this.setContent(this._base.getElem());
			
			this.addButton(__('Cancel'), function() { thisSelf.setVisible(false); });
			this.addButton(__('Apply'), function() { thisSelf._applyAction(); }, true);
		},
		
		setLiteVersionMessage: function(message) {
			this._liteVersionMessage = message;
		},
		
		setDisabled: function(disabled) {
			if (this._mode === self.MODE_NEW) {
				if (disabled) {
					this.buttons.find('.btn-success').attr('disabled', 'disabled');
					this._panel.setMessage(this._liteVersionMessage);
				} else {
					this.buttons.find('.btn-success').removeAttr('disabled');
					this._panel.setMessage(null);
				}
			} else if (this._mode === self.MODE_EDIT) {
				if (disabled) {
					if (!this._liteVersionPopup) {
						this._liteVersionPopup = new self.Popup(this._liteVersionMessage);
						this._leftPane.addChild(this._liteVersionPopup);
					}
					this._liteVersionPopup.appear();
				} else {
					if (this._liteVersionPopup) {
						this._leftPane.removeChild(this._liteVersionPopup);
						this._liteVersionPopup = null;
					}
				}
			}
		},
		
		getNewDialog: function() {
			if (this._mode === self.MODE_NEW) {
				return null;
			}
			if (!this._newDialog) {
				this._newDialog = new self(self.MODE_NEW);
				this._newDialog.setLiteVersionMessage(this._liteVersionMessage);
			}
			return this._newDialog;
		},
		
		setMenu: function(menu, pages) {
			this._currMenu = menu;
			this._panel.setMenu(menu);
			this._pages.removeAllItems();
			this._pages.addItems(pages, false, true);
		},
		
		setOnCancel: function(callback) {
			if (this._mode !== self.MODE_NEW || typeof(callback) !== 'function') return;
			var clb = this.onClose, thisSelf = this;
			this.onClose = function() {
				if (typeof(clb) === 'function') clb();
				if (!thisSelf._fromApplyAction) {
					callback();
				}
			};
		},
		
		_handleItemCopying: function(item) {
			var itemO = item.getOriginal();
			if ('copyFromTargetId' in itemO) {
				var p = this._pages.getItemById(itemO.copyFromTargetId);
				if (p) {
					p = this._pages.newItem(p);
					p.title = item.getTitle();
					p.alias = '';
					p.keywords = '';
					p.description = '';
					p.isFront = false;
					p.isSingle = false;
					p.copyFrom = itemO.copyFromTargetId;
					p.copyClearHeader = itemO.copyClearHeader;
					p.copyClearBody = itemO.copyClearBody;
					p.copyClearFooter = itemO.copyClearFooter;
					p.isNew = true;
					itemO.targetId = p.id;
				}
				itemO.copyFromTargetId = null;
				delete itemO.copyFromTargetId;
				this._panel.loadData(this._pages);
			}
		},
		
		_applyAction: function() {
			var item = this._panel._item;
			this._panel.selectItem(null, !this._visible);
			if (typeof this.applyFunc === 'function') {
				this.applyFunc.call(this, item);
			} else {
				win.wb_builder.setPageModified(true);
				if (this._currMenu) {
					var items;
					if (this._mode === self.MODE_EDIT) {
						this._currMenu.removeAllItems();
						items = this._tree.items;
					} else if (this._mode === self.MODE_NEW) {
						this._handleItemCopying(item);
						items = new TreeListControl.Item('root');
						items.addItem(item);
					}
					
					win.wb_builder.site.updatePageList(this._pages);
					Service.menu.updateEmptyLinks();
					
					if (items) this._currMenu.addAllItems(items);
					this._currMenu.updateStyle();
					this._currMenu.resizeMenuBox();
					BuilderEvent.GlobalEvents.triggerEvent('pages.changed', new BuilderEvent.PagesChangedBuilderEvent());
					win.wb_builder.site.setLanding(win.wb_builder.site.landing);
					win.wb_builder.site.reloadPagesMiId(true);
				}
			}
			this._fromApplyAction = true;
			this.setVisible(false);
			if (this._currMenu) {
				Service.HelpSystemPlayer.notify('item-plugin-' + this._currMenu.getClassType() + '-menu-' + ((this._mode === self.MODE_EDIT) ? 'edit' : 'new') + '-apply', this._currMenu);
			}
		},
		
		_loadItems: function(target, source) {
			var k, k2, item, page, name;
			for (k in source) {
				name = __tr(source[k].name, '__DEFAULT__', __('New Item'), true, true);
				target.addItem(item = new TreeListControl.Item(name, null, source[k].serialize(), 15));
				page = (source[k].targetId && (source[k].type === 'page' || source[k].type === 'internal')) ? win.wb_builder.site.getPage(source[k].targetId) : null;
				this._menuItems.addItem(source[k].serialize());
				item.setHome((page ? page.isFront : false));
				item.setLink((source[k].type === 'internal' || source[k].type === 'external' || source[k].type === 'anchor' || source[k].type === 'empty'));
				for (k2 in source[k].items) {
					this._loadItems(item, source[k].items);
					break;
				}
			}
		},
		
		getTreeRootItem: function(idx) {
			if (!this._tree || !this._tree.items) return null;
			var item = this._tree.items.getItem(idx);
			return item;
		},
		
		selectTreeRootItem: function(idx) {
			var item = this.getTreeRootItem(idx);
			if (!item) return false;
			this._tree.selectItem(item, true);
			return true;
		},
		
		setVisible: function(visible, noAction, ignoreEvent) {
			if (visible) {
				this._fromApplyAction = false;
				if (!this._waitingToReturn) {
					if (this._mode === self.MODE_EDIT) {
						this._tree.items.removeAllItems();
						this._menuItems.removeAllItems();
						if (this._currMenu) this._loadItems(this._tree.items, this._currMenu.items);
						this._tree.updateTree();
						this._panel.loadData(this._pages);
						if (this._tree.items.getItemCount() > 0) {
							this._tree.selectItem(this._tree.items.getItem(0));
						}
					} else if (this._mode === self.MODE_NEW) {
						var item = new TreeListControl.Item(__('New Page'), null, {type: 'page', name: __('New Page')});
						this._panel.loadData(this._pages);
						this._panel.selectItem(item, true);
					}
				} else {
					this._waitingToReturn = false;
				}
			} else {
				this.applyFunc = null;
				this._panel._item = null;
			}
			Dialog.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
			this._visible = (visible ? true : false);
		}
		
	});
	
	self.EditPanel = function() { this.__construct.apply(this, arguments); };
	self.EditPanel.prototype = new VerticalLayout.VerticalLayout('%inherit%');
	self.EditPanel.prototype.constructor = self;
	$.extend(self.EditPanel, {
		_elemIndex: 0
	});
	$.extend(self.EditPanel.prototype, {
		
		_item: null,
		_currMenu: null,
		
		_copyOptions: null,
		_fldCopyPage:null,
		
		_linkOptions: null,
		_fldName: null,
		_fldTypePage: null,
		_fldTypeLink: null,
		_fldTypeLabel: null,
		
		_fldClearHeader: null,
		_fldClearBody: null,
		_fldClearFooter: null,
		
		_itemOptions: null,
		_fldNewWindow: null,
		_fldHideInMenu: null,
		_fldIsDefault: null,
		
		_fldPageLink: null,
		_fldExternalLink: null,
		_fldAnchor: null,
		_fldEmpty: null,
		_pages: null,
		_message: null,
		
		__construct: function(fields, mode) {
			if (!isNaN(self._elemIndex) || self._elemIndex === undefined) self._elemIndex = 0;
			VerticalLayout.VerticalLayout.prototype.constructor.call(this);
			var thisSelf = this, idx = self._elemIndex, types, linkOptionsTypes, copyOptionsBox;
			self._elemIndex++;
			
			this.addChild(new Label.Label(__('Item Name')));
			this.addChild(this._fldName = new MultilangTextField());
			fields.fldName = this._fldName;
			this._fldName.css({marginBottom: 0});
			this._fldName.setOnChange(function() {
				if (thisSelf._pages && thisSelf._item && thisSelf._item.getOriginal().type === 'page'
						&& parseInt(thisSelf._item.getOriginal().targetId)) {
					var page = thisSelf._pages.getItemById(parseInt(thisSelf._item.getOriginal().targetId));
				}
			});
			
			types = new HorizontalLayout.HorizontalLayout();
			types.css({marginTop: 15});
			this._fldTypePage = new RadioBox(__('Page'), true, 'type' + idx);
			this._fldTypePage.on('change', function() {
				if (thisSelf._fldTypePage.getValue()) {
					thisSelf._linkOptions.setVisible(false);
					thisSelf._copyOptions.setVisible(!thisSelf._item.getOriginal().id);
				}
			});
			this._fldTypeLink = new RadioBox(__('Link'), false, 'type' + idx);
			this._fldTypeLink.on('change', function() {
				if (thisSelf._fldTypeLink.getValue()) {
					thisSelf._linkOptions.setVisible(true);
					thisSelf._copyOptions.setVisible(false);
				}
			});
			this._fldTypeLabel = new Label.Label('');
			
			if (mode === self.MODE_NEW) {
				types.addChild(this._fldTypePage);
				types.addChild(this._fldTypeLink);
			} else {
//				types.addChild(this._fldTypeLabel);
			}
			this.addChild(types);
			
			this._copyOptions = new VerticalLayout.VerticalLayout();
			this._copyOptions.css({marginTop: 15});
			this._copyOptions.css({position: 'absolute', width: '100%', zIndex: 10});
			this._copyOptions.addChild(new Label.Label(__('Copy layout from')));
			copyOptionsBox = new VerticalLayout.VerticalLayout();
			copyOptionsBox.css({marginBottom: '5px'});
			copyOptionsBox.addChild(this._fldCopyPage = new DropdownBox());
			this._copyOptions.addChild(copyOptionsBox);
			this._copyOptions.setVisible(false);
			this.addChild(this._copyOptions);
			this._copyOptions.addChild(this._fldClearHeader = new CheckBox(__('Clear header contents')));
			this._copyOptions.addChild(this._fldClearBody = new CheckBox(__('Clear body contents')));
			this._copyOptions.addChild(this._fldClearFooter = new CheckBox(__('Clear footer contents')));
			this.css({position: 'relative'});
			
			this._linkOptions = new VerticalLayout.VerticalLayout();
			this._linkOptions.css({marginTop: 15});
			this._linkOptions.setVisible = function(visible) {
				if (visible) {
					this.css({visibility: 'visible'});
				} else {
					this.css({visibility: 'hidden'});
				}
			};
			this._linkOptions.addChild(new Label.Label(__('Choose link type')));
			linkOptionsTypes = new VerticalLayout.VerticalLayout();
			linkOptionsTypes.css(greyBoxStyle).css({padding: '6px 8px', marginBottom: '20px'});
			linkOptionsTypes.addChild(this._fldPageLink = new RadioBox(__('Internal link to'), true, 'linkType' + idx));
			this._fldPageLink.css({marginTop: 0});
			this._fldPageLink._input.css({marginTop: '33px'});
			linkOptionsTypes.addChild(this._fldPageLinkBox = new DropdownBox());
			this._fldPageLinkBox.on('click', function() {
				thisSelf._fldPageLink.setValue(true);
			});
			this._fldPageLinkBox.css((wb_builder.rtl ? {paddingRight: '20px', marginTop: 2} : {paddingLeft: '20px', marginTop: 2}));
			linkOptionsTypes.addChild(this._fldExternalLink = new RadioBox(__('External link to'), false, 'linkType' + idx));
			this._fldExternalLink.css({marginTop: 5});
			this._fldExternalLink._input.css({marginTop: '33px'});
			linkOptionsTypes.addChild(this._fldExternalLinkBox = new MultilangTextField());
			this._fldExternalLinkBox.on('focus', function() {
				thisSelf._fldExternalLink.setValue(true);
			});
			this._fldExternalLinkBox.setOnChange(function(e, value, langCode) {
				if (value && !/^https?:\/\//.test(value)) {
					thisSelf._fldExternalLinkBox.setText('http://' + value, langCode);
				}
			});
			this._fldExternalLinkBox.setPlaceholder('http://external.com/link');
			this._fldExternalLinkBox.css({display: 'block', marginTop: 2});
			this._fldExternalLinkBox.getElem().parent().css((wb_builder.rtl ? {marginRight: 20} : {marginLeft: 20}));
			linkOptionsTypes.addChild(this._fldAnchor = new RadioBox(__('Anchor to'), false, 'linkType' + idx));
			this._fldAnchor.css({marginTop: 5});
			this._fldAnchor._input.css({marginTop: '33px'});
			linkOptionsTypes.addChild(this._fldAnchorBox = new DropdownBox());
			this._fldAnchorBox.on('click', function() {
				thisSelf._fldAnchor.setValue(true);
			});
			linkOptionsTypes.addChild(this._fldEmpty = new RadioBox(__('Empty'), false, 'linkType' + idx));
			
			this._fldAnchorBox.css((wb_builder.rtl ? {paddingRight: '20px', marginTop: 2} : {paddingLeft: '20px', marginTop: 2}));
			this._fldEmpty.css({marginTop: '16px'});
			this._linkOptions.addChild(linkOptionsTypes);
			this._linkOptions.setVisible(false);
			this.addChild(this._linkOptions);
			
			this._itemOptions = new VerticalLayout.VerticalLayout();
			this._itemOptions.addChild(this._fldNewWindow = new CheckBox(__('Open in New Window')));
			this._itemOptions.addChild(this._fldHideInMenu = new CheckBox(__('Do not show this item in menu')));
			this._itemOptions.addChild(this._fldIsDefault = new CheckBox(__('Default menu item')));
			this.addChild(this._itemOptions);
		},
		
		setMenu: function(menu) {
			this._currMenu = menu;
		},
		
		setMessage: function(message) {
			if (!this._message) {
				this._message = new Label.Label();
				this._message._elem.css({
					width: '100%',
					fontWeight: 'normal'
				});
				this._copyOptions.addChild(this._message);
			}
			this._message.setHtml(message ? message : '');
		},
		
		/**
		 * @param {IdIndexedList} pages
		 */
		loadData: function(pages) {
			var i, n, c, data, tmpItem = null, name;
			if (this._item) {
				tmpItem = this._item;
				this.selectItem(null);
			}
			this._fldPageLinkBox.removeAllItem();
			this._fldCopyPage.removeAllItem();
			this._fldAnchorBox.removeAllItem();
			if (pages) {
				var itemNames = {}, thisMenuPageIds = [], otherMenuPageIds = [];
				var menuList = MenuList.buildMenuStruct(false);
				for (i = 0; i < menuList.length; i++) {
					var menu = menuList[i];
					for (n = 0; n < menu.items.length; n++) {
						var mi = menu.items[n];
						if (!mi.uID) continue;
						if (mi.type === 'page' && mi.pageId) {
							if (this._currMenu && this._currMenu.menuUID === mi.menuUID) {
								thisMenuPageIds.push(mi.pageId);
							} else {
								otherMenuPageIds.push(mi.pageId);
							}
							itemNames['#' + mi.pageId] = __tr(mi.fullName, '__DEFAULT__', null, true, true);
						}
					}
				}
				
				// sort pages
				var thisMenuItems = [];
				var otherMenuItems = [];
				for (i = 0, c = pages.getItemCount(); i < c; i++) {
					data = pages.getItem(i);
					if (thisMenuPageIds.indexOf(data.id) > -1) {
						thisMenuItems.push(data);
					} else {
						otherMenuItems.push(data);
					}
				}
				thisMenuItems.sort(function(a, b) {
					var aIdx = thisMenuPageIds.indexOf(a.id);
					var bIdx = thisMenuPageIds.indexOf(b.id);
					return (aIdx > bIdx) ? 1 : -1;
				});
				otherMenuItems.sort(function(a, b) {
					var aIdx = otherMenuPageIds.indexOf(a.id);
					var bIdx = otherMenuPageIds.indexOf(b.id);
					return (aIdx > bIdx) ? 1 : -1;
				});
				pages.removeAllItems();
				for (i = 0, c = thisMenuItems.length; i < c; i++) { pages.addItem(thisMenuItems[i]); }
				for (i = 0, c = otherMenuItems.length; i < c; i++) { pages.addItem(otherMenuItems[i]); }
				
				for (i = 0, c = pages.getItemCount(); i < c; i++) {
					data = pages.getItem(i);
					name = (('#' + data.id) in itemNames) ? itemNames['#' + data.id] : null;
					if (!name) name = __tr(data.title, '__DEFAULT__', null, true, true);
					this._fldPageLinkBox.addItem(new DropdownBox.Item(name, data.id, data));
					this._fldCopyPage.addItem(new DropdownBox.Item(name, data.id, data));
					
					var anchors = win.wb_builder.site.getAnchors(data.id);
					for (n = 0; n < anchors.length; n++) {
						this._fldAnchorBox.addItem(new DropdownBox.Item(name + ': ' + anchors[n], anchors[n], data));
					}
				}
				this._pages = pages;
				var thisClass = this;
				setTimeout(function() {
					var itm;
					if ((itm = thisClass._fldCopyPage.getItemById(win.wb_builder.pageId))) thisClass._fldCopyPage.selectItem(itm);
					if ((itm = thisClass._fldPageLinkBox.getItemById(win.wb_builder.pageId))) thisClass._fldPageLinkBox.selectItem(itm);
				}, 20);
			} else {
				this._pages = null;
			}
		},
		
		updateFieldType: function(item) {
			var typeLabel = $('<strong>').css({ fontWeight: 'bold' });
			var label = $('<span>').css({ fontWeight: 'normal' }).text(__('Type') + ': ').append(typeLabel);
			this._fldTypeLabel.setHtml(label);
			if (item.getOriginal().type === 'page') {
				this._fldTypePage.setValue(true);
				this._fldTypeLink.setValue(false);
				typeLabel.text(__('Content'));
			} else {
				this._fldTypePage.setValue(false);
				this._fldTypeLink.setValue(true);
				typeLabel.text(__('Link'));
			}
		},
		
		selectItem: function(item, notVisible) {
			var thisSelf = this, p, i, c, data, page, val;
			if (this._item) {
				this._item.getOriginal().name = this._fldName.getText();
				this._item.setTitle(__tr(this._fldName.getText(), '__DEFAULT__', __('New Item'), true, true), 15);
				
				
				if (this._fldTypeLink.getValue()) {
					if ((val = this._fldPageLinkBox.getSelectedItem())) this._item.getOriginal().targetId = val.getId();
					if (this._fldExternalLink.getValue()) {
						this._item.getOriginal().type = 'external';
					} else if (this._fldAnchor.getValue()) {
						this._item.getOriginal().type = 'anchor';
					} else if (this._fldPageLink.getValue()) {
						this._item.getOriginal().type = 'internal';
					} else {
						this._item.getOriginal().type = 'empty';
					}
					this._item.setHome(false);
					this._item.setLink(false);
					this._item.getOriginal().copyFromTargetId = null;
					delete this._item.getOriginal().copyFromTargetId;
					this._item.getOriginal().copyClearHeader = null;
					delete this._item.getOriginal().copyClearHeader;
					this._item.getOriginal().copyClearBody = null;
					delete this._item.getOriginal().copyClearBody;
					this._item.getOriginal().copyClearFooter = null;
					delete this._item.getOriginal().copyClearFooter;
				} else {
					this._item.getOriginal().type = 'page';
					if (this._pages && this._item.getOriginal().id) {
						page = this._item.getOriginal().targetId ? this._pages.getItemById(this._item.getOriginal().targetId) : null;
						if (page) {
							this._item.setHome(this._fldIsDefault.getValue());
							this._item.setLink((this._item.getOriginal().type === 'internal' || this._item.getOriginal().type === 'external' || this._item.getOriginal().type === 'anchor' || this._item.getOriginal().type === 'empty'));
							page.isFront = (this._fldIsDefault.getValue() ? true : false);
							if (page.isFront) {
								for (i = 0, c = this._pages.getItemCount(); i < c; i++) {
									data = this._pages.getItem(i);
									if (page !== data) { data.isFront = false; }
								}
							}
						}
						this._item.getOriginal().copyFromTargetId = null;
						delete this._item.getOriginal().copyFromTargetId;
						this._item.getOriginal().copyClearHeader = null;
						delete this._item.getOriginal().copyClearHeader;
						this._item.getOriginal().copyClearBody = null;
						delete this._item.getOriginal().copyClearBody;
						this._item.getOriginal().copyClearFooter = null;
						delete this._item.getOriginal().copyClearFooter;
					} else {
						this._item.getOriginal().targetId = null;
						this._item.getOriginal().copyFromTargetId = ((val = this._fldCopyPage.getSelectedItem()) ? val.getId() : null);
						this._item.getOriginal().copyClearHeader = (this._fldClearHeader.getValue() ? true : false);
						this._item.getOriginal().copyClearBody = (this._fldClearBody.getValue() ? true : false);
						this._item.getOriginal().copyClearFooter = (this._fldClearFooter.getValue() ? true : false);
						this._item.setHome(false);
						this._item.setLink(false);
					}
				}
				
				this._item.getOriginal().url = this._fldExternalLinkBox.getText();
				val = this._fldAnchorBox.getSelectedItem();
				this._item.getOriginal().anchor = ((val = this._fldAnchorBox.getSelectedItem()) ? {name: val.getId(), pageId: val.getOriginal().id} : null);
				this._item.getOriginal().target = (this._fldNewWindow.getValue() ? '_blank' : '_self');
				this._item.getOriginal().noMenu = this._fldHideInMenu.getValue();
			}
			this._item = item;
			if (!this._item) return;

			this._fldName.setText(this._item.getOriginal().name);
			setTimeout(function() { thisSelf._fldName.focus(); }, (notVisible ? 1000 : 40));
			
			if (this._item.getOriginal().type === 'page') {
				this.updateFieldType(this._item);
				this._linkOptions.setVisible(false);
				this._copyOptions.setVisible(!this._item.getOriginal().id);
				
				if (this._pages && this._item.getOriginal().id) {
					page = this._item.getOriginal().targetId ? this._pages.getItemById(this._item.getOriginal().targetId) : null;
					this._fldIsDefault.setValue((page && page.isFront));
					this._fldIsDefault.setVisible(true);
				} else {
					this._fldIsDefault.setValue(false);
					this._fldIsDefault.setVisible(false);
				}
			} else {
				this.updateFieldType(this._item);
				this._linkOptions.setVisible(true);
				this._copyOptions.setVisible(false);
				
				this._fldIsDefault.setValue(false);
				this._fldIsDefault.setVisible(false);
				
				if (this._item.getOriginal().type === 'external') {
					this._fldPageLink.setValue(false);
					this._fldExternalLink.setValue(true);
					this._fldAnchor.setValue(false);
					this._fldEmpty.setValue(false);
				} else if (this._item.getOriginal().type === 'anchor') {
					this._fldPageLink.setValue(false);
					this._fldExternalLink.setValue(false);
					this._fldAnchor.setValue(true);
					this._fldEmpty.setValue(false);
				} else if (this._item.getOriginal().type === 'internal') {
					this._fldPageLink.setValue(true);
					this._fldExternalLink.setValue(false);
					this._fldAnchor.setValue(false);
					this._fldEmpty.setValue(false);
				} else {
					this._fldPageLink.setValue(false);
					this._fldExternalLink.setValue(false);
					this._fldAnchor.setValue(false);
					this._fldEmpty.setValue(true);
				}
			}
			
			if (this._item.getOriginal().targetId) {
				this._fldPageLinkBox.selectItem(this._fldPageLinkBox.getItemById(this._item.getOriginal().targetId));
			} else {
				this._fldPageLinkBox.selectItem(this._fldPageLinkBox.getItem(0));
			}
			
			this._fldExternalLinkBox.setText(this._item.getOriginal().url ? this._item.getOriginal().url : '');
			
			if (this._item.getOriginal().anchor && (typeof this._item.getOriginal().anchor === 'object')) {
				this._fldAnchorBox.selectItem(this._fldAnchorBox.getItemById(this._item.getOriginal().anchor.name));
			} else {
				this._fldAnchorBox.selectItem(this._fldAnchorBox.getItem(0));
			}
			
			if (this._item.getOriginal().id) {
				this._itemOptions.setVisible(true);
			} else {
				this._itemOptions.setVisible(false);
			}
			this._fldNewWindow.setValue((this._item.getOriginal().target === '_blank'));
			this._fldHideInMenu.setValue(this._item.getOriginal().noMenu);
		}
		
	});
	
	self.Note = function() { this.__construct.apply(this, arguments); };
	self.Note.prototype = new UIComponent.UIComponent('%inherit%');
	self.Note.prototype.constructor = self;
	$.extend(self.Note.prototype, {
		
		_icon: 'glyphicon glyphicon-exclamation-sign',
		_text: null,
		
		_iconElem: null,
		_textElem: null,
		
		__construct: function(text, icon) {
			UIComponent.UIComponent.prototype.constructor.call(this);
			this._elem.addClass('wb-page-tree-notice');
			var css = {marginTop: 8, width: 172};
			if (wb_builder.rtl) {
				css.marginRight = 10;
			} else {
				css.marginLeft = 10;
			}
			this._elem.css(css);
			var sml = $('<small>').appendTo(this._elem);
			this._iconElem = $('<i>').appendTo(sml);
			this._textElem = $('<span>').addClass('txt').appendTo(sml);
			this.setText(text);
			this.setIcon(icon ? icon : this._icon);
		},
		
		setText: function(text) {
			this._text = text;
			this._textElem.text(this._text);
		},
		
		setIcon: function(icon) {
			this._icon = icon;
			this._iconElem.removeClass().addClass(this._icon);
		}
		
	});
	
	self.Popup = function() { this.__construct.apply(this, arguments); };
	self.Popup.prototype = new UIComponent.UIComponent('%inherit%');
	self.Popup.prototype.constructor = self;
	$.extend(self.Popup.prototype, {
		
		_html: null,
		_htmlElem: null,
		_appearTimeout: null,
		
		__construct: function(html) {
			UIComponent.UIComponent.prototype.constructor.call(this);
			this._elem.css({
				position: 'absolute',
				display: 'none',
				bottom: '82px',
				zIndex: 10
			});
			this._htmlElem = $('<div>').css({ padding: '0 10px' })
				.appendTo(this._elem);
			
			this.setHtml(html);
		},
		
		setHtml: function(html) {
			this._html = html;
			this._htmlElem.html(html);
		},
		
		appear: function() {
			var thisSelf = this;
			this._elem.css({ display: 'block', opacity: 1 });
			clearTimeout(this._appearTimeout);
			this._appearTimeout = setTimeout(function() {
				thisSelf._elem.animate({ opacity: 0 }, 400, function() {
					thisSelf._elem.css({ display: 'none' });
				});
			}, 2000);
		}
		
	});
	
	return self;
});
;

/** Gettext **/
(window.defineModule = (window.defineModule || {})).name = 'Gettext';
/*
Pure Javascript implementation of Uniforum message translation.
Copyright (C) 2008 Joshua I. Miller <unrtst@cpan.org>, all rights reserved

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2, or (at your option)
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.

=head1 NAME

Javascript Gettext - Javascript implemenation of GNU Gettext API.

=head1 SYNOPSIS

 // //////////////////////////////////////////////////////////
 // Optimum caching way
 <script language="javascript" src="/path/LC_MESSAGES/myDomain.json"></script>
 <script language="javascript" src="/path/Gettext.js'></script>

 // assuming myDomain.json defines variable json_locale_data
 var params = {  "domain" : "myDomain",
                 "locale_data" : json_locale_data
              };
 var gt = new Gettext(params);
 // create a shortcut if you'd like
 function _ (msgid) { return gt.gettext(msgid); }
 alert(_("some string"));
 // or use fully named method
 alert(gt.gettext("some string"));
 // change to use a different "domain"
 gt.textdomain("anotherDomain");
 alert(gt.gettext("some string"));


 // //////////////////////////////////////////////////////////
 // The other way to load the language lookup is a "link" tag
 // Downside is that not all browsers cache XMLHttpRequests the
 // same way, so caching of the language data isn't guarenteed
 // across page loads.
 // Upside is that it's easy to specify multiple files
 <link rel="gettext" href="/path/LC_MESSAGES/myDomain.json" />
 <script language="javascript" src="/path/Gettext.js'></script>

 var gt = new Gettext({ "domain" : "myDomain" });
 // rest is the same


 // //////////////////////////////////////////////////////////
 // The reson the shortcuts aren't exported by default is because they'd be
 // glued to the single domain you created. So, if you're adding i18n support
 // to some js library, you should use it as so:

 if (typeof(MyNamespace) == 'undefined') MyNamespace = {};
 MyNamespace.MyClass = function () {
     var gtParms = { "domain" : 'MyNamespace_MyClass' };
     this.gt = new Gettext(gtParams);
     return this;
 };
 MyNamespace.MyClass.prototype._ = function (msgid) {
     return this.gt.gettext(msgid);
 };
 MyNamespace.MyClass.prototype.something = function () {
     var myString = this._("this will get translated");
 };

 // //////////////////////////////////////////////////////////
 // Adding the shortcuts to a global scope is easier. If that's
 // ok in your app, this is certainly easier.
 var myGettext = new Gettext({ 'domain' : 'myDomain' });
 function _ (msgid) {
     return myGettext.gettext(msgid);
 }
 alert( _("text") );

 // //////////////////////////////////////////////////////////
 // Data structure of the json data
 // NOTE: if you're loading via the <script> tag, you can only
 // load one file, but it can contain multiple domains.
 var json_locale_data = {
     "MyDomain" : {
         "" : {
             "header_key" : "header value",
             "header_key" : "header value",
         "msgid" : [ "msgid_plural", "msgstr", "msgstr_plural", "msgstr_pluralN" ],
         "msgctxt\004msgid" : [ null, "msgstr" ],
         },
     "AnotherDomain" : {
         },
     }

=head1 DESCRIPTION

This is a javascript implementation of GNU Gettext, providing internationalization support for javascript. It differs from existing javascript implementations in that it will support all current Gettext features (ex. plural and context support), and will also support loading language catalogs from .mo, .po, or preprocessed json files (converter included).

The locale initialization differs from that of GNU Gettext / POSIX. Rather than setting the category, domain, and paths, and letting the libs find the right file, you must explicitly load the file at some point. The "domain" will still be honored. Future versions may be expanded to include support for set_locale like features.


=head1 INSTALL

To install this module, simply copy the file lib/Gettext.js to a web accessable location, and reference it from your application.


=head1 CONFIGURATION

Configure in one of two ways:

=over

=item 1. Optimal. Load language definition from statically defined json data.

    <script language="javascript" src="/path/locale/domain.json"></script>

    // in domain.json
    json_locale_data = {
        "mydomain" : {
            // po header fields
            "" : {
                "plural-forms" : "...",
                "lang" : "en",
                },
            // all the msgid strings and translations
            "msgid" : [ "msgid_plural", "translation", "plural_translation" ],
        },
    };
    // please see the included bin/po2json script for the details on this format

This method also allows you to use unsupported file formats, so long as you can parse them into the above format.

=item 2. Use AJAX to load language file.

Use XMLHttpRequest (actually, SJAX - syncronous) to load an external resource.

Supported external formats are:

=over

=item * Javascript Object Notation (.json)

(see bin/po2json)

    type=application/json

=item * Uniforum Portable Object (.po)

(see GNU Gettext's xgettext)

    type=application/x-po

=item * Machine Object (compiled .po) (.mo)

NOTE: .mo format isn't actually supported just yet, but support is planned.

(see GNU Gettext's msgfmt)

    type=application/x-mo

=back

=back

=head1 METHODS

The following methods are implemented:

  new Gettext(args)
  textdomain  (domain)
  gettext     (msgid)
  dgettext    (domainname, msgid)
  dcgettext   (domainname, msgid, LC_MESSAGES)
  ngettext    (msgid, msgid_plural, count)
  dngettext   (domainname, msgid, msgid_plural, count)
  dcngettext  (domainname, msgid, msgid_plural, count, LC_MESSAGES)
  pgettext    (msgctxt, msgid)
  dpgettext   (domainname, msgctxt, msgid)
  dcpgettext  (domainname, msgctxt, msgid, LC_MESSAGES)
  npgettext   (msgctxt, msgid, msgid_plural, count)
  dnpgettext  (domainname, msgctxt, msgid, msgid_plural, count)
  dcnpgettext (domainname, msgctxt, msgid, msgid_plural, count, LC_MESSAGES)
  strargs     (string, args_array)


=head2 new Gettext (args)

Several methods of loading locale data are included. You may specify a plugin or alternative method of loading data by passing the data in as the "locale_data" option. For example:

    var get_locale_data = function () {
        // plugin does whatever to populate locale_data
        return locale_data;
    };
    var gt = new Gettext( 'domain' : 'messages',
                          'locale_data' : get_locale_data() );

The above can also be used if locale data is specified in a statically included <SCRIPT> tag. Just specify the variable name in the call to new. Ex:

    var gt = new Gettext( 'domain' : 'messages',
                          'locale_data' : json_locale_data_variable );

Finally, you may load the locale data by referencing it in a <LINK> tag. Simply exclude the 'locale_data' option, and all <LINK rel="gettext" ...> items will be tried. The <LINK> should be specified as:

    <link rel="gettext" type="application/json" href="/path/to/file.json">
    <link rel="gettext" type="text/javascript"  href="/path/to/file.json">
    <link rel="gettext" type="application/x-po" href="/path/to/file.po">
    <link rel="gettext" type="application/x-mo" href="/path/to/file.mo">

args:

=over

=item domain

The Gettext domain, not www.whatev.com. It's usually your applications basename. If the .po file was "myapp.po", this would be "myapp".

=item locale_data

Raw locale data (in json structure). If specified, from_link data will be ignored.

=back

=cut

*/

Gettext = function (args) {
    this.domain         = 'messages';
    // locale_data will be populated from <link...> if not specified in args
    this.locale_data    = undefined;

    // set options
    var options = [ "domain", "locale_data" ];
    if (this.isValidObject(args)) {
        for (var i in args) {
            for (var j=0; j<options.length; j++) {
                if (i == options[j]) {
                    // don't set it if it's null or undefined
                    if (this.isValidObject(args[i]))
                        this[i] = args[i];
                }
            }
        }
    }


    // try to load the lang file from somewhere
    this.try_load_lang();

    return this;
}

Gettext.context_glue = "\004";
Gettext._locale_data = {};

Gettext.prototype.try_load_lang = function() {
    // check to see if language is statically included
    if (typeof(this.locale_data) != 'undefined') {
        // we're going to reformat it, and overwrite the variable
        var locale_copy = this.locale_data;
        this.locale_data = undefined;
        this.parse_locale_data(locale_copy);

        if (typeof(Gettext._locale_data[this.domain]) == 'undefined') {
            throw new Error("Error: Gettext 'locale_data' does not contain the domain '"+this.domain+"'");
        }
    }


    // try loading from JSON
    // get lang links
    var lang_link = this.get_lang_refs();

    if (typeof(lang_link) == 'object' && lang_link.length > 0) {
        // NOTE: there will be a delay here, as this is async.
        // So, any i18n calls made right after page load may not
        // get translated.
        // XXX: we may want to see if we can "fix" this behavior
        for (var i=0; i<lang_link.length; i++) {
            var link = lang_link[i];
            if (link.type == 'application/json') {
                if (! this.try_load_lang_json(link.href) ) {
                    throw new Error("Error: Gettext 'try_load_lang_json' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
                }
            } else if (link.type == 'application/x-po') {
                if (! this.try_load_lang_po(link.href) ) {
                    throw new Error("Error: Gettext 'try_load_lang_po' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
                }
            } else {
                // TODO: implement the other types (.mo)
                throw new Error("TODO: link type ["+link.type+"] found, and support is planned, but not implemented at this time.");
            }
        }
    }
};

// This takes the bin/po2json'd data, and moves it into an internal form
// for use in our lib, and puts it in our object as:
//  Gettext._locale_data = {
//      domain : {
//          head : { headfield : headvalue },
//          msgs : {
//              msgid : [ msgid_plural, msgstr, msgstr_plural ],
//          },
Gettext.prototype.parse_locale_data = function(locale_data) {
    if (typeof(Gettext._locale_data) == 'undefined') {
        Gettext._locale_data = { };
    }

    // suck in every domain defined in the supplied data
    for (var domain in locale_data) {
        // skip empty specs (flexibly)
        if ((! locale_data.hasOwnProperty(domain)) || (! this.isValidObject(locale_data[domain])))
            continue;
        // skip if it has no msgid's
        var has_msgids = false;
        for (var msgid in locale_data[domain]) {
            has_msgids = true;
            break;
        }
        if (! has_msgids) continue;

        // grab shortcut to data
        var data = locale_data[domain];

        // if they specifcy a blank domain, default to "messages"
        if (domain == "") domain = "messages";
        // init the data structure
        if (! this.isValidObject(Gettext._locale_data[domain]) )
            Gettext._locale_data[domain] = { };
        if (! this.isValidObject(Gettext._locale_data[domain].head) )
            Gettext._locale_data[domain].head = { };
        if (! this.isValidObject(Gettext._locale_data[domain].msgs) )
            Gettext._locale_data[domain].msgs = { };

        for (var key in data) {
            if (key == "") {
                var header = data[key];
                for (var head in header) {
                    var h = head.toLowerCase();
                    Gettext._locale_data[domain].head[h] = header[head];
                }
            } else {
                Gettext._locale_data[domain].msgs[key] = data[key];
            }
        }
    }

    // build the plural forms function
    for (var domain in Gettext._locale_data) {
        if (this.isValidObject(Gettext._locale_data[domain].head['plural-forms']) &&
            typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
            // untaint data
            var plural_forms = Gettext._locale_data[domain].head['plural-forms'];
            var pf_re = new RegExp('^(\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;a-zA-Z0-9_\(\)])+)', 'm');
            if (pf_re.test(plural_forms)) {
                //ex english: "Plural-Forms: nplurals=2; plural=(n != 1);\n"
                //pf = "nplurals=2; plural=(n != 1);";
                //ex russian: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)
                //pf = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)";

                var pf = Gettext._locale_data[domain].head['plural-forms'];
                if (! /;\s*$/.test(pf)) pf = pf.concat(';');
                /* We used to use eval, but it seems IE has issues with it.
                 * We now use "new Function", though it carries a slightly
                 * bigger performance hit.
                var code = 'function (n) { var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) }; };';
                Gettext._locale_data[domain].head.plural_func = eval("("+code+")");
                */
                var code = 'var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) };';
                Gettext._locale_data[domain].head.plural_func = new Function("n", code);
            } else {
                throw new Error("Syntax error in language file. Plural-Forms header is invalid ["+plural_forms+"]");
            }   

        // default to english plural form
        } else if (typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
            Gettext._locale_data[domain].head.plural_func = function (n) {
                var p = (n != 1) ? 1 : 0;
                return { 'nplural' : 2, 'plural' : p };
                };
        } // else, plural_func already created
    }

    return;
};


// try_load_lang_po : do an ajaxy call to load in the .po lang defs
Gettext.prototype.try_load_lang_po = function(uri) {
    var data = this.sjax(uri);
    if (! data) return;

    var domain = this.uri_basename(uri);
    var parsed = this.parse_po(data);

    var rv = {};
    // munge domain into/outof header
    if (parsed) {
        if (! parsed[""]) parsed[""] = {};
        if (! parsed[""]["domain"]) parsed[""]["domain"] = domain;
        domain = parsed[""]["domain"];
        rv[domain] = parsed;

        this.parse_locale_data(rv);
    }

    return 1;
};

Gettext.prototype.uri_basename = function(uri) {
    var rv;
    if (rv = uri.match(/^(.*\/)?(.*)/)) {
        var ext_strip;
        if (ext_strip = rv[2].match(/^(.*)\..+$/))
            return ext_strip[1];
        else
            return rv[2];
    } else {
        return "";
    }
};

Gettext.prototype.parse_po = function(data) {
    var rv = {};
    var buffer = {};
    var lastbuffer = "";
    var errors = [];
    var lines = data.split("\n");
    for (var i=0; i<lines.length; i++) {
        // chomp
        lines[i] = lines[i].replace(/(\n|\r)+$/, '');

        var match;

        // Empty line / End of an entry.
        if (/^$/.test(lines[i])) {
            if (typeof(buffer['msgid']) != 'undefined') {
                var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
                                   buffer['msgctxt'].length) ?
                                  buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
                                  buffer['msgid'];
                var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
                                    buffer['msgid_plural'].length) ?
                                   buffer['msgid_plural'] :
                                   null;

                // find msgstr_* translations and push them on
                var trans = [];
                for (var str in buffer) {
                    var match;
                    if (match = str.match(/^msgstr_(\d+)/))
                        trans[parseInt(match[1])] = buffer[str];
                }
                trans.unshift(msgid_plural);

                // only add it if we've got a translation
                // NOTE: this doesn't conform to msgfmt specs
                if (trans.length > 1) rv[msg_ctxt_id] = trans;

                buffer = {};
                lastbuffer = "";
            }

        // comments
        } else if (/^#/.test(lines[i])) {
            continue;

        // msgctxt
        } else if (match = lines[i].match(/^msgctxt\s+(.*)/)) {
            lastbuffer = 'msgctxt';
            buffer[lastbuffer] = this.parse_po_dequote(match[1]);

        // msgid
        } else if (match = lines[i].match(/^msgid\s+(.*)/)) {
            lastbuffer = 'msgid';
            buffer[lastbuffer] = this.parse_po_dequote(match[1]);

        // msgid_plural
        } else if (match = lines[i].match(/^msgid_plural\s+(.*)/)) {
            lastbuffer = 'msgid_plural';
            buffer[lastbuffer] = this.parse_po_dequote(match[1]);

        // msgstr
        } else if (match = lines[i].match(/^msgstr\s+(.*)/)) {
            lastbuffer = 'msgstr_0';
            buffer[lastbuffer] = this.parse_po_dequote(match[1]);

        // msgstr[0] (treak like msgstr)
        } else if (match = lines[i].match(/^msgstr\[0\]\s+(.*)/)) {
            lastbuffer = 'msgstr_0';
            buffer[lastbuffer] = this.parse_po_dequote(match[1]);

        // msgstr[n]
        } else if (match = lines[i].match(/^msgstr\[(\d+)\]\s+(.*)/)) {
            lastbuffer = 'msgstr_'+match[1];
            buffer[lastbuffer] = this.parse_po_dequote(match[2]);

        // continued string
        } else if (/^"/.test(lines[i])) {
            buffer[lastbuffer] += this.parse_po_dequote(lines[i]);

        // something strange
        } else {
            errors.push("Strange line ["+i+"] : "+lines[i]);
        }
    }


    // handle the final entry
    if (typeof(buffer['msgid']) != 'undefined') {
        var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
                           buffer['msgctxt'].length) ?
                          buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
                          buffer['msgid'];
        var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
                            buffer['msgid_plural'].length) ?
                           buffer['msgid_plural'] :
                           null;

        // find msgstr_* translations and push them on
        var trans = [];
        for (var str in buffer) {
            var match;
            if (match = str.match(/^msgstr_(\d+)/))
                trans[parseInt(match[1])] = buffer[str];
        }
        trans.unshift(msgid_plural);

        // only add it if we've got a translation
        // NOTE: this doesn't conform to msgfmt specs
        if (trans.length > 1) rv[msg_ctxt_id] = trans;

        buffer = {};
        lastbuffer = "";
    }


    // parse out the header
    if (rv[""] && rv[""][1]) {
        var cur = {};
        var hlines = rv[""][1].split(/\\n/);
        for (var i=0; i<hlines.length; i++) {
            if (! hlines.length) continue;

            var pos = hlines[i].indexOf(':', 0);
            if (pos != -1) {
                var key = hlines[i].substring(0, pos);
                var val = hlines[i].substring(pos +1);
                var keylow = key.toLowerCase();

                if (cur[keylow] && cur[keylow].length) {
                    errors.push("SKIPPING DUPLICATE HEADER LINE: "+hlines[i]);
                } else if (/#-#-#-#-#/.test(keylow)) {
                    errors.push("SKIPPING ERROR MARKER IN HEADER: "+hlines[i]);
                } else {
                    // remove begining spaces if any
                    val = val.replace(/^\s+/, '');
                    cur[keylow] = val;
                }

            } else {
                errors.push("PROBLEM LINE IN HEADER: "+hlines[i]);
                cur[hlines[i]] = '';
            }
        }

        // replace header string with assoc array
        rv[""] = cur;
    } else {
        rv[""] = {};
    }

    // TODO: XXX: if there are errors parsing, what do we want to do?
    // GNU Gettext silently ignores errors. So will we.
    // alert( "Errors parsing po file:\n" + errors.join("\n") );

    return rv;
};


Gettext.prototype.parse_po_dequote = function(str) {
    var match;
    if (match = str.match(/^"(.*)"/)) {
        str = match[1];
    }
    // unescale all embedded quotes (fixes bug #17504)
    str = str.replace(/\\"/g, "\"");
    return str;
};


// try_load_lang_json : do an ajaxy call to load in the lang defs
Gettext.prototype.try_load_lang_json = function(uri) {
    var data = this.sjax(uri);
    if (! data) return;

    var rv = this.JSON(data);
    this.parse_locale_data(rv);

    return 1;
};

// this finds all <link> tags, filters out ones that match our
// specs, and returns a list of hashes of those
Gettext.prototype.get_lang_refs = function() {
    var langs = new Array();
    var links = document.getElementsByTagName("link");
    // find all <link> tags in dom; filter ours
    for (var i=0; i<links.length; i++) {
        if (links[i].rel == 'gettext' && links[i].href) {
            if (typeof(links[i].type) == 'undefined' ||
                links[i].type == '') {
                if (/\.json$/i.test(links[i].href)) {
                    links[i].type = 'application/json';
                } else if (/\.js$/i.test(links[i].href)) {
                    links[i].type = 'application/json';
                } else if (/\.po$/i.test(links[i].href)) {
                    links[i].type = 'application/x-po';
                } else if (/\.mo$/i.test(links[i].href)) {
                    links[i].type = 'application/x-mo';
                } else {
                    throw new Error("LINK tag with rel=gettext found, but the type and extension are unrecognized.");
                }
            }

            links[i].type = links[i].type.toLowerCase();
            if (links[i].type == 'application/json') {
                links[i].type = 'application/json';
            } else if (links[i].type == 'text/javascript') {
                links[i].type = 'application/json';
            } else if (links[i].type == 'application/x-po') {
                links[i].type = 'application/x-po';
            } else if (links[i].type == 'application/x-mo') {
                links[i].type = 'application/x-mo';
            } else {
                throw new Error("LINK tag with rel=gettext found, but the type attribute ["+links[i].type+"] is unrecognized.");
            }

            langs.push(links[i]);
        }
    }
    return langs;
};


/*

=head2 textdomain( domain )

Set domain for future gettext() calls

A  message  domain  is  a  set of translatable msgid messages. Usually,
every software package has its own message domain. The domain  name  is
used to determine the message catalog where a translation is looked up;
it must be a non-empty string.

The current message domain is used by the gettext, ngettext, pgettext,
npgettext functions, and by the dgettext, dcgettext, dngettext, dcngettext,
dpgettext, dcpgettext, dnpgettext and dcnpgettext functions when called
with a NULL domainname argument.

If domainname is not NULL, the current message domain is set to
domainname.

If domainname is undefined, null, or empty string, the function returns
the current message domain.

If  successful,  the  textdomain  function  returns the current message
domain, after possibly changing it. (ie. if you set a new domain, the 
value returned will NOT be the previous domain).

=cut

*/
Gettext.prototype.textdomain = function (domain) {
    if (domain && domain.length) this.domain = domain;
    return this.domain;
}

/*

=head2 gettext( MSGID )

Returns the translation for B<MSGID>.  Example:

    alert( gt.gettext("Hello World!\n") );

If no translation can be found, the unmodified B<MSGID> is returned,
i. e. the function can I<never> fail, and will I<never> mess up your
original message.

One common mistake is to interpolate a variable into the string like this:

  var translated = gt.gettext("Hello " + full_name);

The interpolation will happen before it's passed to gettext, and it's 
unlikely you'll have a translation for every "Hello Tom" and "Hello Dick"
and "Hellow Harry" that may arise.

Use C<strargs()> (see below) to solve this problem:

  var translated = Gettext.strargs( gt.gettext("Hello %1"), [full_name] );

This is espeically useful when multiple replacements are needed, as they 
may not appear in the same order within the translation. As an English to
French example:

  Expected result: "This is the red ball"
  English: "This is the %1 %2"
  French:  "C'est le %2 %1"
  Code: Gettext.strargs( gt.gettext("This is the %1 %2"), ["red", "ball"] );

(The example is stupid because neither color nor thing will get
translated here ...).

=head2 dgettext( TEXTDOMAIN, MSGID )

Like gettext(), but retrieves the message for the specified 
B<TEXTDOMAIN> instead of the default domain.  In case you wonder what
a textdomain is, see above section on the textdomain() call.

=head2 dcgettext( TEXTDOMAIN, MSGID, CATEGORY )

Like dgettext() but retrieves the message from the specified B<CATEGORY>
instead of the default category C<LC_MESSAGES>.

NOTE: the categories are really useless in javascript context. This is
here for GNU Gettext API compatability. In practice, you'll never need
to use this. This applies to all the calls including the B<CATEGORY>.


=head2 ngettext( MSGID, MSGID_PLURAL, COUNT )

Retrieves the correct translation for B<COUNT> items.  In legacy software
you will often find something like:

    alert( count + " file(s) deleted.\n" );

or

    printf(count + " file%s deleted.\n", $count == 1 ? '' : 's');

I<NOTE: javascript lacks a builtin printf, so the above isn't a working example>

The first example looks awkward, the second will only work in English
and languages with similar plural rules.  Before ngettext() was introduced,
the best practice for internationalized programs was:

    if (count == 1) {
        alert( gettext("One file deleted.\n") );
    } else {
        printf( gettext("%d files deleted.\n"), count );
    }

This is a nuisance for the programmer and often still not sufficient
for an adequate translation.  Many languages have completely different
ideas on numerals.  Some (French, Italian, ...) treat 0 and 1 alike,
others make no distinction at all (Japanese, Korean, Chinese, ...),
others have two or more plural forms (Russian, Latvian, Czech,
Polish, ...).  The solution is:

    printf( ngettext("One file deleted.\n",
                     "%d files deleted.\n",
                     count), // argument to ngettext!
            count);          // argument to printf!

In English, or if no translation can be found, the first argument
(B<MSGID>) is picked if C<count> is one, the second one otherwise.
For other languages, the correct plural form (of 1, 2, 3, 4, ...)
is automatically picked, too.  You don't have to know anything about
the plural rules in the target language, ngettext() will take care
of that.

This is most of the time sufficient but you will have to prove your
creativity in cases like

    "%d file(s) deleted, and %d file(s) created.\n"

That said, javascript lacks C<printf()> support. Supplied with Gettext.js
is the C<strargs()> method, which can be used for these cases:

    Gettext.strargs( gt.ngettext( "One file deleted.\n",
                                  "%d files deleted.\n",
                                  count), // argument to ngettext!
                     count); // argument to strargs!

NOTE: the variable replacement isn't done for you, so you must
do it yourself as in the above.

=head2 dngettext( TEXTDOMAIN, MSGID, MSGID_PLURAL, COUNT )

Like ngettext() but retrieves the translation from the specified
textdomain instead of the default domain.

=head2 dcngettext( TEXTDOMAIN, MSGID, MSGID_PLURAL, COUNT, CATEGORY )

Like dngettext() but retrieves the translation from the specified
category, instead of the default category C<LC_MESSAGES>.


=head2 pgettext( MSGCTXT, MSGID )

Returns the translation of MSGID, given the context of MSGCTXT.

Both items are used as a unique key into the message catalog.

This allows the translator to have two entries for words that may
translate to different foreign words based on their context. For
example, the word "View" may be a noun or a verb, which may be
used in a menu as File->View or View->Source.

    alert( pgettext( "Verb: To View", "View" ) );
    alert( pgettext( "Noun: A View", "View"  ) );

The above will both lookup different entries in the message catalog.

In English, or if no translation can be found, the second argument
(B<MSGID>) is returned.

=head2 dpgettext( TEXTDOMAIN, MSGCTXT, MSGID )

Like pgettext(), but retrieves the message for the specified 
B<TEXTDOMAIN> instead of the default domain.

=head2 dcpgettext( TEXTDOMAIN, MSGCTXT, MSGID, CATEGORY )

Like dpgettext() but retrieves the message from the specified B<CATEGORY>
instead of the default category C<LC_MESSAGES>.


=head2 npgettext( MSGCTXT, MSGID, MSGID_PLURAL, COUNT )

Like ngettext() with the addition of context as in pgettext().

In English, or if no translation can be found, the second argument
(MSGID) is picked if B<COUNT> is one, the third one otherwise.

=head2 dnpgettext( TEXTDOMAIN, MSGCTXT, MSGID, MSGID_PLURAL, COUNT )

Like npgettext() but retrieves the translation from the specified
textdomain instead of the default domain.

=head2 dcnpgettext( TEXTDOMAIN, MSGCTXT, MSGID, MSGID_PLURAL, COUNT, CATEGORY )

Like dnpgettext() but retrieves the translation from the specified
category, instead of the default category C<LC_MESSAGES>.

=cut

*/

// gettext
Gettext.prototype.gettext = function (msgid) {
    var msgctxt;
    var msgid_plural;
    var n;
    var category;
    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
};

Gettext.prototype.dgettext = function (domain, msgid) {
    var msgctxt;
    var msgid_plural;
    var n;
    var category;
    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
};

Gettext.prototype.dcgettext = function (domain, msgid, category) {
    var msgctxt;
    var msgid_plural;
    var n;
    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
};

// ngettext
Gettext.prototype.ngettext = function (msgid, msgid_plural, n) {
    var msgctxt;
    var category;
    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
};

Gettext.prototype.dngettext = function (domain, msgid, msgid_plural, n) {
    var msgctxt;
    var category;
    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
};

Gettext.prototype.dcngettext = function (domain, msgid, msgid_plural, n, category) {
    var msgctxt;
    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category, category);
};

// pgettext
Gettext.prototype.pgettext = function (msgctxt, msgid) {
    var msgid_plural;
    var n;
    var category;
    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
};

Gettext.prototype.dpgettext = function (domain, msgctxt, msgid) {
    var msgid_plural;
    var n;
    var category;
    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
};

Gettext.prototype.dcpgettext = function (domain, msgctxt, msgid, category) {
    var msgid_plural;
    var n;
    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
};

// npgettext
Gettext.prototype.npgettext = function (msgctxt, msgid, msgid_plural, n) {
    var category;
    return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
};

Gettext.prototype.dnpgettext = function (domain, msgctxt, msgid, msgid_plural, n) {
    var category;
    return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
};

// this has all the options, so we use it for all of them.
Gettext.prototype.dcnpgettext = function (domain, msgctxt, msgid, msgid_plural, n, category) {
    if (! this.isValidObject(msgid)) return '';

    var plural = this.isValidObject(msgid_plural);
    var msg_ctxt_id = this.isValidObject(msgctxt) ? msgctxt+Gettext.context_glue+msgid : msgid;

    var domainname = this.isValidObject(domain)      ? domain :
                     this.isValidObject(this.domain) ? this.domain :
                                                       'messages';

	// category is always LC_MESSAGES. We ignore all else
    var category_name = 'LC_MESSAGES';
    var category = 5;
	
	
	
    var locale_data = new Array();
    if (typeof(Gettext._locale_data) != 'undefined' &&
        this.isValidObject(Gettext._locale_data[domainname])) {
        locale_data.push( Gettext._locale_data[domainname] );

    } else if (typeof(Gettext._locale_data) != 'undefined') {
        // didn't find domain we're looking for. Search all of them.
        for (var dom in Gettext._locale_data) {
            locale_data.push( Gettext._locale_data[dom] );
        }
    }
	
	
    var trans = [];
    var found = false;
    var domain_used; // so we can find plural-forms if needed
    if (locale_data.length) {
        for (var i=0; i<locale_data.length; i++) {
            var locale = locale_data[i];
            if (this.isValidObject(locale.msgs[msg_ctxt_id])) {
                // make copy of that array (cause we'll be destructive)
                for (var j=0; j<locale.msgs[msg_ctxt_id].length; j++) {
                    trans[j] = locale.msgs[msg_ctxt_id][j];
                }
                trans.shift(); // throw away the msgid_plural
                domain_used = locale;
                found = true;
                // only break if found translation actually has a translation.
                if ( trans.length > 0 && trans[0].length != 0 )
                    break;
            }
        }
    }

    // default to english if we lack a match, or match has zero length
    if ( trans.length == 0 || trans[0].length == 0 ) {
        trans = [ msgid, msgid_plural ];
    }

    var translation = trans[0];
    if (plural) {
        var p;
        if (found && this.isValidObject(domain_used.head.plural_func) ) {
            var rv = domain_used.head.plural_func(n);
            if (! rv.plural) rv.plural = 0;
            if (! rv.nplural) rv.nplural = 0;
            // if plurals returned is out of bound for total plural forms
            if (rv.nplural <= rv.plural) rv.plural = 0;
            p = rv.plural;
        } else {
            p = (n != 1) ? 1 : 0;
        }
        if (this.isValidObject(trans[p]))
            translation = trans[p];
    }

    return translation;
};


/*

=head2 strargs (string, argument_array)

  string : a string that potentially contains formatting characters.
  argument_array : an array of positional replacement values

This is a utility method to provide some way to support positional parameters within a string, as javascript lacks a printf() method.

The format is similar to printf(), but greatly simplified (ie. fewer features).

Any percent signs followed by numbers are replaced with the corrosponding item from the B<argument_array>.

Example:

    var string = "%2 roses are red, %1 violets are blue";
    var args   = new Array("10", "15");
    var result = Gettext.strargs(string, args);
    // result is "15 roses are red, 10 violets are blue"

The format numbers are 1 based, so the first itme is %1.

A lone percent sign may be escaped by preceeding it with another percent sign.

A percent sign followed by anything other than a number or another percent sign will be passed through as is.

Some more examples should clear up any abmiguity. The following were called with the orig string, and the array as Array("[one]", "[two]") :

  orig string "blah" becomes "blah"
  orig string "" becomes ""
  orig string "%%" becomes "%"
  orig string "%%%" becomes "%%"
  orig string "%%%%" becomes "%%"
  orig string "%%%%%" becomes "%%%"
  orig string "tom%%dick" becomes "tom%dick"
  orig string "thing%1bob" becomes "thing[one]bob"
  orig string "thing%1%2bob" becomes "thing[one][two]bob"
  orig string "thing%1asdf%2asdf" becomes "thing[one]asdf[two]asdf"
  orig string "%1%2%3" becomes "[one][two]"
  orig string "tom%1%%2%aDick" becomes "tom[one]%2%aDick"

This is especially useful when using plurals, as the string will nearly always contain the number.

It's also useful in translated strings where the translator may have needed to move the position of the parameters.

For example:

  var count = 14;
  Gettext.strargs( gt.ngettext('one banana', '%1 bananas', count), [count] );

NOTE: this may be called as an instance method, or as a class method.

  // instance method:
  var gt = new Gettext(params);
  gt.strargs(string, args);

  // class method:
  Gettext.strargs(string, args);

=cut

*/
/* utility method, since javascript lacks a printf */
Gettext.strargs = function (str, args) {
    // make sure args is an array
    if ( null == args ||
         'undefined' == typeof(args) ) {
        args = [];
    } else if (args.constructor != Array) {
        args = [args];
    }

    // NOTE: javascript lacks support for zero length negative look-behind
    // in regex, so we must step through w/ index.
    // The perl equiv would simply be:
    //    $string =~ s/(?<!\%)\%([0-9]+)/$args[$1]/g;
    //    $string =~ s/\%\%/\%/g; # restore escaped percent signs

    var newstr = "";
    while (true) {
        var i = str.indexOf('%');
        var match_n;

        // no more found. Append whatever remains
        if (i == -1) {
            newstr += str;
            break;
        }

        // we found it, append everything up to that
        newstr += str.substr(0, i);

        // check for escpaed %%
        if (str.substr(i, 2) == '%%') {
            newstr += '%';
            str = str.substr((i+2));

        // % followed by number
        } else if ( match_n = str.substr(i).match(/^%(\d+)/) ) {
            var arg_n = parseInt(match_n[1]);
            var length_n = match_n[1].length;
            if ( arg_n > 0 && args[arg_n -1] != null && typeof(args[arg_n -1]) != 'undefined' )
                newstr += args[arg_n -1];
            str = str.substr( (i + 1 + length_n) );

        // % followed by some other garbage - just remove the %
        } else {
            newstr += '%';
            str = str.substr((i+1));
        }
    }

    return newstr;
}

/* instance method wrapper of strargs */
Gettext.prototype.strargs = function (str, args) {
    return Gettext.strargs(str, args);
}

/* verify that something is an array */
Gettext.prototype.isArray = function (thisObject) {
    return this.isValidObject(thisObject) && thisObject.constructor == Array;
};

/* verify that an object exists and is valid */
Gettext.prototype.isValidObject = function (thisObject) {
    if (null == thisObject) {
        return false;
    } else if ('undefined' == typeof(thisObject) ) {
        return false;
    } else {
        return true;
    }
};

Gettext.prototype.sjax = function (uri) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    if (! xmlhttp)
        throw new Error("Your browser doesn't do Ajax. Unable to support external language files.");

    xmlhttp.open('GET', uri, false);
    try { xmlhttp.send(null); }
    catch (e) { return; }

    // we consider status 200 and 0 as ok.
    // 0 happens when we request local file, allowing this to run on local files
    var sjax_status = xmlhttp.status;
    if (sjax_status == 200 || sjax_status == 0) {
        return xmlhttp.responseText;
    } else {
        var error = xmlhttp.statusText + " (Error " + xmlhttp.status + ")";
        if (xmlhttp.responseText.length) {
            error += "\n" + xmlhttp.responseText;
        }
        alert(error);
        return;
    }
}

Gettext.prototype.JSON = function (data) {
    return eval('(' + data + ')');
}


/*

=head1 NOTES

These are some notes on the internals

=over

=item LOCALE CACHING

Loaded locale data is currently cached class-wide. This means that if two scripts are both using Gettext.js, and both share the same gettext domain, that domain will only be loaded once. This will allow you to grab a new object many times from different places, utilize the same domain, and share a single translation file. The downside is that a domain won't be RE-loaded if a new object is instantiated on a domain that had already been instantiated.

=back

=head1 BUGS / TODO

=over

=item error handling

Currently, there are several places that throw errors. In GNU Gettext, there are no fatal errors, which allows text to still be displayed regardless of how broken the environment becomes. We should evaluate and determine where we want to stand on that issue.

=item syncronous only support (no ajax support)

Currently, fetching language data is done purely syncronous, which means the page will halt while those files are fetched/loaded.

This is often what you want, as then following translation requests will actually be translated. However, if all your calls are done dynamically (ie. error handling only or something), loading in the background may be more adventagous.

It's still recommended to use the statically defined <script ...> method, which should have the same delay, but it will cache the result.

=item domain support

domain support while using shortcut methods like C<_('string')> or C<i18n('string')>.

Under normal apps, the domain is usually set globally to the app, and a single language file is used. Under javascript, you may have multiple libraries or applications needing translation support, but the namespace is essentially global.

It's recommended that your app initialize it's own shortcut with it's own domain.  (See examples/wrapper/i18n.js for an example.)

Basically, you'll want to accomplish something like this:

    // in some other .js file that needs i18n
    this.i18nObj = new i18n;
    this.i18n = this.i18nObj.init('domain');
    // do translation
    alert( this.i18n("string") );

If you use this raw Gettext object, then this is all handled for you, as you have your own object then, and will be calling C<myGettextObject.gettext('string')> and such.


=item encoding

May want to add encoding/reencoding stuff. See GNU iconv, or the perl module Locale::Recode from libintl-perl.

=back


=head1 COMPATABILITY

This has been tested on the following browsers. It may work on others, but these are all those to which I have access.

    FF1.5, FF2, FF3, IE6, IE7, Opera9, Opera10, Safari3.1, Chrome

    *FF = Firefox
    *IE = Internet Explorer


=head1 REQUIRES

bin/po2json requires perl, and the perl modules Locale::PO and JSON.

=head1 SEE ALSO

bin/po2json (included),
examples/normal/index.html,
examples/wrapper/i18n.html, examples/wrapper/i18n.js,
Locale::gettext_pp(3pm), POSIX(3pm), gettext(1), gettext(3)

=head1 AUTHOR

Copyright (C) 2008, Joshua I. Miller E<lt>unrtst@cpan.orgE<gt>, all rights reserved. See the source code for details.

=cut

*/

;

/** WB Builder **/
(window.defineModule = (window.defineModule || {})).name = 'WB Builder';

define('Builder', [
	'ElementRegister',
	'PluginApi/UIManager',
	'Service',
	'UserInput',
	'SiteLoader',
	'Site',
	'Body',
	'Preloader',
	'Dialog',
	'MsgDialog',
	'Confirm',
	'UIButton',
	'util/MenuList',
	'ComboBox',
	'BorderControl',
	'HelpSystem/HelpSystemPlayer',
	'HelpSystem/HelpOverlay',
	'WidgetToolbar',
	'MobileToolbar',
	'ModeManager',
	'LayoutManager',
	'DragNDropZone',
	'PreviewToolbar',
	'AlertBox',
	'PremiumButton',
	'ElementBox',
	'RemoteLoginDialog',
	'NotificationRibbon',
	'TemplateChooser',
	'FontManager',
	'LangInputControl',
	'WebsiteImporter',
	'BuilderEvent',
	'Guides'
], function(ElementRegister, UIManager, Service, UserInput, SiteLoader, Site, Body, Preloader, Dialog, MsgDialog, Confirm, UIButton,
			MenuList, ComboBox, BorderControl, HelpSystemPlayer, HelpOverlay, WidgetToolbar, MobileToolbar, ModeManager,
			LayoutManager, DragNDropZone, PreviewToolbar, AlertBox, PremiumButton,
			ElementBox, RemoteLoginDialog, NotificationRibbon, TemplateChooser, FontManager, LangInputControl, WebsiteImporter, BuilderEvent, Guides) {
	'use strict';
	
	/**
	 * Website builder main class
	 * @class
	 */
	var Builder = function() { this.__construct(); };

	Builder.isset = function(v) {
		return !(typeof(v) === "undefined" || v === null);
	};
	Builder.arrayUnique = function(arr) {
		var u = {}, a = [];
		for (var i = 0, l = arr.length; i < l; ++i) {
			if (u.hasOwnProperty(arr[i])) {
				continue;
			}
			a.push(arr[i]);
			u[arr[i]] = 1;
		}
		return a;
	};
	Builder.urlEncode = function(url, quotes) {
		var url_ = encodeURI(url).replace(/\(/g, "%28").replace(/\)/g, "%29");
		if (quotes) {
			url_ = url_.replace(/\'/g, "%27");
		}
		return url_;
	};
	Builder.trim = function (str, symbols) {
		var cont = true, a, b, i;
		var symbs = {};
		if (typeof symbols !== 'undefined') {
			symbols = symbols.split('');
		} else {
			symbols = [' '];
		}
		for (i = 0; i < symbols.length; i++) {
			symbs[symbols[i]] = true;
		}
		while (cont) {
			cont = false;
			a = str.substring(0, 1);
			b = str.substring(str.length - 1);
			if (a in symbs) {
				str = str.substring(1);
				cont = true;
			}
			if (b in symbs) {
				str = str.substring(0, str.length - 1);
				cont = true;
			}
		}
		return str;
	};
	
	Builder.prototype.dataInstanceKey = "__WB_CLASS__";
	Builder.prototype.site = null;
	Builder.prototype.body = null;
	Builder.prototype.styleSheet = null;
	Builder.prototype.container = null;
	Builder.prototype.siteCover = null;
	Builder.prototype.gridRenderState = null;
	Builder.prototype.gridSize = 10;
	Builder.prototype.gridColor = "rgba(0, 0, 0, 0.3)";
	Builder.prototype.showLayout = true;
	Builder.prototype.showGrid = false;
	Builder.prototype.showGuides = false;
	Builder.prototype.showMeasurementHelpers = true;
	Builder.prototype.snapToGrid = true;
	Builder.prototype.snapToGuides = true;
	Builder.prototype.snapToObjects = true;
	Builder.prototype.clipboard = null;
	Builder.prototype.historyStack = null;
	Builder.prototype.historyPointer = 0;
	Builder.prototype.historyOnChange = null;

	/** @type Body */
	Builder.prototype.bodyInstance = null;
	Builder.prototype.classList = null;
	Builder.prototype.elementList = null;
	Builder.prototype.pageModified = false;
	Builder.prototype.elemntQueue = null;
	Builder.prototype.preloader = null;
	Builder.prototype.msgDlg = null;
	Builder.prototype.staticMsgDlg = null;
	Builder.prototype.previewWindow = null;

	Builder.prototype.isModRewrite = true;
	Builder.prototype.routeGetKey = "route";
	Builder.prototype.baseUrl = "";
	Builder.prototype.lnBaseUrl = "";
	Builder.prototype.loadPageUrl = "";
	Builder.prototype.publishUrl = "";
	Builder.prototype.previewUrl = "";
	Builder.prototype.resetUrl = "";
	Builder.prototype.buyProUrl = "";
	Builder.prototype.reportUrl = "";
	Builder.prototype.tplBaseUrl = "";
	Builder.prototype.modBaseUrl = "";
	Builder.prototype.userBaseUrl = "";
	Builder.prototype.userGalleyUrl = "";
	Builder.prototype.helpUrl = null;
	Builder.prototype.availableFontsUrl = "";
	Builder.prototype.fontThumbsUrl = "";
	Builder.prototype.favicon = null;
	/**
	 * Currently opened page id
	 * @type Number
	 */
	Builder.prototype.pageId = null;
	Builder.prototype.template = null;
	/**
	 * Builder locale code (ex. en_US)
	 * @type String
	 */
	Builder.prototype.locale = null;
	Builder.prototype.meta = null;
	Builder.prototype.excludedElements = null;
	Builder.prototype.pageSelector = null;
	Builder.prototype.isTouchDevice = null;
	Builder.prototype.touchHandler = null;
	Builder.prototype.backupDialog = null;
	Builder.prototype.allowDemoBackup = false;
	Builder.prototype.reloadScrollStyles = null;
	/**
	 * Additional page data to be passed when saving
	 */
	Builder.prototype.pageBlocksData = {};
	Builder.prototype.availableElements = {};
	Builder.prototype.testMode = false;
	Builder.prototype.tinyMode = false;
	Builder.prototype.testSignUpBtn = null;
	Builder.prototype.signUpBtn = null;
	Builder.prototype.isReseller = false;
	Builder.prototype.premiumButtonType = null;
	Builder.prototype.upgradeUrl = null;
	Builder.prototype.commonErrorMessage = null;
	Builder.prototype.isZyro = false;
	/** @type String */
	Builder.prototype.siteDomain = null;
	Builder.prototype.pluginGroups = null;
	Builder.prototype.pluginToolbar = null;
	Builder.prototype.previewToolbar = null;
	Builder.prototype.whiteLabel = null;
	Builder.prototype.enableForcedHttpsPort = false;
	Builder.prototype.mapsConfig = null;
	Builder.prototype.maxMenuItems = 0;
	Builder.prototype.formsAllowed = null;
	Builder.prototype.templateChooser = null;
	Builder.prototype.saveDataProviders = [];
	Builder.prototype.layoutManager = null;
	Builder.prototype.panelUrl = null;
	Builder.prototype.logoutUrl = null;
	/**
	 * Call to verify session (if multiple builders are open)
	 * @type {Function}
	 */
	Builder.prototype.verifySession = null;
	/**
	 * Payment Gateways
	 * @type {Object[]}
	 */
	Builder.prototype.paymentGateways = null;
	/**
	 * If true then builder UI needs to be rendered in right to left reading direction.
	 * @type {Boolean}
	 */
	Builder.prototype.rtl = false;

	Builder.prototype.maxUploadFileSize = 0;
	Builder.prototype.maxUploadImageFileSize = 0;
	Builder.prototype.maxUploadImageSize = 0;
	/**
	 * If true then autp layout mode is enabled else not (by enabled it means that
	 * there will a be button that you can use to enable it).
	 * @type {boolean}
	 */
	Builder.prototype.enableAutoLayout = true;
	/**
	 * Loaded scenario if any.
	 * @type {Scenario}
	 */
	Builder.prototype.helpScenario = null;
	/**
	 * Builders demo mode configuration.
	 * @type {Object|null}
	 */
	Builder.prototype.demoConfig = null;
	/**
	 * Data to be passed to plugins.
	 * @type {Object|null}
	 */
	Builder.prototype.pluginData = null;

	Builder.prototype.hideImport = false;
	Builder.prototype.enableImport = false;

	Builder.prototype.devTestMode = false;
	Builder.prototype.devDebugMode = false;
	Builder.prototype.publishOnLoad = false;
	Builder.prototype.adminMode = false;

	Builder.prototype.helpPlayerVisible = false;

	Builder.prototype.predefinedElementStyles = null;

	/**
	 * Construct website builder
	 */
	Builder.prototype.__construct = function() {
		var thisClass = this;

		/*
		window.onerror = function(message, url, lineNumber) {  
			console.error(message);
			return true;
		};*/

		/**
		 * Set class instance for jQuery selector
		 * @param {Object} instance
		 */
		$.fn.wbSetClassInstance = function(instance) {
			$(this).each(function() {
				$(this).data(thisClass.dataInstanceKey, instance);
			});
		};

		this.isTouchDevice = ('ontouchstart' in document.documentElement) && (
			navigator.userAgent.match(/Android/i)
			|| navigator.userAgent.match(/webOS/i)
			|| navigator.userAgent.match(/iPhone/i)
			|| navigator.userAgent.match(/iPad/i)
			|| navigator.userAgent.match(/iPod/i)
			|| navigator.userAgent.match(/BlackBerry/i)
			|| navigator.userAgent.match(/Windows Phone/i)
			|| navigator.userAgent.match(/Opera Mini/i)
			|| navigator.userAgent.match(/IEMobile/i)
		);

		var val = this.getCookie("wb_showlayout");
		this.showLayout = !Builder.isset(val) || val === "Y"; // true by default

		val = this.getCookie("wb_showgrid");
		if( Builder.isset(val) ) {
			var gridSettings = val.split("/");
			this.showGrid = gridSettings.length > 0 && gridSettings[0] === "Y"; // false by default
			if( gridSettings.length > 1 ) {
				var gridSize = parseInt(gridSettings[1]);
				if( !isNaN(gridSize) )
					this.gridSize = gridSize; // 10 by default
			}
			if( gridSettings.length > 2 )
				this.gridColor = gridSettings[2]; // rgba(0, 0, 0, 0.3) by default
		}

		val = this.getCookie("wb_snapgrid");
		this.snapToGrid = !Builder.isset(val) || val === "Y"; // true by default

		val = this.getCookie("wb_showguides");
		this.showGuides = Builder.isset(val) && val === "Y"; // false by default

		val = this.getCookie("wb_showhelpers");
		this.showMeasurementHelpers = !Builder.isset(val) || val === "Y"; // true by default

		val = this.getCookie("wb_snapguides");
		this.snapToGuides = !Builder.isset(val) || val === "Y"; // true by default

		val = this.getCookie("wb_snapobjects");
		this.snapToObjects = !Builder.isset(val) || val === "Y"; // true by default

		/**
		 * Get class instance from jQuery selector
		 */
		$.fn.wbGetClassInstance = function() {
			return $(this).data(thisClass.dataInstanceKey);
		};

		/**
		 * Get class name from jQuery selector
		 */
		$.fn.wbGetClassName = function() {
			var instance = $(this).data(thisClass.dataInstanceKey);
			return instance ? instance.constructor.name : null;
		};

		$.ui.plugin.add("resizable", "fixresize", {
			isCorner: false,

			start: function(event, ui) {
				this.isCorner = $(event.target).is(".ui-resizable-se, .ui-resizable-sw, .ui-resizable-ne, .ui-resizable-nw");
			},
			resize: function(event, ui) {
				if (!this.isCorner) return;
				var that = $(this).data("resizable");
				that.size.height = that.originalSize.height * that.size.width / that.originalSize.width;
			},
			stop: function(event, ui){
			}
		});

		String.prototype.repeat = function(num) {
			return new Array(num + 1).join(this);
		};

		if (!Object.keys) {
			Object.keys = function(object) {
				if (typeof object !== 'object')
					throw new TypeError('Object.keys called on non-object');
				var keys = [];
				for (var i in object) {
					keys.push(i);
				}
				return keys;
			};
		}
		
		Object.wbCompare = function(obj1, obj2) {
			if (Object.keys(obj1).length == Object.keys(obj2).length) {
				for (var i in obj1) {
					if (obj1[i] != obj2[i]) {
						return false;
					}
				}
				return true;
			}
			return false;
		};

		this.classList = {};
		this.elementList = {};
		this.elemntQueue = [];
		this.excludedElements = [];
		this.historyStack = [];

		UserInput.UserInput.init(document);
		UserInput.UserInput.addHotKey("Ctrl+Z", function() { thisClass.historyUndo(); });
		UserInput.UserInput.addHotKey("Ctrl+Y", function() { thisClass.historyRedo(); });
		
		this.pluginGroups = {};
		this.pluginToolbar = [];
		this.paymentGateways = [];

		this.predefinedElementStyles = {};
	};

	/**
	 * Called on document ready
	 */
	Builder.prototype.init = function() {
		this.rtl = ($('html').eq(0).attr('dir') === 'rtl');
		
		if (typeof this._loadPlugins === 'function') { this._loadPlugins(); }
		NotificationRibbon.init(this);
		HelpOverlay.init(this); // this should be loaded after notification ribbon
		UIManager.init(this);
	};
	
	Builder.prototype.initContinue = function() {
		$.ajax({
			url: this.getUrl("background-update"),
			type: "GET",
			async: true
		});
		
		NotificationRibbon.defaulMessages();
		
		var thisClass = this;
		
		FontManager.FontManager.init(); // init font manager first because it will make an asynchronous ajax request
		
		BuilderEvent.GlobalEvents.on("help.playershow help.playerhide", function(e) {
			thisClass.helpPlayerVisible = e.visible;
			thisClass.updateDropZones();
		});

		// disable on IE, couse it calls this dialog on every a tags click event, even if it is not changing location
		if (!$.browser.msie) {
			window.onbeforeunload = function() {
				if (thisClass.pageModified)
					return __("Are you sure you want to leave");
			};
		}
		
		$(document).bind("click", function(e) {
			thisClass.clearSelections();
			var t = $(e.target);
			if (!t.is('#page_selector *') && thisClass.pageSelector) {
				thisClass.pageSelector.close();
			}
			ComboBox.onDocumentClick(e);
			LangInputControl.onDocumentClick(e);
			BorderControl.onDocumentClick(e);

			e.stopPropagation();
		}).on("show.bs.modal", function() {
			if( !$('.modal:visible').length ) {
				var ea = BuilderEvent.VisibilityChangedBuilderEvent(true);
				BuilderEvent.GlobalEvents.triggerEvent("modal.show", ea);
			}
		}).on("hidden.bs.modal", function() {
			if( !$('.modal:visible').length ) {
				var ea = BuilderEvent.VisibilityChangedBuilderEvent(false);
				BuilderEvent.GlobalEvents.triggerEvent("modal.hide", ea);
			}
		});
		$('.dropdown-toggle').bind('click', function() {
			if (thisClass.pageSelector) thisClass.pageSelector.close();
		});
		
		this.templateChooser = new TemplateChooser();
		

		var styleSheet = $('<style type="text/css" id="wb_style_sheet"></style>');
		$("head").append(styleSheet);
		if (!window.createPopup) { /* For Safari */
		   styleSheet.append(document.createTextNode(''));
		}
		for (var si = 1; si < document.styleSheets.length; si++) {
			var sheet = document.styleSheets[si];
			var sid = sheet.id ? sheet.id : (sheet.ownerNode ? sheet.ownerNode.id : null);
			if (sid === "wb_style_sheet") {
				this.styleSheet = sheet;
				break;
			}
		}

		$(window).resize(function() {
			if (thisClass.bodyInstance) {
				thisClass.highlightLayout(thisClass.showLayout);
			}
		});
		
		this.previewToolbar = PreviewToolbar.init(this);
		
		PremiumButton.init(this);

		this.historyOnChange = function() {
			var ea = new BuilderEvent.HistoryChangedBuilderEvent();
			BuilderEvent.GlobalEvents.triggerEvent("history.changed", ea);
		};
		this.historyOnChange();

		if (thisClass.isTouchDevice) {
			$('*[data-toggle="dropdown"]').on("click", function(e) {
				e.stopPropagation();
			});
			//scrollbar o_0
			var scrollBarTopOffset = 175;
			var scrollBar = $('<div class="wb-scroll-bar hide" id="WB_scrollBar"><div class="wb-scroll-thumb" id="WB_scrollThumb"><span><span></div></div>');
			var scrollThumb = scrollBar.find(".wb-scroll-thumb");

			thisClass.reloadScrollStyles = function() {
				var dh = $(document).height(),
					wh = $(window).height() - scrollBarTopOffset;
				if (dh <= wh) {
					scrollBar.addClass("hide");
				}
				else {
					scrollBar.css('top', scrollBarTopOffset);
					scrollBar.height(wh);
					scrollBar.removeClass("hide");
				}
			};
			var reloadScrollPos = function(e) {
				var dh = $(document).height(),
					wh = $(window).height();

				var m = dh - wh;
				var proc = $(window).scrollTop() / m;

				var max = wh - scrollBarTopOffset - scrollThumb.height();
				scrollThumb.css('top', parseInt(max * proc, 10));
			};
			var touchStart = 0;
			var topStart = 0;
			scrollThumb.on('touchstart', function(e) {
				e.preventDefault();
				var touch = e.originalEvent.touches[0];
				touchStart = touch.clientY;
				topStart = parseInt(scrollThumb.css('top'), 10);
				//log('touch start y:' + touchStart);
			});
			scrollThumb.on('touchmove', function(e) {
				e.preventDefault();
				var touch = e.originalEvent.touches[0];
				var te = touch.clientY;
				var tt = te - touchStart;
				var dh = $(document).height(),
					wh = $(window).height();

				var tp = Math.max((topStart + tt), 0);
				var max = wh - scrollBarTopOffset - scrollThumb.height();
				tp = Math.min(max, tp);
				var pr = tp / max;

				$(window).scrollTop(parseInt(pr * (dh - wh), 10));
			});

			$(document.body).append(scrollBar);
			$(window).on('resize', thisClass.reloadScrollStyles);
			$(window).on('scroll', reloadScrollPos);

			var helpVisible = false; // this tracking is needed because modal.hide event is triggered after help.show
			BuilderEvent.GlobalEvents.on("help.show help.hide", function(e) {
				helpVisible = e.visible;
			});
			BuilderEvent.GlobalEvents.on("help.show help.hide templates.show templates.hide preview.show preview.hide modal.show modal.hide", function(e) {
				if( e.visible || helpVisible )
					scrollBar.addClass("hidden");
				else
					scrollBar.removeClass("hidden");
			});
		}

		var siteData = {
			"class": "Site",
			content: { pages: [] }
		};
		for (var i = 0; i < this.elemntQueue.length; i++) {
			var data = this.elemntQueue[i];
			if (data["class"] === "Site") {
				siteData = data;
			}
		}
		
		var btnAnchor, buildBtnAnchor = function() {
			if (!btnAnchor) {
				btnAnchor = $('<div>')
					.css({display: 'inline-block', width: 1, position: 'absolute', right: -1})
					.appendTo($('#head').find('.ctrl-right'));
			}
			return btnAnchor;
		};
		
		if (this.panelUrl) {
			$('<button>').addClass('btn btn-danger')
				.attr({type: 'button'})
				.text(__('Back to Cpanel'))
				.append('&nbsp;<span class="glyphicon glyphicon-chevron-right"></span>')
				.css({marginLeft: 10, fontSize: '11px', lineHeight: '20px'})
				.on('click', function() {
					var buttons = [];
					buttons.push({
						title: __('Save'),
						cssClass: 'btn-default',
						func: function() {
							thisClass.save(true, function() {
								setTimeout(function() {
									location.href = thisClass.panelUrl;
								}, 500);
							});
						}
					});
					buttons.push({
						title: __('Save and publish'),
						cssClass: 'btn-success',
						func: function() {
							thisClass.publish(function() {
								setTimeout(function() {
									location.href = thisClass.panelUrl;
								}, 500);
							});
						}
					});
					Confirm.showDialog(__("Confirm"), __("Page was modified.\nDo you want to save changes before exit?"), buttons, 360);
				})
				.appendTo(buildBtnAnchor());
		}
		
		this.site = new Site(siteData);

		if( !WebsiteImporter.WebsiteImporter.onBuilderInit(thisClass.websiteImportStatus) )
			this.initPage();

		$(".wb_badge_help").tooltip();
		
		// session keep alive
		var sessIntId = null;
		this.verifySession = function(func) {
			var d = new Date();
			$.get(thisClass.baseUrl + "session_keep_alive/?sess=" + thisClass.sessUniqKey + "&ts=" + d.getTime(), function(response) {
				var res = true;
				if (response.error && response.error === 'another builder') {
					clearInterval(sessIntId);
					thisClass.moreThanOneBuilder();
					res = false;
				}
				if (typeof func === 'function') func.call(thisClass, res, true);
			}, 'json').fail(function() {
				if (typeof func === 'function') func.call(thisClass, false, false);
			});
		};
		sessIntId = setInterval(function() { thisClass.verifySession(); }, 60000);

		// auto backups save
		if (thisClass.autoBackupsEnable && !thisClass.we) {
			setInterval(function() {
				var d = new Date();
				$.get(thisClass.baseUrl + "auto_save_project/?ts=" + d.getTime());
			}, thisClass.autoBackupsSavingInterval*1000);
		}
		
		DragNDropZone.init(this);
		this.layoutManager = LayoutManager;
		this.layoutManager.init(this);
		ModeManager.init(this);
		ElementBox.init(this);
		RemoteLoginDialog.init();
		HelpSystemPlayer.init(this);
		Service.Store.Module.init(this);
		Service.Blocks.Module.init(this);
		Service.GalleryPictureManager.init();
		Service.ElementStyles.init();

		var ea = new BuilderEvent.BuilderInitBuilderEvent();
		BuilderEvent.GlobalEvents.triggerEvent("builder.init", ea);
	};

	Builder.prototype.initPage = function() {
		if (parseInt(this.pageId, 10) > 0) {
			this.loadPage(this.pageId, null, function() {
				setTimeout(function() { RemoteLoginDialog.handlePublish(); }, 1000);
				var hsp = HelpSystemPlayer.init(this);
				if (hsp) hsp.handlePageLoad(this.helpScenario);
				HelpOverlay.handlePageLoad();
			});
		} else  {
			this.templateChooser.setVisible(true);
		}
	};

	Builder.prototype.setPageModified = function(modified) {
		this.pageModified = modified;
	};
	
	Builder.prototype.moreThanOneBuilder = function() {
		var thisClass = this;
		if (!thisClass.staticMsgDlg)
			thisClass.staticMsgDlg = new MsgDialog(null, null, null, null, true);
		thisClass.staticMsgDlg.setTitle(__("Warning"));
		thisClass.staticMsgDlg.setMessage(__('We have noticed that there is currently another builder opened in the same browser. Please use different browsers for editing several websites at the same time or edit one website after another.<br /><br />If you really need to save this website do the following:<ul><li>Leave this builder open and close other builders;</li><li>Open builder for the website you are currently on in the same browser;</li><li>Return to this builder;</il><li>Click on "Stay on this page" and click "Save".'), null, "block");
		thisClass.staticMsgDlg.removeAllButtons();
		thisClass.staticMsgDlg.addButton(__("Stay on this page"), function() {
			thisClass.staticMsgDlg.setVisible(false);
		}, false, "btn-danger");
		thisClass.staticMsgDlg.addButton(__("Close builder"), function() {
			thisClass.setPageModified(false);
			var thisWnd = window.open('about:blank', '_self');
			thisWnd.close();
		}, false, "btn-success");
		thisClass.staticMsgDlg.setVisible(true);
	};

	/**
	 * Clears selected texts / blocks
	 */
	Builder.prototype.clearSelections = function() {
		
	};

	/**
	 * Register element for easier serialization
	 * @param {Element} elem element to register
	 */
	Builder.prototype.registerElement = function(elem) {
		if (!elem) return;
		this.elementList[elem.id] = elem;
	};

	/**
	 * Snap size to grid
	 * @param {Number} value grid size
	 * @param {Boolean} floor if true result will be floored
	 * @param {Boolean} ceil if true result will be ceiled
	 * @return {Number}
	 */
	Builder.prototype.gridSnap = function(value, floor, ceil) {
		return (floor ? Math.floor(value / this.gridSize) : (ceil ? Math.ceil(value / this.gridSize) : Math.round(value / this.gridSize))) * this.gridSize;
	};

	/**
	 * Snap X coordinate to grid or near guides if snapping is enabled
	 * @param {Number} value
	 * @param {String} axis Must be either "x" or "y"
	 * @param {null|String} blockId Must be one of content block ids for y axis: "wb_header", "wb_main" or "wb_footer"
	 * @return {Number}
	 */
	Builder.prototype.autoSnapOnAxis = function(value, axis, blockId) {
		var points = [];
		var snapDistance = wb_builder.gridSize / 2;
		var i;
		if( this.snapToGrid ) {
			points.push(this.gridSnap(value, false, false));
		}

		if( this.snapToGuides ) {
			var guidesCollection = (axis === "y") ? "horizontal" : "vertical"; // vertical guides are used to snap on x axis and horizontal on y.
			var guides = Guides.GuideManagerInstance.getActiveGuides()[guidesCollection];
			var offset;
			for( i = guides.length - 1; i >= 0; i-- ) {
				if( axis === "y" && guides[i].block !== blockId )
					continue;
				offset = guides[i].getRelOffset();
				if( Math.abs(offset - value) <= snapDistance )
					points.push(offset);
			}
		}

		if( points.length ) {
			var best = null, bestDelta = 0, delta;
			for( i = points.length - 1; i >= 0; i-- ) {
				delta = Math.abs(points[i] - value);
				if( best === null || delta < bestDelta ) {
					best = points[i];
					bestDelta = delta;
				}
			}
			return best;
		}
		return value;
	};

	/**
	 * Snap X coordinate to grid or near guides if snapping is enabled
	 * @param {Number} x
	 * @return {Number}
	 */
	Builder.prototype.autoSnapX = function(x) {
		return this.autoSnapOnAxis(x, "x", null);
	};

	/**
	 * Snap Y coordinate to grid or near guides if snapping is enabled
	 * @param {Number} y
	 * @param {String} blockId Must be one of content block ids: "wb_header", "wb_main" or "wb_footer"
	 * @return {Number}
	 */
	Builder.prototype.autoSnapY = function(y, blockId) {
		return this.autoSnapOnAxis(y, "y", blockId);
	};

	/**
	 * Sets grid visibility
	 * @param {Boolean} visible
	 * @param {Boolean} forceReRender
	 */
	Builder.prototype.gridSetVisible = function(visible, forceReRender) {
		this.showGrid = visible;
		this.gridRender(forceReRender);
		for (var k in this.bodyInstance.blocks) {
			var block = this.bodyInstance.blocks[k];
			block.grid.css("display", (visible ? "block" : "none"));
		}
	};

	/**
	 * Sets grid size
	 * @param {number} gridSize Size of the grid
	 */
	Builder.prototype.gridSetSize = function(gridSize) {
		if( typeof gridSize === "string" ) {
			gridSize = parseInt(gridSize);
			if( isNaN(gridSize) )
				return;
		}
		this.gridSize = Math.min(Math.max(gridSize, 5), 100);
		this.gridRender();
	};

	Builder.prototype.gridSetColor = function(gridColor) {
		this.gridColor = gridColor;
		this.gridRender();
	};

	Builder.prototype.gridRender = function(forceReRender) {
		var renderState = this.gridSize + "|" + this.gridColor;
		if( !forceReRender && this.gridRenderState === renderState )
			return;
		this.gridRenderState = renderState;

		/** @type {HTMLCanvasElement} */
		var canvas = document.createElement('canvas');
		canvas.width = canvas.height = this.gridSize;
		var ctx = canvas.getContext("2d");
		ctx.strokeStyle = this.gridColor;
		ctx.lineWidth = 1;
		ctx.beginPath();
		ctx.moveTo(0.5, this.gridSize - 0.5);
		ctx.lineTo(this.gridSize - 0.5, this.gridSize - 0.5);
		ctx.lineTo(this.gridSize - 0.5, 0.5);
		ctx.stroke();
		var dataUrl = canvas.toDataURL("image/png");

		for (var k in this.bodyInstance.blocks) {
			var block = this.bodyInstance.blocks[k];
			block.grid.css({"opacity": 1, "background-image": "url(" + dataUrl + ")"});
		}
	};

	Builder.prototype.guidesSetVisible = function(visible) {
		if( this.showGuides === visible )
			return;
		var ea = new BuilderEvent.VisibilityChangedBuilderEvent(visible);
		BuilderEvent.GlobalEvents.triggerEvent(visible ? "guides.show" : "guides.hide", ea);
		if( !ea.defaultPrevented )
			this.showGuides = visible;
	};

	/**
	 * Shows / hides layout highlighting
	 * 
	 * @param {Boolean} visible
	 */
	Builder.prototype.highlightLayout = function(visible) {
		this.showLayout = visible;
		this.layoutManager.setVisible(visible);
		Guides.GuideManagerInstance.invalidate();
	};

	/**
	 * Browser to fullscreen mode
	 * 
	 * @param {Boolean} check Want to test only if browser supports it
	 */
	Builder.prototype.goFullScreen = function(check) {
		var pfx = ["webkit", "moz", "ms", "o", ""];
		var el = document.documentElement,
			rfs = false,
			pf = '',
			p = 0, t;

		var chechStr = 'FullScreen',
			callStr = 'RequestFullScreen',
			cancelStr = 'CancelFullScreen';


		//get prefix and calls
		while (p < pfx.length) {
			var m = callStr;
			pf = pfx[p];
			if (pf === "") {
				m = m.substr(0,1).toLowerCase() + m.substr(1);
			}
			m = pfx[p] + m;
			t = typeof el[m];
			if (t !== "undefined") {
				rfs = true;
				callStr = el[m];
				if (pf === 'webkit')
					chechStr = 'IsFullScreen';
				chechStr = pfx[p] === "" ? chechStr.substr(0,1).toLowerCase() + chechStr.substr(1) : pf + chechStr;
				chechStr = document[chechStr];
				cancelStr = pfx[p] === "" ? cancelStr.substr(0,1).toLowerCase() + cancelStr.substr(1) : pf + cancelStr;
				cancelStr = document[cancelStr];
				break;
			}
			p++;
		}

		if (rfs) {
			if (!check) {
				if (chechStr) {
					if (cancelStr)
						cancelStr.call(document);
				}
				else if (callStr)
					callStr.call(el);
			}
			return true;
		}
		//older id
		/*else if(typeof window.ActiveXObject!="undefined"){
			// for Internet Explorer
			var wscript = new ActiveXObject("WScript.Shell");
			if (wscript!=null) {
				if (check)
					return true;
				else
					wscript.SendKeys("{F11}");
			}
			else {
				return false;
			}
		}*/
		else {
			return false;
		}
	};

	/**
	 * Go to page
	 * @param {Number} pageId id of the page to go to
	 * @param {String} custUrl goto custom url instean of page
	 * @param {Callback} callback to trigger after successful page rendering
	 */
	Builder.prototype.goToPage = function(pageId, custUrl, callback) {
		var thisPageId = pageId;
		var thisClass = this;
		var thisCustUrl = custUrl;
		if (thisClass.pageModified) {
			var tpage = this.site.getPage(pageId);
			var mustSave = (!thisCustUrl && pageId && tpage && tpage.copyFrom);
			var buttons = [];
			buttons.push({ title: __("Cancel") });
			if (!mustSave) buttons.push({
					title: __("Don't Save"),
					cssClass: "btn-danger",
					func: function() {
						if (thisCustUrl) {
							location.href = thisCustUrl;
						} else {
							thisClass.loadPage(thisPageId, false, callback);
						}
					}
				});
			buttons.push({
					title: __("Save"),
					cssClass: "btn-success",
					func: function() {
						thisClass.save(true, function() {
							setTimeout(function() {
								if (thisCustUrl) {
									location.href = thisCustUrl;
								} else {
									thisClass.loadPage(thisPageId, false, callback);
								}
							}, 1000);
						}, null, true);
					}
				});
			Confirm.showDialog(__("Confirm"),
				__("Page was modified.\nDo you want to save changes before exit?") +
				(mustSave ? ('<br /><br /><span>' + __("You must save before going to newly created page.") + '</span>') : ""),
				buttons, 560/*, $("#wb_toolbar_pro").find("#menu_sel"), "right"*/);
		} else {
			if (thisCustUrl) {
				location.href = thisCustUrl;
			} else {
				if (this.preloader) {
					while (this.preloader.numStacks() > 1) this.preloader.popStack();
				}
				thisClass.loadPage(thisPageId, false, callback);
			}
		}

	};

	/**
	 * Load page to builder
	 * @param {number} pageId id of page to load
	 * @param {boolean=} reloadSite if true reload site object data
	 * @param {function} doneCallback callback that will be caller when load page complemtes successfully.
	 */
	Builder.prototype.loadPage = function(pageId, reloadSite, doneCallback) {
		if (!this.preloader)
			this.preloader = new Preloader(__("Loading page"));
		this.preloader.setTitle(__("Loading page"));
		this.preloader.reset();
		this.preloader.setVisible(true);
		this.preloader.setMessage("", __("Loading page") + '...');
		this.preloader.setProgress(10);
		if (this.bodyInstance) {
			this.bodyInstance.__destruct();
		}
		this.historyClear();
		WB_Menu.elemList = {};
		WB_Menu.strangeElemList = {};
		this.bodyInstance = null;
		Service.element.resetIdentifierIndex();
		this.preloader.setProgress(20);

		var thisClass = this, thisReloadSite = reloadSite, thisDoneCallback = doneCallback, thisPageId = pageId;
		setTimeout(function() {
			$.getJSON(thisClass.loadPageUrl, {id: pageId, ts: (new Date()).getTime()}, function(pageData) {
				var ea = new BuilderEvent.PageLoadBuilderEvent(thisPageId, pageData);
				BuilderEvent.GlobalEvents.triggerEvent("page.beforeload", ea);
				if( !ea.defaultPrevented ) {
					SiteLoader.loadInitSiteData(pageData, thisClass, thisReloadSite, function() {
						BuilderEvent.GlobalEvents.triggerEvent("page.load", ea);
						if( !ea.defaultPrevented && typeof thisDoneCallback === "function" )
							thisDoneCallback.call(this);
					});
				}
			}).error(function() {
				thisClass.preloader.setMessage("", __("Error loading page"), "error");
				thisClass.preloader.setVisible(false);
				if (!thisClass.staticMsgDlg)
					thisClass.staticMsgDlg = new MsgDialog(null, null, null, null, true);
				thisClass.staticMsgDlg.setTitle(__("Error loading page. Try again later."));
				thisClass.staticMsgDlg.setMessage("", __("Error loading page. Try again later."), "error-big");
				thisClass.staticMsgDlg.removeAllButtons();
				thisClass.staticMsgDlg.addButton(__("Retry loading the page"), function() {
					thisClass.staticMsgDlg.setVisible(false);
					thisClass.loadPage(pageId);
				}, true, "btn-primary");
				thisClass.staticMsgDlg.setVisible(true);
			});
		}, 1000);
	};
	
	/**
	 * Register save data provider.
	 * When save is initiated, system will post data provided by provider
	 * that will be identified by id.
	 * @param {string} id
	 * @param {Function} func
	 */
	Builder.prototype.regSaveDataProvider = function(id, func) {
		this.saveDataProviders.push({id: id, func: func});
	};
	
	/**
	 * Save page info
	 * @param {Boolean} useDialog if true will use save dialog
	 * @param {Function} callback callback to be caled when save completes
	 * @param {String} altUrl alternative save url
	 * @param {Boolean} keepOpen if useDialog then keep open after complete
	 * @param {Boolean} reset add reset post parameter
	 * @param {Boolean} errorsChecked indicates that there is no need to check page for loading errors
	 * @param {String} dialogTitle
	 */
	Builder.prototype.save = function(useDialog, callback, altUrl, keepOpen, reset, errorsChecked, dialogTitle) {
		var i, sdp, thisClass = this;
		var saveAction = function() {
			Service.textArea.hideEditors();
			var ea = new BuilderEvent.SaveEvent();
			BuilderEvent.GlobalEvents.triggerEvent('builder.beforesave', ea);
			var thisUrl = altUrl ? altUrl : WB_SAVE_URL;
			thisUrl += '?sess=' + thisClass.sessUniqKey + '&ts=' + (new Date()).getTime();
			var elemsCommon = [];
			var elems = [];
			// ignore element registration :)
			thisClass.elementList = thisClass.bodyInstance.getContentElements();
			var siteData = thisClass.site.serialize(true);
			siteData.isCommon = true;
			elemsCommon[elemsCommon.length] = siteData;
			var bodyData = thisClass.bodyInstance.serialize();
			bodyData.isCommon = true;
			elemsCommon[elemsCommon.length] = bodyData;
			var id;
			for (id in thisClass.bodyInstance.blocks) {
				var blockData = thisClass.bodyInstance.blocks[id].serialize();
				if (blockData.isCommon) {
					elemsCommon[elemsCommon.length] = blockData;
				} else {
					elems[elems.length] = blockData;
				}
			}
			for (id in thisClass.elementList) {
				var elem = thisClass.elementList[id];
				var data = elem ? elem.serialize() : null;
				if (!data) continue;
				if (data.isCommon) {
					elemsCommon[elemsCommon.length] = data;
				} else {
					elems[elems.length] = data;
				}
			}
			for (var i = 0; i < thisClass.excludedElements.length; i++) {
				elemsCommon[elemsCommon.length] = thisClass.excludedElements[i];
			}

			var opts = {
				reset: (reset ? 1 : null),
				id: thisClass.pageId,
				common_data: $.JSON.encode(elemsCommon),
				page_data: $.JSON.encode(elems),
				meta: $.JSON.encode(thisClass.meta),
				page_blocks_data: $.JSON.encode(thisClass.pageBlocksData),
				removedMenuList: $.JSON.encode(MenuList.getRemovedMenuList()),
				available_elements: $.JSON.encode(thisClass.availableElements)
			};
			for (i = 0; i < thisClass.saveDataProviders.length; i++) {
				sdp = thisClass.saveDataProviders[i];
				if (sdp.id && typeof sdp.func === 'function') {
					opts[sdp.id] = $.JSON.encode(sdp.func.call(thisClass));
				}
			}

			var _useDialog = useDialog ? true : false;
			if (_useDialog) {
				if (!thisClass.preloader)
					thisClass.preloader = new Preloader((dialogTitle ? dialogTitle : __("Save")));
				thisClass.preloader.selectStack(0);
				if (keepOpen) {
					while (thisClass.preloader.numStacks() > 2) thisClass.preloader.popStack();
					thisClass.preloader.resetAll();
					if (thisClass.preloader.numStacks() < 2) thisClass.preloader.pushStack();
				} else {
					while (thisClass.preloader.numStacks() > 1) thisClass.preloader.popStack();
				}
				thisClass.preloader.setTitle((dialogTitle ? dialogTitle : __("Save")));
				var monitorOptions = {
					url: thisUrl,
					method: "post",
					opts: opts
				};
				var monitorRecover = false;
				var monitorFunc = function(success, error) {
					if (success) {
						thisClass.setPageModified(false);
					} else {
						var errMsg = error;
						if (error === 'saving error') {
							errMsg = __('An error occured while saving. Please try again in few seconds.');
						} else if (error === 'another builder') {
							thisClass.moreThanOneBuilder();
							return;
						}
						if (!thisClass.msgDlg)
							thisClass.msgDlg = new MsgDialog();
						thisClass.msgDlg.setTitle(__('Error'));
						thisClass.msgDlg.setMessage(errMsg, __("Error:"), "error");
						thisClass.msgDlg.setVisible(true);
					}
					if (thisClass.preloader.numStacks() > 1) {
						thisClass.preloader.selectStack(1);
					}
					
					if (typeof(callback) === 'function') {
						callback(success, error);
					}
				};
				thisClass.preloader.reset();
				thisClass.preloader.monitor(monitorOptions, monitorFunc, null, keepOpen, function(error) {
					if ((typeof error === 'object') && !monitorRecover && ('recover' in error) && error.recover === 'full-publish') {
						monitorRecover = true;
						setTimeout(function() {
							monitorOptions.opts.full = true;
							thisClass.preloader.monitor(monitorOptions, monitorFunc, null, keepOpen);
						}, 10);
						return true;
					}
					return false;
				});
				thisClass.preloader.setVisible(true);
			} else {
				var thisCallback = callback;
				
				$.post(thisUrl, opts, function() {
					thisClass.pageBlocksData = {};
					thisClass.setPageModified(false);
					if (thisCallback && typeof(thisCallback) === "function") {
						thisCallback(true);
					}
				}).error(function() {
					if (thisCallback && typeof(thisCallback) === "function") {
						thisCallback(false);
					}
				});
			}
		};
		if( errorsChecked )
			saveAction.apply(this, [useDialog, callback, altUrl, keepOpen, reset, errorsChecked]);
		else
			thisClass.checkPageErrors(__("Warning"), saveAction, [useDialog, callback, altUrl, keepOpen, reset, true]);
	};

	/**
	 * Publish page
	 * @param {Function} successCallback
	 */
	Builder.prototype.publish = function(successCallback) {
		var thisClass = this, thisSuccessCallback = successCallback;
		thisClass.checkPageErrors(__("Warning"), function() {
			var url = thisClass.publishUrl + thisClass.pageId + "/";

			thisClass.save(true, function(success, error) {
				if (success) {
					if (typeof thisSuccessCallback === 'function') thisSuccessCallback();
				} else {
					if (!thisClass.msgDlg)
						thisClass.msgDlg = new MsgDialog();
					var errMsg = error, errType = 'error-big';
					if (typeof error === 'object' && ('title' in error) && ('description' in error)) {
						errMsg = error.description;
						error = error.title;
					} else {
						errMsg = error;
					}
					thisClass.msgDlg.setTitle(__pr(error));
					thisClass.msgDlg.setMessage(__pr(errMsg), __("Error:"), errType);
					thisClass.msgDlg.setVisible(false, true); // remove this dialog from stack to prevent duplicate
					thisClass.msgDlg.setVisible(true);
				}
			}, url, null, true, true, __("Publish"));
			if (thisClass.preloader) {
				thisClass.preloader.clearNotifications();
				if (thisClass.maxMenuItems)
					thisClass.preloader.setNotification(__('There are only %s pages allowed to publish in your plan').replace('%s', thisClass.maxMenuItems), __('Note') + ':');
				if (!thisClass.formsAllowed)
					thisClass.preloader.setNotification(__('Forms are only available in premium version'), __('Note') + ':');
				
				var unavailablePlugins = thisClass.getUnavailablePlugins(true, true);
				var onlyForm = (unavailablePlugins.length === 1 && unavailablePlugins[0] === 'Form');
				if (unavailablePlugins.length > 0 && !onlyForm) {
					var msg = __('These plugins will not be published') + ': ' + unavailablePlugins.join(', ');
					thisClass.preloader.setNotification(msg, __('Note') + ':');
				}
			}
		});
	};
	
	/**
	 * Get list of unavailable plugins
	 * @param {Boolean} translate if true get translated plugin names instead of plugin IDs
	 * @param {Boolean} tryShort if true use group names instead of plugin names (for marketplace plugins only)
	 * @returns {Array}
	 */
	Builder.prototype.getUnavailablePlugins = function(translate, tryShort) {
		var list = {};
		var registry = ElementRegister.getPluginRegistry();
		for (var i in this.pluginToolbar) {
			for (var j in this.pluginToolbar[i].items) {
				list[this.pluginToolbar[i].items[j]] = true;
			}
		}
		for (var plgId in this.availableElements) {
			if (this.availableElements[plgId]) {
				delete list[plgId];
			}
		}
		delete list['Menu'];
		delete list['Shape'];
		if (!this.formsAllowed) {
			list['Form'] = true;
		}
		if (tryShort) {
			var shortGroups = {'wb-group-complex': true, 'wb-group-social': true, 'wb-group-advanced': true,
								  'wb-group-commerce': true, 'wb-group-maps': true};
			for (var i in this.pluginToolbar) {
				if (shortGroups[this.pluginToolbar[i].id]) {
					var applyShort = true;
					for (var j in this.pluginToolbar[i].items) {
						if (!((this.pluginToolbar[i].items[j]) in list)) {
							applyShort = false; break;
						}
					}
					if (applyShort) {
						for (var j in this.pluginToolbar[i].items) {
							delete list[this.pluginToolbar[i].items[j]];
						}
						list[this.pluginToolbar[i].id] = true;
					}
				}
			}
		}
		var listArr = Object.keys(list);
		if (translate) {
			for (var i in listArr) {
				if ((listArr[i]) in registry) {
					listArr[i] = registry[listArr[i]].name;
				} else if ((listArr[i]) in this.pluginGroups) {
					listArr[i] = this.pluginGroups[listArr[i]].name;
				}
			}
		}
		return listArr;
	};
	
	Builder.prototype.getModeManager = function() {
		return Service.modeManager;
	};

	/**
	 * Preview site
	 * @param {string} pageId id of the page to load into the preview window
	 * @param {object} [prevWinProvider=null] instance that provides preview window do preview in.
	 * @param {boolean} noBodyMargins if true then generate preview without margins on sides of content.
	 * @param {boolean} noRegen if true loads previously generated preview
	 */
	Builder.prototype.previewPage = function(pageId, prevWinProvider, noBodyMargins, noRegen) {
		var thisClass = this;
		var url = thisClass.previewUrl + pageId + "/";
		var params = [];
		if (thisClass.site.currSelLang && thisClass.site.languages.length > 0)
			params.push('lang=' + thisClass.site.currSelLang);
		if (typeof noBodyMargins == 'boolean' && noBodyMargins)
			params.push('nomargins=1');
		if (typeof noRegen == 'boolean' && noRegen)
			params.push('noregen=1');
		url += params.length ? ('?' + params.join('&')) : '';
		if (!prevWinProvider) {
			thisClass.previewWindow = window.open("about:blank");
			thisClass.previewWindow.document.open();
			var l, content = '<html>' +
					'<head>' +
						'<title>' + __("loading...") + '</title>' +
						'<base href="' + thisClass.baseUrl + '" />' +
						(thisClass.favicon ? ('<link rel="' + thisClass.favicon.rel + '" href="' + thisClass.favicon.href + '" type="' + thisClass.favicon.type + '" />') : '') +
						'<link rel="stylesheet" type="text/css" href="modules/builder/js/lib/bootstrap/css/bootstrap.min.css?v=3.3.6"/>' +
					'</head>' +
					'<body>' +
					'<div class="modal" style="top: 0; margin-top: ' + ((window.innerHeight - 106) / 2 + 'px') + '">' +
						'<div class="modal-header">' +
							'<h3>' + ((l = __('loading...'))[0].toUpperCase() + l.substr(1)) + '</h3>' +
						'</div>' +
						'<div class="modal-body">' +
							'<div class="progress progress-striped active" style="margin-bottom: 5px">' +
								'<div class="bar" style="width: 100%"></div>' +
							'</div>' +
						'</div>' +
					'</div>' +
					'</body>' +
					'</html>';
			thisClass.previewWindow.document.write(content);
			thisClass.previewWindow.document.close();
		}

		if (prevWinProvider) thisClass.previewWindow = prevWinProvider.open();
		var body = thisClass.previewWindow.document.getElementsByTagName('body');
		thisClass.previewWindow.location.target = "_self";
		thisClass.previewWindow.location.href = url;
		thisClass.previewWindow.focus();
	};

	/**
	 * Preview site
	 * @param {object} [prevWinProvider=null] instance that provides preview window do preview in.
	 * @param {boolean} noSave if true then do not save before previewing.
	 * @param {boolean} noBodyMargins if true then generate preview without margins on sides of content.
	 */
	Builder.prototype.preview = function(prevWinProvider, noSave, noBodyMargins) {
		var thisClass = this;
		thisClass.checkPageErrors(__("Warning"), function() {
			if (noSave) {
				thisClass.previewPage(thisClass.pageId, prevWinProvider, noBodyMargins, false);
			} else {
				thisClass.save(false, function(success, error) {
					if (success) {
						thisClass.previewPage(thisClass.pageId, prevWinProvider, noBodyMargins, false);
					} else {
						if (thisClass.previewWindow) thisClass.previewWindow.close();
						if (!thisClass.msgDlg)
							thisClass.msgDlg = new MsgDialog();
						thisClass.msgDlg.setTitle(error);
						thisClass.msgDlg.setMessage(error, __("Error:"), "error-big");
						thisClass.msgDlg.setVisible(true);
					}
				}, null, false, false, true);
			}
		});
	};

	/**
	 * In case of a bad page load it warns the user about loading error and/or possible loss of template.
	 *
	 * @param {string} title Title of warning dialog (if it appears).
	 * @param {function} confirmCallback Function to call if there is no error or the user wants to save anyway.
	 * @param {object} args Array of arguments to pass to the callback function.
	 */
	Builder.prototype.checkPageErrors = function(title, confirmCallback, args) {
		if( typeof(args) !== "object" ) args = [];
		var thisClass = this;
		if( thisClass.bodyInstance.getContentElements().length === 0 ) {
			if (!thisClass.staticMsgDlg)
				thisClass.staticMsgDlg = new MsgDialog(null, null, null, null, true);
			thisClass.staticMsgDlg.setTitle(title);
			thisClass.staticMsgDlg.setMessage(__("Completing this action will make your website empty. Are you sure you want to continue?") + "<br/><br/>" + __("If the page you loaded, due to some errors, was empty from the beginning, then please don't save it and try reloading the page in a few minutes."), __("You are saving an empty page."), "block");
			thisClass.staticMsgDlg.removeAllButtons();
			thisClass.staticMsgDlg.addButton(__("Yes, this is intentional"), function() {
				thisClass.staticMsgDlg.setVisible(false);
				confirmCallback.apply(thisClass, args);
			}, false, "btn-danger");
			thisClass.staticMsgDlg.addButton(__("Reload the page"), function() {
				thisClass.staticMsgDlg.setVisible(false);
				thisClass.loadPage(thisClass.pageId);
			}, true, "btn-success");
			thisClass.staticMsgDlg.addButton(__("Cancel"), function() {
				thisClass.staticMsgDlg.setVisible(false);
			}, false, "");
			thisClass.staticMsgDlg.setVisible(true);
		}
		else {
			confirmCallback.apply(thisClass, args);
		}
	};

	/**
	 * Show backup/restore dialog
	 */
	Builder.prototype.backupRestore = function() {
		var thisClass = this, fields,
			restoreUrl = this.baseUrl + this.getLanguageByLocale(this.locale).code + '/restore_project/';
		if (!this.backupDialog) {
			var canUseBackup = (!wb_builder.testMode || wb_builder.allowDemoBackup);
			this.backupDialog = new Dialog(__('Backup/Restore'), null, new Service.UIBuilder({type: 'TabbedPane', tabs: [
				{name: __('Backup'), ignore: canUseBackup, children: [
					{type: 'AlertBox', text: __('Unavailable in test mode'),
						css: {marginTop: 15},
						style: AlertBox.STYLE_INFO
					}
				]},
				{name: __('Backup'), ignore: !canUseBackup, children: [
					{type: 'VerticalLayout', spacing: 15, css: {marginTop: 15, textAlign: 'center'}, children: [
						{type: 'Label', css: {fontWeight: 'normal'},
							text: __('Download Zyro Builder template to your computer to restore it later.')},
						{type: 'Button', text: __('Download Backup'), buttonStyle: UIButton.UIButton.STYLE_SUCCESS, click: function() {
							var thisSelf = this;
							this.setIcon('icon-loading');
							this.setButtonStyle(UIButton.UIButton.STYLE_DEFAULT);
							this.setEnabled(false);
							thisClass.save(false, function() {
								thisSelf.setIcon(null);
								thisSelf.setButtonStyle(UIButton.UIButton.STYLE_SUCCESS);
								thisSelf.setEnabled(true);
								location.href = thisClass.baseUrl + 'save_project/';
							});
						}}
					]}
				]},
				{name: __('Restore'), children: [
					{type: 'VerticalLayout', spacing: 15, css: {marginTop: 15}, children: [
						{type: 'Label', css: {fontWeight: 'normal', textAlign: 'center'}, ignore: wb_builder.autoBackupsEnable,
							text: __('Choose Zyro Builder template file to restore from. Current template will be lost.') + (wb_builder.maxUploadBackupFileSize ? ' (' + __('max') + ': ' + wb_builder.maxUploadBackupFileSize + ')' : '')},
						{type: 'Form', action: restoreUrl, method: 'post', enctype: 'multipart/form-data', id: 'form',
							css: {marginBottom: 0},
							init: function() {
								this.getElem().prepend('<input type="hidden" name="backup_type" value="file" />');
							},
							submit: function(fields) {
								if (!fields.typeFile || fields.typeFile.getValue()) {
									if (!fields.upl.getValue()) {
										alert(__('No file chosen'));
										return false;
									}
								}
								if (fields.backupList) {
									var backup = fields.backupList.getElem().find('li.active').data('file');
									if (backup) {
										this.getElem().append('<input type="hidden" name="backup" value="' + backup + '" />');
									}
								}
							},
							children: [
								{type: 'VerticalLayout', children: [
									{type: 'VerticalLayout', children: [
										{type: 'RadioBox', id: 'typeFile', group: 'backup_type', inputValue: 'file',
											ignore: !wb_builder.autoBackupsEnable,
											label: __('Restore from file') + (wb_builder.maxUploadBackupFileSize ? ' (' + __('max') + ': ' + wb_builder.maxUploadBackupFileSize + ')' : '')
										},
										{type: 'FlowLayout', css: {marginTop: 5, textAlign: (wb_builder.autoBackupsEnable ? 'left' : 'center')}, children: [
											{type: 'FileField', id: 'upl', name: 'pro_upl', accept: '.sitebuilder', css: {marginRight: 20, maxWidth: 200},
												click: function(def, fields) { if (fields.typeFile) fields.typeFile.setValue(true); },
												change: function() {
													var file = this.files.length ? this.files[0] : null;
													if (!file) return true;
													if (!/^.+\.sitebuilder$/i.test(file.name)) {
														alert(__('File must have extension "%s"').replace('%s', '.sitebuilder'));
														fields.upl.setValue(null);
													} else if (wb_builder.maxUploadBackupFileSizeInt && file.size > wb_builder.maxUploadBackupFileSizeInt) {
														alert(__('File size is larger than allowed'));
														fields.upl.setValue(null);
													}
												}
											},
											{type: 'Button', text: __('Restore'), ignore: wb_builder.autoBackupsEnable,
												buttonStyle: UIButton.UIButton.STYLE_DANGER,
												buttonType: UIButton.UIButton.TYPE_SUBMIT
											}
										]}
									]},
									{type: 'VerticalLayout', ignore: !wb_builder.autoBackupsEnable, css: {marginTop: 15},
										styleClass: 'wb_backup_block left',
										children: [
											{type: 'RadioBox', id: 'typeAuto', group: 'backup_type', inputValue: 'auto',
												label: __('Choose auto backup version to restore')
											},
											{type: 'CustomContainer', id: 'backupList',
												css: {overflow: 'auto', maxHeight: 200, marginTop: 5},
												init: function(def, fields) {
													this.refreshAutoBackups = function() {
														var thisSelf = this,
															url = thisClass.baseUrl + thisClass.getLanguageByLocale(thisClass.locale).code + '/get_backups?ts=' + (new Date()).getTime();
														$.get(url, function(response) {
															var cnt = '', i, backup, date, mo, d, h, m, s, t, name;
															if (!response.error) {
																if (response.backups && response.backups.length) {
																	cnt += '<ul class="nav nav-pills nav-stacked" style="font-size: 12px;">';
																	for (i = 0; i < response.backups.length; i++) {
																		backup = response.backups[i];
																		date = new Date(backup.ts * 1000);
																		t = {
																			year: date.getFullYear(),
																			mon: ((mo = date.getMonth() + 1) < 10) ? '0' + mo : mo,
																			day: ((d = date.getDate()) < 10) ? '0' + d : d,
																			hour: ((h = date.getHours()) < 10) ? '0' + h : h,
																			minute: ((m = date.getMinutes()) < 10) ? '0' + m : m,
																			second: ((s = date.getSeconds()) < 10) ? '0' + s : s
																		};
																		name = t.year + '-' + t.mon + '-' + t.day + ' ' + t.hour + ':' + t.minute;
																		if (backup.template) name += ' - ' + backup.template;
																		cnt += '<li' + ((i === 0) ? ' class="active"' : '') + ' data-file="' + backup.file +'">' +
																			'<a href="javascript:void(0);">' + name + '</a>' +
																		'</li>';
																	}
																	cnt += '</ul>';
																} else {
																	cnt += '<p class="no-backups">' + __('There are no auto backups.') + '</p>';
																}
															} else {
																cnt += '<p class="no-backups">' + response.error;
															}
															thisSelf.getElem().html(cnt);
															var lis = thisSelf.getElem().find('li');
															lis.on('click', function() {
																lis.removeClass('active');
																$(this).addClass('active');
																fields.typeAuto.setValue(true);
															});
														}, 'json');
													};
												}
											}
										]}
									]
								}
							]
						}
					]}
				]}
			]}));
			this.backupDialog.setSize(400);
			fields = this.backupDialog.fields;
			this.backupDialog.addButton(__('Close'));
			if (wb_builder.autoBackupsEnable) {
				this.backupDialog.addButton(__('Restore'), function() { fields.form.trigger('submit'); }, true);
			}
		}
		fields = this.backupDialog.fields;
		if (wb_builder.autoBackupsEnable) {
			fields.typeFile.setValue(true);
			fields.backupList.refreshAutoBackups();
		}
		this.backupDialog.show();
	};
	
	/**
	 * Remove element from excluded list by element ID
	 * @param {String} elementId
	 */
	Builder.prototype.removeFromExcluded = function(elementId) {
		var i, len, elem;
		for (i=0, len = this.excludedElements.length; i < len; i++) {
			elem = this.excludedElements[i];
			if (elem.id == elementId) {
				this.excludedElements[i] = null;
				this.excludedElements.splice(i, 1);
			}
		}
	};

	/**
	 * Add elements to builder
	 * @param elems array of element objects
	 * @param isCommon if true this is a common element list
	 */
	Builder.prototype.addElements = function(elems, isCommon) {
		for (var i = 0; i < elems.length; i++) {
			elems[i].isCommon = isCommon ? true : false;
			this.elemntQueue[this.elemntQueue.length] = elems[i];
		}
	};

	/**
	 * Detect page doctype
	 * @return doctype
	 */
	Builder.prototype.detectDoctype = function() {
		var re = /\s+(X?HTML)\s+([\d\.]+)\s*([^\/]+)*\//gi;
		if (typeof document.namespaces !== "undefined") {
			if (document.all[0].nodeType === 8)
				re.exec(document.all[0].nodeValue);
			else
				return null;
		} else {
			if(document.doctype !== null)
				re.exec(document.doctype.publicId);
			else
				return null;
		}
		return ((RegExp.$1) + "").toLowerCase();
	};

	/**
	 * Make event object crossbrowser
	 * @param event browser specific event object
	 * @return crossbrowser event
	 */
	Builder.prototype.normalizeEvent = function(event) {
		var e = { left: 0, top: 0, returnValue: null };
		for (var key in event) {
			if (typeof(event[key]) !== "function" && key !== "returnValue") {
				e[key] = event[key];
			}
		}
		var thisEvent = event;
		e.stopPropagation = function() {
			if (thisEvent.stopPropagation) thisEvent.stopPropagation();
		};

		var docType = this.detectDoctype();

		var sl = window.pageXOffset ? window.pageXOffset
			: ((docType === "xhtml") ? document.body.parentNode.scrollLeft
				: document.body.scrollLeft);
		var st = window.pageYOffset ? window.pageYOffset
			: ((docType === "xhtml") ? document.body.parentNode.scrollTop 
				: document.body.scrollTop);
		if (!e.pageX) e.pageX = e.clientX + sl;
		if (!e.pageY) e.pageY = e.clientY + st;
		if (!e.which && e.button) e.which = e.button;
		if (!e.target && e.srcElement) e.target = e.srcElement;
		return e;
	};

	/**
	 * Add CSS rule to the current document
	 * @param {String} name CSS selector
	 * @param {String} rule CSS rules
	 * @param {Document} doc document object
	 * @param {Number} replaceIndex index of the rule to replace
	 * @return {Number} added CSS rule index
	 */
	Builder.prototype.addCSSRule = function(name, rule, doc, replaceIndex) {
		if (!Builder.isset(replaceIndex) || isNaN(replaceIndex)) {
			replaceIndex = -1;
		}
		var docIsSet = true;
		if (!doc || typeof(doc) !== "object") {
			doc = document;
			docIsSet = false;
		}
		var sheet = null;
		if (docIsSet || !this.styleSheet) {
			sheet = doc.styleSheets[doc.styleSheets.length - 1];
		} else {
			sheet = this.styleSheet;
		}
		var rule_ = rule;
		if (typeof(rule_) === "object") {
			var rule__ = $.extend({}, rule_);
			rule_ = [];
			for (var k in rule__) {
				rule_.push(k + ": " + rule__[k] + ";");
			}
			rule_ = rule_.join(" ");
		}
		var ruleList = sheet.cssRules ? sheet.cssRules : sheet.rules;
		if (replaceIndex !== -1 && (!ruleList || ruleList.length < replaceIndex)) {
			try {
				sheet.deleteRule(replaceIndex);
			} catch (ex) {}
		}
		var idx = -1;
		if (sheet.insertRule) {
			if (ruleList && replaceIndex >= ruleList.length) {
				replaceIndex = -1;
			}
			idx = sheet.insertRule(name + " { " + rule_ + " }",
				((replaceIndex !== -1) ? replaceIndex : ruleList.length));
		} else {
			if (ruleList && replaceIndex >= ruleList.length) {
				replaceIndex = -1;
			}
			idx = sheet.addRule(name, rule_,
				((replaceIndex !== -1) ? replaceIndex : -1));
		}
		//console.log("[" + idx + " => " + replaceIndex + "] " + name + " { " + rule_ + " }");
		return idx;
	};

	/**
	 * Add action to history
	 * @param {string} type
	 * @param {Object} data action descriptor as object
	 * @param {Function} undoCallback history callback when undo button is pressed (callback will be called func(data))
	 * @param {Function} redoCallback history callback when redo button is pressed (callback will be called func(data))
	 */
	Builder.prototype.historyAdd = function(type, data, undoCallback, redoCallback) {
		if (this.historyStack.length > this.historyPointer) {
			this.historyStack.splice(this.historyPointer, this.historyStack.length - this.historyPointer);
		}
		this.historyStack.push({ type: type, data: data, undo: undoCallback, redo: redoCallback });
		this.historyPointer = this.historyStack.length;
		if (typeof(this.historyOnChange) === "function") this.historyOnChange();
	};

	/**
	 * Check if there is undo stages
	 * @return {Boolean}
	 */
	Builder.prototype.historyHasUndo = function() {
		return (this.historyPointer > 0);
	};

	/**
	 * Check if there is redo stages
	 * @return {Boolean}
	 */
	Builder.prototype.historyHasRedo = function() {
		return (this.historyPointer < this.historyStack.length);
	};

	/**
	 * Find latest available record in undo buffer (only undo)
	 * @param {string|null} type Type of searched history record or NULL for any type. Defaults to NULL.
	 * @return {object|null} Returns an object containing all information on the found record or null if no record was found.
	 */
	Builder.prototype.historyGetLatestRecord = function(type) {
		for( var i = this.historyPointer - 1; i >= 0; i-- ) {
			if( !type || this.historyStack[i].type == type )
				return this.historyStack[i];
		}
		return null;
	};

	/**
	 * Undo action at history pointer
	 */
	Builder.prototype.historyUndo = function() {
		while( this.historyPointer > 0 ) {
			var isLast = (this.historyPointer === this.historyStack.length);
			var a = this.historyStack[--this.historyPointer];
			if( a.undo ) {
				a.undo.call(a, a.data);
				break;
			}
		}
		if (typeof(this.historyOnChange) === "function") this.historyOnChange();
	};

	/**
	 * Redo next action from history pointer
	 */
	Builder.prototype.historyRedo = function() {
		while( this.historyPointer < this.historyStack.length ) {
			var a = this.historyStack[this.historyPointer++];
			if( a.redo ) {
				a.redo.call(a, a.data);
				break;
			}
		}
		if (typeof(this.historyOnChange) === "function") this.historyOnChange();
	};
	
	Builder.prototype.historyClear = function() {
		this.historyStack = [];
		this.historyPointer = 0;
		if (typeof(this.historyOnChange) === "function") this.historyOnChange();
	};

	/**
	 * Set cookie
	 * @param {String} c_name cookie name
	 * @param {String} value cookie value (value will always be converted to string)
	 * @param {Number} exdays (optional) expires after days
	 */
	Builder.prototype.setCookie = function(c_name, value, exdays, path) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString()) + (path ? "; path=" + path : "");
		document.cookie = c_name + "=" + c_value;
	};

	/**
	 * Get cookie
	 * @param {String} c_name cookie name
	 * @return {String} cookie value (value will always be converted to string)
	 */
	Builder.prototype.getCookie = function(c_name) {
		var i, x, y, ARRcookies = document.cookie.split(";");
		for (i = 0; i < ARRcookies.length; i++) {
			x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
			y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
			x = x.replace(/^\s+|\s+$/g, "");
			if (x === c_name) return unescape(y);
		}
		return null;
	};

	/**
	 * Get url from route
	 * 
	 * @param {String} route route to add to base url
	 * @returns {String} url
	 */
	Builder.prototype.getUrl = function(route) {
		var url = this.baseUrl;
		if (this.isModRewrite) {
			url += (route ? (route + "/") : "");
		} else {
			url += "?" + this.routeGetKey + "=" + route;
		}
		return url;
	};

	/**
	 * Make local system URL
	 * 
	 * @param {String} url url to make into local URL
	 * @param {Boolean} escapeBaseName
	 * @return {String} local system URL
	 */
	Builder.prototype.makeLocalUrl = function(url, escapeBaseName) {
		var _url = null;
		if (url.substr(0, 4) === "http")
			_url = url;
		else
			_url = this.userBaseUrl + (escapeBaseName ? Builder.urlEncode(this.makeRelUrl(url)) : this.makeRelUrl(url));
		return _url;
	};

	/**
	 * Make relative URL
	 * 
	 * @param {String} url url to make into relative URL
	 * @return {String} relative url
	 */
	Builder.prototype.makeRelUrl = function(url) {
		var _url = (url + "").replace(this.userBaseUrl, "");
		return _url;
	};

	/**
	 * Quot string to use in regular expression
	 * @param {String} str string to quote
	 * @param delimiter
	 * @return {String} quoted string
	 */
	Builder.prototype.pregQuote = function(str, delimiter) {
		return (str+'').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\'+(delimiter || '')+'-]', 'g'), '\\$&');
	};

	/**
	 * Save data to virtual clipboard
	 * @param {Array} obj data to be saved
	 */
	Builder.prototype.setClipboard = function(obj) {
		this.clipboard = [];
		for (var i = 0; i < obj.length; i++) {
			this.clipboard.push($.extend(true, {}, obj[i]));
		}
	};

	/**
	 * Get data from virtual clipboard
	 * @return {Array} data from clipboard
	 */
	Builder.prototype.getClipboard = function() {
		return this.clipboard;
	};
	
	/**
	 * Get language by locale code
	 * @param {string} locale language locale code
	 * @returns {Object}
	 */
	Builder.prototype.getLanguageByLocale = function(locale) {
		if (!locale) return null;
		for (var i = 0, lang; (lang = wb_builder.availableLanguages[i]); i++) {
			if (lang.locale === locale) {
				return lang;
			}
		}
		return null;
	};
	
	/**
	 * Get country code by language code
	 * @param {String} langCode
	 * @returns {String} country code
	 */
	Builder.prototype.getCountryCode = function(langCode) {
		for (var i=0, lang; (lang = this.availableLanguages[i]); i++) {
			if (lang.code === langCode) {
				if (lang.countryCode === 'us') return 'gb';
				if (lang.countryCode === 'cs') return 'rs';
				if (lang.countryCode === 'ct') return 'es-ct';
				if (lang.countryCode === 'gb') return 'gb-wls';
				if (lang.countryCode === 'gl') return 'gal';
				return lang.countryCode;
			}
		}
		return langCode;
	};
	
	/**
	 * Get language by code
	 * @param {string} code language code
	 * @returns {Object}
	 */
	Builder.prototype.getLanguageByCode = function(code) {
		if (!code) return null;
		for (var i = 0, lang; (lang = wb_builder.availableLanguages[i]); i++) {
			if (lang.code === code) {
				return lang;
			}
		}
		return null;
	};
	
	/**
	 * Get indexed languages list
	 * @returns {Object}
	 */
	Builder.prototype.getLanguageCodeIndex = function() {
		if (!wb_builder.availableLanguagesIndex) {
			wb_builder.availableLanguagesIndex = {};
			for (var i = 0, lang; (lang = wb_builder.availableLanguages[i]); i++) {
				if (lang.code) {
					wb_builder.availableLanguagesIndex[lang.code] = lang;
				}
			}
		}
		return wb_builder.availableLanguagesIndex;
	};

	/**
	 * @param {boolean} enable
	 * @param {boolean} recreate
	 */
	Builder.prototype.setAutoLayout = function(enable, recreate) {
		if( enable && this.site.renderMode == Site.RENDER_MODE_RESPONSIVE2 )
			return;
		if( !enable && this.site.renderMode != Site.RENDER_MODE_RESPONSIVE2 )
			return;

		var thisClass = this;

		var errorMsg = function(errors) {
			if (!thisClass.msgDlg)
				thisClass.msgDlg = new MsgDialog();
			errors = $.unique(errors);
			thisClass.msgDlg.setTitle(__('Error'));
			thisClass.msgDlg.setMessage(errors.join('<br />'), __("Error:"), "error-big");
			thisClass.msgDlg.setVisible(true);
		};

		var enableAutoLayout = function() {
			var progress = new Preloader(__('Switch automatic layout'));
			progress.setProgress(0);
			progress.setVisible(true);
			progress.setMessage(__('Switching to automatic responsive layout generation'), '', 'warning');
			$.ajax({
				url: wb_builder.enableAutoLayoutUrl,
				data: {
					mode: ModeManager.getMode(),
					width: ModeManager.getModeWidth(ModeManager.getMode())
				},
				type: 'post',
				dataType: 'json',
				async: true,
				success: function(resp) {
					if( 'success' in resp && resp.success ) {
						thisClass.site.renderMode = Site.RENDER_MODE_RESPONSIVE2;
						ModeManager.setAutoLayoutEnabled(true);
						thisClass.loadPage(thisClass.pageId);
					}
					else if( 'error' in resp && error )
						errorMsg([resp.error]);
				},
				error: function() {
					errorMsg([__('Connection error')]);
				},
				complete: function() {
					progress.setProgress(100);
					progress.setVisible(false);
				}
			});
		};

		var disableAutoLayout = function() {
			var pageMap = {};
			var errors = [];
			var loaded = 0, total = 0;
			var progress = new Preloader(__('Switch automatic layout'));
			progress.setProgress(0);
			progress.setVisible(true);

			var finishResizing = function() {
				if( errors.length > 0 ) {
					errorMsg(errors);
					return;
				}
				progress.setMessage(__('Updating pages'), '', 'warning');
				$.ajax({
					url: wb_builder.disableAutoLayoutUrl,
					data: {
						data: JSON.stringify(pageMap)
					},
					type: 'post',
					dataType: 'json',
					async: true,
					success: function(resp) {
						progress.setProgress(100);
						progress.setVisible(false);
						if( 'success' in resp && resp.success ) {
							thisClass.site.renderMode = Site.RENDER_MODE_RESPONSIVE1;
							ModeManager.setAutoLayoutEnabled(false);
							thisClass.loadPage(thisClass.pageId);
						}
						else if( 'error' in resp && error )
							errorMsg([resp.error]);
					},
					error: function() {
						progress.setProgress(100);
						progress.setVisible(false);
						errorMsg([__('Connection error')]);
					}
				});
			};

			var loadResizedElements = function(pages) {
				var modes = ModeManager.getModes();
				total = pages.length * modes.length;
				progress.setProgress(Math.round(100 / (total + 2)));
				progress.setMessage(__('Recreating mode specific layout information'), '', 'warning');
				for( var i = 0; i < pages.length; i++ ) {
					for( var j = 0; j < modes.length; j++ ) {
						(function(pageId, mode) {
							var modeWidth = ModeManager.getModeWidth(mode);
							var iframe = document.createElement('iframe');
							var $iframe = $(iframe);
							$iframe
								.attr({
									frameborder: 0,
									marginwidth: 0,
									marginheight: 0,
									scrolling: 'no',
									width: modeWidth,
									height: 100
								})
								.css({
									position: 'absolute',
									left: '-' + (modeWidth + 1000) + 'px',
									top: 0,
									width: modeWidth + 'px',
									height: '100%',
									'z-index': '10000'
								})
							;
							$('body').append($iframe);
							thisClass.previewPage(pageId, {
								open: function() {
									return iframe.contentWindow;
								}
							}, true, true);
							$iframe
								.on('load', function(e) {
									loaded++;
									progress.setProgress(Math.round(100 * (1 + loaded) / (total + 2)));
									var elementMap = {};
									if( 'previewElementIdMap' in iframe.contentWindow ) {
										var idMap = iframe.contentWindow.previewElementIdMap;
										for (var previewId in idMap) {
											if (!idMap.hasOwnProperty(previewId))
												continue;
											var $elem = iframe.contentWindow.jQuery('#' + previewId);
											var $block = $elem.closest('.wb_page, .wb_container');
											var blockPos = $block.offset();
											var pos = $elem.offset();
											elementMap[idMap[previewId]] = {
												left: Math.round(pos.left),
												top: Math.round(pos.top - blockPos.top),
												width: Math.round($elem.outerWidth()),
												height: Math.round($elem.outerHeight()),
												verticalOrientation: $elem.is('.wb-elm-orient-vertical')
											};
										}
										$iframe.remove();
										if( !(pageId in pageMap) )
											pageMap[pageId] = {};
										pageMap[pageId][mode] = elementMap;
										if( loaded == total )
											finishResizing();
									}
									else {
										errors.push(__('Error loading resizing data'));
										if( loaded == total )
											finishResizing();
									}
								})
								.on('error', function(e) {
									$iframe.remove();
									loaded++;
									errors.push(__('Error loading resizing data'));
									progress.setProgress(Math.round(100 * (1 + loaded) / (total + 2)));
									if( loaded == total )
										finishResizing();
								})
							;
						})(pages[i], modes[j]);
					}
				}
			};

			if( recreate ) {
				progress.setMessage(__('Loading pages'), '', 'warning');
				$.ajax({
					url: wb_builder.resizeSiteUrl,
					type: 'post',
					dataType: 'json',
					async: true,
					success: function(resp) {
						if( 'success' in resp && resp.success )
							loadResizedElements(resp.pages);
						else if( 'error' in resp && error )
							errorMsg([resp.error]);
					},
					error: function() {
						errorMsg([__('Connection error')]);
					}
				});
			}
			else {
				progress.setMessage(__('Switching to manual responsive layout design'), '', 'warning');
				finishResizing();
			}
		};

		thisClass.checkPageErrors(__("Warning"), function() {
			thisClass.save(false, function(success, error) {
				if (success) {
					if( enable )
						enableAutoLayout();
					else
						disableAutoLayout();
				}
				else
					errorMsg([error]);
			}, null, false, false, true);
		});
	};

	Builder.prototype.resizeSite = function(newWidth) {
		var thisClass = this;
		thisClass.checkPageErrors(__("Warning"), function() {
			var pageMap = {};
			var errors = [];
			var loaded = 0, total = 0;
			var progress = new Preloader(__('Resizing website'));
			progress.setProgress(0);
			progress.setVisible(true);
			progress.setMessage(__('Loading pages'), '', 'warning');
			var errorMsg = function(errors) {
				if (!thisClass.msgDlg)
					thisClass.msgDlg = new MsgDialog();
				errors = $.unique(errors);
				thisClass.msgDlg.setTitle(__('Error'));
				thisClass.msgDlg.setMessage(errors.join('<br />'), __("Error:"), "error-big");
				thisClass.msgDlg.setVisible(true);
			};
			var finishResizing = function() {
				if( errors.length > 0 ) {
					errorMsg(errors);
					return;
				}
				progress.setMessage(__('Updating pages'), '', 'warning');
				$.ajax({
					url: wb_builder.resizeSiteUrl,
					data: {
						width: newWidth,
						data: JSON.stringify(pageMap)
					},
					type: 'post',
					dataType: 'json',
					async: true,
					success: function(resp) {
						progress.setProgress(100);
						progress.setVisible(false);
						if( 'success' in resp && resp.success ) {
							thisClass.loadPage(thisClass.pageId); // reload the page
						}
						else if( 'error' in resp && error )
							errorMsg([resp.error]);
					},
					error: function() {
						progress.setProgress(100);
						progress.setVisible(false);
						errorMsg([__('Connection error')]);
					}
				});
			};
			var loadResizedElements = function(pages) {
				total = pages.length;
				progress.setProgress(Math.round(100 / (total + 2)));
				progress.setMessage(__('Resizing and moving elements'), '', 'warning');
				for( var i = 0; i < pages.length; i++ ) {
					(function(pageId) {
						var iframe = document.createElement('iframe');
						var $iframe = $(iframe);
						$iframe
							.attr({
								frameborder: 0,
								marginwidth: 0,
								marginheight: 0,
								scrolling: 'no',
								width: newWidth,
								height: 100
							})
							.css({
								position: 'absolute',
								left: '-' + (newWidth + 1000) + 'px',
								top: 0,
								width: newWidth + 'px',
								height: '100%',
								'z-index': '10000'
							})
						;
						$('body').append($iframe);
						thisClass.previewPage(pageId, {
							open: function() {
								return iframe.contentWindow;
							}
						}, true, true);
						$iframe
							.on('load', function(e) {
								loaded++;
								progress.setProgress(Math.round(100 * (1 + loaded) / (total + 2)));
								var elementMap = {};
								if( 'previewElementIdMap' in iframe.contentWindow ) {
									var idMap = iframe.contentWindow.previewElementIdMap;
									for (var previewId in idMap) {
										if (!idMap.hasOwnProperty(previewId))
											continue;
										var $elem = iframe.contentWindow.jQuery('#' + previewId);
										var $block = $elem.closest('.wb_page, .wb_container');
										var blockPos = $block.offset();
										var pos = $elem.offset();
										elementMap[idMap[previewId]] = {
											left: Math.round(pos.left),
											top: Math.round(pos.top - blockPos.top),
											width: Math.round($elem.outerWidth()),
											height: Math.round($elem.outerHeight()),
											verticalOrientation: $elem.is('.wb-elm-orient-vertical')
										};
									}
									$iframe.remove();
									pageMap[pageId] = elementMap;
									if( loaded == total )
										finishResizing();
								}
								else {
									errors.push(__('Error loading resizing data'));
									if( loaded == total )
										finishResizing();
								}
							})
							.on('error', function(e) {
								$iframe.remove();
								loaded++;
								errors.push(__('Error loading resizing data'));
								progress.setProgress(Math.round(100 * (1 + loaded) / (total + 2)));
								if( loaded == total )
									finishResizing();
							})
						;
					})(pages[i]);
				}
			};
			var requestResizing = function() {
				$.ajax({
					url: wb_builder.resizeSiteUrl,
					type: 'post',
					dataType: 'json',
					async: true,
					success: function(resp) {
						if( 'success' in resp && resp.success )
							loadResizedElements(resp.pages);
						else if( 'error' in resp && error )
							errorMsg([resp.error]);
					},
					error: function() {
						errorMsg([__('Connection error')]);
					}
				});
			};
			thisClass.save(false, function(success, error) {
				if (success)
					requestResizing();
				else
					errorMsg([error]);
			}, null, false, false, true);
		});
	};

	/**
	 * Returns list of elements either in body or in help system player overlay if it is currently visible.
	 * @return {Element[]}
	 */
	Builder.prototype.getActiveViewElements = function() {
		var elements = null;
		if( this.helpPlayerVisible ) {
			var playerCanvas = Service.HelpSystemPlayer.getCanvas();
			if( playerCanvas )
				elements = playerCanvas.getElements();
		}
		if( elements === null )
			elements = this.bodyInstance ? this.bodyInstance.getContentElements() : [];
		return elements;
	};

	Builder.prototype.updateDropZones = function() {
		if( this.bodyInstance )
			this.bodyInstance.enableDropZones(!this.helpPlayerVisible);
	};

	Service.builder = Builder;
	window.WB_Builder = Builder;
	
	return Builder;
});

/**
 * @param {String|Object} value value from LangInputControl or similar
 * @param {String|Array} [langCode=null] desired language. If array then foreaches languages until finds the one with which the "translated" value is true.
 * @param {String} [defText=""] returned if "translated" value is not true.
 * @param {Boolean} [canTakeAny=false] allow to return any object value if "translated" value is not true.
 * @param {Boolean} [forceNonEmpty=false] forces returned value to be not empty if possible.
 * @return {String} "translated" value of specified language (or defText)
 */
window.__tr = function(value, langCode, defText, canTakeAny, forceNonEmpty) {
	if (!value) return value;
	var site = (window.wb_builder && window.wb_builder.site) ? window.wb_builder.site : null;
	
	var defLang = site ? site.getLastDefLang() : null,
		currLang = site ? site.currSelLang : null,
		mDefText = defText || '',
		returnValue = null;
	if (langCode === '__DEFAULT__') langCode = defLang;
	
	if (typeof value === 'string') {
		returnValue = value;
	} else if (typeof value === 'object') {
		if (langCode && (langCode in value) && (!forceNonEmpty || value[langCode]))
			returnValue = value[langCode];
		else if (currLang && (currLang in value) && (!forceNonEmpty || value[currLang]))
			returnValue = value[currLang];
		else if (defLang && (defLang in value) && (!forceNonEmpty || value[defLang]))
			returnValue = value[defLang];
		else if (canTakeAny) {
			for (var i in value) {
				if (!forceNonEmpty || value[i]) {
					returnValue = value[i];
					break;
				}
			}
		}
	}
	return returnValue ? returnValue : mDefText;
};

/**
 * Applies function to multilanguage value (value from LangInputControl) and returns modified value.
 * @param {String|Object} value
 * @param {Callback} func
 * @returns {String|Object}
 */
window.__trf = function(value, func) {
	if (!value) return value;
	if (typeof(func) !== 'function') return value;
	if (typeof(value) === 'string') {
		return func(value);
	} else if (typeof(value) === 'object') {
		var obj = {};
		for (var i in value) {
			obj[i] = func(value[i]);
		}
		return obj;
	}
	return null;
};

/**
 * Takes multilang value translation of builder language
 * @param value multilang value
 */
window.__trr = function(value) {
	return __tr(value, wb_builder.getLanguageByLocale(wb_builder.locale).code, null, true);
};

/**
 * Translates and propagates string with variables
 * @param {Object|String} value either string or object containing key and args
 * @return {String}
 */
window.__pr = function(value) {
	var message = null;
	if (typeof value === 'object' && ('key' in value)) {
		message = __(value.key);
		if (('vars' in value) && (value.vars instanceof Array)) {
			for (var i=0; i < value.vars.length; i++) {
				message = message.replace(/(?:%s|%d)/, value.vars[i]);
			}
		}
	} else if (typeof value === 'string') {
		message = __(value);
	} else {
		message = value;
	}
	return message;
};

// initialize JavaScript GetText
window.gt = window.Gettext ? new Gettext({"domain": "webbuilder"}) : null;

/**
 * GetText translation functionality
 * @param {string} msgid string to translate
 * @returns {string} translated string
 */
window.__ = function(msgid) {
	if (window.gt) {
		return window.gt.gettext(msgid);
	}
	return msgid;
};

window.__c = function(msg) {
	return '{{' + msg + '}}';
};

window.getElementById = function(id) {
	var elems = wb_builder.bodyInstance.getContentElements();
	for (var i in elems) {
		var elem = elems[i];
		if (elem.id === 'wb_element_instance' + id) {
			return elem;
		}
	}
	return null;
};

window.sanitizeAlias = function(alias) {
	var sepSym = '-';
	alias = alias.replace(/<\/?[^>]+>/gi, '')
			.replace(/%([a-fA-F0-9][a-fA-F0-9])/g, '---$1---')
			.replace('%', '')
			.replace(/---([a-fA-F0-9][a-fA-F0-9])--/, '%$1')
			.replace(/&.+?;/, '')
			.replace('.', sepSym)
			.replace(/—|–/g, sepSym)
			.replace(/¡|¿|«|»|‹|›|‘|’|“|”|‚|‛|„|‟|©|®|°|…|™|̀|́|̄|̌|×|\!|@|#|\$|%|\^|&|\*|\(|\)|"/g, '')
			.replace(/\s+/g, sepSym)
			.replace(/-+/g, sepSym)
			.replace(/^-*(.*)-*$/, '$1')
	return decodeURIComponent(alias);
};
;

/** jQuery ColorPicker plugin **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery ColorPicker plugin';
/**
 *
 * Color picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 * Dual licensed under the MIT and GPL licenses
 * 
 * @param {jQuery} $
 */
(function ($) {
	var WB_ColorPicker;
	
	var ColorPicker = function () {
		var
			ids = {},
			inAction,
			charMin = 65,
			hexMode = false,
			visible,
			tpl = '<div class="colorpicker">'
					+ '<div class="colorpicker_color"><div><div></div></div></div>'
					+ '<div class="colorpicker_hue"><div></div></div>'
					+ '<div class="colorpicker_alpha"><div class="cp-oo"></div><div class="cp-vi"></div></div>'
					+ '<div class="colorpicker_color1 colorpicker_new_color"><div></div></div>'
					+ '<div class="colorpicker_color1 colorpicker_current_color"><div></div></div>'
					+ '<div class="prep">#</div>'
					+ '<div class="colorpicker_hex input-group input-group-sm">'
						+ '<input class="cpc-hex form-control" type="text" maxlength="6" size="6" />'
						+ '<span class="input-group-btn">'
							+ '<button tabindex="-1" data-toggle="dropdown" class="more_controls btn btn-default dropdown-toggle"><span class="caret"></span></button>'
						+ '</span>'
					+ '</div>'
					+ '<div class="colorpicker_rgb_a colorpicker_field hide input-group input-group-sm">'
						+ '<span class="letter input-group-addon">A</span>'
						+ '<input class="cpc-rgb-a form-control" type="text" maxlength="3" size="3" />'
						+ '<span class="buttons input-group-btn"></span>'
					+ '</div>'
					+ '<div class="colorpicker_rgb">'
						+ '<div class="colorpicker_rgb_r colorpicker_field hide input-group input-group-sm">'
							+ '<span class="letter input-group-addon">R</span>'
							+ '<input class="cpc-rgb-r form-control" type="text" maxlength="3" size="3" />'
							+ '<span class="buttons input-group-btn"></span>'
						+ '</div>'
						+ '<div class="colorpicker_rgb_g colorpicker_field hide input-group input-group-sm">'
							+ '<span class="letter input-group-addon">G</span>'
							+ '<input class="cpc-rgb-g form-control" type="text" maxlength="3" size="3" />'
							+ '<span class="buttons input-group-btn"></span>'
						+ '</div>'
						+ '<div class="colorpicker_rgb_b colorpicker_field hide input-group input-group-sm">'
							+ '<span class="letter input-group-addon">B</span>'
							+ '<input class="cpc-rgb-b form-control" type="text" maxlength="3" size="3" />'
							+ '<span class="buttons input-group-btn"></span>'
						+ '</div>'
						+ '<div class="colorpicker_hsb_h colorpicker_field hide input-group input-group-sm">'
							+ '<span class="letter input-group-addon">H</span>'
							+ '<input class="cpc-hsb-h form-control" type="text" maxlength="3" size="3" />'
							+ '<span class="buttons input-group-btn"></span>'
						+ '</div>'
						+ '<div class="colorpicker_hsb_s colorpicker_field hide input-group input-group-sm">'
							+ '<span class="letter input-group-addon">S</span>'
							+ '<input class="cpc-hsb-s form-control" type="text" maxlength="3" size="3" />'
							+ '<span class="buttons input-group-btn"></span>'
						+ '</div>'
						+ '<div class="colorpicker_hsb_b colorpicker_field hide input-group input-group-sm">'
							+ '<span class="letter input-group-addon">B</span>'
							+ '<input class="cpc-hsb-b form-control" type="text" maxlength="3" size="3" />'
							+ '<span class="buttons input-group-btn"></span>'
						+ '</div>'
					+ '</div>'
					+ '<div class="colorpicker_buttons">'
						+ '<button class="btn btn-default btn-sm colorpicker_cancel">'+ __('Cancel') +'</button>'
						+ ' <button class="btn btn-default btn-sm colorpicker_transparent">'+ __('Transparent') +'</button>'
						+ ' <button class="btn btn-default btn-sm colorpicker_automatic hide2">'+ __('Automatic') +'</button>'
						+ ' <button class="btn btn-success btn-sm colorpicker_submit">'+ __('Apply') +'</button>'
					+ '</div>'
				+ '</div>',
			defaults = {
				eventName: "click",
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				color: "ff0000",
				trans: false,
				allowAlpha: true,
				auto: false,
				livePreview: true,
				flat: false
			},
			fillRGBFields = function  (hsb, cal) {
				var rgb = HSBToRGB(hsb);
				$(cal).data('colorpicker').fields
					.filter('.cpc-rgb-r').val(rgb.r).end()
					.filter('.cpc-rgb-g').val(rgb.g).end()
					.filter('.cpc-rgb-b').val(rgb.b).end()
					.filter('.cpc-rgb-a').val(Math.round(rgb.a * 100)).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colorpicker').fields
					.filter('.cpc-hsb-h').val(hsb.h).end()
					.filter('.cpc-hsb-s').val(hsb.s).end()
					.filter('.cpc-hsb-b').val(hsb.b).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colorpicker').fields
					.filter('.cpc-hex').val(HSBToHex(hsb)).end();
			},
			setSelector = function (hsb, cal) {
				$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colorpicker').selectorIndic.css({
					left: parseInt(150 * hsb.s/100, 10),
					top: parseInt(150 * (100-hsb.b)/100, 10)
				});
			},
			setHue = function (hsb, cal) {
				$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
			},
			setAlpha = function(hsb, cal) {
				$(cal).data('colorpicker').alpha.css('background-color', '#' + HSBToHex(hsb));
				$(cal).data('colorpicker').alphaIndic.css('left', parseInt(150 * (1 - hsb.a), 10));
			},
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colorpicker').currentColor
					.css('backgroundColor', '#' + HSBToHex(hsb))
					.children().css('opacity', 1 - hsb.a)
				;
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colorpicker').newColor
					.css('backgroundColor', '#' + HSBToHex(hsb))
					.children().css('opacity', 1 - hsb.a)
				;
			},
			keyDown = function (e) {
				var valid = false;
				if (e.ctrlKey && (e.keyCode === 67 || e.keyCode === 86)) { // allow copy/paste with Ctrl+C/Ctrl+V
					valid = true;
				}
				if ((!e.charCode && e.keyCode >= 48 && e.keyCode <= 57) ||
					(!e.charCode && e.keyCode >= 96 && e.keyCode <= 105) ||
					(e.charCode >= 48 && e.charCode <= 57)) { // validate numbers
					valid = true;
				}
				if ((e.keyCode >= 35 && e.keyCode <= 40) || e.keyCode === 45 ||
					e.keyCode === 46 || e.keyCode === 17 || e.keyCode === 13) { // validate controll keys
					valid = true;
				}
				if (hexMode) {
					if ((!e.charCode && e.keyCode >= 65 && e.keyCode <= 70) ||
						(e.charCode >= 65 && e.charCode <= 70) ||
						(e.charCode >= 97 && e.charCode <= 102)) { // validate hex
						valid = true;
					}
				}
				if (!valid) {
					return false;
				}
				var cal = $(this).parents(".colorpicker");
				if (cal.data('colorpicker').livePreview === true) {
					change.apply(this);
				}
			},
			change = function (ev) {
				var $this = $(this);
				var cal = $this.parents(".colorpicker"), col;
				var cp = cal.data('colorpicker');
				var fields = cp.fields;
				var alpha = parseInt(fields.filter('.cpc-rgb-a').val(), 10) / 100;
				if( !$this.is('.cpc-rgb-a') && (isNaN(alpha) || alpha < 0.00390625) )
					alpha = 1;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					col = HexToHSB(fixHex(this.value));
					col.a = alpha;
					cal.data('colorpicker').color = col;
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colorpicker').color = col = fixHSB({
						h: parseInt(fields.filter('.cpc-hsb-h').val(), 10),
						s: parseInt(fields.filter('.cpc-hsb-s').val(), 10),
						b: parseInt(fields.filter('.cpc-hsb-b').val(), 10),
						a: alpha
					});
				} else {
					cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
						r: parseInt(fields.filter('.cpc-rgb-r').val(), 10),
						g: parseInt(fields.filter('.cpc-rgb-g').val(), 10),
						b: parseInt(fields.filter('.cpc-rgb-b').val(), 10),
						a: alpha
					}));
				}
				if (ev) {
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setAlpha(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cp.onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
			},
			blur = function (ev) {
				var cal = $(this).parents(".colorpicker");
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
			},
			focus = function () {
				var cal = $(this).parents(".colorpicker");
				charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
				hexMode = (this.parentNode.className.indexOf('_hex') > 0);
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
				$(this).parent().addClass('colorpicker_focus');
			},
			downIncrement = function (ev) {
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colorpicker_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).closest('.colorpicker').data('colorpicker').livePreview
				};
				$(document).bind('mouseup', current, upIncrement);
				$(document).bind('mousemove', current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colorpicker_slider').find('input').focus();
				$(document).unbind('mouseup', upIncrement);
				$(document).unbind('mousemove', moveIncrement);
				return false;
			},
			downHue = function (ev) {
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upHue);
				$(document).bind('mousemove', current, moveHue);
			},
			moveHue = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.filter('.cpc-hsb-h')
						.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				moveHue(ev); // update on click
				$(document).unbind('mouseup', upHue);
				$(document).unbind('mousemove', moveHue);
				return false;
			},
			downAlpha = function (ev) {
				var current = {
					cal: $(this).parent(),
					x: $(this).offset().left
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upAlpha);
				$(document).bind('mousemove', current, moveAlpha);
			},
			moveAlpha = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.filter('.cpc-rgb-a')
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageX - ev.data.x))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upAlpha = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				moveAlpha(ev); // update on click
				$(document).unbind('mouseup', upAlpha);
				$(document).unbind('mousemove', moveAlpha);
				return false;
			},
			downSelector = function (ev) {
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upSelector);
				$(document).bind('mousemove', current, moveSelector);
			},
			moveSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.filter('.cpc-hsb-b')
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.filter('.cpc-hsb-s')
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				moveSelector(ev); // update on click
				$(document).unbind('mouseup', upSelector);
				$(document).unbind('mousemove', moveSelector);
				return false;
			},
			enterSubmit = function (ev) {
				$(this).addClass('colorpicker_focus');
			},
			leaveSubmit = function (ev) {
				$(this).removeClass('colorpicker_focus');
			},
			clickSubmit = function (ev) {
				var cal = $(this).parents(".colorpicker");
				var col = cal.data('colorpicker').color;
				cal.data('colorpicker').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('colorpickerId'));
				cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
				var pos = $(this).offset();
				var viewPort = getViewport();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				if (top + 176 > viewPort.t + viewPort.h) {
					top -= this.offsetHeight + 176;
				}
				if (left + 356 > viewPort.l + viewPort.w) {
					left -= 356;
				}
				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				$(document).bind('mousedown', {cal: cal}, hide);
				return false;
			},
			hide = function (ev, force) {
				if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
				else if (force) {
					ev.data.cal.data('colorpicker').onHide(ev.data.cal, ev);
					$(document).unbind('mousedown', hide);
				}
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b)),
					a: Math.min(1, Math.max(0, ("a" in hsb) ? hsb.a : 1))
				};
			}, 
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b)),
					a: Math.min(1, Math.max(0, ("a" in rgb) ? rgb.a : 1))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			},
			HexToRGB = function (text) {
				var color, matches;
				if( text && typeof text === "object" ) {
					color = $.extend(true, {}, text);
				}
				else if( !text || text === "transparent" ) {
					color = {r: 255, g: 255, b: 255, a: 0};
				}
				else {
					text = text.trim();
					if( matches = text.match(/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i) )
						color = {
							r: parseInt(matches[1] + matches[1], 16),
							g: parseInt(matches[2] + matches[2], 16),
							b: parseInt(matches[3] + matches[3], 16),
							a: 1
						};
					else if( matches = text.match(/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i) ) {
						color = {
							r: parseInt(matches[1], 16),
							g: parseInt(matches[2], 16),
							b: parseInt(matches[3], 16),
							a: 1
						};
					}
					else if( matches = text.match(/^rgb\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)$/i) ) {
						color = {
							r: parseFloat(matches[1]),
							g: parseFloat(matches[2]),
							b: parseFloat(matches[3]),
							a: 1
						};
					}
					else if( matches = text.match(/^rgba\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)$/i) ) {
						color = {
							r: parseFloat(matches[1]),
							g: parseFloat(matches[2]),
							b: parseFloat(matches[3]),
							a: parseFloat(matches[4])
						};
					}
					else if( matches = text.match(/^hsl\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)%\s*,\s*([0-9\.]+)%\s*\)$/i) ) {
						color = WB_ColorPicker.HSL2RGB({
							h: parseFloat(matches[1]) / 360,
							s: parseFloat(matches[2]) / 100,
							l: parseFloat(matches[3]) / 100,
							a: 1
						});
					}
					else if( matches = text.match(/^hsla\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)%\s*,\s*([0-9\.]+)%\s*,\s*([0-9\.]+)\s*\)$/i) ) {
						color = WB_ColorPicker.HSL2RGB({
							h: parseFloat(matches[1]) / 360,
							s: parseFloat(matches[2]) / 100,
							l: parseFloat(matches[3]) / 100,
							a: parseFloat(matches[4])
						});
					}
					else {
						color = {r: 255, g: 255, b: 255, a: 1};
					}
				}
				return color;
			},
			HexToHSB = function (hex) {
				return RGBToHSB(HexToRGB(hex));
			},
			RGBToHSB = function (rgb) {
				var hsb = {
					h: 0,
					s: 0,
					b: 0,
					a: ("a" in rgb) ? rgb.a : 1
				};
				var min = Math.min(rgb.r, rgb.g, rgb.b);
				var max = Math.max(rgb.r, rgb.g, rgb.b);
				var delta = max - min;
				hsb.b = max;
				if (max != 0) {
					
				}
				hsb.s = max != 0 ? 255 * delta / max : 0;
				if (hsb.s != 0) {
					if (rgb.r == max) {
						hsb.h = (rgb.g - rgb.b) / delta;
					} else if (rgb.g == max) {
						hsb.h = 2 + (rgb.b - rgb.r) / delta;
					} else {
						hsb.h = 4 + (rgb.r - rgb.g) / delta;
					}
				} else {
					hsb.h = -1;
				}
				hsb.h *= 60;
				if (hsb.h < 0) {
					hsb.h += 360;
				}
				hsb.s *= 100/255;
				hsb.b *= 100/255;
				return hsb;
			},
			HSBToRGB = function(hsv){
				var h = hsv.h / 360, s = hsv.s / 100, v = hsv.b / 100;
			    var r, g, b;
			    var i = Math.floor(h * 6);
			    var f = h * 6 - i;
			    var p = v * (1 - s);
			    var q = v * (1 - f * s);
			    var t = v * (1 - (1 - f) * s);
			    switch(i % 6){
			        case 0: r = v; g = t; b = p; break;
			        case 1: r = q; g = v; b = p; break;
			        case 2: r = p; g = v; b = t; break;
			        case 3: r = p; g = q; b = v; break;
			        case 4: r = t; g = p; b = v; break;
			        case 5: r = v; g = p; b = q; break;
			    }
			    return {r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255), a: ("a" in hsv) ? Math.round(hsv.a * 100) / 100 : 1};
			},
			RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			},
			HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			},
			restoreOriginal = function () {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').origColor;
				cal.data('colorpicker').color = col;
				fillRGBFields(col, cal.get(0));
				fillHexFields(col, cal.get(0));
				fillHSBFields(col, cal.get(0));
				setSelector(col, cal.get(0));
				setAlpha(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
			};
		return {
			init: function (opt) {
				if (!WB_ColorPicker) WB_ColorPicker = opt.WB_ColorPicker;
				
				opt = $.extend({}, defaults, opt||{});
				if (typeof opt.color == 'string') {
					opt.color = HexToHSB(opt.color);
				} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
					opt.color = RGBToHSB(fixRGB(opt.color));
				} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
					opt.color = fixHSB(opt.color);
				} else {
					return this;
				}
				return this.each(function () {
					if (!$(this).data('colorpickerId')) {
						var options = $.extend({}, opt);
						options.origColor = opt.color;
						var id = 'collorpicker_' + parseInt(Math.random() * 1000);
						$(this).data('colorpickerId', id);
						var cal = $(tpl).attr('id', id);
						if (options.flat) {
							cal.appendTo(this).show();
						} else {
							cal.appendTo(document.body);
						}
						options.fields = cal
											.find('input')
												.bind('keyup', keyDown)
												.bind('change', change)
												.bind('blur', blur)
												.bind('focus', focus);
						cal
							.find('span.buttons').bind('mousedown', downIncrement).end()
							.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
						if( options.allowAlpha )
							cal.addClass('allow-alpha');
						options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
						options.selectorIndic = options.selector.find('div div');
						options.el = this;
						options.hue = cal.find('div.colorpicker_hue div');
						options.alpha = cal.find('div.colorpicker_alpha .cp-oo');
						options.alphaIndic = cal.find('div.colorpicker_alpha .cp-vi');
						cal.find('div.colorpicker_hue').bind('mousedown', downHue);
						cal.find('div.colorpicker_alpha').bind('mousedown', downAlpha);
						options.newColor = cal.find('div.colorpicker_new_color');
						options.currentColor = cal.find('div.colorpicker_current_color');
						cal.data('colorpicker', options);
						cal.find('button.colorpicker_submit')
							.bind('mouseenter', enterSubmit)
							.bind('mouseleave', leaveSubmit)
							.bind('click', clickSubmit);
						cal.find('button.colorpicker_cancel')
							.bind('click', function(e) {
								e.data = {cal:cal};
								hide(e, true);
							});
						cal.find('button.colorpicker_transparent')
						.bind('click', function(e) {
							cal.data('colorpicker').onSubmit(null, 'transparent', null, cal.data('colorpicker').el);
						});
						cal.find('button.colorpicker_automatic')
							.bind('click', function(e) {
								cal.data('colorpicker').onSubmit(null, 'inherit', null, cal.data('colorpicker').el);
							});
						if (options.auto) {
							cal.find('button.colorpicker_automatic').removeClass("hide2");
						}
						cal.find('button.more_controls')
							.bind('click', function(e) {
								cal.css("height", cal.hasClass("allow-alpha") ? "338px" : "305px");
								cal.find(".colorpicker_field").removeClass('hide');
								$(this).attr("disabled", "disabled");
							});
						cal.find('.colorpicker_field span.buttons').each(function(i, el) {
							$(el).html('<button class="btn btn-default btn-arrow arrow-up"><span class="caret"></span></button><button class="btn btn-default btn-arrow arrow-down"><span class="caret"></span></button>');
							$(el).find("button").click(function() {
								var inc = $(this).hasClass("arrow-up") ? true : false;
								var field = $(this).parents('.colorpicker_field').find('input').focus();
								var max =  $(this).parents('.colorpicker_field').attr('class').indexOf('_hsb_h') > 0 ? 360 : ($(this).parents('.colorpicker_field').attr('class').indexOf('_hsb') > 0 ? 100 : 255);
								var val = parseInt(field.val());
								if (inc) {
									val++;
								}
								else {
									val--;
								}
								if (val < 0) {
									val = 0;
								}
								else if (val > max) {
									val = max;
								}
								field.val(val);
								field.change();
							});
						});
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setAlpha(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						if (options.flat) {
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							$(this).bind(options.eventName, show);
						}
					}
				});
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						$('#' + $(this).data('colorpickerId')).hide();
					}
				});
			},
			setColor: function(col) {
				if (typeof col == 'string') {
					col = HexToHSB(col);
				} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
					col = RGBToHSB(fixRGB(col));
				} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
					col = fixHSB(col);
				} else {
					return this;
				}
				return this.each(function(){
					if ($(this).data('colorpickerId')) {
						var cal = $('#' + $(this).data('colorpickerId'));
						cal.data('colorpicker').color = col;
						cal.data('colorpicker').origColor = col;
						fillRGBFields(col, cal.get(0));
						fillHSBFields(col, cal.get(0));
						fillHexFields(col, cal.get(0));
						setHue(col, cal.get(0));
						setSelector(col, cal.get(0));
						setAlpha(col, cal.get(0));
						setCurrentColor(col, cal.get(0));
						setNewColor(col, cal.get(0));
					}
				});
			}
		};
	}();
	$.fn.extend({
		ColorPicker: ColorPicker.init,
		ColorPickerHide: ColorPicker.hidePicker,
		ColorPickerShow: ColorPicker.showPicker,
		ColorPickerSetColor: ColorPicker.setColor
	});
})(jQuery);
;

/** jQuery JSON plugin **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery JSON plugin';
jQuery.JSON = {
useHasOwn : ({}.hasOwnProperty ? true : false),
pad : function(n) {
return n < 10 ? "0" + n : n;
},
m : {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"' : '\\"',
"\\": '\\\\'
},
encodeString : function(s){
if (/["\\\x00-\x1f]/.test(s)) {
var m = this.m;
return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if(c){
return c;
}
c = b.charCodeAt();
return "\\u00" +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + s + '"';
},
encodeArray : function(o){
var a = ["["], b, i, l = o.length, v;
for (i = 0; i < l; i += 1) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(v === null ? "null" : this.encode(v));
b = true;
}
}
a.push("]");
return a.join("");
},
encodeDate : function(o){
return '"' + o.getFullYear() + "-" +
pad(o.getMonth() + 1) + "-" +
pad(o.getDate()) + "T" +
pad(o.getHours()) + ":" +
pad(o.getMinutes()) + ":" +
pad(o.getSeconds()) + '"';
},
encode : function(o){
if(typeof o == "undefined" || o === null){
return "null";
}else if(o instanceof Array){
return this.encodeArray(o);
}else if(o instanceof Date){
return this.encodeDate(o);
}else if(typeof o == "string"){
return this.encodeString(o);
}else if(typeof o == "number"){
return isFinite(o) ? String(o) : "null";
}else if(typeof o == "boolean"){
return String(o);
}else {
var self = this;

var a = ["{"], b, i, v;
for (i in o) {
if(!this.useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if(b){
a.push(',');
}
a.push(self.encode(i), ":",
v === null ? "null" : self.encode(v));
b = true;
}
}
}
a.push("}");
return a.join("");
}
},
decode : function(json){
return eval("(" + json + ')');
}
};;

/** jQuery jsTree **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery jsTree';
/*
 * jsTree 1.0-rc3
 * http://jstree.com/
 *
 * Copyright (c) 2010 Ivan Bozhanov (vakata.com)
 *
 * Licensed same as jquery - under the terms of either the MIT License or the GPL Version 2 License
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Date: 2011-02-09 01:17:14 +0200 (ср, 09 февр 2011) $
 * $Revision: 236 $
 */

/*jslint browser: true, onevar: true, undef: true, bitwise: true, strict: true */
/*global window : false, clearInterval: false, clearTimeout: false, document: false, setInterval: false, setTimeout: false, jQuery: false, navigator: false, XSLTProcessor: false, DOMParser: false, XMLSerializer: false*/

"use strict";

// top wrapper to prevent multiple inclusion (is this OK?)
(function () { if(jQuery && jQuery.jstree) { return; }
	var is_ie6 = false, is_ie7 = false, is_ff2 = false;

/* 
 * jsTree core
 */
(function ($) {
	// Common functions not related to jsTree 
	// decided to move them to a `vakata` "namespace"
	$.vakata = {};
	// CSS related functions
	$.vakata.css = {
		get_css : function(rule_name, delete_flag, sheet) {
			rule_name = rule_name.toLowerCase();
			var css_rules = sheet.cssRules || sheet.rules,
				j = 0;
			do {
				if(css_rules.length && j > css_rules.length + 5) { return false; }
				if(css_rules[j].selectorText && css_rules[j].selectorText.toLowerCase() == rule_name) {
					if(delete_flag === true) {
						if(sheet.removeRule) { sheet.removeRule(j); }
						if(sheet.deleteRule) { sheet.deleteRule(j); }
						return true;
					}
					else { return css_rules[j]; }
				}
			}
			while (css_rules[++j]);
			return false;
		},
		add_css : function(rule_name, sheet) {
			if($.jstree.css.get_css(rule_name, false, sheet)) { return false; }
			if(sheet.insertRule) { sheet.insertRule(rule_name + ' { }', 0); } else { sheet.addRule(rule_name, null, 0); }
			return $.vakata.css.get_css(rule_name);
		},
		remove_css : function(rule_name, sheet) { 
			return $.vakata.css.get_css(rule_name, true, sheet); 
		},
		add_sheet : function(opts) {
			var tmp = false, is_new = true;
			if(opts.str) {
				if(opts.title) { tmp = $("style[id='" + opts.title + "-stylesheet']")[0]; }
				if(tmp) { is_new = false; }
				else {
					tmp = document.createElement("style");
					tmp.setAttribute('type',"text/css");
					if(opts.title) { tmp.setAttribute("id", opts.title + "-stylesheet"); }
				}
				if(tmp.styleSheet) {
					if(is_new) { 
						document.getElementsByTagName("head")[0].appendChild(tmp); 
						tmp.styleSheet.cssText = opts.str; 
					}
					else {
						tmp.styleSheet.cssText = tmp.styleSheet.cssText + " " + opts.str; 
					}
				}
				else {
					tmp.appendChild(document.createTextNode(opts.str));
					document.getElementsByTagName("head")[0].appendChild(tmp);
				}
				return tmp.sheet || tmp.styleSheet;
			}
			if(opts.url) {
				if(document.createStyleSheet) {
					try { tmp = document.createStyleSheet(opts.url); } catch (e) { }
				}
				else {
					tmp			= document.createElement('link');
					tmp.rel		= 'stylesheet';
					tmp.type	= 'text/css';
					tmp.media	= "all";
					tmp.href	= opts.url;
					document.getElementsByTagName("head")[0].appendChild(tmp);
					return tmp.styleSheet;
				}
			}
		}
	};

	// private variables 
	var instances = [],			// instance array (used by $.jstree.reference/create/focused)
		focused_instance = -1,	// the index in the instance array of the currently focused instance
		plugins = {},			// list of included plugins
		prepared_move = {};		// for the move_node function

	// jQuery plugin wrapper (thanks to jquery UI widget function)
	$.fn.jstree = function (settings) {
		var isMethodCall = (typeof settings == 'string'), // is this a method call like $().jstree("open_node")
			args = Array.prototype.slice.call(arguments, 1), 
			returnValue = this;

		// if a method call execute the method on all selected instances
		if(isMethodCall) {
			if(settings.substring(0, 1) == '_') { return returnValue; }
			this.each(function() {
				var instance = instances[$.data(this, "jstree_instance_id")],
					methodValue = (instance && $.isFunction(instance[settings])) ? instance[settings].apply(instance, args) : instance;
					if(typeof methodValue !== "undefined" && (settings.indexOf("is_") === 0 || (methodValue !== true && methodValue !== false))) { returnValue = methodValue; return false; }
			});
		}
		else {
			this.each(function() {
				// extend settings and allow for multiple hashes and $.data
				var instance_id = $.data(this, "jstree_instance_id"),
					a = [],
					b = settings ? $.extend({}, true, settings) : {},
					c = $(this), 
					s = false, 
					t = [];
				a = a.concat(args);
				if(c.data("jstree")) { a.push(c.data("jstree")); }
				b = a.length ? $.extend.apply(null, [true, b].concat(a)) : b;

				// if an instance already exists, destroy it first
				if(typeof instance_id !== "undefined" && instances[instance_id]) { instances[instance_id].destroy(); }
				// push a new empty object to the instances array
				instance_id = parseInt(instances.push({}),10) - 1;
				// store the jstree instance id to the container element
				$.data(this, "jstree_instance_id", instance_id);
				// clean up all plugins
				b.plugins = $.isArray(b.plugins) ? b.plugins : $.jstree.defaults.plugins.slice();
				b.plugins.unshift("core");
				// only unique plugins
				b.plugins = b.plugins.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");

				// extend defaults with passed data
				s = $.extend(true, {}, $.jstree.defaults, b);
				s.plugins = b.plugins;
				$.each(plugins, function (i, val) { 
					if($.inArray(i, s.plugins) === -1) { s[i] = null; delete s[i]; } 
					else { t.push(i); }
				});
				s.plugins = t;

				// push the new object to the instances array (at the same time set the default classes to the container) and init
				instances[instance_id] = new $.jstree._instance(instance_id, $(this).addClass("jstree jstree-" + instance_id), s); 
				// init all activated plugins for this instance
				$.each(instances[instance_id]._get_settings().plugins, function (i, val) { instances[instance_id].data[val] = {}; });
				$.each(instances[instance_id]._get_settings().plugins, function (i, val) { if(plugins[val]) { plugins[val].__init.apply(instances[instance_id]); } });
				// initialize the instance
				setTimeout(function() { if(instances[instance_id]) { instances[instance_id].init(); } }, 0);
			});
		}
		// return the jquery selection (or if it was a method call that returned a value - the returned value)
		return returnValue;
	};
	// object to store exposed functions and objects
	$.jstree = {
		defaults : {
			plugins : []
		},
		_focused : function () { return instances[focused_instance] || null; },
		_reference : function (needle) { 
			// get by instance id
			if(instances[needle]) { return instances[needle]; }
			// get by DOM (if still no luck - return null
			var o = $(needle); 
			if(!o.length && typeof needle === "string") { o = $("#" + needle); }
			if(!o.length) { return null; }
			return instances[o.closest(".jstree").data("jstree_instance_id")] || null; 
		},
		_instance : function (index, container, settings) { 
			// for plugins to store data in
			this.data = { core : {} };
			this.get_settings	= function () { return $.extend(true, {}, settings); };
			this._get_settings	= function () { return settings; };
			this.get_index		= function () { return index; };
			this.get_container	= function () { return container; };
			this.get_container_ul = function () { return container.children("ul:eq(0)"); };
			this._set_settings	= function (s) { 
				settings = $.extend(true, {}, settings, s);
			};
		},
		_fn : { },
		plugin : function (pname, pdata) {
			pdata = $.extend({}, {
				__init		: $.noop, 
				__destroy	: $.noop,
				_fn			: {},
				defaults	: false
			}, pdata);
			plugins[pname] = pdata;

			$.jstree.defaults[pname] = pdata.defaults;
			$.each(pdata._fn, function (i, val) {
				val.plugin		= pname;
				val.old			= $.jstree._fn[i];
				$.jstree._fn[i] = function () {
					var rslt,
						func = val,
						args = Array.prototype.slice.call(arguments),
						evnt = new $.Event("before.jstree"),
						rlbk = false;

					if(this.data.core.locked === true && i !== "unlock" && i !== "is_locked") { return; }

					// Check if function belongs to the included plugins of this instance
					do {
						if(func && func.plugin && $.inArray(func.plugin, this._get_settings().plugins) !== -1) { break; }
						func = func.old;
					} while(func);
					if(!func) { return; }

					// context and function to trigger events, then finally call the function
					if(i.indexOf("_") === 0) {
						rslt = func.apply(this, args);
					}
					else {
						rslt = this.get_container().triggerHandler(evnt, { "func" : i, "inst" : this, "args" : args, "plugin" : func.plugin });
						if(rslt === false) { return; }
						if(typeof rslt !== "undefined") { args = rslt; }

						rslt = func.apply(
							$.extend({}, this, { 
								__callback : function (data) { 
									this.get_container().triggerHandler( i + '.jstree', { "inst" : this, "args" : args, "rslt" : data, "rlbk" : rlbk });
								},
								__rollback : function () { 
									rlbk = this.get_rollback();
									return rlbk;
								},
								__call_old : function (replace_arguments) {
									return func.old.apply(this, (replace_arguments ? Array.prototype.slice.call(arguments, 1) : args ) );
								}
							}), args);
					}

					// return the result
					return rslt;
				};
				$.jstree._fn[i].old = val.old;
				$.jstree._fn[i].plugin = pname;
			});
		},
		rollback : function (rb) {
			if(rb) {
				if(!$.isArray(rb)) { rb = [ rb ]; }
				$.each(rb, function (i, val) {
					instances[val.i].set_rollback(val.h, val.d);
				});
			}
		}
	};
	// set the prototype for all instances
	$.jstree._fn = $.jstree._instance.prototype = {};

	// load the css when DOM is ready
	$(function() {
		// code is copied from jQuery ($.browser is deprecated + there is a bug in IE)
		var u = navigator.userAgent.toLowerCase(),
			v = (u.match( /.+?(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
			css_string = '' + 
				'.jstree ul, .jstree li { display:block; margin:0 0 0 0; padding:0 0 0 0; list-style-type:none; } ' + 
				'.jstree li { display:block; min-height:18px; line-height:24px; white-space:nowrap; margin-left:18px; min-width:18px; } ' + 
				'.jstree-rtl li { margin-left:0; margin-right:18px; } ' + 
				'.jstree > ul > li { margin-left:0px; } ' + 
				'.jstree-rtl > ul > li { margin-right:0px; } ' + 
				'.jstree ins { display:inline-block; text-decoration:none; width:18px; height:18px; margin:0 0 0 0; padding:0; } ' + 
				'.jstree a { display:inline-block; line-height:16px; color:black; white-space:nowrap; text-decoration:none; padding:1px 2px; margin:0; } ' + 
				'.jstree a:focus { outline: none; } ' + 
				//'.jstree a > ins { height:16px; width:16px; } ' + 
				'.jstree a > .jstree-icon { margin-right:3px; } ' + 
				'.jstree-rtl a > .jstree-icon { margin-left:3px; margin-right:0; } ' + 
				'li.jstree-open > ul { display:block; } ' + 
				'li.jstree-closed > ul { display:none; } ';
		// Correct IE 6 (does not support the > CSS selector)
		if(/msie/.test(u) && parseInt(v, 10) == 6) { 
			is_ie6 = true;

			// fix image flicker and lack of caching
			try {
				document.execCommand("BackgroundImageCache", false, true);
			} catch (err) { }

			css_string += '' + 
				'.jstree li { height:18px; margin-left:0; margin-right:0; } ' + 
				'.jstree li li { margin-left:18px; } ' + 
				'.jstree-rtl li li { margin-left:0px; margin-right:18px; } ' + 
				'li.jstree-open ul { display:block; } ' + 
				'li.jstree-closed ul { display:none !important; } ' + 
				'.jstree li a { display:inline; border-width:0 !important; padding:0px 2px !important; } ' + 
				'.jstree li a ins { height:16px; width:16px; margin-right:3px; } ' + 
				'.jstree-rtl li a ins { margin-right:0px; margin-left:3px; } ';
		}
		// Correct IE 7 (shifts anchor nodes onhover)
		if(/msie/.test(u) && parseInt(v, 10) == 7) { 
			is_ie7 = true;
			css_string += '.jstree li a { border-width:0 !important; padding:0px 2px !important; } ';
		}
		// correct ff2 lack of display:inline-block
		if(!/compatible/.test(u) && /mozilla/.test(u) && parseFloat(v, 10) < 1.9) {
			is_ff2 = true;
			css_string += '' + 
				'.jstree ins { display:-moz-inline-box; } ' + 
				'.jstree li { line-height:12px; } ' + // WHY??
				'.jstree a { display:-moz-inline-box; } ' + 
				'.jstree .jstree-no-icons .jstree-checkbox { display:-moz-inline-stack !important; } ';
				/* this shouldn't be here as it is theme specific */
		}
		// the default stylesheet
		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
	});

	// core functions (open, close, create, update, delete)
	$.jstree.plugin("core", {
		__init : function () {
			this.data.core.locked = false;
			this.data.core.to_open = this.get_settings().core.initially_open;
			this.data.core.to_load = this.get_settings().core.initially_load;
		},
		defaults : { 
			html_titles	: false,
			animation	: 500,
			initially_open : [],
			initially_load : [],
			open_parents : true,
			notify_plugins : true,
			rtl			: false,
			load_open	: false,
			strings		: {
				loading		: "Loading ...",
				new_node	: "New node",
				multiple_selection : "Multiple selection"
			}
		},
		_fn : { 
			init	: function () { 
				this.set_focus(); 
				if(this._get_settings().core.rtl) {
					this.get_container().addClass("jstree-rtl").css("direction", "rtl");
				}
				this.get_container().html("<ul><li class='jstree-last jstree-leaf'><ins>&#160;</ins><a class='jstree-loading' href='#'><ins class='jstree-icon'>&#160;</ins>" + this._get_string("loading") + "</a></li></ul>");
				this.data.core.li_height = this.get_container_ul().find("li.jstree-closed, li.jstree-leaf").eq(0).height() || 18;

				this.get_container()
					.delegate("li > ins", "click.jstree", $.proxy(function (event) {
							var trgt = $(event.target);
							// if(trgt.is("ins") && event.pageY - trgt.offset().top < this.data.core.li_height) { this.toggle_node(trgt); }
							this.toggle_node(trgt);
						}, this))
					.bind("mousedown.jstree", $.proxy(function () { 
							this.set_focus(); // This used to be setTimeout(set_focus,0) - why?
						}, this))
					.bind("dblclick.jstree", function (event) { 
						var sel;
						if(document.selection && document.selection.empty) { document.selection.empty(); }
						else {
							if(window.getSelection) {
								sel = window.getSelection();
								try { 
									sel.removeAllRanges();
									sel.collapse();
								} catch (err) { }
							}
						}
					});
				if(this._get_settings().core.notify_plugins) {
					this.get_container()
						.bind("load_node.jstree", $.proxy(function (e, data) { 
								var o = this._get_node(data.rslt.obj),
									t = this;
								if(o === -1) { o = this.get_container_ul(); }
								if(!o.length) { return; }
								o.find("li").each(function () {
									var th = $(this);
									if(th.data("jstree")) {
										$.each(th.data("jstree"), function (plugin, values) {
											if(t.data[plugin] && $.isFunction(t["_" + plugin + "_notify"])) {
												t["_" + plugin + "_notify"].call(t, th, values);
											}
										});
									}
								});
							}, this));
				}
				if(this._get_settings().core.load_open) {
					this.get_container()
						.bind("load_node.jstree", $.proxy(function (e, data) { 
								var o = this._get_node(data.rslt.obj),
									t = this;
								if(o === -1) { o = this.get_container_ul(); }
								if(!o.length) { return; }
								o.find("li.jstree-open:not(:has(ul))").each(function () {
									t.load_node(this, $.noop, $.noop);
								});
							}, this));
				}
				this.__callback();
				this.load_node(-1, function () { this.loaded(); this.reload_nodes(); });
			},
			destroy	: function () { 
				var i,
					n = this.get_index(),
					s = this._get_settings(),
					_this = this;

				$.each(s.plugins, function (i, val) {
					try { plugins[val].__destroy.apply(_this); } catch(err) { }
				});
				this.__callback();
				// set focus to another instance if this one is focused
				if(this.is_focused()) { 
					for(i in instances) { 
						if(instances.hasOwnProperty(i) && i != n) { 
							instances[i].set_focus(); 
							break; 
						} 
					}
				}
				// if no other instance found
				if(n === focused_instance) { focused_instance = -1; }
				// remove all traces of jstree in the DOM (only the ones set using jstree*) and cleans all events
				this.get_container()
					.unbind(".jstree")
					.undelegate(".jstree")
					.removeData("jstree_instance_id")
					.find("[class^='jstree']")
						.andSelf()
						.attr("class", function () { return this.className.replace(/jstree[^ ]*|$/ig,''); });
				$(document)
					.unbind(".jstree-" + n)
					.undelegate(".jstree-" + n);
				// remove the actual data
				instances[n] = null;
				delete instances[n];
			},

			_core_notify : function (n, data) {
				if(data.opened) {
					this.open_node(n, false, true);
				}
			},

			lock : function () {
				this.data.core.locked = true;
				this.get_container().children("ul").addClass("jstree-locked").css("opacity","0.7");
				this.__callback({});
			},
			unlock : function () {
				this.data.core.locked = false;
				this.get_container().children("ul").removeClass("jstree-locked").css("opacity","1");
				this.__callback({});
			},
			is_locked : function () { return this.data.core.locked; },
			save_opened : function () {
				var _this = this;
				this.data.core.to_open = [];
				this.get_container_ul().find("li.jstree-open").each(function () { 
					if(this.id) { _this.data.core.to_open.push("#" + this.id.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:")); }
				});
				this.__callback(_this.data.core.to_open);
			},
			save_loaded : function () { },
			reload_nodes : function (is_callback) {
				var _this = this,
					done = true,
					current = [],
					remaining = [];
				if(!is_callback) { 
					this.data.core.reopen = false; 
					this.data.core.refreshing = true; 
					this.data.core.to_open = $.map($.makeArray(this.data.core.to_open), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
					this.data.core.to_load = $.map($.makeArray(this.data.core.to_load), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
					if(this.data.core.to_open.length) {
						this.data.core.to_load = this.data.core.to_load.concat(this.data.core.to_open);
					}
				}
				if(this.data.core.to_load.length) {
					$.each(this.data.core.to_load, function (i, val) {
						if(val == "#") { return true; }
						if($(val).length) { current.push(val); }
						else { remaining.push(val); }
					});
					if(current.length) {
						this.data.core.to_load = remaining;
						$.each(current, function (i, val) { 
							if(!_this._is_loaded(val)) {
								_this.load_node(val, function () { _this.reload_nodes(true); }, function () { _this.reload_nodes(true); });
								done = false;
							}
						});
					}
				}
				if(this.data.core.to_open.length) {
					$.each(this.data.core.to_open, function (i, val) {
						_this.open_node(val, false, true); 
					});
				}
				if(done) { 
					// TODO: find a more elegant approach to syncronizing returning requests
					if(this.data.core.reopen) { clearTimeout(this.data.core.reopen); }
					this.data.core.reopen = setTimeout(function () { _this.__callback({}, _this); }, 50);
					this.data.core.refreshing = false;
					this.reopen();
				}
			},
			reopen : function () {
				var _this = this;
				if(this.data.core.to_open.length) {
					$.each(this.data.core.to_open, function (i, val) {
						_this.open_node(val, false, true); 
					});
				}
				this.__callback({});
			},
			refresh : function (obj) {
				var _this = this;
				this.save_opened();
				if(!obj) { obj = -1; }
				obj = this._get_node(obj);
				if(!obj) { obj = -1; }
				if(obj !== -1) { obj.children("UL").remove(); }
				else { this.get_container_ul().empty(); }
				this.load_node(obj, function () { _this.__callback({ "obj" : obj}); _this.reload_nodes(); });
			},
			// Dummy function to fire after the first load (so that there is a jstree.loaded event)
			loaded	: function () { 
				this.__callback(); 
			},
			// deal with focus
			set_focus	: function () { 
				if(this.is_focused()) { return; }
				var f = $.jstree._focused();
				if(f) { f.unset_focus(); }

				this.get_container().addClass("jstree-focused"); 
				focused_instance = this.get_index(); 
				this.__callback();
			},
			is_focused	: function () { 
				return focused_instance == this.get_index(); 
			},
			unset_focus	: function () {
				if(this.is_focused()) {
					this.get_container().removeClass("jstree-focused"); 
					focused_instance = -1; 
				}
				this.__callback();
			},

			// traverse
			_get_node		: function (obj) { 
				var $obj = $(obj, this.get_container()); 
				if($obj.is(".jstree") || obj == -1) { return -1; } 
				$obj = $obj.closest("li", this.get_container()); 
				return $obj.length ? $obj : false; 
			},
			_get_next		: function (obj, strict) {
				obj = this._get_node(obj);
				if(obj === -1) { return this.get_container().find("> ul > li:first-child"); }
				if(!obj.length) { return false; }
				if(strict) { return (obj.nextAll("li").size() > 0) ? obj.nextAll("li:eq(0)") : false; }

				if(obj.hasClass("jstree-open")) { return obj.find("li:eq(0)"); }
				else if(obj.nextAll("li").size() > 0) { return obj.nextAll("li:eq(0)"); }
				else { return obj.parentsUntil(".jstree","li").next("li").eq(0); }
			},
			_get_prev		: function (obj, strict) {
				obj = this._get_node(obj);
				if(obj === -1) { return this.get_container().find("> ul > li:last-child"); }
				if(!obj.length) { return false; }
				if(strict) { return (obj.prevAll("li").length > 0) ? obj.prevAll("li:eq(0)") : false; }

				if(obj.prev("li").length) {
					obj = obj.prev("li").eq(0);
					while(obj.hasClass("jstree-open")) { obj = obj.children("ul:eq(0)").children("li:last"); }
					return obj;
				}
				else { var o = obj.parentsUntil(".jstree","li:eq(0)"); return o.length ? o : false; }
			},
			_get_parent		: function (obj) {
				obj = this._get_node(obj);
				if(obj == -1 || !obj.length) { return false; }
				var o = obj.parentsUntil(".jstree", "li:eq(0)");
				return o.length ? o : -1;
			},
			_get_children	: function (obj) {
				obj = this._get_node(obj);
				if(obj === -1) { return this.get_container().children("ul:eq(0)").children("li"); }
				if(!obj.length) { return false; }
				return obj.children("ul:eq(0)").children("li");
			},
			get_path		: function (obj, id_mode) {
				var p = [],
					_this = this;
				obj = this._get_node(obj);
				if(obj === -1 || !obj || !obj.length) { return false; }
				obj.parentsUntil(".jstree", "li").each(function () {
					p.push( id_mode ? this.id : _this.get_text(this) );
				});
				p.reverse();
				p.push( id_mode ? obj.attr("id") : this.get_text(obj) );
				return p;
			},

			// string functions
			_get_string : function (key) {
				return this._get_settings().core.strings[key] || key;
			},

			is_open		: function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-open"); },
			is_closed	: function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-closed"); },
			is_leaf		: function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-leaf"); },
			correct_state	: function (obj) {
				obj = this._get_node(obj);
				if(!obj || obj === -1) { return false; }
				obj.removeClass("jstree-closed jstree-open").addClass("jstree-leaf").children("ul").remove();
				this.__callback({ "obj" : obj });
			},
			// open/close
			open_node	: function (obj, callback, skip_animation) {
				obj = this._get_node(obj);
				if(!obj.length) { return false; }
				if(!obj.hasClass("jstree-closed")) { if(callback) { callback.call(); } return false; }
				var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation,
					t = this;
				if(!this._is_loaded(obj)) {
					obj.children("a").addClass("jstree-loading");
					this.load_node(obj, function () { t.open_node(obj, callback, skip_animation); }, callback);
				}
				else {
					if(this._get_settings().core.open_parents) {
						obj.parentsUntil(".jstree",".jstree-closed").each(function () {
							t.open_node(this, false, true);
						});
					}
					if(s) { obj.children("ul").css("display","none"); }
					obj.removeClass("jstree-closed").addClass("jstree-open").children("a").removeClass("jstree-loading");
					if(s) { obj.children("ul").stop(true, true).slideDown(s, function () { this.style.display = ""; t.after_open(obj); }); }
					else { t.after_open(obj); }
					this.__callback({ "obj" : obj });
					if(callback) { callback.call(); }
				}
			},
			after_open	: function (obj) { this.__callback({ "obj" : obj }); },
			close_node	: function (obj, skip_animation) {
				obj = this._get_node(obj);
				var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation,
					t = this;
				if(!obj.length || !obj.hasClass("jstree-open")) { return false; }
				if(s) { obj.children("ul").attr("style","display:block !important"); }
				obj.removeClass("jstree-open").addClass("jstree-closed");
				if(s) { obj.children("ul").stop(true, true).slideUp(s, function () { this.style.display = ""; t.after_close(obj); }); }
				else { t.after_close(obj); }
				this.__callback({ "obj" : obj });
			},
			after_close	: function (obj) { this.__callback({ "obj" : obj }); },
			toggle_node	: function (obj) {
				obj = this._get_node(obj);
				if(obj.hasClass("jstree-closed")) { return this.open_node(obj); }
				if(obj.hasClass("jstree-open")) { return this.close_node(obj); }
			},
			open_all	: function (obj, do_animation, original_obj) {
				obj = obj ? this._get_node(obj) : -1;
				if(!obj || obj === -1) { obj = this.get_container_ul(); }
				if(original_obj) { 
					obj = obj.find("li.jstree-closed");
				}
				else {
					original_obj = obj;
					if(obj.is(".jstree-closed")) { obj = obj.find("li.jstree-closed").andSelf(); }
					else { obj = obj.find("li.jstree-closed"); }
				}
				var _this = this;
				obj.each(function () { 
					var __this = this; 
					if(!_this._is_loaded(this)) { _this.open_node(this, function() { _this.open_all(__this, do_animation, original_obj); }, !do_animation); }
					else { _this.open_node(this, false, !do_animation); }
				});
				// so that callback is fired AFTER all nodes are open
				if(original_obj.find('li.jstree-closed').length === 0) { this.__callback({ "obj" : original_obj }); }
			},
			close_all	: function (obj, do_animation) {
				var _this = this;
				obj = obj ? this._get_node(obj) : this.get_container();
				if(!obj || obj === -1) { obj = this.get_container_ul(); }
				obj.find("li.jstree-open").andSelf().each(function () { _this.close_node(this, !do_animation); });
				this.__callback({ "obj" : obj });
			},
			clean_node	: function (obj) {
				obj = obj && obj != -1 ? $(obj) : this.get_container_ul();
				obj = obj.is("li") ? obj.find("li").andSelf() : obj.find("li");
				obj.removeClass("jstree-last")
					.filter("li:last-child").addClass("jstree-last").end()
					.filter(":has(li)")
						.not(".jstree-open").removeClass("jstree-leaf").addClass("jstree-closed");
				obj.not(".jstree-open, .jstree-closed").addClass("jstree-leaf").children("ul").remove();
				this.__callback({ "obj" : obj });
			},
			// rollback
			get_rollback : function () { 
				this.__callback();
				return { i : this.get_index(), h : this.get_container().children("ul").clone(true), d : this.data }; 
			},
			set_rollback : function (html, data) {
				this.get_container().empty().append(html);
				this.data = data;
				this.__callback();
			},
			// Dummy functions to be overwritten by any datastore plugin included
			load_node	: function (obj, s_call, e_call) { this.__callback({ "obj" : obj }); },
			_is_loaded	: function (obj) { return true; },

			// Basic operations: create
			create_node	: function (obj, position, js, callback, is_loaded) {
				obj = this._get_node(obj);
				position = typeof position === "undefined" ? "last" : position;
				var d = $("<li />"),
					s = this._get_settings().core,
					tmp;

				if(obj !== -1 && !obj.length) { return false; }
				if(!is_loaded && !this._is_loaded(obj)) { this.load_node(obj, function () { this.create_node(obj, position, js, callback, true); }); return false; }

				this.__rollback();

				if(typeof js === "string") { js = { "data" : js }; }
				if(!js) { js = {}; }
				if(js.attr) { d.attr(js.attr); }
				if(js.metadata) { d.data(js.metadata); }
				if(js.state) { d.addClass("jstree-" + js.state); }
				if(!js.data) { js.data = this._get_string("new_node"); }
				if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); }
				$.each(js.data, function (i, m) {
					tmp = $("<a />");
					if($.isFunction(m)) { m = m.call(this, js); }
					if(typeof m == "string") { tmp.attr('href','#')[ s.html_titles ? "html" : "text" ](m); }
					else {
						if(!m.attr) { m.attr = {}; }
						if(!m.attr.href) { m.attr.href = '#'; }
						tmp.attr(m.attr)[ s.html_titles ? "html" : "text" ](m.title);
						if(m.language) { tmp.addClass(m.language); }
					}
					tmp.prepend("<ins class='jstree-icon'>&#160;</ins>");
					if(!m.icon && js.icon) { m.icon = js.icon; }
					if(m.icon) { 
						if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); }
						else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); }
					}
					d.append(tmp);
				});
				d.prepend("<ins class='jstree-icon'>&#160;</ins>");
				if(obj === -1) {
					obj = this.get_container();
					if(position === "before") { position = "first"; }
					if(position === "after") { position = "last"; }
				}
				switch(position) {
					case "before": obj.before(d); tmp = this._get_parent(obj); break;
					case "after" : obj.after(d);  tmp = this._get_parent(obj); break;
					case "inside":
					case "first" :
						if(!obj.children("ul").length) { obj.append("<ul />"); }
						obj.children("ul").prepend(d);
						tmp = obj;
						break;
					case "last":
						if(!obj.children("ul").length) { obj.append("<ul />"); }
						obj.children("ul").append(d);
						tmp = obj;
						break;
					default:
						if(!obj.children("ul").length) { obj.append("<ul />"); }
						if(!position) { position = 0; }
						tmp = obj.children("ul").children("li").eq(position);
						if(tmp.length) { tmp.before(d); }
						else { obj.children("ul").append(d); }
						tmp = obj;
						break;
				}
				if(tmp === -1 || tmp.get(0) === this.get_container().get(0)) { tmp = -1; }
				this.clean_node(tmp);
				this.__callback({ "obj" : d, "parent" : tmp });
				if(callback) { callback.call(this, d); }
				return d;
			},
			// Basic operations: rename (deal with text)
			get_text	: function (obj) {
				obj = this._get_node(obj);
				if(!obj.length) { return false; }
				var s = this._get_settings().core.html_titles;
				obj = obj.children("a:eq(0)");
				if(s) {
					obj = obj.clone();
					obj.children("INS").remove();
					return obj.html();
				}
				else {
					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
					return obj.nodeValue;
				}
			},
			set_text	: function (obj, val) {
				obj = this._get_node(obj);
				if(!obj.length) { return false; }
				obj = obj.children("a:eq(0)");
				if(this._get_settings().core.html_titles) {
					var tmp = obj.children("INS").clone();
					obj.html(val).prepend(tmp);
					this.__callback({ "obj" : obj, "name" : val });
					return true;
				}
				else {
					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
					this.__callback({ "obj" : obj, "name" : val });
					return (obj.nodeValue = val);
				}
			},
			rename_node : function (obj, val) {
				obj = this._get_node(obj);
				this.__rollback();
				if(obj && obj.length && this.set_text.apply(this, Array.prototype.slice.call(arguments))) { this.__callback({ "obj" : obj, "name" : val }); }
			},
			// Basic operations: deleting nodes
			delete_node : function (obj) {
				obj = this._get_node(obj);
				if(!obj.length) { return false; }
				this.__rollback();
				var p = this._get_parent(obj), prev = $([]), t = this;
				obj.each(function () {
					prev = prev.add(t._get_prev(this));
				});
				obj = obj.detach();
				if(p !== -1 && p.find("> ul > li").length === 0) {
					p.removeClass("jstree-open jstree-closed").addClass("jstree-leaf");
				}
				this.clean_node(p);
				this.__callback({ "obj" : obj, "prev" : prev, "parent" : p });
				return obj;
			},
			prepare_move : function (o, r, pos, cb, is_cb) {
				var p = {};

				p.ot = $.jstree._reference(o) || this;
				p.o = p.ot._get_node(o);
				p.r = r === - 1 ? -1 : this._get_node(r);
				p.p = (typeof pos === "undefined" || pos === false) ? "last" : pos; // TODO: move to a setting
				if(!is_cb && prepared_move.o && prepared_move.o[0] === p.o[0] && prepared_move.r[0] === p.r[0] && prepared_move.p === p.p) {
					this.__callback(prepared_move);
					if(cb) { cb.call(this, prepared_move); }
					return;
				}
				p.ot = $.jstree._reference(p.o) || this;
				p.rt = $.jstree._reference(p.r) || this; // r === -1 ? p.ot : $.jstree._reference(p.r) || this
				if(p.r === -1 || !p.r) {
					p.cr = -1;
					switch(p.p) {
						case "first":
						case "before":
						case "inside":
							p.cp = 0; 
							break;
						case "after":
						case "last":
							p.cp = p.rt.get_container().find(" > ul > li").length; 
							break;
						default:
							p.cp = p.p;
							break;
					}
				}
				else {
					if(!/^(before|after)$/.test(p.p) && !this._is_loaded(p.r)) {
						return this.load_node(p.r, function () { this.prepare_move(o, r, pos, cb, true); });
					}
					switch(p.p) {
						case "before":
							p.cp = p.r.index();
							p.cr = p.rt._get_parent(p.r);
							break;
						case "after":
							p.cp = p.r.index() + 1;
							p.cr = p.rt._get_parent(p.r);
							break;
						case "inside":
						case "first":
							p.cp = 0;
							p.cr = p.r;
							break;
						case "last":
							p.cp = p.r.find(" > ul > li").length; 
							p.cr = p.r;
							break;
						default: 
							p.cp = p.p;
							p.cr = p.r;
							break;
					}
				}
				p.np = p.cr == -1 ? p.rt.get_container() : p.cr;
				p.op = p.ot._get_parent(p.o);
				p.cop = p.o.index();
				if(p.op === -1) { p.op = p.ot ? p.ot.get_container() : this.get_container(); }
				if(!/^(before|after)$/.test(p.p) && p.op && p.np && p.op[0] === p.np[0] && p.o.index() < p.cp) { p.cp++; }
				//if(p.p === "before" && p.op && p.np && p.op[0] === p.np[0] && p.o.index() < p.cp) { p.cp--; }
				p.or = p.np.find(" > ul > li:nth-child(" + (p.cp + 1) + ")");
				prepared_move = p;
				this.__callback(prepared_move);
				if(cb) { cb.call(this, prepared_move); }
			},
			check_move : function () {
				var obj = prepared_move, ret = true, r = obj.r === -1 ? this.get_container() : obj.r;
				if(!obj || !obj.o || obj.or[0] === obj.o[0]) { return false; }
				if(obj.op && obj.np && obj.op[0] === obj.np[0] && obj.cp - 1 === obj.o.index()) { return false; }
				obj.o.each(function () { 
					if(r.parentsUntil(".jstree", "li").andSelf().index(this) !== -1) { ret = false; return false; }
				});
				return ret;
			},
			move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) {
				if(!is_prepared) { 
					return this.prepare_move(obj, ref, position, function (p) {
						this.move_node(p, false, false, is_copy, true, skip_check);
					});
				}
				if(is_copy) { 
					prepared_move.cy = true;
				}
				if(!skip_check && !this.check_move()) { return false; }

				this.__rollback();
				var o = false;
				if(is_copy) {
					o = obj.o.clone(true);
					o.find("*[id]").andSelf().each(function () {
						if(this.id) { this.id = "copy_" + this.id; }
					});
				}
				else { o = obj.o; }

				if(obj.or.length) { obj.or.before(o); }
				else { 
					if(!obj.np.children("ul").length) { $("<ul />").appendTo(obj.np); }
					obj.np.children("ul:eq(0)").append(o); 
				}

				try { 
					obj.ot.clean_node(obj.op);
					obj.rt.clean_node(obj.np);
					if(!obj.op.find("> ul > li").length) {
						obj.op.removeClass("jstree-open jstree-closed").addClass("jstree-leaf").children("ul").remove();
					}
				} catch (e) { }

				if(is_copy) { 
					prepared_move.cy = true;
					prepared_move.oc = o; 
				}
				this.__callback(prepared_move);
				return prepared_move;
			},
			_get_move : function () { return prepared_move; }
		}
	});
})(jQuery);
//*/

/* 
 * jsTree ui plugin
 * This plugins handles selecting/deselecting/hovering/dehovering nodes
 */
(function ($) {
	var scrollbar_width, e1, e2;
	$(function() {
		if (/msie/.test(navigator.userAgent.toLowerCase())) {
			e1 = $('<textarea cols="10" rows="2"></textarea>').css({ position: 'absolute', top: -1000, left: 0 }).appendTo('body');
			e2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>').css({ position: 'absolute', top: -1000, left: 0 }).appendTo('body');
			scrollbar_width = e1.width() - e2.width();
			e1.add(e2).remove();
		} 
		else {
			e1 = $('<div />').css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: 0 })
					.prependTo('body').append('<div />').find('div').css({ width: '100%', height: 200 });
			scrollbar_width = 100 - e1.width();
			e1.parent().remove();
		}
	});
	$.jstree.plugin("ui", {
		__init : function () { 
			this.data.ui.selected = $(); 
			this.data.ui.last_selected = false; 
			this.data.ui.hovered = null;
			this.data.ui.to_select = this.get_settings().ui.initially_select;

			this.get_container()
				.delegate("a", "click.jstree", $.proxy(function (event) {
						event.preventDefault();
						event.currentTarget.blur();
						if(!$(event.currentTarget).hasClass("jstree-loading")) {
							this.select_node(event.currentTarget, true, event);
						}
					}, this))
				.delegate("a", "mouseenter.jstree", $.proxy(function (event) {
						if(!$(event.currentTarget).hasClass("jstree-loading")) {
							this.hover_node(event.target);
						}
					}, this))
				.delegate("a", "mouseleave.jstree", $.proxy(function (event) {
						if(!$(event.currentTarget).hasClass("jstree-loading")) {
							this.dehover_node(event.target);
						}
					}, this))
				.bind("reopen.jstree", $.proxy(function () { 
						this.reselect();
					}, this))
				.bind("get_rollback.jstree", $.proxy(function () { 
						this.dehover_node();
						this.save_selected();
					}, this))
				.bind("set_rollback.jstree", $.proxy(function () { 
						this.reselect();
					}, this))
				.bind("close_node.jstree", $.proxy(function (event, data) { 
						var s = this._get_settings().ui,
							obj = this._get_node(data.rslt.obj),
							clk = (obj && obj.length) ? obj.children("ul").find("a.jstree-clicked") : $(),
							_this = this;
						if(s.selected_parent_close === false || !clk.length) { return; }
						clk.each(function () { 
							_this.deselect_node(this);
							if(s.selected_parent_close === "select_parent") { _this.select_node(obj); }
						});
					}, this))
				.bind("delete_node.jstree", $.proxy(function (event, data) { 
						var s = this._get_settings().ui.select_prev_on_delete,
							obj = this._get_node(data.rslt.obj),
							clk = (obj && obj.length) ? obj.find("a.jstree-clicked") : [],
							_this = this;
						clk.each(function () { _this.deselect_node(this); });
						if(s && clk.length) { 
							data.rslt.prev.each(function () { 
								if(this.parentNode) { _this.select_node(this); return false; /* if return false is removed all prev nodes will be selected */}
							});
						}
					}, this))
				.bind("move_node.jstree", $.proxy(function (event, data) { 
						if(data.rslt.cy) { 
							data.rslt.oc.find("a.jstree-clicked").removeClass("jstree-clicked");
						}
					}, this));
		},
		defaults : {
			select_limit : -1, // 0, 1, 2 ... or -1 for unlimited
			select_multiple_modifier : "ctrl", // on, or ctrl, shift, alt
			select_range_modifier : "shift",
			selected_parent_close : "select_parent", // false, "deselect", "select_parent"
			selected_parent_open : true,
			select_prev_on_delete : true,
			disable_selecting_children : false,
			initially_select : []
		},
		_fn : { 
			_get_node : function (obj, allow_multiple) {
				if(typeof obj === "undefined" || obj === null) { return allow_multiple ? this.data.ui.selected : this.data.ui.last_selected; }
				var $obj = $(obj, this.get_container()); 
				if($obj.is(".jstree") || obj == -1) { return -1; } 
				$obj = $obj.closest("li", this.get_container()); 
				return $obj.length ? $obj : false; 
			},
			_ui_notify : function (n, data) {
				if(data.selected) {
					this.select_node(n, false);
				}
			},
			save_selected : function () {
				var _this = this;
				this.data.ui.to_select = [];
				this.data.ui.selected.each(function () { if(this.id) { _this.data.ui.to_select.push("#" + this.id.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:")); } });
				this.__callback(this.data.ui.to_select);
			},
			reselect : function () {
				var _this = this,
					s = this.data.ui.to_select;
				s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
				// this.deselect_all(); WHY deselect, breaks plugin state notifier?
				$.each(s, function (i, val) { if(val && val !== "#") { _this.select_node(val); } });
				this.data.ui.selected = this.data.ui.selected.filter(function () { return this.parentNode; });
				this.__callback();
			},
			refresh : function (obj) {
				this.save_selected();
				return this.__call_old();
			},
			hover_node : function (obj) {
				obj = this._get_node(obj);
				if(!obj.length) { return false; }
				//if(this.data.ui.hovered && obj.get(0) === this.data.ui.hovered.get(0)) { return; }
				if(!obj.hasClass("jstree-hovered")) { this.dehover_node(); }
				this.data.ui.hovered = obj.children("a").addClass("jstree-hovered").parent();
				this._fix_scroll(obj);
				this.__callback({ "obj" : obj });
			},
			dehover_node : function () {
				var obj = this.data.ui.hovered, p;
				if(!obj || !obj.length) { return false; }
				p = obj.children("a").removeClass("jstree-hovered").parent();
				if(this.data.ui.hovered[0] === p[0]) { this.data.ui.hovered = null; }
				this.__callback({ "obj" : obj });
			},
			select_node : function (obj, check, e) {
				obj = this._get_node(obj);
				if(obj == -1 || !obj || !obj.length) { return false; }
				var s = this._get_settings().ui,
					is_multiple = (s.select_multiple_modifier == "on" || (s.select_multiple_modifier !== false && e && e[s.select_multiple_modifier + "Key"])),
					is_range = (s.select_range_modifier !== false && e && e[s.select_range_modifier + "Key"] && this.data.ui.last_selected && this.data.ui.last_selected[0] !== obj[0] && this.data.ui.last_selected.parent()[0] === obj.parent()[0]),
					is_selected = this.is_selected(obj),
					proceed = true,
					t = this;
				if(check) {
					if(s.disable_selecting_children && is_multiple && 
						(
							(obj.parentsUntil(".jstree","li").children("a.jstree-clicked").length) ||
							(obj.children("ul").find("a.jstree-clicked:eq(0)").length)
						)
					) {
						return false;
					}
					proceed = false;
					switch(!0) {
						case (is_range):
							this.data.ui.last_selected.addClass("jstree-last-selected");
							obj = obj[ obj.index() < this.data.ui.last_selected.index() ? "nextUntil" : "prevUntil" ](".jstree-last-selected").andSelf();
							if(s.select_limit == -1 || obj.length < s.select_limit) {
								this.data.ui.last_selected.removeClass("jstree-last-selected");
								this.data.ui.selected.each(function () {
									if(this !== t.data.ui.last_selected[0]) { t.deselect_node(this); }
								});
								is_selected = false;
								proceed = true;
							}
							else {
								proceed = false;
							}
							break;
						case (is_selected && !is_multiple): 
							this.deselect_all();
							is_selected = false;
							proceed = true;
							break;
						case (!is_selected && !is_multiple): 
							if(s.select_limit == -1 || s.select_limit > 0) {
								this.deselect_all();
								proceed = true;
							}
							break;
						case (is_selected && is_multiple): 
							this.deselect_node(obj);
							break;
						case (!is_selected && is_multiple): 
							if(s.select_limit == -1 || this.data.ui.selected.length + 1 <= s.select_limit) { 
								proceed = true;
							}
							break;
					}
				}
				if(proceed && !is_selected) {
					if(!is_range) { this.data.ui.last_selected = obj; }
					obj.children("a").addClass("jstree-clicked");
					if(s.selected_parent_open) {
						obj.parents(".jstree-closed").each(function () { t.open_node(this, false, true); });
					}
					this.data.ui.selected = this.data.ui.selected.add(obj);
					this._fix_scroll(obj.eq(0));
					this.__callback({ "obj" : obj, "e" : e });
				}
			},
			_fix_scroll : function (obj) {
				var c = this.get_container()[0], t;
				if(c.scrollHeight > c.offsetHeight) {
					obj = this._get_node(obj);
					if(!obj || obj === -1 || !obj.length || !obj.is(":visible")) { return; }
					t = obj.offset().top - this.get_container().offset().top;
					if(t < 0) { 
						c.scrollTop = c.scrollTop + t - 1; 
					}
					if(t + this.data.core.li_height + (c.scrollWidth > c.offsetWidth ? scrollbar_width : 0) > c.offsetHeight) { 
						c.scrollTop = c.scrollTop + (t - c.offsetHeight + this.data.core.li_height + 1 + (c.scrollWidth > c.offsetWidth ? scrollbar_width : 0)); 
					}
				}
			},
			deselect_node : function (obj) {
				obj = this._get_node(obj);
				if(!obj.length) { return false; }
				if(this.is_selected(obj)) {
					obj.children("a").removeClass("jstree-clicked");
					this.data.ui.selected = this.data.ui.selected.not(obj);
					if(this.data.ui.last_selected.get(0) === obj.get(0)) { this.data.ui.last_selected = this.data.ui.selected.eq(0); }
					this.__callback({ "obj" : obj });
				}
			},
			toggle_select : function (obj) {
				obj = this._get_node(obj);
				if(!obj.length) { return false; }
				if(this.is_selected(obj)) { this.deselect_node(obj); }
				else { this.select_node(obj); }
			},
			is_selected : function (obj) { return this.data.ui.selected.index(this._get_node(obj)) >= 0; },
			get_selected : function (context) { 
				return context ? $(context).find("a.jstree-clicked").parent() : this.data.ui.selected; 
			},
			deselect_all : function (context) {
				var ret = context ? $(context).find("a.jstree-clicked").parent() : this.get_container().find("a.jstree-clicked").parent();
				ret.children("a.jstree-clicked").removeClass("jstree-clicked");
				this.data.ui.selected = $([]);
				this.data.ui.last_selected = false;
				this.__callback({ "obj" : ret });
			}
		}
	});
	// include the selection plugin by default
	$.jstree.defaults.plugins.push("ui");
})(jQuery);
//*/

/* 
 * jsTree CRRM plugin
 * Handles creating/renaming/removing/moving nodes by user interaction.
 */
(function ($) {
	$.jstree.plugin("crrm", { 
		__init : function () {
			this.get_container()
				.bind("move_node.jstree", $.proxy(function (e, data) {
					if(this._get_settings().crrm.move.open_onmove) {
						var t = this;
						data.rslt.np.parentsUntil(".jstree").andSelf().filter(".jstree-closed").each(function () {
							t.open_node(this, false, true);
						});
					}
				}, this));
		},
		defaults : {
			input_width_limit : 200,
			move : {
				always_copy			: false, // false, true or "multitree"
				open_onmove			: true,
				default_position	: "last",
				check_move			: function (m) { return true; }
			}
		},
		_fn : {
			_show_input : function (obj, callback) {
				obj = this._get_node(obj);
				var rtl = this._get_settings().core.rtl,
					w = this._get_settings().crrm.input_width_limit,
					w1 = obj.children("ins").width(),
					w2 = obj.find("> a:visible > ins").width() * obj.find("> a:visible > ins").length,
					t = this.get_text(obj),
					h1 = $("<div />", { css : { "position" : "absolute", "top" : "-200px", "left" : (rtl ? "0px" : "-1000px"), "visibility" : "hidden" } }).appendTo("body"),
					h2 = obj.css("position","relative").append(
					$("<input />", { 
						"value" : t,
						"class" : "jstree-rename-input",
						// "size" : t.length,
						"css" : {
							"padding" : "0",
							"border" : "1px solid silver",
							"position" : "absolute",
							"left"  : (rtl ? "auto" : (w1 + w2 + 4) + "px"),
							"right" : (rtl ? (w1 + w2 + 4) + "px" : "auto"),
							"top" : "0px",
							"height" : (this.data.core.li_height - 2) + "px",
							"lineHeight" : (this.data.core.li_height - 2) + "px",
							"width" : "150px" // will be set a bit further down
						},
						"blur" : $.proxy(function () {
							var i = obj.children(".jstree-rename-input"),
								v = i.val();
							if(v === "") { v = t; }
							h1.remove();
							i.remove(); // rollback purposes
							this.set_text(obj,t); // rollback purposes
							this.rename_node(obj, v);
							callback.call(this, obj, v, t);
							obj.css("position","");
						}, this),
						"keyup" : function (event) {
							var key = event.keyCode || event.which;
							if(key == 27) { this.value = t; this.blur(); return; }
							else if(key == 13) { this.blur(); return; }
							else {
								h2.width(Math.min(h1.text("pW" + this.value).width(),w));
							}
						},
						"keypress" : function(event) {
							var key = event.keyCode || event.which;
							if(key == 13) { return false; }
						}
					})
				).children(".jstree-rename-input"); 
				this.set_text(obj, "");
				h1.css({
						fontFamily		: h2.css('fontFamily')		|| '',
						fontSize		: h2.css('fontSize')		|| '',
						fontWeight		: h2.css('fontWeight')		|| '',
						fontStyle		: h2.css('fontStyle')		|| '',
						fontStretch		: h2.css('fontStretch')		|| '',
						fontVariant		: h2.css('fontVariant')		|| '',
						letterSpacing	: h2.css('letterSpacing')	|| '',
						wordSpacing		: h2.css('wordSpacing')		|| ''
				});
				h2.width(Math.min(h1.text("pW" + h2[0].value).width(),w))[0].select();
			},
			rename : function (obj) {
				obj = this._get_node(obj);
				this.__rollback();
				var f = this.__callback;
				this._show_input(obj, function (obj, new_name, old_name) { 
					f.call(this, { "obj" : obj, "new_name" : new_name, "old_name" : old_name });
				});
			},
			create : function (obj, position, js, callback, skip_rename) {
				var t, _this = this;
				obj = this._get_node(obj);
				if(!obj) { obj = -1; }
				this.__rollback();
				t = this.create_node(obj, position, js, function (t) {
					var p = this._get_parent(t),
						pos = $(t).index();
					if(callback) { callback.call(this, t); }
					if(p.length && p.hasClass("jstree-closed")) { this.open_node(p, false, true); }
					if(!skip_rename) { 
						this._show_input(t, function (obj, new_name, old_name) { 
							_this.__callback({ "obj" : obj, "name" : new_name, "parent" : p, "position" : pos });
						});
					}
					else { _this.__callback({ "obj" : t, "name" : this.get_text(t), "parent" : p, "position" : pos }); }
				});
				return t;
			},
			remove : function (obj) {
				obj = this._get_node(obj, true);
				var p = this._get_parent(obj), prev = this._get_prev(obj);
				this.__rollback();
				obj = this.delete_node(obj);
				if(obj !== false) { this.__callback({ "obj" : obj, "prev" : prev, "parent" : p }); }
			},
			check_move : function () {
				if(!this.__call_old()) { return false; }
				var s = this._get_settings().crrm.move;
				if(!s.check_move.call(this, this._get_move())) { return false; }
				return true;
			},
			move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) {
				var s = this._get_settings().crrm.move;
				if(!is_prepared) { 
					if(typeof position === "undefined") { position = s.default_position; }
					if(position === "inside" && !s.default_position.match(/^(before|after)$/)) { position = s.default_position; }
					return this.__call_old(true, obj, ref, position, is_copy, false, skip_check);
				}
				// if the move is already prepared
				if(s.always_copy === true || (s.always_copy === "multitree" && obj.rt.get_index() !== obj.ot.get_index() )) {
					is_copy = true;
				}
				this.__call_old(true, obj, ref, position, is_copy, true, skip_check);
			},

			cut : function (obj) {
				obj = this._get_node(obj, true);
				if(!obj || !obj.length) { return false; }
				this.data.crrm.cp_nodes = false;
				this.data.crrm.ct_nodes = obj;
				this.__callback({ "obj" : obj });
			},
			copy : function (obj) {
				obj = this._get_node(obj, true);
				if(!obj || !obj.length) { return false; }
				this.data.crrm.ct_nodes = false;
				this.data.crrm.cp_nodes = obj;
				this.__callback({ "obj" : obj });
			},
			paste : function (obj) { 
				obj = this._get_node(obj);
				if(!obj || !obj.length) { return false; }
				var nodes = this.data.crrm.ct_nodes ? this.data.crrm.ct_nodes : this.data.crrm.cp_nodes;
				if(!this.data.crrm.ct_nodes && !this.data.crrm.cp_nodes) { return false; }
				if(this.data.crrm.ct_nodes) { this.move_node(this.data.crrm.ct_nodes, obj); this.data.crrm.ct_nodes = false; }
				if(this.data.crrm.cp_nodes) { this.move_node(this.data.crrm.cp_nodes, obj, false, true); }
				this.__callback({ "obj" : obj, "nodes" : nodes });
			}
		}
	});
	// include the crr plugin by default
	// $.jstree.defaults.plugins.push("crrm");
})(jQuery);
//*/

/* 
 * jsTree themes plugin
 * Handles loading and setting themes, as well as detecting path to themes, etc.
 */
(function ($) {
	var themes_loaded = [];
	// this variable stores the path to the themes folder - if left as false - it will be autodetected
	$.jstree._themes = false;
	$.jstree.plugin("themes", {
		__init : function () { 
			this.get_container()
				.bind("init.jstree", $.proxy(function () {
						var s = this._get_settings().themes;
						this.data.themes.dots = s.dots; 
						this.data.themes.icons = s.icons; 
						this.set_theme(s.theme, s.url);
					}, this))
				.bind("loaded.jstree", $.proxy(function () {
						// bound here too, as simple HTML tree's won't honor dots & icons otherwise
						if(!this.data.themes.dots) { this.hide_dots(); }
						else { this.show_dots(); }
						if(!this.data.themes.icons) { this.hide_icons(); }
						else { this.show_icons(); }
					}, this));
		},
		defaults : { 
			theme : "default", 
			url : false,
			dots : true,
			icons : true
		},
		_fn : {
			set_theme : function (theme_name, theme_url) {
				if(!theme_name) { return false; }
				if(!theme_url) { theme_url = $.jstree._themes + theme_name + '/style.css'; }
				if($.inArray(theme_url, themes_loaded) == -1) {
					$.vakata.css.add_sheet({ "url" : theme_url });
					themes_loaded.push(theme_url);
				}
				if(this.data.themes.theme != theme_name) {
					this.get_container().removeClass('jstree-' + this.data.themes.theme);
					this.data.themes.theme = theme_name;
				}
				this.get_container().addClass('jstree-' + theme_name);
				if(!this.data.themes.dots) { this.hide_dots(); }
				else { this.show_dots(); }
				if(!this.data.themes.icons) { this.hide_icons(); }
				else { this.show_icons(); }
				this.__callback();
			},
			get_theme	: function () { return this.data.themes.theme; },

			show_dots	: function () { this.data.themes.dots = true; this.get_container().children("ul").removeClass("jstree-no-dots"); },
			hide_dots	: function () { this.data.themes.dots = false; this.get_container().children("ul").addClass("jstree-no-dots"); },
			toggle_dots	: function () { if(this.data.themes.dots) { this.hide_dots(); } else { this.show_dots(); } },

			show_icons	: function () { this.data.themes.icons = true; this.get_container().children("ul").removeClass("jstree-no-icons"); },
			hide_icons	: function () { this.data.themes.icons = false; this.get_container().children("ul").addClass("jstree-no-icons"); },
			toggle_icons: function () { if(this.data.themes.icons) { this.hide_icons(); } else { this.show_icons(); } }
		}
	});
	// autodetect themes path
	$(function () {
		if($.jstree._themes === false) {
			$("script").each(function () { 
				if(this.src.toString().match(/jquery\.jstree[^\/]*?\.js(\?.*)?$/)) { 
					$.jstree._themes = this.src.toString().replace(/jquery\.jstree[^\/]*?\.js(\?.*)?$/, "") + 'themes/'; 
					return false; 
				}
			});
		}
		if($.jstree._themes === false) { $.jstree._themes = "themes/"; }
	});
	// include the themes plugin by default
	$.jstree.defaults.plugins.push("themes");
})(jQuery);
//*/

/*
 * jsTree hotkeys plugin
 * Enables keyboard navigation for all tree instances
 * Depends on the jstree ui & jquery hotkeys plugins
 */
(function ($) {
	var bound = [];
	function exec(i, event) {
		var f = $.jstree._focused(), tmp;
		if(f && f.data && f.data.hotkeys && f.data.hotkeys.enabled) { 
			tmp = f._get_settings().hotkeys[i];
			if(tmp) { return tmp.call(f, event); }
		}
	}
	$.jstree.plugin("hotkeys", {
		__init : function () {
			if(typeof $.hotkeys === "undefined") { throw "jsTree hotkeys: jQuery hotkeys plugin not included."; }
			if(!this.data.ui) { throw "jsTree hotkeys: jsTree UI plugin not included."; }
			$.each(this._get_settings().hotkeys, function (i, v) {
				if(v !== false && $.inArray(i, bound) == -1) {
					$(document).bind("keydown", i, function (event) { return exec(i, event); });
					bound.push(i);
				}
			});
			this.get_container()
				.bind("lock.jstree", $.proxy(function () {
						if(this.data.hotkeys.enabled) { this.data.hotkeys.enabled = false; this.data.hotkeys.revert = true; }
					}, this))
				.bind("unlock.jstree", $.proxy(function () {
						if(this.data.hotkeys.revert) { this.data.hotkeys.enabled = true; }
					}, this));
			this.enable_hotkeys();
		},
		defaults : {
			"up" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
				this.hover_node(this._get_prev(o));
				return false; 
			},
			"ctrl+up" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
				this.hover_node(this._get_prev(o));
				return false; 
			},
			"shift+up" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
				this.hover_node(this._get_prev(o));
				return false; 
			},
			"down" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
				this.hover_node(this._get_next(o));
				return false;
			},
			"ctrl+down" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
				this.hover_node(this._get_next(o));
				return false;
			},
			"shift+down" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
				this.hover_node(this._get_next(o));
				return false;
			},
			"left" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected;
				if(o) {
					if(o.hasClass("jstree-open")) { this.close_node(o); }
					else { this.hover_node(this._get_prev(o)); }
				}
				return false;
			},
			"ctrl+left" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected;
				if(o) {
					if(o.hasClass("jstree-open")) { this.close_node(o); }
					else { this.hover_node(this._get_prev(o)); }
				}
				return false;
			},
			"shift+left" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected;
				if(o) {
					if(o.hasClass("jstree-open")) { this.close_node(o); }
					else { this.hover_node(this._get_prev(o)); }
				}
				return false;
			},
			"right" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected;
				if(o && o.length) {
					if(o.hasClass("jstree-closed")) { this.open_node(o); }
					else { this.hover_node(this._get_next(o)); }
				}
				return false;
			},
			"ctrl+right" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected;
				if(o && o.length) {
					if(o.hasClass("jstree-closed")) { this.open_node(o); }
					else { this.hover_node(this._get_next(o)); }
				}
				return false;
			},
			"shift+right" : function () { 
				var o = this.data.ui.hovered || this.data.ui.last_selected;
				if(o && o.length) {
					if(o.hasClass("jstree-closed")) { this.open_node(o); }
					else { this.hover_node(this._get_next(o)); }
				}
				return false;
			},
			"space" : function () { 
				if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").click(); } 
				return false; 
			},
			"ctrl+space" : function (event) { 
				event.type = "click";
				if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").trigger(event); } 
				return false; 
			},
			"shift+space" : function (event) { 
				event.type = "click";
				if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").trigger(event); } 
				return false; 
			},
			"f2" : function () { this.rename(this.data.ui.hovered || this.data.ui.last_selected); },
			"del" : function () { this.remove(this.data.ui.hovered || this._get_node(null)); }
		},
		_fn : {
			enable_hotkeys : function () {
				this.data.hotkeys.enabled = true;
			},
			disable_hotkeys : function () {
				this.data.hotkeys.enabled = false;
			}
		}
	});
})(jQuery);
//*/

/* 
 * jsTree JSON plugin
 * The JSON data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions.
 */
(function ($) {
	$.jstree.plugin("json_data", {
		__init : function() {
			var s = this._get_settings().json_data;
			if(s.progressive_unload) {
				this.get_container().bind("after_close.jstree", function (e, data) {
					data.rslt.obj.children("ul").remove();
				});
			}
		},
		defaults : { 
			// `data` can be a function:
			//  * accepts two arguments - node being loaded and a callback to pass the result to
			//  * will be executed in the current tree's scope & ajax won't be supported
			data : false, 
			ajax : false,
			correct_state : true,
			progressive_render : false,
			progressive_unload : false
		},
		_fn : {
			load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_json(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); },
			_is_loaded : function (obj) { 
				var s = this._get_settings().json_data;
				obj = this._get_node(obj); 
				return obj == -1 || !obj || (!s.ajax && !s.progressive_render && !$.isFunction(s.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").length > 0;
			},
			refresh : function (obj) {
				obj = this._get_node(obj);
				var s = this._get_settings().json_data;
				if(obj && obj !== -1 && s.progressive_unload && ($.isFunction(s.data) || !!s.ajax)) {
					obj.removeData("jstree_children");
				}
				return this.__call_old();
			},
			load_node_json : function (obj, s_call, e_call) {
				var s = this.get_settings().json_data, d,
					error_func = function () {},
					success_func = function () {};
				obj = this._get_node(obj);

				if(obj && obj !== -1 && (s.progressive_render || s.progressive_unload) && !obj.is(".jstree-open, .jstree-leaf") && obj.children("ul").children("li").length === 0 && obj.data("jstree_children")) {
					d = this._parse_json(obj.data("jstree_children"), obj);
					if(d) {
						obj.append(d);
						if(!s.progressive_unload) { obj.removeData("jstree_children"); }
					}
					this.clean_node(obj);
					if(s_call) { s_call.call(this); }
					return;
				}

				if(obj && obj !== -1) {
					if(obj.data("jstree_is_loading")) { return; }
					else { obj.data("jstree_is_loading",true); }
				}
				switch(!0) {
					case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
					// function option added here for easier model integration (also supporting async - see callback)
					case ($.isFunction(s.data)):
						s.data.call(this, obj, $.proxy(function (d) {
							d = this._parse_json(d, obj);
							if(!d) { 
								if(obj === -1 || !obj) {
									if(s.correct_state) { this.get_container().children("ul").empty(); }
								}
								else {
									obj.children("a.jstree-loading").removeClass("jstree-loading");
									obj.removeData("jstree_is_loading");
									if(s.correct_state) { this.correct_state(obj); }
								}
								if(e_call) { e_call.call(this); }
							}
							else {
								if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
								else { obj.append(d).children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); }
								this.clean_node(obj);
								if(s_call) { s_call.call(this); }
							}
						}, this));
						break;
					case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
						if(!obj || obj == -1) {
							d = this._parse_json(s.data, obj);
							if(d) {
								this.get_container().children("ul").empty().append(d.children());
								this.clean_node();
							}
							else { 
								if(s.correct_state) { this.get_container().children("ul").empty(); }
							}
						}
						if(s_call) { s_call.call(this); }
						break;
					case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
						error_func = function (x, t, e) {
							var ef = this.get_settings().json_data.ajax.error; 
							if(ef) { ef.call(this, x, t, e); }
							if(obj != -1 && obj.length) {
								obj.children("a.jstree-loading").removeClass("jstree-loading");
								obj.removeData("jstree_is_loading");
								if(t === "success" && s.correct_state) { this.correct_state(obj); }
							}
							else {
								if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
							}
							if(e_call) { e_call.call(this); }
						};
						success_func = function (d, t, x) {
							var sf = this.get_settings().json_data.ajax.success; 
							if(sf) { d = sf.call(this,d,t,x) || d; }
							if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "") || (!$.isArray(d) && !$.isPlainObject(d))) {
								return error_func.call(this, x, t, "");
							}
							d = this._parse_json(d, obj);
							if(d) {
								if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
								else { obj.append(d).children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); }
								this.clean_node(obj);
								if(s_call) { s_call.call(this); }
							}
							else {
								if(obj === -1 || !obj) {
									if(s.correct_state) { 
										this.get_container().children("ul").empty(); 
										if(s_call) { s_call.call(this); }
									}
								}
								else {
									obj.children("a.jstree-loading").removeClass("jstree-loading");
									obj.removeData("jstree_is_loading");
									if(s.correct_state) { 
										this.correct_state(obj);
										if(s_call) { s_call.call(this); } 
									}
								}
							}
						};
						s.ajax.context = this;
						s.ajax.error = error_func;
						s.ajax.success = success_func;
						if(!s.ajax.dataType) { s.ajax.dataType = "json"; }
						if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
						if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
						$.ajax(s.ajax);
						break;
				}
			},
			_parse_json : function (js, obj, is_callback) {
				var d = false, 
					p = this._get_settings(),
					s = p.json_data,
					t = p.core.html_titles,
					tmp, i, j, ul1, ul2;

				if(!js) { return d; }
				if(s.progressive_unload && obj && obj !== -1) { 
					obj.data("jstree_children", d);
				}
				if($.isArray(js)) {
					d = $();
					if(!js.length) { return false; }
					for(i = 0, j = js.length; i < j; i++) {
						tmp = this._parse_json(js[i], obj, true);
						if(tmp.length) { d = d.add(tmp); }
					}
				}
				else {
					if(typeof js == "string") { js = { data : js }; }
					if(!js.data && js.data !== "") { return d; }
					d = $("<li />");
					if(js.attr) { d.attr(js.attr); }
					if(js.metadata) { d.data(js.metadata); }
					if(js.state) { d.addClass("jstree-" + js.state); }
					if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); }
					$.each(js.data, function (i, m) {
						tmp = $("<a />");
						if($.isFunction(m)) { m = m.call(this, js); }
						if(typeof m == "string") { tmp.attr('href','#')[ t ? "html" : "text" ](m); }
						else {
							if(!m.attr) { m.attr = {}; }
							if(!m.attr.href) { m.attr.href = '#'; }
							tmp.attr(m.attr)[ t ? "html" : "text" ](m.title);
							if(m.language) { tmp.addClass(m.language); }
						}
						tmp.prepend("<ins class='jstree-icon'>&#160;</ins>");
						if(!m.icon && js.icon) { m.icon = js.icon; }
						if(m.icon) { 
							if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); }
							else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); }
						}
						d.append(tmp);
					});
					d.prepend("<ins class='jstree-icon'>&#160;</ins>");
					if(js.children) { 
						if(s.progressive_render && js.state !== "open") {
							d.addClass("jstree-closed").data("jstree_children", js.children);
						}
						else {
							if(s.progressive_unload) { d.data("jstree_children", js.children); }
							if($.isArray(js.children) && js.children.length) {
								tmp = this._parse_json(js.children, obj, true);
								if(tmp.length) {
									ul2 = $("<ul />");
									ul2.append(tmp);
									d.append(ul2);
								}
							}
						}
					}
				}
				if(!is_callback) {
					ul1 = $("<ul />");
					ul1.append(d);
					d = ul1;
				}
				return d;
			},
			get_json : function (obj, li_attr, a_attr, is_callback) {
				var result = [], 
					s = this._get_settings(), 
					_this = this,
					tmp1, tmp2, li, a, t, lang;
				obj = this._get_node(obj);
				if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); }
				li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ];
				if(!is_callback && this.data.types) { li_attr.push(s.types.type_attr); }
				a_attr = $.isArray(a_attr) ? a_attr : [ ];

				obj.each(function () {
					li = $(this);
					tmp1 = { data : [] };
					if(li_attr.length) { tmp1.attr = { }; }
					$.each(li_attr, function (i, v) { 
						tmp2 = li.attr(v); 
						if(tmp2 && tmp2.length && tmp2.replace(/jstree[^ ]*/ig,'').length) {
							tmp1.attr[v] = (" " + tmp2).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,""); 
						}
					});
					if(li.hasClass("jstree-open")) { tmp1.state = "open"; }
					if(li.hasClass("jstree-closed")) { tmp1.state = "closed"; }
					if(li.data()) { tmp1.metadata = li.data(); }
					a = li.children("a");
					a.each(function () {
						t = $(this);
						if(
							a_attr.length || 
							$.inArray("languages", s.plugins) !== -1 || 
							t.children("ins").get(0).style.backgroundImage.length || 
							(t.children("ins").get(0).className && t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').length)
						) { 
							lang = false;
							if($.inArray("languages", s.plugins) !== -1 && $.isArray(s.languages) && s.languages.length) {
								$.each(s.languages, function (l, lv) {
									if(t.hasClass(lv)) {
										lang = lv;
										return false;
									}
								});
							}
							tmp2 = { attr : { }, title : _this.get_text(t, lang) }; 
							$.each(a_attr, function (k, z) {
								tmp2.attr[z] = (" " + (t.attr(z) || "")).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"");
							});
							if($.inArray("languages", s.plugins) !== -1 && $.isArray(s.languages) && s.languages.length) {
								$.each(s.languages, function (k, z) {
									if(t.hasClass(z)) { tmp2.language = z; return true; }
								});
							}
							if(t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) {
								tmp2.icon = t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"");
							}
							if(t.children("ins").get(0).style.backgroundImage.length) {
								tmp2.icon = t.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")","");
							}
						}
						else {
							tmp2 = _this.get_text(t);
						}
						if(a.length > 1) { tmp1.data.push(tmp2); }
						else { tmp1.data = tmp2; }
					});
					li = li.find("> ul > li");
					if(li.length) { tmp1.children = _this.get_json(li, li_attr, a_attr, true); }
					result.push(tmp1);
				});
				return result;
			}
		}
	});
})(jQuery);
//*/

/* 
 * jsTree languages plugin
 * Adds support for multiple language versions in one tree
 * This basically allows for many titles coexisting in one node, but only one of them being visible at any given time
 * This is useful for maintaining the same structure in many languages (hence the name of the plugin)
 */
(function ($) {
	$.jstree.plugin("languages", {
		__init : function () { this._load_css();  },
		defaults : [],
		_fn : {
			set_lang : function (i) { 
				var langs = this._get_settings().languages,
					st = false,
					selector = ".jstree-" + this.get_index() + ' a';
				if(!$.isArray(langs) || langs.length === 0) { return false; }
				if($.inArray(i,langs) == -1) {
					if(!!langs[i]) { i = langs[i]; }
					else { return false; }
				}
				if(i == this.data.languages.current_language) { return true; }
				st = $.vakata.css.get_css(selector + "." + this.data.languages.current_language, false, this.data.languages.language_css);
				if(st !== false) { st.style.display = "none"; }
				st = $.vakata.css.get_css(selector + "." + i, false, this.data.languages.language_css);
				if(st !== false) { st.style.display = ""; }
				this.data.languages.current_language = i;
				this.__callback(i);
				return true;
			},
			get_lang : function () {
				return this.data.languages.current_language;
			},
			_get_string : function (key, lang) {
				var langs = this._get_settings().languages,
					s = this._get_settings().core.strings;
				if($.isArray(langs) && langs.length) {
					lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
				}
				if(s[lang] && s[lang][key]) { return s[lang][key]; }
				if(s[key]) { return s[key]; }
				return key;
			},
			get_text : function (obj, lang) {
				obj = this._get_node(obj) || this.data.ui.last_selected;
				if(!obj.size()) { return false; }
				var langs = this._get_settings().languages,
					s = this._get_settings().core.html_titles;
				if($.isArray(langs) && langs.length) {
					lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
					obj = obj.children("a." + lang);
				}
				else { obj = obj.children("a:eq(0)"); }
				if(s) {
					obj = obj.clone();
					obj.children("INS").remove();
					return obj.html();
				}
				else {
					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
					return obj.nodeValue;
				}
			},
			set_text : function (obj, val, lang) {
				obj = this._get_node(obj) || this.data.ui.last_selected;
				if(!obj.size()) { return false; }
				var langs = this._get_settings().languages,
					s = this._get_settings().core.html_titles,
					tmp;
				if($.isArray(langs) && langs.length) {
					lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
					obj = obj.children("a." + lang);
				}
				else { obj = obj.children("a:eq(0)"); }
				if(s) {
					tmp = obj.children("INS").clone();
					obj.html(val).prepend(tmp);
					this.__callback({ "obj" : obj, "name" : val, "lang" : lang });
					return true;
				}
				else {
					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
					this.__callback({ "obj" : obj, "name" : val, "lang" : lang });
					return (obj.nodeValue = val);
				}
			},
			_load_css : function () {
				var langs = this._get_settings().languages,
					str = "/* languages css */",
					selector = ".jstree-" + this.get_index() + ' a',
					ln;
				if($.isArray(langs) && langs.length) {
					this.data.languages.current_language = langs[0];
					for(ln = 0; ln < langs.length; ln++) {
						str += selector + "." + langs[ln] + " {";
						if(langs[ln] != this.data.languages.current_language) { str += " display:none; "; }
						str += " } ";
					}
					this.data.languages.language_css = $.vakata.css.add_sheet({ 'str' : str, 'title' : "jstree-languages" });
				}
			},
			create_node : function (obj, position, js, callback) {
				var t = this.__call_old(true, obj, position, js, function (t) {
					var langs = this._get_settings().languages,
						a = t.children("a"),
						ln;
					if($.isArray(langs) && langs.length) {
						for(ln = 0; ln < langs.length; ln++) {
							if(!a.is("." + langs[ln])) {
								t.append(a.eq(0).clone().removeClass(langs.join(" ")).addClass(langs[ln]));
							}
						}
						a.not("." + langs.join(", .")).remove();
					}
					if(callback) { callback.call(this, t); }
				});
				return t;
			}
		}
	});
})(jQuery);
//*/

/*
 * jsTree cookies plugin
 * Stores the currently opened/selected nodes in a cookie and then restores them
 * Depends on the jquery.cookie plugin
 */
(function ($) {
	$.jstree.plugin("cookies", {
		__init : function () {
			if(typeof $.cookie === "undefined") { throw "jsTree cookie: jQuery cookie plugin not included."; }

			var s = this._get_settings().cookies,
				tmp;
			if(!!s.save_loaded) {
				tmp = $.cookie(s.save_loaded);
				if(tmp && tmp.length) { this.data.core.to_load = tmp.split(","); }
			}
			if(!!s.save_opened) {
				tmp = $.cookie(s.save_opened);
				if(tmp && tmp.length) { this.data.core.to_open = tmp.split(","); }
			}
			if(!!s.save_selected) {
				tmp = $.cookie(s.save_selected);
				if(tmp && tmp.length && this.data.ui) { this.data.ui.to_select = tmp.split(","); }
			}
			this.get_container()
				.one( ( this.data.ui ? "reselect" : "reopen" ) + ".jstree", $.proxy(function () {
					this.get_container()
						.bind("open_node.jstree close_node.jstree select_node.jstree deselect_node.jstree", $.proxy(function (e) { 
								if(this._get_settings().cookies.auto_save) { this.save_cookie((e.handleObj.namespace + e.handleObj.type).replace("jstree","")); }
							}, this));
				}, this));
		},
		defaults : {
			save_loaded		: "jstree_load",
			save_opened		: "jstree_open",
			save_selected	: "jstree_select",
			auto_save		: true,
			cookie_options	: {}
		},
		_fn : {
			save_cookie : function (c) {
				if(this.data.core.refreshing) { return; }
				var s = this._get_settings().cookies;
				if(!c) { // if called manually and not by event
					if(s.save_loaded) {
						this.save_loaded();
						$.cookie(s.save_loaded, this.data.core.to_load.join(","), s.cookie_options);
					}
					if(s.save_opened) {
						this.save_opened();
						$.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options);
					}
					if(s.save_selected && this.data.ui) {
						this.save_selected();
						$.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options);
					}
					return;
				}
				switch(c) {
					case "open_node":
					case "close_node":
						if(!!s.save_opened) { 
							this.save_opened(); 
							$.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options); 
						}
						if(!!s.save_loaded) { 
							this.save_loaded(); 
							$.cookie(s.save_loaded, this.data.core.to_load.join(","), s.cookie_options); 
						}
						break;
					case "select_node":
					case "deselect_node":
						if(!!s.save_selected && this.data.ui) { 
							this.save_selected(); 
							$.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options); 
						}
						break;
				}
			}
		}
	});
	// include cookies by default
	// $.jstree.defaults.plugins.push("cookies");
})(jQuery);
//*/

/*
 * jsTree sort plugin
 * Sorts items alphabetically (or using any other function)
 */
(function ($) {
	$.jstree.plugin("sort", {
		__init : function () {
			this.get_container()
				.bind("load_node.jstree", $.proxy(function (e, data) {
						var obj = this._get_node(data.rslt.obj);
						obj = obj === -1 ? this.get_container().children("ul") : obj.children("ul");
						this.sort(obj);
					}, this))
				.bind("rename_node.jstree create_node.jstree create.jstree", $.proxy(function (e, data) {
						this.sort(data.rslt.obj.parent());
					}, this))
				.bind("move_node.jstree", $.proxy(function (e, data) {
						var m = data.rslt.np == -1 ? this.get_container() : data.rslt.np;
						this.sort(m.children("ul"));
					}, this));
		},
		defaults : function (a, b) { return this.get_text(a) > this.get_text(b) ? 1 : -1; },
		_fn : {
			sort : function (obj) {
				var s = this._get_settings().sort,
					t = this;
				obj.append($.makeArray(obj.children("li")).sort($.proxy(s, t)));
				obj.find("> li > ul").each(function() { t.sort($(this)); });
				this.clean_node(obj);
			}
		}
	});
})(jQuery);
//*/

/*
 * jsTree DND plugin
 * Drag and drop plugin for moving/copying nodes
 */
(function ($) {
	var o = false,
		r = false,
		m = false,
		ml = false,
		sli = false,
		sti = false,
		dir1 = false,
		dir2 = false,
		last_pos = false;
	$.vakata.dnd = {
		is_down : false,
		is_drag : false,
		helper : false,
		scroll_spd : 10,
		init_x : 0,
		init_y : 0,
		threshold : 5,
		helper_left : 5,
		helper_top : 10,
		user_data : {},

		drag_start : function (e, data, html) { 
			if($.vakata.dnd.is_drag) { $.vakata.drag_stop({}); }
			try {
				e.currentTarget.unselectable = "on";
				e.currentTarget.onselectstart = function() { return false; };
				if(e.currentTarget.style) { e.currentTarget.style.MozUserSelect = "none"; }
			} catch(err) { }
			$.vakata.dnd.init_x = e.pageX;
			$.vakata.dnd.init_y = e.pageY;
			$.vakata.dnd.user_data = data;
			$.vakata.dnd.is_down = true;
			$.vakata.dnd.helper = $("<div id='vakata-dragged' />").html(html); //.fadeTo(10,0.25);
			$(document).bind("mousemove", $.vakata.dnd.drag);
			$(document).bind("mouseup", $.vakata.dnd.drag_stop);
			return false;
		},
		drag : function (e) { 
			if(!$.vakata.dnd.is_down) { return; }
			if(!$.vakata.dnd.is_drag) {
				if(Math.abs(e.pageX - $.vakata.dnd.init_x) > 5 || Math.abs(e.pageY - $.vakata.dnd.init_y) > 5) { 
					$.vakata.dnd.helper.appendTo("body");
					$.vakata.dnd.is_drag = true;
					$(document).triggerHandler("drag_start.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
				}
				else { return; }
			}

			// maybe use a scrolling parent element instead of document?
			if(e.type === "mousemove") { // thought of adding scroll in order to move the helper, but mouse poisition is n/a
				var d = $(document), t = d.scrollTop(), l = d.scrollLeft();
				if(e.pageY - t < 20) { 
					if(sti && dir1 === "down") { clearInterval(sti); sti = false; }
					if(!sti) { dir1 = "up"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() - $.vakata.dnd.scroll_spd); }, 150); }
				}
				else { 
					if(sti && dir1 === "up") { clearInterval(sti); sti = false; }
				}
				if($(window).height() - (e.pageY - t) < 20) {
					if(sti && dir1 === "up") { clearInterval(sti); sti = false; }
					if(!sti) { dir1 = "down"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() + $.vakata.dnd.scroll_spd); }, 150); }
				}
				else { 
					if(sti && dir1 === "down") { clearInterval(sti); sti = false; }
				}

				if(e.pageX - l < 20) {
					if(sli && dir2 === "right") { clearInterval(sli); sli = false; }
					if(!sli) { dir2 = "left"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() - $.vakata.dnd.scroll_spd); }, 150); }
				}
				else { 
					if(sli && dir2 === "left") { clearInterval(sli); sli = false; }
				}
				if($(window).width() - (e.pageX - l) < 20) {
					if(sli && dir2 === "left") { clearInterval(sli); sli = false; }
					if(!sli) { dir2 = "right"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() + $.vakata.dnd.scroll_spd); }, 150); }
				}
				else { 
					if(sli && dir2 === "right") { clearInterval(sli); sli = false; }
				}
			}
			var rtl = ($('html').eq(0).attr('dir') === 'rtl');
			$.vakata.dnd.helper.css({ left : (e.pageX + $.vakata.dnd.helper_left - (rtl ? $.vakata.dnd.helper.outerWidth() : 0)) + "px", top : (e.pageY + $.vakata.dnd.helper_top) + "px" });
			$(document).triggerHandler("drag.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
		},
		drag_stop : function (e) {
			//console.log("Point One");
			if(sli) { clearInterval(sli); }
			if(sti) { clearInterval(sti); }
			$(document).unbind("mousemove", $.vakata.dnd.drag);
			$(document).unbind("mouseup", $.vakata.dnd.drag_stop);
			$(document).triggerHandler("drag_stop.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
			$.vakata.dnd.helper.remove();
			$.vakata.dnd.init_x = 0;
			$.vakata.dnd.init_y = 0;
			$.vakata.dnd.user_data = {};
			$.vakata.dnd.is_down = false;
			$.vakata.dnd.is_drag = false;
		}
	};
	$(function() {
		var css_string = '#vakata-dragged { display:block; margin:0 0 0 0; padding:4px 4px 4px 24px; position:absolute; top:-2000px; line-height:16px; z-index:10000; } '+
				'html[dir=rtl] #vakata-dragged { padding:4px 24px 4px 4px; }';
		$.vakata.css.add_sheet({ str : css_string, title : "vakata" });
	});

	$.jstree.plugin("dnd", {
		__init : function () {
			this.data.dnd = {
				active : false,
				after : false,
				inside : false,
				before : false,
				off : false,
				prepared : false,
				w : 0,
				to1 : false,
				to2 : false,
				cof : false,
				cw : false,
				ch : false,
				i1 : false,
				i2 : false,
				mto : false
			};
			this.get_container()
				.bind("mouseenter.jstree", $.proxy(function (e) {
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
							if(this.data.themes) {
								m.attr("class", "jstree-" + this.data.themes.theme); 
								if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); }
								$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme);
							}
							//if($(e.currentTarget).find("> ul > li").length === 0) {
							if(e.currentTarget === e.target && $.vakata.dnd.user_data.obj && $($.vakata.dnd.user_data.obj).length && $($.vakata.dnd.user_data.obj).parents(".jstree:eq(0)")[0] !== e.target) { // node should not be from the same tree
								var tr = $.jstree._reference(e.target), dc;
								if(tr.data.dnd.foreign) {
									dc = tr._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : tr.get_container(), is_root : true });
									if(dc === true || dc.inside === true || dc.before === true || dc.after === true) {
										$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
									}
								}
								else {
									tr.prepare_move(o, tr.get_container(), "last");
									if(tr.check_move()) {
										$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
									}
								}
							}
						}
					}, this))
				.bind("mouseup.jstree", $.proxy(function (e) {
						//if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && $(e.currentTarget).find("> ul > li").length === 0) {
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && e.currentTarget === e.target && $.vakata.dnd.user_data.obj && $($.vakata.dnd.user_data.obj).length && $($.vakata.dnd.user_data.obj).parents(".jstree:eq(0)")[0] !== e.target) { // node should not be from the same tree
							var tr = $.jstree._reference(e.currentTarget), dc;
							if(tr.data.dnd.foreign) {
								dc = tr._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : tr.get_container(), is_root : true });
								if(dc === true || dc.inside === true || dc.before === true || dc.after === true) {
									tr._get_settings().dnd.drag_finish.call(this, { "o" : o, "r" : tr.get_container(), is_root : true });
								}
							}
							else {
								tr.move_node(o, tr.get_container(), "last", e[tr._get_settings().dnd.copy_modifier + "Key"]);
							}
						}
					}, this))
				.bind("mouseleave.jstree", $.proxy(function (e) {
						if(e.relatedTarget && e.relatedTarget.id && e.relatedTarget.id === "jstree-marker-line") {
							return false; 
						}
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
							if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
							if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
							if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); }
							if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); }
							if($.vakata.dnd.helper.children("ins").hasClass("jstree-ok")) {
								$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
							}
						}
					}, this))
				.bind("mousemove.jstree", $.proxy(function (e) {
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
							var cnt = this.get_container()[0];

							// Horizontal scroll
							if(e.pageX + 24 > this.data.dnd.cof.left + this.data.dnd.cw) {
								if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
								this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft += $.vakata.dnd.scroll_spd; }, cnt), 100);
							}
							else if(e.pageX - 24 < this.data.dnd.cof.left) {
								if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
								this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft -= $.vakata.dnd.scroll_spd; }, cnt), 100);
							}
							else {
								if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
							}

							// Vertical scroll
							if(e.pageY + 24 > this.data.dnd.cof.top + this.data.dnd.ch) {
								if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
								this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop += $.vakata.dnd.scroll_spd; }, cnt), 100);
							}
							else if(e.pageY - 24 < this.data.dnd.cof.top) {
								if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
								this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop -= $.vakata.dnd.scroll_spd; }, cnt), 100);
							}
							else {
								if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
							}

						}
					}, this))
				.bind("scroll.jstree", $.proxy(function (e) { 
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && m && ml) {
							m.hide();
							ml.hide();
						}
					}, this))
				.delegate("a", "mousedown.jstree", $.proxy(function (e) { 
						if(e.which === 1) {
							this.start_drag(e.currentTarget, e);
							return false;
						}
					}, this))
				.delegate("a", "mouseenter.jstree", $.proxy(function (e) { 
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
							this.dnd_enter(e.currentTarget);
						}
					}, this))
				.delegate("a", "mousemove.jstree", $.proxy(function (e) { 
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
							if(!r || !r.length || r.children("a")[0] !== e.currentTarget) {
								this.dnd_enter(e.currentTarget);
							}
							if(typeof this.data.dnd.off.top === "undefined") { this.data.dnd.off = $(e.target).offset(); }
							this.data.dnd.w = (e.pageY - (this.data.dnd.off.top || 0)) % this.data.core.li_height;
							if(this.data.dnd.w < 0) { this.data.dnd.w += this.data.core.li_height; }
							this.dnd_show();
						}
					}, this))
				.delegate("a", "mouseleave.jstree", $.proxy(function (e) { 
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
							if(e.relatedTarget && e.relatedTarget.id && e.relatedTarget.id === "jstree-marker-line") {
								return false; 
							}
								if(m) { m.hide(); }
								if(ml) { ml.hide(); }
							/*
							var ec = $(e.currentTarget).closest("li"), 
								er = $(e.relatedTarget).closest("li");
							if(er[0] !== ec.prev()[0] && er[0] !== ec.next()[0]) {
								if(m) { m.hide(); }
								if(ml) { ml.hide(); }
							}
							*/
							this.data.dnd.mto = setTimeout( 
								(function (t) { return function () { t.dnd_leave(e); }; })(this),
							0);
						}
					}, this))
				.delegate("a", "mouseup.jstree", $.proxy(function (e) {
						//console.log("Where is finish");
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
							this.dnd_finish(e);
						}
					}, this));

			$(document)
				.bind("drag_stop.vakata", $.proxy(function () {
						if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); }
						if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); }
						if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
						if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
						this.data.dnd.after		= false;
						this.data.dnd.before	= false;
						this.data.dnd.inside	= false;
						this.data.dnd.off		= false;
						this.data.dnd.prepared	= false;
						this.data.dnd.w			= false;
						this.data.dnd.to1		= false;
						this.data.dnd.to2		= false;
						this.data.dnd.i1		= false;
						this.data.dnd.i2		= false;
						this.data.dnd.active	= false;
						this.data.dnd.foreign	= false;
						if(m) { m.css({ "top" : "-2000px" }); }
						if(ml) { ml.css({ "top" : "-2000px" }); }
					}, this))
				.bind("drag_start.vakata", $.proxy(function (e, data) {
						if(data.data.jstree) { 
							var et = $(data.event.target);
							if(et.closest(".jstree").hasClass("jstree-" + this.get_index())) {
								this.dnd_enter(et);
							}
						}
					}, this));
				/*
				.bind("keydown.jstree-" + this.get_index() + " keyup.jstree-" + this.get_index(), $.proxy(function(e) {
						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && !this.data.dnd.foreign) {
							var h = $.vakata.dnd.helper.children("ins");
							if(e[this._get_settings().dnd.copy_modifier + "Key"] && h.hasClass("jstree-ok")) {
								h.parent().html(h.parent().html().replace(/ \(Copy\)$/, "") + " (Copy)");
							} 
							else {
								h.parent().html(h.parent().html().replace(/ \(Copy\)$/, ""));
							}
						}
					}, this)); */



			var s = this._get_settings().dnd;
			if(s.drag_target) {
				$(document)
					.delegate(s.drag_target, "mousedown.jstree-" + this.get_index(), $.proxy(function (e) {
						o = e.target;
						$.vakata.dnd.drag_start(e, { jstree : true, obj : e.target }, "<ins class='jstree-icon'></ins>" + $(e.target).text() );
						if(this.data.themes) { 
							if(m) { m.attr("class", "jstree-" + this.data.themes.theme); }
							if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); }
							$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme); 
						}
						$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
						var cnt = this.get_container();
						this.data.dnd.cof = cnt.offset();
						this.data.dnd.cw = parseInt(cnt.width(),10);
						this.data.dnd.ch = parseInt(cnt.height(),10);
						this.data.dnd.foreign = true;
						e.preventDefault();
					}, this));
			}
			if(s.drop_target) {
				$(document)
					.delegate(s.drop_target, "mouseenter.jstree-" + this.get_index(), $.proxy(function (e) {
							if(this.data.dnd.active && this._get_settings().dnd.drop_check.call(this, { "o" : o, "r" : $(e.target), "e" : e })) {
								$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
							}
						}, this))
					.delegate(s.drop_target, "mouseleave.jstree-" + this.get_index(), $.proxy(function (e) {
							if(this.data.dnd.active) {
								$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
							}
						}, this))
					.delegate(s.drop_target, "mouseup.jstree-" + this.get_index(), $.proxy(function (e) {
							if(this.data.dnd.active && $.vakata.dnd.helper.children("ins").hasClass("jstree-ok")) {
								this._get_settings().dnd.drop_finish.call(this, { "o" : o, "r" : $(e.target), "e" : e });
							}
						}, this));
			}
		},
		defaults : {
			copy_modifier	: "ctrl",
			check_timeout	: 100,
			open_timeout	: 500,
			drop_target		: ".jstree-drop",
			drop_check		: function (data) { return true; },
			drop_finish		: $.noop,
			drag_target		: ".jstree-draggable",
			drag_finish		: $.noop,
			drag_check		: function (data) { return { after : false, before : false, inside : true }; }
		},
		_fn : {
			dnd_prepare : function () {
				if(!r || !r.length) { return; }
				this.data.dnd.off = r.offset();
				if(this._get_settings().core.rtl) {
					this.data.dnd.off.right = this.data.dnd.off.left + r.width();
				}
				if(this.data.dnd.foreign) {
					var a = this._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : r });
					this.data.dnd.after = a.after;
					this.data.dnd.before = a.before;
					this.data.dnd.inside = a.inside;
					this.data.dnd.prepared = true;
					return this.dnd_show();
				}
				this.prepare_move(o, r, "before");
				this.data.dnd.before = this.check_move();
				this.prepare_move(o, r, "after");
				this.data.dnd.after = this.check_move();
				if(this._is_loaded(r)) {
					this.prepare_move(o, r, "inside");
					this.data.dnd.inside = this.check_move();
				}
				else {
					this.data.dnd.inside = false;
				}
				this.data.dnd.prepared = true;
				return this.dnd_show();
			},
			dnd_show : function () {
				if(!this.data.dnd.prepared) { return; }
				var o = ["before","inside","after"],
					r = false,
					rtl = this._get_settings().core.rtl,
					pos;
				if(this.data.dnd.w < this.data.core.li_height/3) { o = ["before","inside","after"]; }
				else if(this.data.dnd.w <= this.data.core.li_height*2/3) {
					o = this.data.dnd.w < this.data.core.li_height/2 ? ["inside","before","after"] : ["inside","after","before"];
				}
				else { o = ["after","inside","before"]; }
				$.each(o, $.proxy(function (i, val) { 
					if(this.data.dnd[val]) {
						$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
						r = val;
						return false;
					}
				}, this));
				if(r === false) { $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); }
				
				pos = rtl ? (this.data.dnd.off.right - 18) : (this.data.dnd.off.left + 10);
				switch(r) {
					case "before":
						m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top - 6) + "px" }).show();
						if(ml) { ml.css({ "left" : (pos + (rtl ? (-ml.width() - 8) : 8)) + "px", "top" : (this.data.dnd.off.top - 1) + "px" }).show(); }
						break;
					case "after":
						m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height - 6) + "px" }).show();
						if(ml) { ml.css({ "left" : (pos + (rtl ? (-ml.width() - 8) : 8)) + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height - 1) + "px" }).show(); }
						break;
					case "inside":
						m.css({ "left" : pos + ( rtl ? -4 : 4) + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height/2 - 5) + "px" }).show();
						if(ml) { ml.hide(); }
						break;
					default:
						m.hide();
						if(ml) { ml.hide(); }
						break;
				}
				last_pos = r;
				return r;
			},
			dnd_open : function () {
				this.data.dnd.to2 = false;
				this.open_node(r, $.proxy(this.dnd_prepare,this), true);
			},
			dnd_finish : function (e) {
				if(this.data.dnd.foreign) {
					if(this.data.dnd.after || this.data.dnd.before || this.data.dnd.inside) {
						this._get_settings().dnd.drag_finish.call(this, { "o" : o, "r" : r, "p" : last_pos });
					}
				}
				else {
					this.dnd_prepare();
					this.move_node(o, r, last_pos, e[this._get_settings().dnd.copy_modifier + "Key"]);
				}
				o = false;
				r = false;
				m.hide();
				if(ml) { ml.hide(); }
			},
			dnd_enter : function (obj) {
				if(this.data.dnd.mto) { 
					clearTimeout(this.data.dnd.mto);
					this.data.dnd.mto = false;
				}
				var s = this._get_settings().dnd;
				this.data.dnd.prepared = false;
				r = this._get_node(obj);
				if(s.check_timeout) { 
					// do the calculations after a minimal timeout (users tend to drag quickly to the desired location)
					if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); }
					this.data.dnd.to1 = setTimeout($.proxy(this.dnd_prepare, this), s.check_timeout); 
				}
				else { 
					this.dnd_prepare(); 
				}
				if(s.open_timeout) { 
					if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); }
					if(r && r.length && r.hasClass("jstree-closed")) { 
						// if the node is closed - open it, then recalculate
						this.data.dnd.to2 = setTimeout($.proxy(this.dnd_open, this), s.open_timeout);
					}
				}
				else {
					if(r && r.length && r.hasClass("jstree-closed")) { 
						this.dnd_open();
					}
				}
			},
			dnd_leave : function (e) {
				this.data.dnd.after		= false;
				this.data.dnd.before	= false;
				this.data.dnd.inside	= false;
				$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
				m.hide();
				if(ml) { ml.hide(); }
				if(r && r[0] === e.target.parentNode) {
					if(this.data.dnd.to1) {
						clearTimeout(this.data.dnd.to1);
						this.data.dnd.to1 = false;
					}
					if(this.data.dnd.to2) {
						clearTimeout(this.data.dnd.to2);
						this.data.dnd.to2 = false;
					}
				}
			},
			start_drag : function (obj, e) {
				o = this._get_node(obj);
				if(this.data.ui && this.is_selected(o)) { o = this._get_node(null, true); }
				var dt = o.length > 1 ? this._get_string("multiple_selection") : this.get_text(o),
					cnt = this.get_container();
				if(!this._get_settings().core.html_titles) { dt = dt.replace(/</ig,"&lt;").replace(/>/ig,"&gt;"); }
				$.vakata.dnd.drag_start(e, { jstree : true, obj : o }, "<ins class='jstree-icon'></ins>" + dt );
				if(this.data.themes) { 
					if(m) { m.attr("class", "jstree-" + this.data.themes.theme); }
					if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); }
					$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme); 
				}
				this.data.dnd.cof = cnt.offset();
				this.data.dnd.cw = parseInt(cnt.width(),10);
				this.data.dnd.ch = parseInt(cnt.height(),10);
				this.data.dnd.active = true;
			}
		}
	});
	$(function() {
		var css_string = '' + 
			'#vakata-dragged ins { display:block; text-decoration:none; width:16px; height:16px; margin:0 0 0 0; padding:0; position:absolute; top:4px; left:4px; ' + 
			' -moz-border-radius:4px; border-radius:4px; -webkit-border-radius:4px; ' +
			'} ' + 
			'html[dir=rtl] #vakata-dragged ins { left:auto; right:4px; }' +
			'#vakata-dragged .jstree-ok { background:green; } ' + 
			'#vakata-dragged .jstree-invalid { background:red; } ' + 
			'#jstree-marker { padding:0; margin:0; font-size:12px; overflow:hidden; height:12px; width:8px; position:absolute; top:-30px; z-index:10001; background-repeat:no-repeat; display:none; background-color:transparent; text-shadow:1px 1px 1px white; color:black; line-height:10px; } ' + 
			'#jstree-marker-line { padding:0; margin:0; line-height:0%; font-size:1px; overflow:hidden; height:1px; width:100px; position:absolute; top:-30px; z-index:10000; background-repeat:no-repeat; display:none; background-color:#456c43; ' + 
			' cursor:pointer; border:1px solid #eeeeee; border-left:0; -moz-box-shadow: 0px 0px 2px #666; -webkit-box-shadow: 0px 0px 2px #666; box-shadow: 0px 0px 2px #666; ' + 
			' -moz-border-radius:1px; border-radius:1px; -webkit-border-radius:1px; ' +
			'}' + 
			'';
		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
		m = $("<div />").attr({ id : "jstree-marker" }).hide().html("&raquo;")
			.bind("mouseleave mouseenter", function (e) { 
				m.hide();
				ml.hide();
				e.preventDefault(); 
				e.stopImmediatePropagation(); 
				return false; 
			})
			.appendTo("body");
		ml = $("<div />").attr({ id : "jstree-marker-line" }).hide()
			.bind("mouseup", function (e) {
				if(r && r.length) { 
					var a = r.children("a");
					a.trigger("mouseup.jstree");
					a.trigger(e);
					e.preventDefault(); 
					e.stopImmediatePropagation(); 
					return false; 
				} 
			})
			.bind("mouseleave", function (e) { 
				var rt = $(e.relatedTarget);
				if(rt.is(".jstree") || rt.closest(".jstree").length === 0) {
					if(r && r.length) { 
						r.children("a").trigger(e); 
						m.hide();
						ml.hide();
						e.preventDefault(); 
						e.stopImmediatePropagation(); 
						return false; 
					}
				}
			})
			.appendTo("body");
		$(document).bind("drag_start.vakata", function (e, data) {
			if(data.data.jstree) { m.show(); if(ml) { ml.show(); } }
		});
		$(document).bind("drag_stop.vakata", function (e, data) {
			if(data.data.jstree) { m.hide(); if(ml) { ml.hide(); } }
		});
	});
})(jQuery);
//*/

/*
 * jsTree checkbox plugin
 * Inserts checkboxes in front of every node
 * Depends on the ui plugin
 * DOES NOT WORK NICELY WITH MULTITREE DRAG'N'DROP
 */
(function ($) {
	$.jstree.plugin("checkbox", {
		__init : function () {
			this.data.checkbox.noui = this._get_settings().checkbox.override_ui;
			if(this.data.ui && this.data.checkbox.noui) {
				this.select_node = this.deselect_node = this.deselect_all = $.noop;
				this.get_selected = this.get_checked;
			}

			this.get_container()
				.bind("open_node.jstree create_node.jstree clean_node.jstree refresh.jstree", $.proxy(function (e, data) { 
						this._prepare_checkboxes(data.rslt.obj);
					}, this))
				.bind("loaded.jstree", $.proxy(function (e) {
						this._prepare_checkboxes();
					}, this))
				.delegate( (this.data.ui && this.data.checkbox.noui ? "a" : "ins.jstree-checkbox") , "click.jstree", $.proxy(function (e) {
						e.preventDefault();
						if(this._get_node(e.target).hasClass("jstree-checked")) { this.uncheck_node(e.target); }
						else { this.check_node(e.target); }
						if(this.data.ui && this.data.checkbox.noui) {
							this.save_selected();
							if(this.data.cookies) { this.save_cookie("select_node"); }
						}
						else {
							e.stopImmediatePropagation();
							return false;
						}
					}, this));
		},
		defaults : {
			override_ui : false,
			two_state : false,
			real_checkboxes : false,
			checked_parent_open : true,
			real_checkboxes_names : function (n) { return [ ("check_" + (n[0].id || Math.ceil(Math.random() * 10000))) , 1]; }
		},
		__destroy : function () {
			this.get_container()
				.find("input.jstree-real-checkbox").removeClass("jstree-real-checkbox").end()
				.find("ins.jstree-checkbox").remove();
		},
		_fn : {
			_checkbox_notify : function (n, data) {
				if(data.checked) {
					this.check_node(n, false);
				}
			},
			_prepare_checkboxes : function (obj) {
				obj = !obj || obj == -1 ? this.get_container().find("> ul > li") : this._get_node(obj);
				if(obj === false) { return; } // added for removing root nodes
				var c, _this = this, t, ts = this._get_settings().checkbox.two_state, rc = this._get_settings().checkbox.real_checkboxes, rcn = this._get_settings().checkbox.real_checkboxes_names;
				obj.each(function () {
					t = $(this);
					c = t.is("li") && (t.hasClass("jstree-checked") || (rc && t.children(":checked").length)) ? "jstree-checked" : "jstree-unchecked";
					t.find("li").andSelf().each(function () {
						var $t = $(this), nm;
						$t.children("a" + (_this.data.languages ? "" : ":eq(0)") ).not(":has(.jstree-checkbox)").prepend("<ins class='jstree-checkbox'>&#160;</ins>").parent().not(".jstree-checked, .jstree-unchecked").addClass( ts ? "jstree-unchecked" : c );
						if(rc) {
							if(!$t.children(":checkbox").length) {
								nm = rcn.call(_this, $t);
								$t.prepend("<input type='checkbox' class='jstree-real-checkbox' id='" + nm[0] + "' name='" + nm[0] + "' value='" + nm[1] + "' />");
							}
							else {
								$t.children(":checkbox").addClass("jstree-real-checkbox");
							}
						}
						if(!ts) {
							if(c === "jstree-checked" || $t.hasClass("jstree-checked") || $t.children(':checked').length) {
								$t.find("li").andSelf().addClass("jstree-checked").children(":checkbox").prop("checked", true);
							}
						}
						else {
							if($t.hasClass("jstree-checked") || $t.children(':checked').length) {
								$t.addClass("jstree-checked").children(":checkbox").prop("checked", true);
							}
						}
					});
				});
				if(!ts) {
					obj.find(".jstree-checked").parent().parent().each(function () { _this._repair_state(this); }); 
				}
			},
			change_state : function (obj, state) {
				obj = this._get_node(obj);
				var coll = false, rc = this._get_settings().checkbox.real_checkboxes;
				if(!obj || obj === -1) { return false; }
				state = (state === false || state === true) ? state : obj.hasClass("jstree-checked");
				if(this._get_settings().checkbox.two_state) {
					if(state) { 
						obj.removeClass("jstree-checked").addClass("jstree-unchecked"); 
						if(rc) { obj.children(":checkbox").prop("checked", false); }
					}
					else { 
						obj.removeClass("jstree-unchecked").addClass("jstree-checked"); 
						if(rc) { obj.children(":checkbox").prop("checked", true); }
					}
				}
				else {
					if(state) { 
						coll = obj.find("li").andSelf();
						if(!coll.filter(".jstree-checked, .jstree-undetermined").length) { return false; }
						coll.removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked"); 
						if(rc) { coll.children(":checkbox").prop("checked", false); }
					}
					else { 
						coll = obj.find("li").andSelf();
						if(!coll.filter(".jstree-unchecked, .jstree-undetermined").length) { return false; }
						coll.removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked"); 
						if(rc) { coll.children(":checkbox").prop("checked", true); }
						if(this.data.ui) { this.data.ui.last_selected = obj; }
						this.data.checkbox.last_selected = obj;
					}
					obj.parentsUntil(".jstree", "li").each(function () {
						var $this = $(this);
						if(state) {
							if($this.children("ul").children("li.jstree-checked, li.jstree-undetermined").length) {
								$this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
								if(rc) { $this.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); }
								return false;
							}
							else {
								$this.removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked");
								if(rc) { $this.children(":checkbox").prop("checked", false); }
							}
						}
						else {
							if($this.children("ul").children("li.jstree-unchecked, li.jstree-undetermined").length) {
								$this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
								if(rc) { $this.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); }
								return false;
							}
							else {
								$this.removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked");
								if(rc) { $this.children(":checkbox").prop("checked", true); }
							}
						}
					});
				}
				if(this.data.ui && this.data.checkbox.noui) { this.data.ui.selected = this.get_checked(); }
				this.__callback(obj);
				return true;
			},
			check_node : function (obj) {
				if(this.change_state(obj, false)) { 
					obj = this._get_node(obj);
					if(this._get_settings().checkbox.checked_parent_open) {
						var t = this;
						obj.parents(".jstree-closed").each(function () { t.open_node(this, false, true); });
					}
					this.__callback({ "obj" : obj }); 
				}
			},
			uncheck_node : function (obj) {
				if(this.change_state(obj, true)) { this.__callback({ "obj" : this._get_node(obj) }); }
			},
			check_all : function () {
				var _this = this, 
					coll = this._get_settings().checkbox.two_state ? this.get_container_ul().find("li") : this.get_container_ul().children("li");
				coll.each(function () {
					_this.change_state(this, false);
				});
				this.__callback();
			},
			uncheck_all : function () {
				var _this = this,
					coll = this._get_settings().checkbox.two_state ? this.get_container_ul().find("li") : this.get_container_ul().children("li");
				coll.each(function () {
					_this.change_state(this, true);
				});
				this.__callback();
			},

			is_checked : function(obj) {
				obj = this._get_node(obj);
				return obj.length ? obj.is(".jstree-checked") : false;
			},
			get_checked : function (obj, get_all) {
				obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj);
				return get_all || this._get_settings().checkbox.two_state ? obj.find(".jstree-checked") : obj.find("> ul > .jstree-checked, .jstree-undetermined > ul > .jstree-checked");
			},
			get_unchecked : function (obj, get_all) { 
				obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj);
				return get_all || this._get_settings().checkbox.two_state ? obj.find(".jstree-unchecked") : obj.find("> ul > .jstree-unchecked, .jstree-undetermined > ul > .jstree-unchecked");
			},

			show_checkboxes : function () { this.get_container().children("ul").removeClass("jstree-no-checkboxes"); },
			hide_checkboxes : function () { this.get_container().children("ul").addClass("jstree-no-checkboxes"); },

			_repair_state : function (obj) {
				obj = this._get_node(obj);
				if(!obj.length) { return; }
				if(this._get_settings().checkbox.two_state) {
					obj.find('li').andSelf().not('.jstree-checked').removeClass('jstree-undetermined').addClass('jstree-unchecked').children(':checkbox').prop('checked', true);
					return;
				}
				var rc = this._get_settings().checkbox.real_checkboxes,
					a = obj.find("> ul > .jstree-checked").length,
					b = obj.find("> ul > .jstree-undetermined").length,
					c = obj.find("> ul > li").length;
				if(c === 0) { if(obj.hasClass("jstree-undetermined")) { this.change_state(obj, false); } }
				else if(a === 0 && b === 0) { this.change_state(obj, true); }
				else if(a === c) { this.change_state(obj, false); }
				else { 
					obj.parentsUntil(".jstree","li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
					if(rc) { obj.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); }
				}
			},
			reselect : function () {
				if(this.data.ui && this.data.checkbox.noui) { 
					var _this = this,
						s = this.data.ui.to_select;
					s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
					this.deselect_all();
					$.each(s, function (i, val) { _this.check_node(val); });
					this.__callback();
				}
				else { 
					this.__call_old(); 
				}
			},
			save_loaded : function () {
				var _this = this;
				this.data.core.to_load = [];
				this.get_container_ul().find("li.jstree-closed.jstree-undetermined").each(function () {
					if(this.id) { _this.data.core.to_load.push("#" + this.id); }
				});
			}
		}
	});
	$(function() {
		var css_string = '.jstree .jstree-real-checkbox { display:none; } ';
		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
	});
})(jQuery);
//*/

/* 
 * jsTree XML plugin
 * The XML data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions.
 */
(function ($) {
	$.vakata.xslt = function (xml, xsl, callback) {
		var rs = "", xm, xs, processor, support;
		// TODO: IE9 no XSLTProcessor, no document.recalc
		if(document.recalc) {
			xm = document.createElement('xml');
			xs = document.createElement('xml');
			xm.innerHTML = xml;
			xs.innerHTML = xsl;
			$("body").append(xm).append(xs);
			setTimeout( (function (xm, xs, callback) {
				return function () {
					callback.call(null, xm.transformNode(xs.XMLDocument));
					setTimeout( (function (xm, xs) { return function () { $(xm).remove(); $(xs).remove(); }; })(xm, xs), 200);
				};
			})(xm, xs, callback), 100);
			return true;
		}
		if(typeof window.DOMParser !== "undefined" && typeof window.XMLHttpRequest !== "undefined" && typeof window.XSLTProcessor === "undefined") {
			xml = new DOMParser().parseFromString(xml, "text/xml");
			xsl = new DOMParser().parseFromString(xsl, "text/xml");
			// alert(xml.transformNode());
			// callback.call(null, new XMLSerializer().serializeToString(rs));
			
		}
		if(typeof window.DOMParser !== "undefined" && typeof window.XMLHttpRequest !== "undefined" && typeof window.XSLTProcessor !== "undefined") {
			processor = new XSLTProcessor();
			support = $.isFunction(processor.transformDocument) ? (typeof window.XMLSerializer !== "undefined") : true;
			if(!support) { return false; }
			xml = new DOMParser().parseFromString(xml, "text/xml");
			xsl = new DOMParser().parseFromString(xsl, "text/xml");
			if($.isFunction(processor.transformDocument)) {
				rs = document.implementation.createDocument("", "", null);
				processor.transformDocument(xml, xsl, rs, null);
				callback.call(null, new XMLSerializer().serializeToString(rs));
				return true;
			}
			else {
				processor.importStylesheet(xsl);
				rs = processor.transformToFragment(xml, document);
				callback.call(null, $("<div />").append(rs).html());
				return true;
			}
		}
		return false;
	};
	var xsl = {
		'nest' : '<' + '?xml version="1.0" encoding="utf-8" ?>' + 
			'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' + 
			'<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/html" />' + 
			'<xsl:template match="/">' + 
			'	<xsl:call-template name="nodes">' + 
			'		<xsl:with-param name="node" select="/root" />' + 
			'	</xsl:call-template>' + 
			'</xsl:template>' + 
			'<xsl:template name="nodes">' + 
			'	<xsl:param name="node" />' + 
			'	<ul>' + 
			'	<xsl:for-each select="$node/item">' + 
			'		<xsl:variable name="children" select="count(./item) &gt; 0" />' + 
			'		<li>' + 
			'			<xsl:attribute name="class">' + 
			'				<xsl:if test="position() = last()">jstree-last </xsl:if>' + 
			'				<xsl:choose>' + 
			'					<xsl:when test="@state = \'open\'">jstree-open </xsl:when>' + 
			'					<xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' + 
			'					<xsl:otherwise>jstree-leaf </xsl:otherwise>' + 
			'				</xsl:choose>' + 
			'				<xsl:value-of select="@class" />' + 
			'			</xsl:attribute>' + 
			'			<xsl:for-each select="@*">' + 
			'				<xsl:if test="name() != \'class\' and name() != \'state\' and name() != \'hasChildren\'">' + 
			'					<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
			'				</xsl:if>' + 
			'			</xsl:for-each>' + 
			'	<ins class="jstree-icon"><xsl:text>&#xa0;</xsl:text></ins>' + 
			'			<xsl:for-each select="content/name">' + 
			'				<a>' + 
			'				<xsl:attribute name="href">' + 
			'					<xsl:choose>' + 
			'					<xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' + 
			'					<xsl:otherwise>#</xsl:otherwise>' + 
			'					</xsl:choose>' + 
			'				</xsl:attribute>' + 
			'				<xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' + 
			'				<xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' + 
			'				<xsl:for-each select="@*">' + 
			'					<xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' + 
			'						<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
			'					</xsl:if>' + 
			'				</xsl:for-each>' + 
			'					<ins>' + 
			'						<xsl:attribute name="class">jstree-icon ' + 
			'							<xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' + 
			'						</xsl:attribute>' + 
			'						<xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' + 
			'						<xsl:text>&#xa0;</xsl:text>' + 
			'					</ins>' + 
			'					<xsl:copy-of select="./child::node()" />' + 
			'				</a>' + 
			'			</xsl:for-each>' + 
			'			<xsl:if test="$children or @hasChildren"><xsl:call-template name="nodes"><xsl:with-param name="node" select="current()" /></xsl:call-template></xsl:if>' + 
			'		</li>' + 
			'	</xsl:for-each>' + 
			'	</ul>' + 
			'</xsl:template>' + 
			'</xsl:stylesheet>',

		'flat' : '<' + '?xml version="1.0" encoding="utf-8" ?>' + 
			'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' + 
			'<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/xml" />' + 
			'<xsl:template match="/">' + 
			'	<ul>' + 
			'	<xsl:for-each select="//item[not(@parent_id) or @parent_id=0 or not(@parent_id = //item/@id)]">' + /* the last `or` may be removed */
			'		<xsl:call-template name="nodes">' + 
			'			<xsl:with-param name="node" select="." />' + 
			'			<xsl:with-param name="is_last" select="number(position() = last())" />' + 
			'		</xsl:call-template>' + 
			'	</xsl:for-each>' + 
			'	</ul>' + 
			'</xsl:template>' + 
			'<xsl:template name="nodes">' + 
			'	<xsl:param name="node" />' + 
			'	<xsl:param name="is_last" />' + 
			'	<xsl:variable name="children" select="count(//item[@parent_id=$node/attribute::id]) &gt; 0" />' + 
			'	<li>' + 
			'	<xsl:attribute name="class">' + 
			'		<xsl:if test="$is_last = true()">jstree-last </xsl:if>' + 
			'		<xsl:choose>' + 
			'			<xsl:when test="@state = \'open\'">jstree-open </xsl:when>' + 
			'			<xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' + 
			'			<xsl:otherwise>jstree-leaf </xsl:otherwise>' + 
			'		</xsl:choose>' + 
			'		<xsl:value-of select="@class" />' + 
			'	</xsl:attribute>' + 
			'	<xsl:for-each select="@*">' + 
			'		<xsl:if test="name() != \'parent_id\' and name() != \'hasChildren\' and name() != \'class\' and name() != \'state\'">' + 
			'		<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
			'		</xsl:if>' + 
			'	</xsl:for-each>' + 
			'	<ins class="jstree-icon"><xsl:text>&#xa0;</xsl:text></ins>' + 
			'	<xsl:for-each select="content/name">' + 
			'		<a>' + 
			'		<xsl:attribute name="href">' + 
			'			<xsl:choose>' + 
			'			<xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' + 
			'			<xsl:otherwise>#</xsl:otherwise>' + 
			'			</xsl:choose>' + 
			'		</xsl:attribute>' + 
			'		<xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' + 
			'		<xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' + 
			'		<xsl:for-each select="@*">' + 
			'			<xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' + 
			'				<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
			'			</xsl:if>' + 
			'		</xsl:for-each>' + 
			'			<ins>' + 
			'				<xsl:attribute name="class">jstree-icon ' + 
			'					<xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' + 
			'				</xsl:attribute>' + 
			'				<xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' + 
			'				<xsl:text>&#xa0;</xsl:text>' + 
			'			</ins>' + 
			'			<xsl:copy-of select="./child::node()" />' + 
			'		</a>' + 
			'	</xsl:for-each>' + 
			'	<xsl:if test="$children">' + 
			'		<ul>' + 
			'		<xsl:for-each select="//item[@parent_id=$node/attribute::id]">' + 
			'			<xsl:call-template name="nodes">' + 
			'				<xsl:with-param name="node" select="." />' + 
			'				<xsl:with-param name="is_last" select="number(position() = last())" />' + 
			'			</xsl:call-template>' + 
			'		</xsl:for-each>' + 
			'		</ul>' + 
			'	</xsl:if>' + 
			'	</li>' + 
			'</xsl:template>' + 
			'</xsl:stylesheet>'
	},
	escape_xml = function(string) {
		return string
			.toString()
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&apos;');
	};
	$.jstree.plugin("xml_data", {
		defaults : { 
			data : false,
			ajax : false,
			xsl : "flat",
			clean_node : false,
			correct_state : true,
			get_skip_empty : false,
			get_include_preamble : true
		},
		_fn : {
			load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_xml(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); },
			_is_loaded : function (obj) { 
				var s = this._get_settings().xml_data;
				obj = this._get_node(obj);
				return obj == -1 || !obj || (!s.ajax && !$.isFunction(s.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0;
			},
			load_node_xml : function (obj, s_call, e_call) {
				var s = this.get_settings().xml_data,
					error_func = function () {},
					success_func = function () {};

				obj = this._get_node(obj);
				if(obj && obj !== -1) {
					if(obj.data("jstree_is_loading")) { return; }
					else { obj.data("jstree_is_loading",true); }
				}
				switch(!0) {
					case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
					case ($.isFunction(s.data)):
						s.data.call(this, obj, $.proxy(function (d) {
							this.parse_xml(d, $.proxy(function (d) {
								if(d) {
									d = d.replace(/ ?xmlns="[^"]*"/ig, "");
									if(d.length > 10) {
										d = $(d);
										if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
										else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d); obj.removeData("jstree_is_loading"); }
										if(s.clean_node) { this.clean_node(obj); }
										if(s_call) { s_call.call(this); }
									}
									else {
										if(obj && obj !== -1) { 
											obj.children("a.jstree-loading").removeClass("jstree-loading");
											obj.removeData("jstree_is_loading");
											if(s.correct_state) { 
												this.correct_state(obj);
												if(s_call) { s_call.call(this); } 
											}
										}
										else {
											if(s.correct_state) { 
												this.get_container().children("ul").empty();
												if(s_call) { s_call.call(this); } 
											}
										}
									}
								}
							}, this));
						}, this));
						break;
					case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
						if(!obj || obj == -1) {
							this.parse_xml(s.data, $.proxy(function (d) {
								if(d) {
									d = d.replace(/ ?xmlns="[^"]*"/ig, "");
									if(d.length > 10) {
										d = $(d);
										this.get_container().children("ul").empty().append(d.children());
										if(s.clean_node) { this.clean_node(obj); }
										if(s_call) { s_call.call(this); }
									}
								}
								else { 
									if(s.correct_state) { 
										this.get_container().children("ul").empty(); 
										if(s_call) { s_call.call(this); }
									}
								}
							}, this));
						}
						break;
					case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
						error_func = function (x, t, e) {
							var ef = this.get_settings().xml_data.ajax.error; 
							if(ef) { ef.call(this, x, t, e); }
							if(obj !== -1 && obj.length) {
								obj.children("a.jstree-loading").removeClass("jstree-loading");
								obj.removeData("jstree_is_loading");
								if(t === "success" && s.correct_state) { this.correct_state(obj); }
							}
							else {
								if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
							}
							if(e_call) { e_call.call(this); }
						};
						success_func = function (d, t, x) {
							d = x.responseText;
							var sf = this.get_settings().xml_data.ajax.success; 
							if(sf) { d = sf.call(this,d,t,x) || d; }
							if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "")) {
								return error_func.call(this, x, t, "");
							}
							this.parse_xml(d, $.proxy(function (d) {
								if(d) {
									d = d.replace(/ ?xmlns="[^"]*"/ig, "");
									if(d.length > 10) {
										d = $(d);
										if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
										else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d); obj.removeData("jstree_is_loading"); }
										if(s.clean_node) { this.clean_node(obj); }
										if(s_call) { s_call.call(this); }
									}
									else {
										if(obj && obj !== -1) { 
											obj.children("a.jstree-loading").removeClass("jstree-loading");
											obj.removeData("jstree_is_loading");
											if(s.correct_state) { 
												this.correct_state(obj);
												if(s_call) { s_call.call(this); } 
											}
										}
										else {
											if(s.correct_state) { 
												this.get_container().children("ul").empty();
												if(s_call) { s_call.call(this); } 
											}
										}
									}
								}
							}, this));
						};
						s.ajax.context = this;
						s.ajax.error = error_func;
						s.ajax.success = success_func;
						if(!s.ajax.dataType) { s.ajax.dataType = "xml"; }
						if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
						if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
						$.ajax(s.ajax);
						break;
				}
			},
			parse_xml : function (xml, callback) {
				var s = this._get_settings().xml_data;
				$.vakata.xslt(xml, xsl[s.xsl], callback);
			},
			get_xml : function (tp, obj, li_attr, a_attr, is_callback) {
				var result = "", 
					s = this._get_settings(), 
					_this = this,
					tmp1, tmp2, li, a, lang;
				if(!tp) { tp = "flat"; }
				if(!is_callback) { is_callback = 0; }
				obj = this._get_node(obj);
				if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); }
				li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ];
				if(!is_callback && this.data.types && $.inArray(s.types.type_attr, li_attr) === -1) { li_attr.push(s.types.type_attr); }

				a_attr = $.isArray(a_attr) ? a_attr : [ ];

				if(!is_callback) { 
					if(s.xml_data.get_include_preamble) { 
						result += '<' + '?xml version="1.0" encoding="UTF-8"?' + '>'; 
					}
					result += "<root>"; 
				}
				obj.each(function () {
					result += "<item";
					li = $(this);
					$.each(li_attr, function (i, v) { 
						var t = li.attr(v);
						if(!s.xml_data.get_skip_empty || typeof t !== "undefined") {
							result += " " + v + "=\"" + escape_xml((" " + (t || "")).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + "\""; 
						}
					});
					if(li.hasClass("jstree-open")) { result += " state=\"open\""; }
					if(li.hasClass("jstree-closed")) { result += " state=\"closed\""; }
					if(tp === "flat") { result += " parent_id=\"" + escape_xml(is_callback) + "\""; }
					result += ">";
					result += "<content>";
					a = li.children("a");
					a.each(function () {
						tmp1 = $(this);
						lang = false;
						result += "<name";
						if($.inArray("languages", s.plugins) !== -1) {
							$.each(s.languages, function (k, z) {
								if(tmp1.hasClass(z)) { result += " lang=\"" + escape_xml(z) + "\""; lang = z; return false; }
							});
						}
						if(a_attr.length) { 
							$.each(a_attr, function (k, z) {
								var t = tmp1.attr(z);
								if(!s.xml_data.get_skip_empty || typeof t !== "undefined") {
									result += " " + z + "=\"" + escape_xml((" " + t || "").replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + "\"";
								}
							});
						}
						if(tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) {
							result += ' icon="' + escape_xml(tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + '"';
						}
						if(tmp1.children("ins").get(0).style.backgroundImage.length) {
							result += ' icon="' + escape_xml(tmp1.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")","").replace(/'/ig,"").replace(/"/ig,"")) + '"';
						}
						result += ">";
						result += "<![CDATA[" + _this.get_text(tmp1, lang) + "]]>";
						result += "</name>";
					});
					result += "</content>";
					tmp2 = li[0].id || true;
					li = li.find("> ul > li");
					if(li.length) { tmp2 = _this.get_xml(tp, li, li_attr, a_attr, tmp2); }
					else { tmp2 = ""; }
					if(tp == "nest") { result += tmp2; }
					result += "</item>";
					if(tp == "flat") { result += tmp2; }
				});
				if(!is_callback) { result += "</root>"; }
				return result;
			}
		}
	});
})(jQuery);
//*/

/*
 * jsTree search plugin
 * Enables both sync and async search on the tree
 * DOES NOT WORK WITH JSON PROGRESSIVE RENDER
 */
(function ($) {
	$.expr[':'].jstree_contains = function(a,i,m){
		return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
	};
	$.expr[':'].jstree_title_contains = function(a,i,m) {
		return (a.getAttribute("title") || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
	};
	$.jstree.plugin("search", {
		__init : function () {
			this.data.search.str = "";
			this.data.search.result = $();
			if(this._get_settings().search.show_only_matches) {
				this.get_container()
					.bind("search.jstree", function (e, data) {
						$(this).children("ul").find("li").hide().removeClass("jstree-last");
						data.rslt.nodes.parentsUntil(".jstree").andSelf().show()
							.filter("ul").each(function () { $(this).children("li:visible").eq(-1).addClass("jstree-last"); });
					})
					.bind("clear_search.jstree", function () {
						$(this).children("ul").find("li").css("display","").end().end().jstree("clean_node", -1);
					});
			}
		},
		defaults : {
			ajax : false,
			search_method : "jstree_contains", // for case insensitive - jstree_contains
			show_only_matches : false
		},
		_fn : {
			search : function (str, skip_async) {
				if($.trim(str) === "") { this.clear_search(); return; }
				var s = this.get_settings().search, 
					t = this,
					error_func = function () { },
					success_func = function () { };
				this.data.search.str = str;

				if(!skip_async && s.ajax !== false && this.get_container_ul().find("li.jstree-closed:not(:has(ul)):eq(0)").length > 0) {
					this.search.supress_callback = true;
					error_func = function () { };
					success_func = function (d, t, x) {
						var sf = this.get_settings().search.ajax.success; 
						if(sf) { d = sf.call(this,d,t,x) || d; }
						this.data.search.to_open = d;
						this._search_open();
					};
					s.ajax.context = this;
					s.ajax.error = error_func;
					s.ajax.success = success_func;
					if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, str); }
					if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, str); }
					if(!s.ajax.data) { s.ajax.data = { "search_string" : str }; }
					if(!s.ajax.dataType || /^json/.exec(s.ajax.dataType)) { s.ajax.dataType = "json"; }
					$.ajax(s.ajax);
					return;
				}
				if(this.data.search.result.length) { this.clear_search(); }
				this.data.search.result = this.get_container().find("a" + (this.data.languages ? "." + this.get_lang() : "" ) + ":" + (s.search_method) + "(" + this.data.search.str + ")");
				this.data.search.result.addClass("jstree-search").parent().parents(".jstree-closed").each(function () {
					t.open_node(this, false, true);
				});
				this.__callback({ nodes : this.data.search.result, str : str });
			},
			clear_search : function (str) {
				this.data.search.result.removeClass("jstree-search");
				this.__callback(this.data.search.result);
				this.data.search.result = $();
			},
			_search_open : function (is_callback) {
				var _this = this,
					done = true,
					current = [],
					remaining = [];
				if(this.data.search.to_open.length) {
					$.each(this.data.search.to_open, function (i, val) {
						if(val == "#") { return true; }
						if($(val).length && $(val).is(".jstree-closed")) { current.push(val); }
						else { remaining.push(val); }
					});
					if(current.length) {
						this.data.search.to_open = remaining;
						$.each(current, function (i, val) { 
							_this.open_node(val, function () { _this._search_open(true); }); 
						});
						done = false;
					}
				}
				if(done) { this.search(this.data.search.str, true); }
			}
		}
	});
})(jQuery);
//*/

/* 
 * jsTree contextmenu plugin
 */
(function ($) {
	$.vakata.context = {
		hide_on_mouseleave : false,

		cnt		: $("<div id='vakata-contextmenu' />"),
		vis		: false,
		tgt		: false,
		par		: false,
		func	: false,
		data	: false,
		rtl		: false,
		show	: function (s, t, x, y, d, p, rtl) {
			$.vakata.context.rtl = !!rtl;
			var html = $.vakata.context.parse(s), h, w;
			if(!html) { return; }
			$.vakata.context.vis = true;
			$.vakata.context.tgt = t;
			$.vakata.context.par = p || t || null;
			$.vakata.context.data = d || null;
			$.vakata.context.cnt
				.html(html)
				.css({ "visibility" : "hidden", "display" : "block", "left" : 0, "top" : 0 });

			if($.vakata.context.hide_on_mouseleave) {
				$.vakata.context.cnt
					.one("mouseleave", function(e) { $.vakata.context.hide(); });
			}

			h = $.vakata.context.cnt.height();
			w = $.vakata.context.cnt.width();
			if(x + w > $(document).width()) { 
				x = $(document).width() - (w + 5); 
				$.vakata.context.cnt.find("li > ul").addClass("right"); 
			}
			if(y + h > $(document).height()) { 
				y = y - (h + t[0].offsetHeight); 
				$.vakata.context.cnt.find("li > ul").addClass("bottom"); 
			}

			$.vakata.context.cnt
				.css({ "left" : x, "top" : y })
				.find("li:has(ul)")
					.bind("mouseenter", function (e) { 
						var w = $(document).width(),
							h = $(document).height(),
							ul = $(this).children("ul").show(); 
						if(w !== $(document).width()) { ul.toggleClass("right"); }
						if(h !== $(document).height()) { ul.toggleClass("bottom"); }
					})
					.bind("mouseleave", function (e) { 
						$(this).children("ul").hide(); 
					})
					.end()
				.css({ "visibility" : "visible" })
				.show();
			$(document).triggerHandler("context_show.vakata");
		},
		hide	: function () {
			$.vakata.context.vis = false;
			$.vakata.context.cnt.attr("class","").css({ "visibility" : "hidden" });
			$(document).triggerHandler("context_hide.vakata");
		},
		parse	: function (s, is_callback) {
			if(!s) { return false; }
			var str = "",
				tmp = false,
				was_sep = true;
			if(!is_callback) { $.vakata.context.func = {}; }
			str += "<ul>";
			$.each(s, function (i, val) {
				if(!val) { return true; }
				$.vakata.context.func[i] = val.action;
				if(!was_sep && val.separator_before) {
					str += "<li class='vakata-separator vakata-separator-before'></li>";
				}
				was_sep = false;
				str += "<li class='" + (val._class || "") + (val._disabled ? " jstree-contextmenu-disabled " : "") + "'><ins ";
				if(val.icon && val.icon.indexOf("/") === -1) { str += " class='" + val.icon + "' "; }
				if(val.icon && val.icon.indexOf("/") !== -1) { str += " style='background:url(" + val.icon + ") center center no-repeat;' "; }
				str += ">&#160;</ins><a href='#' rel='" + i + "'>";
				if(val.submenu) {
					str += "<span style='float:" + ($.vakata.context.rtl ? "left" : "right") + ";'>&raquo;</span>";
				}
				str += val.label + "</a>";
				if(val.submenu) {
					tmp = $.vakata.context.parse(val.submenu, true);
					if(tmp) { str += tmp; }
				}
				str += "</li>";
				if(val.separator_after) {
					str += "<li class='vakata-separator vakata-separator-after'></li>";
					was_sep = true;
				}
			});
			str = str.replace(/<li class\='vakata-separator vakata-separator-after'\><\/li\>$/,"");
			str += "</ul>";
			$(document).triggerHandler("context_parse.vakata");
			return str.length > 10 ? str : false;
		},
		exec	: function (i) {
			if($.isFunction($.vakata.context.func[i])) {
				// if is string - eval and call it!
				$.vakata.context.func[i].call($.vakata.context.data, $.vakata.context.par);
				return true;
			}
			else { return false; }
		}
	};
	$(function () {
		var css_string = '' + 
			'#vakata-contextmenu { display:block; visibility:hidden; left:0; top:-200px; position:absolute; margin:0; padding:0; min-width:180px; background:#ebebeb; border:1px solid silver; z-index:10000; *width:180px; } ' + 
			'#vakata-contextmenu ul { min-width:180px; *width:180px; } ' + 
			'#vakata-contextmenu ul, #vakata-contextmenu li { margin:0; padding:0; list-style-type:none; display:block; } ' + 
			'#vakata-contextmenu li { line-height:20px; min-height:20px; position:relative; padding:0px; } ' + 
			'#vakata-contextmenu li a { padding:1px 6px; line-height:17px; display:block; text-decoration:none; margin:1px 1px 0 1px; } ' + 
			'#vakata-contextmenu li ins { float:left; width:16px; height:16px; text-decoration:none; margin-right:2px; } ' + 
			'#vakata-contextmenu li a:hover, #vakata-contextmenu li.vakata-hover > a { background:gray; color:white; } ' + 
			'#vakata-contextmenu li ul { display:none; position:absolute; top:-2px; left:100%; background:#ebebeb; border:1px solid gray; } ' + 
			'#vakata-contextmenu .right { right:100%; left:auto; } ' + 
			'#vakata-contextmenu .bottom { bottom:-1px; top:auto; } ' + 
			'#vakata-contextmenu li.vakata-separator { min-height:0; height:1px; line-height:1px; font-size:1px; overflow:hidden; margin:0 2px; background:silver; /* border-top:1px solid #fefefe; */ padding:0; } ';
		$.vakata.css.add_sheet({ str : css_string, title : "vakata" });
		$.vakata.context.cnt
			.delegate("a","click", function (e) { e.preventDefault(); })
			.delegate("a","mouseup", function (e) {
				if(!$(this).parent().hasClass("jstree-contextmenu-disabled") && $.vakata.context.exec($(this).attr("rel"))) {
					$.vakata.context.hide();
				}
				else { $(this).blur(); }
			})
			.delegate("a","mouseover", function () {
				$.vakata.context.cnt.find(".vakata-hover").removeClass("vakata-hover");
			})
			.appendTo("body");
		$(document).bind("mousedown", function (e) { if($.vakata.context.vis && !$.contains($.vakata.context.cnt[0], e.target)) { $.vakata.context.hide(); } });
		if(typeof $.hotkeys !== "undefined") {
			$(document)
				.bind("keydown", "up", function (e) { 
					if($.vakata.context.vis) { 
						var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").prevAll("li:not(.vakata-separator)").first();
						if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").last(); }
						o.addClass("vakata-hover");
						e.stopImmediatePropagation(); 
						e.preventDefault();
					} 
				})
				.bind("keydown", "down", function (e) { 
					if($.vakata.context.vis) { 
						var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").nextAll("li:not(.vakata-separator)").first();
						if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").first(); }
						o.addClass("vakata-hover");
						e.stopImmediatePropagation(); 
						e.preventDefault();
					} 
				})
				.bind("keydown", "right", function (e) { 
					if($.vakata.context.vis) { 
						$.vakata.context.cnt.find(".vakata-hover").children("ul").show().children("li:not(.vakata-separator)").removeClass("vakata-hover").first().addClass("vakata-hover");
						e.stopImmediatePropagation(); 
						e.preventDefault();
					} 
				})
				.bind("keydown", "left", function (e) { 
					if($.vakata.context.vis) { 
						$.vakata.context.cnt.find(".vakata-hover").children("ul").hide().children(".vakata-separator").removeClass("vakata-hover");
						e.stopImmediatePropagation(); 
						e.preventDefault();
					} 
				})
				.bind("keydown", "esc", function (e) { 
					$.vakata.context.hide(); 
					e.preventDefault();
				})
				.bind("keydown", "space", function (e) { 
					$.vakata.context.cnt.find(".vakata-hover").last().children("a").click();
					e.preventDefault();
				});
		}
	});

	$.jstree.plugin("contextmenu", {
		__init : function () {
			this.get_container()
				.delegate("a", "contextmenu.jstree", $.proxy(function (e) {
						e.preventDefault();
						if(!$(e.currentTarget).hasClass("jstree-loading")) {
							this.show_contextmenu(e.currentTarget, e.pageX, e.pageY);
						}
					}, this))
				.delegate("a", "click.jstree", $.proxy(function (e) {
						if(this.data.contextmenu) {
							$.vakata.context.hide();
						}
					}, this))
				.bind("destroy.jstree", $.proxy(function () {
						// TODO: move this to descruct method
						if(this.data.contextmenu) {
							$.vakata.context.hide();
						}
					}, this));
			$(document).bind("context_hide.vakata", $.proxy(function () { this.data.contextmenu = false; }, this));
		},
		defaults : { 
			select_node : false, // requires UI plugin
			show_at_node : true,
			items : { // Could be a function that should return an object like this one
				"create" : {
					"separator_before"	: false,
					"separator_after"	: true,
					"label"				: "Create",
					"action"			: function (obj) { this.create(obj); }
				},
				"rename" : {
					"separator_before"	: false,
					"separator_after"	: false,
					"label"				: "Rename",
					"action"			: function (obj) { this.rename(obj); }
				},
				"remove" : {
					"separator_before"	: false,
					"icon"				: false,
					"separator_after"	: false,
					"label"				: "Delete",
					"action"			: function (obj) { if(this.is_selected(obj)) { this.remove(); } else { this.remove(obj); } }
				},
				"ccp" : {
					"separator_before"	: true,
					"icon"				: false,
					"separator_after"	: false,
					"label"				: "Edit",
					"action"			: false,
					"submenu" : { 
						"cut" : {
							"separator_before"	: false,
							"separator_after"	: false,
							"label"				: "Cut",
							"action"			: function (obj) { this.cut(obj); }
						},
						"copy" : {
							"separator_before"	: false,
							"icon"				: false,
							"separator_after"	: false,
							"label"				: "Copy",
							"action"			: function (obj) { this.copy(obj); }
						},
						"paste" : {
							"separator_before"	: false,
							"icon"				: false,
							"separator_after"	: false,
							"label"				: "Paste",
							"action"			: function (obj) { this.paste(obj); }
						}
					}
				}
			}
		},
		_fn : {
			show_contextmenu : function (obj, x, y) {
				obj = this._get_node(obj);
				var s = this.get_settings().contextmenu,
					a = obj.children("a:visible:eq(0)"),
					o = false,
					i = false;
				if(s.select_node && this.data.ui && !this.is_selected(obj)) {
					this.deselect_all();
					this.select_node(obj, true);
				}
				if(s.show_at_node || typeof x === "undefined" || typeof y === "undefined") {
					o = a.offset();
					x = o.left;
					y = o.top + this.data.core.li_height;
				}
				i = obj.data("jstree") && obj.data("jstree").contextmenu ? obj.data("jstree").contextmenu : s.items;
				if($.isFunction(i)) { i = i.call(this, obj); }
				this.data.contextmenu = true;
				$.vakata.context.show(i, a, x, y, this, obj, this._get_settings().core.rtl);
				if(this.data.themes) { $.vakata.context.cnt.attr("class", "jstree-" + this.data.themes.theme + "-context"); }
			}
		}
	});
})(jQuery);
//*/

/* 
 * jsTree types plugin
 * Adds support types of nodes
 * You can set an attribute on each li node, that represents its type.
 * According to the type setting the node may get custom icon/validation rules
 */
(function ($) {
	$.jstree.plugin("types", {
		__init : function () {
			var s = this._get_settings().types;
			this.data.types.attach_to = [];
			this.get_container()
				.bind("init.jstree", $.proxy(function () { 
						var types = s.types, 
							attr  = s.type_attr, 
							icons_css = "", 
							_this = this;

						$.each(types, function (i, tp) {
							$.each(tp, function (k, v) { 
								if(!/^(max_depth|max_children|icon|valid_children)$/.test(k)) { _this.data.types.attach_to.push(k); }
							});
							if(!tp.icon) { return true; }
							if( tp.icon.image || tp.icon.position) {
								if(i == "default")	{ icons_css += '.jstree-' + _this.get_index() + ' a > .jstree-icon { '; }
								else				{ icons_css += '.jstree-' + _this.get_index() + ' li[' + attr + '="' + i + '"] > a > .jstree-icon { '; }
								if(tp.icon.image)	{ icons_css += ' background-image:url(' + tp.icon.image + '); '; }
								if(tp.icon.position){ icons_css += ' background-position:' + tp.icon.position + '; '; }
								else				{ icons_css += ' background-position:0 0; '; }
								icons_css += '} ';
							}
						});
						if(icons_css !== "") { $.vakata.css.add_sheet({ 'str' : icons_css, title : "jstree-types" }); }
					}, this))
				.bind("before.jstree", $.proxy(function (e, data) { 
						var s, t, 
							o = this._get_settings().types.use_data ? this._get_node(data.args[0]) : false, 
							d = o && o !== -1 && o.length ? o.data("jstree") : false;
						if(d && d.types && d.types[data.func] === false) { e.stopImmediatePropagation(); return false; }
						if($.inArray(data.func, this.data.types.attach_to) !== -1) {
							if(!data.args[0] || (!data.args[0].tagName && !data.args[0].jquery)) { return; }
							s = this._get_settings().types.types;
							t = this._get_type(data.args[0]);
							if(
								( 
									(s[t] && typeof s[t][data.func] !== "undefined") || 
									(s["default"] && typeof s["default"][data.func] !== "undefined") 
								) && this._check(data.func, data.args[0]) === false
							) {
								e.stopImmediatePropagation();
								return false;
							}
						}
					}, this));
			if(is_ie6) {
				this.get_container()
					.bind("load_node.jstree set_type.jstree", $.proxy(function (e, data) {
							var r = data && data.rslt && data.rslt.obj && data.rslt.obj !== -1 ? this._get_node(data.rslt.obj).parent() : this.get_container_ul(),
								c = false,
								s = this._get_settings().types;
							$.each(s.types, function (i, tp) {
								if(tp.icon && (tp.icon.image || tp.icon.position)) {
									c = i === "default" ? r.find("li > a > .jstree-icon") : r.find("li[" + s.type_attr + "='" + i + "'] > a > .jstree-icon");
									if(tp.icon.image) { c.css("backgroundImage","url(" + tp.icon.image + ")"); }
									c.css("backgroundPosition", tp.icon.position || "0 0");
								}
							});
						}, this));
			}
		},
		defaults : {
			// defines maximum number of root nodes (-1 means unlimited, -2 means disable max_children checking)
			max_children		: -1,
			// defines the maximum depth of the tree (-1 means unlimited, -2 means disable max_depth checking)
			max_depth			: -1,
			// defines valid node types for the root nodes
			valid_children		: "all",

			// whether to use $.data
			use_data : false, 
			// where is the type stores (the rel attribute of the LI element)
			type_attr : "rel",
			// a list of types
			types : {
				// the default type
				"default" : {
					"max_children"	: -1,
					"max_depth"		: -1,
					"valid_children": "all"

					// Bound functions - you can bind any other function here (using boolean or function)
					//"select_node"	: true
				}
			}
		},
		_fn : {
			_types_notify : function (n, data) {
				if(data.type && this._get_settings().types.use_data) {
					this.set_type(data.type, n);
				}
			},
			_get_type : function (obj) {
				obj = this._get_node(obj);
				return (!obj || !obj.length) ? false : obj.attr(this._get_settings().types.type_attr) || "default";
			},
			set_type : function (str, obj) {
				obj = this._get_node(obj);
				var ret = (!obj.length || !str) ? false : obj.attr(this._get_settings().types.type_attr, str);
				if(ret) { this.__callback({ obj : obj, type : str}); }
				return ret;
			},
			_check : function (rule, obj, opts) {
				obj = this._get_node(obj);
				var v = false, t = this._get_type(obj), d = 0, _this = this, s = this._get_settings().types, data = false;
				if(obj === -1) { 
					if(!!s[rule]) { v = s[rule]; }
					else { return; }
				}
				else {
					if(t === false) { return; }
					data = s.use_data ? obj.data("jstree") : false;
					if(data && data.types && typeof data.types[rule] !== "undefined") { v = data.types[rule]; }
					else if(!!s.types[t] && typeof s.types[t][rule] !== "undefined") { v = s.types[t][rule]; }
					else if(!!s.types["default"] && typeof s.types["default"][rule] !== "undefined") { v = s.types["default"][rule]; }
				}
				if($.isFunction(v)) { v = v.call(this, obj); }
				if(rule === "max_depth" && obj !== -1 && opts !== false && s.max_depth !== -2 && v !== 0) {
					// also include the node itself - otherwise if root node it is not checked
					obj.children("a:eq(0)").parentsUntil(".jstree","li").each(function (i) {
						// check if current depth already exceeds global tree depth
						if(s.max_depth !== -1 && s.max_depth - (i + 1) <= 0) { v = 0; return false; }
						d = (i === 0) ? v : _this._check(rule, this, false);
						// check if current node max depth is already matched or exceeded
						if(d !== -1 && d - (i + 1) <= 0) { v = 0; return false; }
						// otherwise - set the max depth to the current value minus current depth
						if(d >= 0 && (d - (i + 1) < v || v < 0) ) { v = d - (i + 1); }
						// if the global tree depth exists and it minus the nodes calculated so far is less than `v` or `v` is unlimited
						if(s.max_depth >= 0 && (s.max_depth - (i + 1) < v || v < 0) ) { v = s.max_depth - (i + 1); }
					});
				}
				return v;
			},
			check_move : function () {
				if(!this.__call_old()) { return false; }
				var m  = this._get_move(),
					s  = m.rt._get_settings().types,
					mc = m.rt._check("max_children", m.cr),
					md = m.rt._check("max_depth", m.cr),
					vc = m.rt._check("valid_children", m.cr),
					ch = 0, d = 1, t;

				if(vc === "none") { return false; } 
				if($.isArray(vc) && m.ot && m.ot._get_type) {
					m.o.each(function () {
						if($.inArray(m.ot._get_type(this), vc) === -1) { d = false; return false; }
					});
					if(d === false) { return false; }
				}
				if(s.max_children !== -2 && mc !== -1) {
					ch = m.cr === -1 ? this.get_container().find("> ul > li").not(m.o).length : m.cr.find("> ul > li").not(m.o).length;
					if(ch + m.o.length > mc) { return false; }
				}
				if(s.max_depth !== -2 && md !== -1) {
					d = 0;
					if(md === 0) { return false; }
					if(typeof m.o.d === "undefined") {
						// TODO: deal with progressive rendering and async when checking max_depth (how to know the depth of the moved node)
						t = m.o;
						while(t.length > 0) {
							t = t.find("> ul > li");
							d ++;
						}
						m.o.d = d;
					}
					if(md - m.o.d < 0) { return false; }
				}
				return true;
			},
			create_node : function (obj, position, js, callback, is_loaded, skip_check) {
				if(!skip_check && (is_loaded || this._is_loaded(obj))) {
					var p  = (typeof position == "string" && position.match(/^before|after$/i) && obj !== -1) ? this._get_parent(obj) : this._get_node(obj),
						s  = this._get_settings().types,
						mc = this._check("max_children", p),
						md = this._check("max_depth", p),
						vc = this._check("valid_children", p),
						ch;
					if(typeof js === "string") { js = { data : js }; }
					if(!js) { js = {}; }
					if(vc === "none") { return false; } 
					if($.isArray(vc)) {
						if(!js.attr || !js.attr[s.type_attr]) { 
							if(!js.attr) { js.attr = {}; }
							js.attr[s.type_attr] = vc[0]; 
						}
						else {
							if($.inArray(js.attr[s.type_attr], vc) === -1) { return false; }
						}
					}
					if(s.max_children !== -2 && mc !== -1) {
						ch = p === -1 ? this.get_container().find("> ul > li").length : p.find("> ul > li").length;
						if(ch + 1 > mc) { return false; }
					}
					if(s.max_depth !== -2 && md !== -1 && (md - 1) < 0) { return false; }
				}
				return this.__call_old(true, obj, position, js, callback, is_loaded, skip_check);
			}
		}
	});
})(jQuery);
//*/

/* 
 * jsTree HTML plugin
 * The HTML data store. Datastores are build by replacing the `load_node` and `_is_loaded` functions.
 */
(function ($) {
	$.jstree.plugin("html_data", {
		__init : function () { 
			// this used to use html() and clean the whitespace, but this way any attached data was lost
			this.data.html_data.original_container_html = this.get_container().find(" > ul > li").clone(true);
			// remove white space from LI node - otherwise nodes appear a bit to the right
			this.data.html_data.original_container_html.find("li").andSelf().contents().filter(function() { return this.nodeType == 3; }).remove();
		},
		defaults : { 
			data : false,
			ajax : false,
			correct_state : true
		},
		_fn : {
			load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_html(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); },
			_is_loaded : function (obj) { 
				obj = this._get_node(obj); 
				return obj == -1 || !obj || (!this._get_settings().html_data.ajax && !$.isFunction(this._get_settings().html_data.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0;
			},
			load_node_html : function (obj, s_call, e_call) {
				var d,
					s = this.get_settings().html_data,
					error_func = function () {},
					success_func = function () {};
				obj = this._get_node(obj);
				if(obj && obj !== -1) {
					if(obj.data("jstree_is_loading")) { return; }
					else { obj.data("jstree_is_loading",true); }
				}
				switch(!0) {
					case ($.isFunction(s.data)):
						s.data.call(this, obj, $.proxy(function (d) {
							if(d && d !== "" && d.toString && d.toString().replace(/^[\s\n]+$/,"") !== "") {
								d = $(d);
								if(!d.is("ul")) { d = $("<ul />").append(d); }
								if(obj == -1 || !obj) { this.get_container().children("ul").empty().append(d.children()).find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); }
								else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d).children("ul").find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); obj.removeData("jstree_is_loading"); }
								this.clean_node(obj);
								if(s_call) { s_call.call(this); }
							}
							else {
								if(obj && obj !== -1) {
									obj.children("a.jstree-loading").removeClass("jstree-loading");
									obj.removeData("jstree_is_loading");
									if(s.correct_state) { 
										this.correct_state(obj);
										if(s_call) { s_call.call(this); } 
									}
								}
								else {
									if(s.correct_state) { 
										this.get_container().children("ul").empty();
										if(s_call) { s_call.call(this); } 
									}
								}
							}
						}, this));
						break;
					case (!s.data && !s.ajax):
						if(!obj || obj == -1) {
							this.get_container()
								.children("ul").empty()
								.append(this.data.html_data.original_container_html)
								.find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end()
								.filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon");
							this.clean_node();
						}
						if(s_call) { s_call.call(this); }
						break;
					case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
						if(!obj || obj == -1) {
							d = $(s.data);
							if(!d.is("ul")) { d = $("<ul />").append(d); }
							this.get_container()
								.children("ul").empty().append(d.children())
								.find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end()
								.filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon");
							this.clean_node();
						}
						if(s_call) { s_call.call(this); }
						break;
					case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
						obj = this._get_node(obj);
						error_func = function (x, t, e) {
							var ef = this.get_settings().html_data.ajax.error; 
							if(ef) { ef.call(this, x, t, e); }
							if(obj != -1 && obj.length) {
								obj.children("a.jstree-loading").removeClass("jstree-loading");
								obj.removeData("jstree_is_loading");
								if(t === "success" && s.correct_state) { this.correct_state(obj); }
							}
							else {
								if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
							}
							if(e_call) { e_call.call(this); }
						};
						success_func = function (d, t, x) {
							var sf = this.get_settings().html_data.ajax.success; 
							if(sf) { d = sf.call(this,d,t,x) || d; }
							if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "")) {
								return error_func.call(this, x, t, "");
							}
							if(d) {
								d = $(d);
								if(!d.is("ul")) { d = $("<ul />").append(d); }
								if(obj == -1 || !obj) { this.get_container().children("ul").empty().append(d.children()).find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); }
								else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d).children("ul").find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); obj.removeData("jstree_is_loading"); }
								this.clean_node(obj);
								if(s_call) { s_call.call(this); }
							}
							else {
								if(obj && obj !== -1) {
									obj.children("a.jstree-loading").removeClass("jstree-loading");
									obj.removeData("jstree_is_loading");
									if(s.correct_state) { 
										this.correct_state(obj);
										if(s_call) { s_call.call(this); } 
									}
								}
								else {
									if(s.correct_state) { 
										this.get_container().children("ul").empty();
										if(s_call) { s_call.call(this); } 
									}
								}
							}
						};
						s.ajax.context = this;
						s.ajax.error = error_func;
						s.ajax.success = success_func;
						if(!s.ajax.dataType) { s.ajax.dataType = "html"; }
						if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
						if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
						$.ajax(s.ajax);
						break;
				}
			}
		}
	});
	// include the HTML data plugin by default
	$.jstree.defaults.plugins.push("html_data");
})(jQuery);
//*/

/* 
 * jsTree themeroller plugin
 * Adds support for jQuery UI themes. Include this at the end of your plugins list, also make sure "themes" is not included.
 */
(function ($) {
	$.jstree.plugin("themeroller", {
		__init : function () {
			var s = this._get_settings().themeroller;
			this.get_container()
				.addClass("ui-widget-content")
				.addClass("jstree-themeroller")
				.delegate("a","mouseenter.jstree", function (e) {
					if(!$(e.currentTarget).hasClass("jstree-loading")) {
						$(this).addClass(s.item_h);
					}
				})
				.delegate("a","mouseleave.jstree", function () {
					$(this).removeClass(s.item_h);
				})
				.bind("init.jstree", $.proxy(function (e, data) { 
						data.inst.get_container().find("> ul > li > .jstree-loading > ins").addClass("ui-icon-refresh");
						this._themeroller(data.inst.get_container().find("> ul > li"));
					}, this))
				.bind("open_node.jstree create_node.jstree", $.proxy(function (e, data) { 
						this._themeroller(data.rslt.obj);
					}, this))
				.bind("loaded.jstree refresh.jstree", $.proxy(function (e) {
						this._themeroller();
					}, this))
				.bind("close_node.jstree", $.proxy(function (e, data) {
						this._themeroller(data.rslt.obj);
					}, this))
				.bind("delete_node.jstree", $.proxy(function (e, data) {
						this._themeroller(data.rslt.parent);
					}, this))
				.bind("correct_state.jstree", $.proxy(function (e, data) {
						data.rslt.obj
							.children("ins.jstree-icon").removeClass(s.opened + " " + s.closed + " ui-icon").end()
							.find("> a > ins.ui-icon")
								.filter(function() { 
									return this.className.toString()
										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
										.indexOf("ui-icon-") === -1; 
								}).removeClass(s.item_open + " " + s.item_clsd).addClass(s.item_leaf || "jstree-no-icon");
					}, this))
				.bind("select_node.jstree", $.proxy(function (e, data) {
						data.rslt.obj.children("a").addClass(s.item_a);
					}, this))
				.bind("deselect_node.jstree deselect_all.jstree", $.proxy(function (e, data) {
						this.get_container()
							.find("a." + s.item_a).removeClass(s.item_a).end()
							.find("a.jstree-clicked").addClass(s.item_a);
					}, this))
				.bind("dehover_node.jstree", $.proxy(function (e, data) {
						data.rslt.obj.children("a").removeClass(s.item_h);
					}, this))
				.bind("hover_node.jstree", $.proxy(function (e, data) {
						this.get_container()
							.find("a." + s.item_h).not(data.rslt.obj).removeClass(s.item_h);
						data.rslt.obj.children("a").addClass(s.item_h);
					}, this))
				.bind("move_node.jstree", $.proxy(function (e, data) {
						this._themeroller(data.rslt.o);
						this._themeroller(data.rslt.op);
					}, this));
		},
		__destroy : function () {
			var s = this._get_settings().themeroller,
				c = [ "ui-icon" ];
			$.each(s, function (i, v) {
				v = v.split(" ");
				if(v.length) { c = c.concat(v); }
			});
			this.get_container()
				.removeClass("ui-widget-content")
				.find("." + c.join(", .")).removeClass(c.join(" "));
		},
		_fn : {
			_themeroller : function (obj) {
				var s = this._get_settings().themeroller;
				obj = !obj || obj == -1 ? this.get_container_ul() : this._get_node(obj).parent();
				obj
					.find("li.jstree-closed")
						.children("ins.jstree-icon").removeClass(s.opened).addClass("ui-icon " + s.closed).end()
						.children("a").addClass(s.item)
							.children("ins.jstree-icon").addClass("ui-icon")
								.filter(function() { 
									return this.className.toString()
										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
										.indexOf("ui-icon-") === -1; 
								}).removeClass(s.item_leaf + " " + s.item_open).addClass(s.item_clsd || "jstree-no-icon")
								.end()
							.end()
						.end()
					.end()
					.find("li.jstree-open")
						.children("ins.jstree-icon").removeClass(s.closed).addClass("ui-icon " + s.opened).end()
						.children("a").addClass(s.item)
							.children("ins.jstree-icon").addClass("ui-icon")
								.filter(function() { 
									return this.className.toString()
										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
										.indexOf("ui-icon-") === -1; 
								}).removeClass(s.item_leaf + " " + s.item_clsd).addClass(s.item_open || "jstree-no-icon")
								.end()
							.end()
						.end()
					.end()
					.find("li.jstree-leaf")
						.children("ins.jstree-icon").removeClass(s.closed + " ui-icon " + s.opened).end()
						.children("a").addClass(s.item)
							.children("ins.jstree-icon").addClass("ui-icon")
								.filter(function() { 
									return this.className.toString()
										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
										.indexOf("ui-icon-") === -1; 
								}).removeClass(s.item_clsd + " " + s.item_open).addClass(s.item_leaf || "jstree-no-icon");
			}
		},
		defaults : {
			"opened"	: "ui-icon-triangle-1-se",
			"closed"	: "ui-icon-triangle-1-e",
			"item"		: "ui-state-default",
			"item_h"	: "ui-state-hover",
			"item_a"	: "ui-state-active",
			"item_open"	: "ui-icon-folder-open",
			"item_clsd"	: "ui-icon-folder-collapsed",
			"item_leaf"	: "ui-icon-document"
		}
	});
	$(function() {
		var css_string = '' + 
			'.jstree-themeroller .ui-icon { overflow:visible; } ' + 
			'.jstree-themeroller a { padding:0 2px; } ' + 
			'.jstree-themeroller .jstree-no-icon { display:none; }';
		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
	});
})(jQuery);
//*/

/* 
 * jsTree unique plugin
 * Forces different names amongst siblings (still a bit experimental)
 * NOTE: does not check language versions (it will not be possible to have nodes with the same title, even in different languages)
 */
(function ($) {
	$.jstree.plugin("unique", {
		__init : function () {
			this.get_container()
				.bind("before.jstree", $.proxy(function (e, data) { 
						var nms = [], res = true, p, t;
						if(data.func == "move_node") {
							// obj, ref, position, is_copy, is_prepared, skip_check
							if(data.args[4] === true) {
								if(data.args[0].o && data.args[0].o.length) {
									data.args[0].o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); });
									res = this._check_unique(nms, data.args[0].np.find("> ul > li").not(data.args[0].o), "move_node");
								}
							}
						}
						if(data.func == "create_node") {
							// obj, position, js, callback, is_loaded
							if(data.args[4] || this._is_loaded(data.args[0])) {
								p = this._get_node(data.args[0]);
								if(data.args[1] && (data.args[1] === "before" || data.args[1] === "after")) {
									p = this._get_parent(data.args[0]);
									if(!p || p === -1) { p = this.get_container(); }
								}
								if(typeof data.args[2] === "string") { nms.push(data.args[2]); }
								else if(!data.args[2] || !data.args[2].data) { nms.push(this._get_string("new_node")); }
								else { nms.push(data.args[2].data); }
								res = this._check_unique(nms, p.find("> ul > li"), "create_node");
							}
						}
						if(data.func == "rename_node") {
							// obj, val
							nms.push(data.args[1]);
							t = this._get_node(data.args[0]);
							p = this._get_parent(t);
							if(!p || p === -1) { p = this.get_container(); }
							res = this._check_unique(nms, p.find("> ul > li").not(t), "rename_node");
						}
						if(!res) {
							e.stopPropagation();
							return false;
						}
					}, this));
		},
		defaults : { 
			error_callback : $.noop
		},
		_fn : { 
			_check_unique : function (nms, p, func) {
				var cnms = [];
				p.children("a").each(function () { cnms.push($(this).text().replace(/^\s+/g,"")); });
				if(!cnms.length || !nms.length) { return true; }
				cnms = cnms.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
				if((cnms.length + nms.length) != cnms.concat(nms).sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",").length) {
					this._get_settings().unique.error_callback.call(null, nms, p, func);
					return false;
				}
				return true;
			},
			check_move : function () {
				if(!this.__call_old()) { return false; }
				var p = this._get_move(), nms = [];
				if(p.o && p.o.length) {
					p.o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); });
					return this._check_unique(nms, p.np.find("> ul > li").not(p.o), "check_move");
				}
				return true;
			}
		}
	});
})(jQuery);
//*/

/*
 * jsTree wholerow plugin
 * Makes select and hover work on the entire width of the node
 * MAY BE HEAVY IN LARGE DOM
 */
(function ($) {
	$.jstree.plugin("wholerow", {
		__init : function () {
			if(!this.data.ui) { throw "jsTree wholerow: jsTree UI plugin not included."; }
			this.data.wholerow.html = false;
			this.data.wholerow.to = false;
			this.get_container()
				.bind("init.jstree", $.proxy(function (e, data) { 
						this._get_settings().core.animation = 0;
					}, this))
				.bind("open_node.jstree create_node.jstree clean_node.jstree loaded.jstree", $.proxy(function (e, data) { 
						this._prepare_wholerow_span( data && data.rslt && data.rslt.obj ? data.rslt.obj : -1 );
					}, this))
				.bind("search.jstree clear_search.jstree reopen.jstree after_open.jstree after_close.jstree create_node.jstree delete_node.jstree clean_node.jstree", $.proxy(function (e, data) { 
						if(this.data.to) { clearTimeout(this.data.to); }
						this.data.to = setTimeout( (function (t, o) { return function() { t._prepare_wholerow_ul(o); }; })(this,  data && data.rslt && data.rslt.obj ? data.rslt.obj : -1), 0);
					}, this))
				.bind("deselect_all.jstree", $.proxy(function (e, data) { 
						this.get_container().find(" > .jstree-wholerow .jstree-clicked").removeClass("jstree-clicked " + (this.data.themeroller ? this._get_settings().themeroller.item_a : "" ));
					}, this))
				.bind("select_node.jstree deselect_node.jstree ", $.proxy(function (e, data) { 
						data.rslt.obj.each(function () { 
							var ref = data.inst.get_container().find(" > .jstree-wholerow li:visible:eq(" + ( parseInt((($(this).offset().top - data.inst.get_container().offset().top + data.inst.get_container()[0].scrollTop) / data.inst.data.core.li_height),10)) + ")");
							// ref.children("a")[e.type === "select_node" ? "addClass" : "removeClass"]("jstree-clicked");
							ref.children("a").attr("class",data.rslt.obj.children("a").attr("class"));
						});
					}, this))
				.bind("hover_node.jstree dehover_node.jstree", $.proxy(function (e, data) { 
						this.get_container().find(" > .jstree-wholerow .jstree-hovered").removeClass("jstree-hovered " + (this.data.themeroller ? this._get_settings().themeroller.item_h : "" ));
						if(e.type === "hover_node") {
							var ref = this.get_container().find(" > .jstree-wholerow li:visible:eq(" + ( parseInt(((data.rslt.obj.offset().top - this.get_container().offset().top + this.get_container()[0].scrollTop) / this.data.core.li_height),10)) + ")");
							// ref.children("a").addClass("jstree-hovered");
							ref.children("a").attr("class",data.rslt.obj.children(".jstree-hovered").attr("class"));
						}
					}, this))
				.delegate(".jstree-wholerow-span, ins.jstree-icon, li", "click.jstree", function (e) {
						var n = $(e.currentTarget);
						if(e.target.tagName === "A" || (e.target.tagName === "INS" && n.closest("li").is(".jstree-open, .jstree-closed"))) { return; }
						n.closest("li").children("a:visible:eq(0)").click();
						e.stopImmediatePropagation();
					})
				.delegate("li", "mouseover.jstree", $.proxy(function (e) {
						e.stopImmediatePropagation();
						if($(e.currentTarget).children(".jstree-hovered, .jstree-clicked").length) { return false; }
						this.hover_node(e.currentTarget);
						return false;
					}, this))
				.delegate("li", "mouseleave.jstree", $.proxy(function (e) {
						if($(e.currentTarget).children("a").hasClass("jstree-hovered").length) { return; }
						this.dehover_node(e.currentTarget);
					}, this));
			if(is_ie7 || is_ie6) {
				$.vakata.css.add_sheet({ str : ".jstree-" + this.get_index() + " { position:relative; } ", title : "jstree" });
			}
		},
		defaults : {
		},
		__destroy : function () {
			this.get_container().children(".jstree-wholerow").remove();
			this.get_container().find(".jstree-wholerow-span").remove();
		},
		_fn : {
			_prepare_wholerow_span : function (obj) {
				obj = !obj || obj == -1 ? this.get_container().find("> ul > li") : this._get_node(obj);
				if(obj === false) { return; } // added for removing root nodes
				obj.each(function () {
					$(this).find("li").andSelf().each(function () {
						var $t = $(this);
						if($t.children(".jstree-wholerow-span").length) { return true; }
						$t.prepend("<span class='jstree-wholerow-span' style='width:" + ($t.parentsUntil(".jstree","li").length * 18) + "px;'>&#160;</span>");
					});
				});
			},
			_prepare_wholerow_ul : function () {
				var o = this.get_container().children("ul").eq(0), h = o.html();
				o.addClass("jstree-wholerow-real");
				if(this.data.wholerow.last_html !== h) {
					this.data.wholerow.last_html = h;
					this.get_container().children(".jstree-wholerow").remove();
					this.get_container().append(
						o.clone().removeClass("jstree-wholerow-real")
							.wrapAll("<div class='jstree-wholerow' />").parent()
							.width(o.parent()[0].scrollWidth)
							.css("top", (o.height() + ( is_ie7 ? 5 : 0)) * -1 )
							.find("li[id]").each(function () { this.removeAttribute("id"); }).end()
					);
				}
			}
		}
	});
	$(function() {
		var css_string = '' + 
			'.jstree .jstree-wholerow-real { position:relative; z-index:1; } ' + 
			'.jstree .jstree-wholerow-real li { cursor:pointer; } ' + 
			'.jstree .jstree-wholerow-real a { border-left-color:transparent !important; border-right-color:transparent !important; } ' + 
			'.jstree .jstree-wholerow { position:relative; z-index:0; height:0; } ' + 
			'.jstree .jstree-wholerow ul, .jstree .jstree-wholerow li { width:100%; } ' + 
			'.jstree .jstree-wholerow, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow li, .jstree .jstree-wholerow a { margin:0 !important; padding:0 !important; } ' + 
			'.jstree .jstree-wholerow, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow li { background:transparent !important; }' + 
			'.jstree .jstree-wholerow ins, .jstree .jstree-wholerow span, .jstree .jstree-wholerow input { display:none !important; }' + 
			'.jstree .jstree-wholerow a, .jstree .jstree-wholerow a:hover { text-indent:-9999px; !important; width:100%; padding:0 !important; border-right-width:0px !important; border-left-width:0px !important; } ' + 
			'.jstree .jstree-wholerow-span { position:absolute; left:0; margin:0px; padding:0; height:18px; border-width:0; padding:0; z-index:0; }';
		if(is_ff2) {
			css_string += '' + 
				'.jstree .jstree-wholerow a { display:block; height:18px; margin:0; padding:0; border:0; } ' + 
				'.jstree .jstree-wholerow-real a { border-color:transparent !important; } ';
		}
		if(is_ie7 || is_ie6) {
			css_string += '' + 
				'.jstree .jstree-wholerow, .jstree .jstree-wholerow li, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow a { margin:0; padding:0; line-height:18px; } ' + 
				'.jstree .jstree-wholerow a { display:block; height:18px; line-height:18px; overflow:hidden; } ';
		}
		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
	});
})(jQuery);
//*/

/*
* jsTree model plugin
* This plugin gets jstree to use a class model to retrieve data, creating great dynamism
*/
(function ($) {
	var nodeInterface = ["getChildren","getChildrenCount","getAttr","getName","getProps"],
		validateInterface = function(obj, inter) {
			var valid = true;
			obj = obj || {};
			inter = [].concat(inter);
			$.each(inter, function (i, v) {
				if(!$.isFunction(obj[v])) { valid = false; return false; }
			});
			return valid;
		};
	$.jstree.plugin("model", {
		__init : function () {
			if(!this.data.json_data) { throw "jsTree model: jsTree json_data plugin not included."; }
			this._get_settings().json_data.data = function (n, b) {
				var obj = (n == -1) ? this._get_settings().model.object : n.data("jstree_model");
				if(!validateInterface(obj, nodeInterface)) { return b.call(null, false); }
				if(this._get_settings().model.async) {
					obj.getChildren($.proxy(function (data) {
						this.model_done(data, b);
					}, this));
				}
				else {
					this.model_done(obj.getChildren(), b);
				}
			};
		},
		defaults : {
			object : false,
			id_prefix : false,
			'async': false
		},
		_fn : {
			model_done : function (data, callback) {
				var ret = [], 
					s = this._get_settings(),
					_this = this;

				if(!$.isArray(data)) { data = [data]; }
				$.each(data, function (i, nd) {
					var r = nd.getProps() || {};
					r.attr = nd.getAttr() || {};
					if(nd.getChildrenCount()) { r.state = "closed"; }
					r.data = nd.getName();
					if(!$.isArray(r.data)) { r.data = [r.data]; }
					if(_this.data.types && $.isFunction(nd.getType)) {
						r.attr[s.types.type_attr] = nd.getType();
					}
					if(r.attr.id && s.model.id_prefix) { r.attr.id = s.model.id_prefix + r.attr.id; }
					if(!r.metadata) { r.metadata = { }; }
					r.metadata.jstree_model = nd;
					ret.push(r);
				});
				callback.call(null, ret);
			}
		}
	});
})(jQuery);
//*/

})();;

/** jQuery FancyBox **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery FancyBox';
/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 * 
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function(b){var m,t,u,f,D,j,E,n,z,A,q=0,e={},o=[],p=0,d={},l=[],G=null,v=new Image,J=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,W=/[^\.]\.(swf)\s*$/i,K,L=1,y=0,s="",r,i,h=false,B=b.extend(b("<div/>")[0],{prop:0}),M=b.browser.msie&&b.browser.version<7&&!window.XMLHttpRequest,N=function(){t.hide();v.onerror=v.onload=null;G&&G.abort();m.empty()},O=function(){if(false===e.onError(o,q,e)){t.hide();h=false}else{e.titleShow=false;e.width="auto";e.height="auto";m.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');
F()}},I=function(){var a=o[q],c,g,k,C,P,w;N();e=b.extend({},b.fn.fancybox.defaults,typeof b(a).data("fancybox")=="undefined"?e:b(a).data("fancybox"));w=e.onStart(o,q,e);if(w===false)h=false;else{if(typeof w=="object")e=b.extend(e,w);k=e.title||(a.nodeName?b(a).attr("title"):a.title)||"";if(a.nodeName&&!e.orig)e.orig=b(a).children("img:first").length?b(a).children("img:first"):b(a);if(k===""&&e.orig&&e.titleFromAlt)k=e.orig.attr("alt");c=e.href||(a.nodeName?b(a).attr("href"):a.href)||null;if(/^(?:javascript)/i.test(c)||
c=="#")c=null;if(e.type){g=e.type;if(!c)c=e.content}else if(e.content)g="html";else if(c)g=c.match(J)?"image":c.match(W)?"swf":b(a).hasClass("iframe")?"iframe":c.indexOf("#")===0?"inline":"ajax";if(g){if(g=="inline"){a=c.substr(c.indexOf("#"));g=b(a).length>0?"inline":"ajax"}e.type=g;e.href=c;e.title=k;if(e.autoDimensions)if(e.type=="html"||e.type=="inline"||e.type=="ajax"){e.width="auto";e.height="auto"}else e.autoDimensions=false;if(e.modal){e.overlayShow=true;e.hideOnOverlayClick=false;e.hideOnContentClick=
false;e.enableEscapeButton=false;e.showCloseButton=false}e.padding=parseInt(e.padding,10);e.margin=parseInt(e.margin,10);m.css("padding",e.padding+e.margin);b(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){b(this).replaceWith(j.children())});switch(g){case "html":m.html(e.content);F();break;case "inline":if(b(a).parent().is("#fancybox-content")===true){h=false;break}b('<div class="fancybox-inline-tmp" />').hide().insertBefore(b(a)).bind("fancybox-cleanup",function(){b(this).replaceWith(j.children())}).bind("fancybox-cancel",
function(){b(this).replaceWith(m.children())});b(a).appendTo(m);F();break;case "image":h=false;b.fancybox.showActivity();v=new Image;v.onerror=function(){O()};v.onload=function(){h=true;v.onerror=v.onload=null;e.width=v.width;e.height=v.height;b("<img />").attr({id:"fancybox-img",src:v.src,alt:e.title}).appendTo(m);Q()};v.src=c;break;case "swf":e.scrolling="no";C='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+e.width+'" height="'+e.height+'"><param name="movie" value="'+c+
'"></param>';P="";b.each(e.swf,function(x,H){C+='<param name="'+x+'" value="'+H+'"></param>';P+=" "+x+'="'+H+'"'});C+='<embed src="'+c+'" type="application/x-shockwave-flash" width="'+e.width+'" height="'+e.height+'"'+P+"></embed></object>";m.html(C);F();break;case "ajax":h=false;b.fancybox.showActivity();e.ajax.win=e.ajax.success;G=b.ajax(b.extend({},e.ajax,{url:c,data:e.ajax.data||{},error:function(x){x.status>0&&O()},success:function(x,H,R){if((typeof R=="object"?R:G).status==200){if(typeof e.ajax.win==
"function"){w=e.ajax.win(c,x,H,R);if(w===false){t.hide();return}else if(typeof w=="string"||typeof w=="object")x=w}m.html(x);F()}}}));break;case "iframe":Q()}}else O()}},F=function(){var a=e.width,c=e.height;a=a.toString().indexOf("%")>-1?parseInt((b(window).width()-e.margin*2)*parseFloat(a)/100,10)+"px":a=="auto"?"auto":a+"px";c=c.toString().indexOf("%")>-1?parseInt((b(window).height()-e.margin*2)*parseFloat(c)/100,10)+"px":c=="auto"?"auto":c+"px";m.wrapInner('<div style="width:'+a+";height:"+c+
";overflow: "+(e.scrolling=="auto"?"auto":e.scrolling=="yes"?"scroll":"hidden")+';position:relative;"></div>');e.width=m.width();e.height=m.height();Q()},Q=function(){var a,c;t.hide();if(f.is(":visible")&&false===d.onCleanup(l,p,d)){b.event.trigger("fancybox-cancel");h=false}else{h=true;b(j.add(u)).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");f.is(":visible")&&d.titlePosition!=="outside"&&f.css("height",f.height());l=o;p=q;d=e;if(d.overlayShow){u.css({"background-color":d.overlayColor,
opacity:d.overlayOpacity,cursor:d.hideOnOverlayClick?"pointer":"auto",height:b(document).height()});if(!u.is(":visible")){M&&b("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"});u.show()}}else u.hide();i=X();s=d.title||"";y=0;n.empty().removeAttr("style").removeClass();if(d.titleShow!==false){if(b.isFunction(d.titleFormat))a=d.titleFormat(s,l,p,d);else a=s&&s.length?
d.titlePosition=="float"?'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+s+'</td><td id="fancybox-title-float-right"></td></tr></table>':'<div id="fancybox-title-'+d.titlePosition+'">'+s+"</div>":false;s=a;if(!(!s||s==="")){n.addClass("fancybox-title-"+d.titlePosition).html(s).appendTo("body").show();switch(d.titlePosition){case "inside":n.css({width:i.width-d.padding*2,marginLeft:d.padding,marginRight:d.padding});
y=n.outerHeight(true);n.appendTo(D);i.height+=y;break;case "over":n.css({marginLeft:d.padding,width:i.width-d.padding*2,bottom:d.padding}).appendTo(D);break;case "float":n.css("left",parseInt((n.width()-i.width-40)/2,10)*-1).appendTo(f);break;default:n.css({width:i.width-d.padding*2,paddingLeft:d.padding,paddingRight:d.padding}).appendTo(f)}}}n.hide();if(f.is(":visible")){b(E.add(z).add(A)).hide();a=f.position();r={top:a.top,left:a.left,width:f.width(),height:f.height()};c=r.width==i.width&&r.height==
i.height;j.fadeTo(d.changeFade,0.3,function(){var g=function(){j.html(m.contents()).fadeTo(d.changeFade,1,S)};b.event.trigger("fancybox-change");j.empty().removeAttr("filter").css({"border-width":d.padding,width:i.width-d.padding*2,height:e.autoDimensions?"auto":i.height-y-d.padding*2});if(c)g();else{B.prop=0;b(B).animate({prop:1},{duration:d.changeSpeed,easing:d.easingChange,step:T,complete:g})}})}else{f.removeAttr("style");j.css("border-width",d.padding);if(d.transitionIn=="elastic"){r=V();j.html(m.contents());
f.show();if(d.opacity)i.opacity=0;B.prop=0;b(B).animate({prop:1},{duration:d.speedIn,easing:d.easingIn,step:T,complete:S})}else{d.titlePosition=="inside"&&y>0&&n.show();j.css({width:i.width-d.padding*2,height:e.autoDimensions?"auto":i.height-y-d.padding*2}).html(m.contents());f.css(i).fadeIn(d.transitionIn=="none"?0:d.speedIn,S)}}}},Y=function(){if(d.enableEscapeButton||d.enableKeyboardNav)b(document).bind("keydown.fb",function(a){if(a.keyCode==27&&d.enableEscapeButton){a.preventDefault();b.fancybox.close()}else if((a.keyCode==
37||a.keyCode==39)&&d.enableKeyboardNav&&a.target.tagName!=="INPUT"&&a.target.tagName!=="TEXTAREA"&&a.target.tagName!=="SELECT"){a.preventDefault();b.fancybox[a.keyCode==37?"prev":"next"]()}});if(d.showNavArrows){if(d.cyclic&&l.length>1||p!==0)z.show();if(d.cyclic&&l.length>1||p!=l.length-1)A.show()}else{z.hide();A.hide()}},S=function(){if(!b.support.opacity){j.get(0).style.removeAttribute("filter");f.get(0).style.removeAttribute("filter")}e.autoDimensions&&j.css("height","auto");f.css("height","auto");
s&&s.length&&n.show();d.showCloseButton&&E.show();Y();d.hideOnContentClick&&j.bind("click",b.fancybox.close);d.hideOnOverlayClick&&u.bind("click",b.fancybox.close);b(window).bind("resize.fb",b.fancybox.resize);d.centerOnScroll&&b(window).bind("scroll.fb",b.fancybox.center);if(d.type=="iframe")b('<iframe id="fancybox-frame" name="fancybox-frame'+(new Date).getTime()+'" frameborder="0" hspace="0" '+(b.browser.msie?'allowtransparency="true""':"")+' scrolling="'+e.scrolling+'" src="'+d.href+'"></iframe>').appendTo(j);
f.show();h=false;b.fancybox.center();d.onComplete(l,p,d);var a,c;if(l.length-1>p){a=l[p+1].href;if(typeof a!=="undefined"&&a.match(J)){c=new Image;c.src=a}}if(p>0){a=l[p-1].href;if(typeof a!=="undefined"&&a.match(J)){c=new Image;c.src=a}}},T=function(a){var c={width:parseInt(r.width+(i.width-r.width)*a,10),height:parseInt(r.height+(i.height-r.height)*a,10),top:parseInt(r.top+(i.top-r.top)*a,10),left:parseInt(r.left+(i.left-r.left)*a,10)};if(typeof i.opacity!=="undefined")c.opacity=a<0.5?0.5:a;f.css(c);
j.css({width:c.width-d.padding*2,height:c.height-y*a-d.padding*2})},U=function(){return[b(window).width()-d.margin*2,b(window).height()-d.margin*2,b(document).scrollLeft()+d.margin,b(document).scrollTop()+d.margin]},X=function(){var a=U(),c={},g=d.autoScale,k=d.padding*2;c.width=d.width.toString().indexOf("%")>-1?parseInt(a[0]*parseFloat(d.width)/100,10):d.width+k;c.height=d.height.toString().indexOf("%")>-1?parseInt(a[1]*parseFloat(d.height)/100,10):d.height+k;if(g&&(c.width>a[0]||c.height>a[1]))if(e.type==
"image"||e.type=="swf"){g=d.width/d.height;if(c.width>a[0]){c.width=a[0];c.height=parseInt((c.width-k)/g+k,10)}if(c.height>a[1]){c.height=a[1];c.width=parseInt((c.height-k)*g+k,10)}}else{c.width=Math.min(c.width,a[0]);c.height=Math.min(c.height,a[1])}c.top=parseInt(Math.max(a[3]-20,a[3]+(a[1]-c.height-40)*0.5),10);c.left=parseInt(Math.max(a[2]-20,a[2]+(a[0]-c.width-40)*0.5),10);return c},V=function(){var a=e.orig?b(e.orig):false,c={};if(a&&a.length){c=a.offset();c.top+=parseInt(a.css("paddingTop"),
10)||0;c.left+=parseInt(a.css("paddingLeft"),10)||0;c.top+=parseInt(a.css("border-top-width"),10)||0;c.left+=parseInt(a.css("border-left-width"),10)||0;c.width=a.width();c.height=a.height();c={width:c.width+d.padding*2,height:c.height+d.padding*2,top:c.top-d.padding-20,left:c.left-d.padding-20}}else{a=U();c={width:d.padding*2,height:d.padding*2,top:parseInt(a[3]+a[1]*0.5,10),left:parseInt(a[2]+a[0]*0.5,10)}}return c},Z=function(){if(t.is(":visible")){b("div",t).css("top",L*-40+"px");L=(L+1)%12}else clearInterval(K)};
b.fn.fancybox=function(a){if(!b(this).length)return this;b(this).data("fancybox",b.extend({},a,b.metadata?b(this).metadata():{})).unbind("click.fb").bind("click.fb",function(c){c.preventDefault();if(!h){h=true;b(this).blur();o=[];q=0;c=b(this).attr("rel")||"";if(!c||c==""||c==="nofollow")o.push(this);else{o=b("a[rel="+c+"], area[rel="+c+"]");q=o.index(this)}I()}});return this};b.fancybox=function(a,c){var g;if(!h){h=true;g=typeof c!=="undefined"?c:{};o=[];q=parseInt(g.index,10)||0;if(b.isArray(a)){for(var k=
0,C=a.length;k<C;k++)if(typeof a[k]=="object")b(a[k]).data("fancybox",b.extend({},g,a[k]));else a[k]=b({}).data("fancybox",b.extend({content:a[k]},g));o=jQuery.merge(o,a)}else{if(typeof a=="object")b(a).data("fancybox",b.extend({},g,a));else a=b({}).data("fancybox",b.extend({content:a},g));o.push(a)}if(q>o.length||q<0)q=0;I()}};b.fancybox.showActivity=function(){clearInterval(K);t.show();K=setInterval(Z,66)};b.fancybox.hideActivity=function(){t.hide()};b.fancybox.next=function(){return b.fancybox.pos(p+
1)};b.fancybox.prev=function(){return b.fancybox.pos(p-1)};b.fancybox.pos=function(a){if(!h){a=parseInt(a);o=l;if(a>-1&&a<l.length){q=a;I()}else if(d.cyclic&&l.length>1){q=a>=l.length?0:l.length-1;I()}}};b.fancybox.cancel=function(){if(!h){h=true;b.event.trigger("fancybox-cancel");N();e.onCancel(o,q,e);h=false}};b.fancybox.close=function(){function a(){u.fadeOut("fast");n.empty().hide();f.hide();b.event.trigger("fancybox-cleanup");j.empty();d.onClosed(l,p,d);l=e=[];p=q=0;d=e={};h=false}if(!(h||f.is(":hidden"))){h=
true;if(d&&false===d.onCleanup(l,p,d))h=false;else{N();b(E.add(z).add(A)).hide();b(j.add(u)).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");j.find("iframe").attr("src",M&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank");d.titlePosition!=="inside"&&n.empty();f.stop();if(d.transitionOut=="elastic"){r=V();var c=f.position();i={top:c.top,left:c.left,width:f.width(),height:f.height()};if(d.opacity)i.opacity=1;n.empty().hide();B.prop=1;
b(B).animate({prop:0},{duration:d.speedOut,easing:d.easingOut,step:T,complete:a})}else f.fadeOut(d.transitionOut=="none"?0:d.speedOut,a)}}};b.fancybox.resize=function(){u.is(":visible")&&u.css("height",b(document).height());b.fancybox.center(true)};b.fancybox.center=function(a){var c,g;if(!h){g=a===true?1:0;c=U();!g&&(f.width()>c[0]||f.height()>c[1])||f.stop().animate({top:parseInt(Math.max(c[3]-20,c[3]+(c[1]-j.height()-40)*0.5-d.padding)),left:parseInt(Math.max(c[2]-20,c[2]+(c[0]-j.width()-40)*0.5-
d.padding))},typeof a=="number"?a:200)}};b.fancybox.init=function(){if(!b("#fancybox-wrap").length){b("body").append(m=b('<div id="fancybox-tmp"></div>'),t=b('<div id="fancybox-loading"><div></div></div>'),u=b('<div id="fancybox-overlay"></div>'),f=b('<div id="fancybox-wrap"></div>'));D=b('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(f);
D.append(j=b('<div id="fancybox-content"></div>'),E=b('<a id="fancybox-close"></a>'),n=b('<div id="fancybox-title"></div>'),z=b('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),A=b('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));E.click(b.fancybox.close);t.click(b.fancybox.cancel);z.click(function(a){a.preventDefault();b.fancybox.prev()});A.click(function(a){a.preventDefault();b.fancybox.next()});
b.fn.mousewheel&&f.bind("mousewheel.fb",function(a,c){if(h)a.preventDefault();else if(b(a.target).get(0).clientHeight==0||b(a.target).get(0).scrollHeight===b(a.target).get(0).clientHeight){a.preventDefault();b.fancybox[c>0?"prev":"next"]()}});b.support.opacity||f.addClass("fancybox-ie");if(M){t.addClass("fancybox-ie6");f.addClass("fancybox-ie6");b('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(D)}}};
b.fn.fancybox.defaults={padding:10,margin:40,opacity:false,modal:false,cyclic:false,scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.7,overlayColor:"#777",titleShow:true,titlePosition:"float",titleFormat:null,titleFromAlt:false,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",
easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,enableKeyboardNav:true,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}};b(document).ready(function(){b.fancybox.init()})})(jQuery);;

/** Masonry **/
(window.defineModule = (window.defineModule || {})).name = 'Masonry';
/*!
 * Masonry PACKAGED v4.2.2
 * Cascading grid layout library
 * https://masonry.desandro.com
 * MIT License
 * by David DeSandro
 */

!function(t,e){"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,r,a){function h(t,e,n){var o,r="$()."+i+'("'+e+'")';return t.each(function(t,h){var u=a.data(h,i);if(!u)return void s(i+" not initialized. Cannot call methods, i.e. "+r);var d=u[e];if(!d||"_"==e.charAt(0))return void s(r+" is not a valid method");var l=d.apply(u,n);o=void 0===o?l:o}),void 0!==o?o:t}function u(t,e){t.each(function(t,n){var o=a.data(n,i);o?(o.option(e),o._init()):(o=new r(n,e),a.data(n,i,o))})}a=a||e||t.jQuery,a&&(r.prototype.option||(r.prototype.option=function(t){a.isPlainObject(t)&&(this.options=a.extend(!0,this.options,t))}),a.fn[i]=function(t){if("string"==typeof t){var e=o.call(arguments,1);return h(this,t,e)}return u(this,t),this},n(a))}function n(t){!t||t&&t.bridget||(t.bridget=i)}var o=Array.prototype.slice,r=t.console,s="undefined"==typeof r?function(){}:function(t){r.error(t)};return n(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},n=i[t]=i[t]||[];return-1==n.indexOf(e)&&n.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},n=i[t]=i[t]||{};return n[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=i.indexOf(e);return-1!=n&&i.splice(n,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){i=i.slice(0),e=e||[];for(var n=this._onceEvents&&this._onceEvents[t],o=0;o<i.length;o++){var r=i[o],s=n&&n[r];s&&(this.off(t,r),delete n[r]),r.apply(this,e)}return this}},e.allOff=function(){delete this._events,delete this._onceEvents},t}),function(t,e){"function"==typeof define&&define.amd?define("get-size/get-size",e):"object"==typeof module&&module.exports?module.exports=e():t.getSize=e()}(window,function(){"use strict";function t(t){var e=parseFloat(t),i=-1==t.indexOf("%")&&!isNaN(e);return i&&e}function e(){}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0;u>e;e++){var i=h[e];t[i]=0}return t}function n(t){var e=getComputedStyle(t);return e||a("Style returned "+e+". Are you running this code in a hidden iframe on Firefox? See https://bit.ly/getsizebug1"),e}function o(){if(!d){d=!0;var e=document.createElement("div");e.style.width="200px",e.style.padding="1px 2px 3px 4px",e.style.borderStyle="solid",e.style.borderWidth="1px 2px 3px 4px",e.style.boxSizing="border-box";var i=document.body||document.documentElement;i.appendChild(e);var o=n(e);s=200==Math.round(t(o.width)),r.isBoxSizeOuter=s,i.removeChild(e)}}function r(e){if(o(),"string"==typeof e&&(e=document.querySelector(e)),e&&"object"==typeof e&&e.nodeType){var r=n(e);if("none"==r.display)return i();var a={};a.width=e.offsetWidth,a.height=e.offsetHeight;for(var d=a.isBorderBox="border-box"==r.boxSizing,l=0;u>l;l++){var c=h[l],f=r[c],m=parseFloat(f);a[c]=isNaN(m)?0:m}var p=a.paddingLeft+a.paddingRight,g=a.paddingTop+a.paddingBottom,y=a.marginLeft+a.marginRight,v=a.marginTop+a.marginBottom,_=a.borderLeftWidth+a.borderRightWidth,z=a.borderTopWidth+a.borderBottomWidth,E=d&&s,b=t(r.width);b!==!1&&(a.width=b+(E?0:p+_));var x=t(r.height);return x!==!1&&(a.height=x+(E?0:g+z)),a.innerWidth=a.width-(p+_),a.innerHeight=a.height-(g+z),a.outerWidth=a.width+y,a.outerHeight=a.height+v,a}}var s,a="undefined"==typeof console?e:function(t){console.error(t)},h=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"],u=h.length,d=!1;return r}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("desandro-matches-selector/matches-selector",e):"object"==typeof module&&module.exports?module.exports=e():t.matchesSelector=e()}(window,function(){"use strict";var t=function(){var t=window.Element.prototype;if(t.matches)return"matches";if(t.matchesSelector)return"matchesSelector";for(var e=["webkit","moz","ms","o"],i=0;i<e.length;i++){var n=e[i],o=n+"MatchesSelector";if(t[o])return o}}();return function(e,i){return e[t](i)}}),function(t,e){"function"==typeof define&&define.amd?define("fizzy-ui-utils/utils",["desandro-matches-selector/matches-selector"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("desandro-matches-selector")):t.fizzyUIUtils=e(t,t.matchesSelector)}(window,function(t,e){var i={};i.extend=function(t,e){for(var i in e)t[i]=e[i];return t},i.modulo=function(t,e){return(t%e+e)%e};var n=Array.prototype.slice;i.makeArray=function(t){if(Array.isArray(t))return t;if(null===t||void 0===t)return[];var e="object"==typeof t&&"number"==typeof t.length;return e?n.call(t):[t]},i.removeFrom=function(t,e){var i=t.indexOf(e);-1!=i&&t.splice(i,1)},i.getParent=function(t,i){for(;t.parentNode&&t!=document.body;)if(t=t.parentNode,e(t,i))return t},i.getQueryElement=function(t){return"string"==typeof t?document.querySelector(t):t},i.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},i.filterFindElements=function(t,n){t=i.makeArray(t);var o=[];return t.forEach(function(t){if(t instanceof HTMLElement){if(!n)return void o.push(t);e(t,n)&&o.push(t);for(var i=t.querySelectorAll(n),r=0;r<i.length;r++)o.push(i[r])}}),o},i.debounceMethod=function(t,e,i){i=i||100;var n=t.prototype[e],o=e+"Timeout";t.prototype[e]=function(){var t=this[o];clearTimeout(t);var e=arguments,r=this;this[o]=setTimeout(function(){n.apply(r,e),delete r[o]},i)}},i.docReady=function(t){var e=document.readyState;"complete"==e||"interactive"==e?setTimeout(t):document.addEventListener("DOMContentLoaded",t)},i.toDashed=function(t){return t.replace(/(.)([A-Z])/g,function(t,e,i){return e+"-"+i}).toLowerCase()};var o=t.console;return i.htmlInit=function(e,n){i.docReady(function(){var r=i.toDashed(n),s="data-"+r,a=document.querySelectorAll("["+s+"]"),h=document.querySelectorAll(".js-"+r),u=i.makeArray(a).concat(i.makeArray(h)),d=s+"-options",l=t.jQuery;u.forEach(function(t){var i,r=t.getAttribute(s)||t.getAttribute(d);try{i=r&&JSON.parse(r)}catch(a){return void(o&&o.error("Error parsing "+s+" on "+t.className+": "+a))}var h=new e(t,i);l&&l.data(t,n,h)})})},i}),function(t,e){"function"==typeof define&&define.amd?define("outlayer/item",["ev-emitter/ev-emitter","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("ev-emitter"),require("get-size")):(t.Outlayer={},t.Outlayer.Item=e(t.EvEmitter,t.getSize))}(window,function(t,e){"use strict";function i(t){for(var e in t)return!1;return e=null,!0}function n(t,e){t&&(this.element=t,this.layout=e,this.position={x:0,y:0},this._create())}function o(t){return t.replace(/([A-Z])/g,function(t){return"-"+t.toLowerCase()})}var r=document.documentElement.style,s="string"==typeof r.transition?"transition":"WebkitTransition",a="string"==typeof r.transform?"transform":"WebkitTransform",h={WebkitTransition:"webkitTransitionEnd",transition:"transitionend"}[s],u={transform:a,transition:s,transitionDuration:s+"Duration",transitionProperty:s+"Property",transitionDelay:s+"Delay"},d=n.prototype=Object.create(t.prototype);d.constructor=n,d._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},d.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},d.getSize=function(){this.size=e(this.element)},d.css=function(t){var e=this.element.style;for(var i in t){var n=u[i]||i;e[n]=t[i]}},d.getPosition=function(){var t=getComputedStyle(this.element),e=this.layout._getOption("originLeft"),i=this.layout._getOption("originTop"),n=t[e?"left":"right"],o=t[i?"top":"bottom"],r=parseFloat(n),s=parseFloat(o),a=this.layout.size;-1!=n.indexOf("%")&&(r=r/100*a.width),-1!=o.indexOf("%")&&(s=s/100*a.height),r=isNaN(r)?0:r,s=isNaN(s)?0:s,r-=e?a.paddingLeft:a.paddingRight,s-=i?a.paddingTop:a.paddingBottom,this.position.x=r,this.position.y=s},d.layoutPosition=function(){var t=this.layout.size,e={},i=this.layout._getOption("originLeft"),n=this.layout._getOption("originTop"),o=i?"paddingLeft":"paddingRight",r=i?"left":"right",s=i?"right":"left",a=this.position.x+t[o];e[r]=this.getXValue(a),e[s]="";var h=n?"paddingTop":"paddingBottom",u=n?"top":"bottom",d=n?"bottom":"top",l=this.position.y+t[h];e[u]=this.getYValue(l),e[d]="",this.css(e),this.emitEvent("layout",[this])},d.getXValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&!e?t/this.layout.size.width*100+"%":t+"px"},d.getYValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&e?t/this.layout.size.height*100+"%":t+"px"},d._transitionTo=function(t,e){this.getPosition();var i=this.position.x,n=this.position.y,o=t==this.position.x&&e==this.position.y;if(this.setPosition(t,e),o&&!this.isTransitioning)return void this.layoutPosition();var r=t-i,s=e-n,a={};a.transform=this.getTranslate(r,s),this.transition({to:a,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},d.getTranslate=function(t,e){var i=this.layout._getOption("originLeft"),n=this.layout._getOption("originTop");return t=i?t:-t,e=n?e:-e,"translate3d("+t+"px, "+e+"px, 0)"},d.goTo=function(t,e){this.setPosition(t,e),this.layoutPosition()},d.moveTo=d._transitionTo,d.setPosition=function(t,e){this.position.x=parseFloat(t),this.position.y=parseFloat(e)},d._nonTransition=function(t){this.css(t.to),t.isCleaning&&this._removeStyles(t.to);for(var e in t.onTransitionEnd)t.onTransitionEnd[e].call(this)},d.transition=function(t){if(!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(t);var e=this._transn;for(var i in t.onTransitionEnd)e.onEnd[i]=t.onTransitionEnd[i];for(i in t.to)e.ingProperties[i]=!0,t.isCleaning&&(e.clean[i]=!0);if(t.from){this.css(t.from);var n=this.element.offsetHeight;n=null}this.enableTransition(t.to),this.css(t.to),this.isTransitioning=!0};var l="opacity,"+o(a);d.enableTransition=function(){if(!this.isTransitioning){var t=this.layout.options.transitionDuration;t="number"==typeof t?t+"ms":t,this.css({transitionProperty:l,transitionDuration:t,transitionDelay:this.staggerDelay||0}),this.element.addEventListener(h,this,!1)}},d.onwebkitTransitionEnd=function(t){this.ontransitionend(t)},d.onotransitionend=function(t){this.ontransitionend(t)};var c={"-webkit-transform":"transform"};d.ontransitionend=function(t){if(t.target===this.element){var e=this._transn,n=c[t.propertyName]||t.propertyName;if(delete e.ingProperties[n],i(e.ingProperties)&&this.disableTransition(),n in e.clean&&(this.element.style[t.propertyName]="",delete e.clean[n]),n in e.onEnd){var o=e.onEnd[n];o.call(this),delete e.onEnd[n]}this.emitEvent("transitionEnd",[this])}},d.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(h,this,!1),this.isTransitioning=!1},d._removeStyles=function(t){var e={};for(var i in t)e[i]="";this.css(e)};var f={transitionProperty:"",transitionDuration:"",transitionDelay:""};return d.removeTransitionStyles=function(){this.css(f)},d.stagger=function(t){t=isNaN(t)?0:t,this.staggerDelay=t+"ms"},d.removeElem=function(){this.element.parentNode.removeChild(this.element),this.css({display:""}),this.emitEvent("remove",[this])},d.remove=function(){return s&&parseFloat(this.layout.options.transitionDuration)?(this.once("transitionEnd",function(){this.removeElem()}),void this.hide()):void this.removeElem()},d.reveal=function(){delete this.isHidden,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("visibleStyle");e[i]=this.onRevealTransitionEnd,this.transition({from:t.hiddenStyle,to:t.visibleStyle,isCleaning:!0,onTransitionEnd:e})},d.onRevealTransitionEnd=function(){this.isHidden||this.emitEvent("reveal")},d.getHideRevealTransitionEndProperty=function(t){var e=this.layout.options[t];if(e.opacity)return"opacity";for(var i in e)return i},d.hide=function(){this.isHidden=!0,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("hiddenStyle");e[i]=this.onHideTransitionEnd,this.transition({from:t.visibleStyle,to:t.hiddenStyle,isCleaning:!0,onTransitionEnd:e})},d.onHideTransitionEnd=function(){this.isHidden&&(this.css({display:"none"}),this.emitEvent("hide"))},d.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},n}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("outlayer/outlayer",["ev-emitter/ev-emitter","get-size/get-size","fizzy-ui-utils/utils","./item"],function(i,n,o,r){return e(t,i,n,o,r)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter"),require("get-size"),require("fizzy-ui-utils"),require("./item")):t.Outlayer=e(t,t.EvEmitter,t.getSize,t.fizzyUIUtils,t.Outlayer.Item)}(window,function(t,e,i,n,o){"use strict";function r(t,e){var i=n.getQueryElement(t);if(!i)return void(h&&h.error("Bad element for "+this.constructor.namespace+": "+(i||t)));this.element=i,u&&(this.$element=u(this.element)),this.options=n.extend({},this.constructor.defaults),this.option(e);var o=++l;this.element.outlayerGUID=o,c[o]=this,this._create();var r=this._getOption("initLayout");r&&this.layout()}function s(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e}function a(t){if("number"==typeof t)return t;var e=t.match(/(^\d*\.?\d*)(\w*)/),i=e&&e[1],n=e&&e[2];if(!i.length)return 0;i=parseFloat(i);var o=m[n]||1;return i*o}var h=t.console,u=t.jQuery,d=function(){},l=0,c={};r.namespace="outlayer",r.Item=o,r.defaults={containerStyle:{position:"relative"},initLayout:!0,originLeft:!0,originTop:!0,resize:!0,resizeContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}};var f=r.prototype;n.extend(f,e.prototype),f.option=function(t){n.extend(this.options,t)},f._getOption=function(t){var e=this.constructor.compatOptions[t];return e&&void 0!==this.options[e]?this.options[e]:this.options[t]},r.compatOptions={initLayout:"isInitLayout",horizontal:"isHorizontal",layoutInstant:"isLayoutInstant",originLeft:"isOriginLeft",originTop:"isOriginTop",resize:"isResizeBound",resizeContainer:"isResizingContainer"},f._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),n.extend(this.element.style,this.options.containerStyle);var t=this._getOption("resize");t&&this.bindResize()},f.reloadItems=function(){this.items=this._itemize(this.element.children)},f._itemize=function(t){for(var e=this._filterFindItemElements(t),i=this.constructor.Item,n=[],o=0;o<e.length;o++){var r=e[o],s=new i(r,this);n.push(s)}return n},f._filterFindItemElements=function(t){return n.filterFindElements(t,this.options.itemSelector)},f.getItemElements=function(){return this.items.map(function(t){return t.element})},f.layout=function(){this._resetLayout(),this._manageStamps();var t=this._getOption("layoutInstant"),e=void 0!==t?t:!this._isLayoutInited;this.layoutItems(this.items,e),this._isLayoutInited=!0},f._init=f.layout,f._resetLayout=function(){this.getSize()},f.getSize=function(){this.size=i(this.element)},f._getMeasurement=function(t,e){var n,o=this.options[t];o?("string"==typeof o?n=this.element.querySelector(o):o instanceof HTMLElement&&(n=o),this[t]=n?i(n)[e]:o):this[t]=0},f.layoutItems=function(t,e){t=this._getItemsForLayout(t),this._layoutItems(t,e),this._postLayout()},f._getItemsForLayout=function(t){return t.filter(function(t){return!t.isIgnored})},f._layoutItems=function(t,e){if(this._emitCompleteOnItems("layout",t),t&&t.length){var i=[];t.forEach(function(t){var n=this._getItemLayoutPosition(t);n.item=t,n.isInstant=e||t.isLayoutInstant,i.push(n)},this),this._processLayoutQueue(i)}},f._getItemLayoutPosition=function(){return{x:0,y:0}},f._processLayoutQueue=function(t){this.updateStagger(),t.forEach(function(t,e){this._positionItem(t.item,t.x,t.y,t.isInstant,e)},this)},f.updateStagger=function(){var t=this.options.stagger;return null===t||void 0===t?void(this.stagger=0):(this.stagger=a(t),this.stagger)},f._positionItem=function(t,e,i,n,o){n?t.goTo(e,i):(t.stagger(o*this.stagger),t.moveTo(e,i))},f._postLayout=function(){this.resizeContainer()},f.resizeContainer=function(){var t=this._getOption("resizeContainer");if(t){var e=this._getContainerSize();e&&(this._setContainerMeasure(e.width,!0),this._setContainerMeasure(e.height,!1))}},f._getContainerSize=d,f._setContainerMeasure=function(t,e){if(void 0!==t){var i=this.size;i.isBorderBox&&(t+=e?i.paddingLeft+i.paddingRight+i.borderLeftWidth+i.borderRightWidth:i.paddingBottom+i.paddingTop+i.borderTopWidth+i.borderBottomWidth),t=Math.max(t,0),this.element.style[e?"width":"height"]=t+"px"}},f._emitCompleteOnItems=function(t,e){function i(){o.dispatchEvent(t+"Complete",null,[e])}function n(){s++,s==r&&i()}var o=this,r=e.length;if(!e||!r)return void i();var s=0;e.forEach(function(e){e.once(t,n)})},f.dispatchEvent=function(t,e,i){var n=e?[e].concat(i):i;if(this.emitEvent(t,n),u)if(this.$element=this.$element||u(this.element),e){var o=u.Event(e);o.type=t,this.$element.trigger(o,i)}else this.$element.trigger(t,i)},f.ignore=function(t){var e=this.getItem(t);e&&(e.isIgnored=!0)},f.unignore=function(t){var e=this.getItem(t);e&&delete e.isIgnored},f.stamp=function(t){t=this._find(t),t&&(this.stamps=this.stamps.concat(t),t.forEach(this.ignore,this))},f.unstamp=function(t){t=this._find(t),t&&t.forEach(function(t){n.removeFrom(this.stamps,t),this.unignore(t)},this)},f._find=function(t){return t?("string"==typeof t&&(t=this.element.querySelectorAll(t)),t=n.makeArray(t)):void 0},f._manageStamps=function(){this.stamps&&this.stamps.length&&(this._getBoundingRect(),this.stamps.forEach(this._manageStamp,this))},f._getBoundingRect=function(){var t=this.element.getBoundingClientRect(),e=this.size;this._boundingRect={left:t.left+e.paddingLeft+e.borderLeftWidth,top:t.top+e.paddingTop+e.borderTopWidth,right:t.right-(e.paddingRight+e.borderRightWidth),bottom:t.bottom-(e.paddingBottom+e.borderBottomWidth)}},f._manageStamp=d,f._getElementOffset=function(t){var e=t.getBoundingClientRect(),n=this._boundingRect,o=i(t),r={left:e.left-n.left-o.marginLeft,top:e.top-n.top-o.marginTop,right:n.right-e.right-o.marginRight,bottom:n.bottom-e.bottom-o.marginBottom};return r},f.handleEvent=n.handleEvent,f.bindResize=function(){t.addEventListener("resize",this),this.isResizeBound=!0},f.unbindResize=function(){t.removeEventListener("resize",this),this.isResizeBound=!1},f.onresize=function(){this.resize()},n.debounceMethod(r,"onresize",100),f.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},f.needsResizeLayout=function(){var t=i(this.element),e=this.size&&t;return e&&t.innerWidth!==this.size.innerWidth},f.addItems=function(t){var e=this._itemize(t);return e.length&&(this.items=this.items.concat(e)),e},f.appended=function(t){var e=this.addItems(t);e.length&&(this.layoutItems(e,!0),this.reveal(e))},f.prepended=function(t){var e=this._itemize(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._resetLayout(),this._manageStamps(),this.layoutItems(e,!0),this.reveal(e),this.layoutItems(i)}},f.reveal=function(t){if(this._emitCompleteOnItems("reveal",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.reveal()})}},f.hide=function(t){if(this._emitCompleteOnItems("hide",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.hide()})}},f.revealItemElements=function(t){var e=this.getItems(t);this.reveal(e)},f.hideItemElements=function(t){var e=this.getItems(t);this.hide(e)},f.getItem=function(t){for(var e=0;e<this.items.length;e++){var i=this.items[e];if(i.element==t)return i}},f.getItems=function(t){t=n.makeArray(t);var e=[];return t.forEach(function(t){var i=this.getItem(t);i&&e.push(i)},this),e},f.remove=function(t){var e=this.getItems(t);this._emitCompleteOnItems("remove",e),e&&e.length&&e.forEach(function(t){t.remove(),n.removeFrom(this.items,t)},this)},f.destroy=function(){var t=this.element.style;t.height="",t.position="",t.width="",this.items.forEach(function(t){t.destroy()}),this.unbindResize();var e=this.element.outlayerGUID;delete c[e],delete this.element.outlayerGUID,u&&u.removeData(this.element,this.constructor.namespace)},r.data=function(t){t=n.getQueryElement(t);var e=t&&t.outlayerGUID;return e&&c[e]},r.create=function(t,e){var i=s(r);return i.defaults=n.extend({},r.defaults),n.extend(i.defaults,e),i.compatOptions=n.extend({},r.compatOptions),i.namespace=t,i.data=r.data,i.Item=s(o),n.htmlInit(i,t),u&&u.bridget&&u.bridget(t,i),i};var m={ms:1,s:1e3};return r.Item=o,r}),function(t,e){"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("outlayer"),require("get-size")):t.Masonry=e(t.Outlayer,t.getSize)}(window,function(t,e){var i=t.create("masonry");i.compatOptions.fitWidth="isFitWidth";var n=i.prototype;return n._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns(),this.colYs=[];for(var t=0;t<this.cols;t++)this.colYs.push(0);this.maxY=0,this.horizontalColIndex=0},n.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var t=this.items[0],i=t&&t.element;this.columnWidth=i&&e(i).outerWidth||this.containerWidth}var n=this.columnWidth+=this.gutter,o=this.containerWidth+this.gutter,r=o/n,s=n-o%n,a=s&&1>s?"round":"floor";r=Math[a](r),this.cols=Math.max(r,1)},n.getContainerWidth=function(){var t=this._getOption("fitWidth"),i=t?this.element.parentNode:this.element,n=e(i);this.containerWidth=n&&n.innerWidth},n._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth%this.columnWidth,i=e&&1>e?"round":"ceil",n=Math[i](t.size.outerWidth/this.columnWidth);n=Math.min(n,this.cols);for(var o=this.options.horizontalOrder?"_getHorizontalColPosition":"_getTopColPosition",r=this[o](n,t),s={x:this.columnWidth*r.col,y:r.y},a=r.y+t.size.outerHeight,h=n+r.col,u=r.col;h>u;u++)this.colYs[u]=a;return s},n._getTopColPosition=function(t){var e=this._getTopColGroup(t),i=Math.min.apply(Math,e);return{col:e.indexOf(i),y:i}},n._getTopColGroup=function(t){if(2>t)return this.colYs;for(var e=[],i=this.cols+1-t,n=0;i>n;n++)e[n]=this._getColGroupY(n,t);return e},n._getColGroupY=function(t,e){if(2>e)return this.colYs[t];var i=this.colYs.slice(t,t+e);return Math.max.apply(Math,i)},n._getHorizontalColPosition=function(t,e){var i=this.horizontalColIndex%this.cols,n=t>1&&i+t>this.cols;i=n?0:i;var o=e.size.outerWidth&&e.size.outerHeight;return this.horizontalColIndex=o?i+t:this.horizontalColIndex,{col:i,y:this._getColGroupY(i,t)}},n._manageStamp=function(t){var i=e(t),n=this._getElementOffset(t),o=this._getOption("originLeft"),r=o?n.left:n.right,s=r+i.outerWidth,a=Math.floor(r/this.columnWidth);a=Math.max(0,a);var h=Math.floor(s/this.columnWidth);h-=s%this.columnWidth?0:1,h=Math.min(this.cols-1,h);for(var u=this._getOption("originTop"),d=(u?n.top:n.bottom)+i.outerHeight,l=a;h>=l;l++)this.colYs[l]=Math.max(d,this.colYs[l])},n._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var t={height:this.maxY};return this._getOption("fitWidth")&&(t.width=this._getContainerFitWidth()),t},n._getContainerFitWidth=function(){for(var t=0,e=this.cols;--e&&0===this.colYs[e];)t++;return(this.cols-t)*this.columnWidth-this.gutter},n.needsResizeLayout=function(){var t=this.containerWidth;return this.getContainerWidth(),t!=this.containerWidth},i});;

/** JavaScript Load Image **/
(window.defineModule = (window.defineModule || {})).name = 'JavaScript Load Image';
!function(e){"use strict";function t(e,i,a){var o,r=document.createElement("img");if(r.onerror=function(o){return t.onerror(r,o,e,i,a)},r.onload=function(o){return t.onload(r,o,e,i,a)},t.isInstanceOf("Blob",e)||t.isInstanceOf("File",e))o=r._objectURL=t.createObjectURL(e);else{if("string"!=typeof e)return!1;o=e,a&&a.crossOrigin&&(r.crossOrigin=a.crossOrigin)}return o?(r.src=o,r):t.readFile(e,function(e){var t=e.target;t&&t.result?r.src=t.result:i&&i(e)})}function i(e,i){!e._objectURL||i&&i.noRevoke||(t.revokeObjectURL(e._objectURL),delete e._objectURL)}var a=window.createObjectURL&&window||window.URL&&URL.revokeObjectURL&&URL||window.webkitURL&&webkitURL;t.isInstanceOf=function(e,t){return Object.prototype.toString.call(t)==="[object "+e+"]"},t.transform=function(e,i,a,o,r){a(t.scale(e,i,r),r)},t.onerror=function(e,t,a,o,r){i(e,r),o&&o.call(e,t)},t.onload=function(e,a,o,r,n){i(e,n),r&&t.transform(e,n,r,o,{})},t.transformCoordinates=function(){},t.getTransformedOptions=function(e,t){var i,a,o,r,n=t.aspectRatio;if(!n)return t;i={};for(a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);return i.crop=!0,o=e.naturalWidth||e.width,r=e.naturalHeight||e.height,o/r>n?(i.maxWidth=r*n,i.maxHeight=r):(i.maxWidth=o,i.maxHeight=o/n),i},t.renderImageToCanvas=function(e,t,i,a,o,r,n,s,l,d){return e.getContext("2d").drawImage(t,i,a,o,r,n,s,l,d),e},t.hasCanvasOption=function(e){return e.canvas||e.crop||!!e.aspectRatio},t.scale=function(e,i,a){function o(){var e=Math.max((l||v)/v,(d||P)/P);e>1&&(v*=e,P*=e)}function r(){var e=Math.min((n||v)/v,(s||P)/P);e<1&&(v*=e,P*=e)}i=i||{};var n,s,l,d,u,c,f,g,h,m,p,S=document.createElement("canvas"),b=e.getContext||t.hasCanvasOption(i)&&S.getContext,x=e.naturalWidth||e.width,y=e.naturalHeight||e.height,v=x,P=y;if(b&&(i=t.getTransformedOptions(e,i,a),f=i.left||0,g=i.top||0,i.sourceWidth?(u=i.sourceWidth,void 0!==i.right&&void 0===i.left&&(f=x-u-i.right)):u=x-f-(i.right||0),i.sourceHeight?(c=i.sourceHeight,void 0!==i.bottom&&void 0===i.top&&(g=y-c-i.bottom)):c=y-g-(i.bottom||0),v=u,P=c),n=i.maxWidth,s=i.maxHeight,l=i.minWidth,d=i.minHeight,b&&n&&s&&i.crop?(v=n,P=s,p=u/c-n/s,p<0?(c=s*u/n,void 0===i.top&&void 0===i.bottom&&(g=(y-c)/2)):p>0&&(u=n*c/s,void 0===i.left&&void 0===i.right&&(f=(x-u)/2))):((i.contain||i.cover)&&(l=n=n||l,d=s=s||d),i.cover?(r(),o()):(o(),r())),b){if(h=i.pixelRatio,h>1&&(S.style.width=v+"px",S.style.height=P+"px",v*=h,P*=h,S.getContext("2d").scale(h,h)),m=i.downsamplingRatio,m>0&&m<1&&v<u&&P<c)for(;u*m>v;)S.width=u*m,S.height=c*m,t.renderImageToCanvas(S,e,f,g,u,c,0,0,S.width,S.height),f=0,g=0,u=S.width,c=S.height,e=document.createElement("canvas"),e.width=u,e.height=c,t.renderImageToCanvas(e,S,0,0,u,c,0,0,u,c);return S.width=v,S.height=P,t.transformCoordinates(S,i),t.renderImageToCanvas(S,e,f,g,u,c,0,0,v,P)}return e.width=v,e.height=P,e},t.createObjectURL=function(e){return!!a&&a.createObjectURL(e)},t.revokeObjectURL=function(e){return!!a&&a.revokeObjectURL(e)},t.readFile=function(e,t,i){if(window.FileReader){var a=new FileReader;if(a.onload=a.onerror=t,i=i||"readAsDataURL",a[i])return a[i](e),a}return!1},"function"==typeof define&&define.amd?define(function(){return t}):"object"==typeof module&&module.exports?module.exports=t:e.loadImage=t}(window),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image"],e):e("object"==typeof module&&module.exports?require("./load-image"):window.loadImage)}(function(e){"use strict";var t=window.Blob&&(Blob.prototype.slice||Blob.prototype.webkitSlice||Blob.prototype.mozSlice);e.blobSlice=t&&function(){var e=this.slice||this.webkitSlice||this.mozSlice;return e.apply(this,arguments)},e.metaDataParsers={jpeg:{65505:[]}},e.parseMetaData=function(t,i,a,o){a=a||{},o=o||{};var r=this,n=a.maxMetaDataSize||262144,s=!(window.DataView&&t&&t.size>=12&&"image/jpeg"===t.type&&e.blobSlice);!s&&e.readFile(e.blobSlice.call(t,0,n),function(t){if(t.target.error)return console.log(t.target.error),void i(o);var n,s,l,d,u=t.target.result,c=new DataView(u),f=2,g=c.byteLength-4,h=f;if(65496===c.getUint16(0)){for(;f<g&&(n=c.getUint16(f),n>=65504&&n<=65519||65534===n);){if(s=c.getUint16(f+2)+2,f+s>c.byteLength){console.log("Invalid meta data: Invalid segment size.");break}if(l=e.metaDataParsers.jpeg[n])for(d=0;d<l.length;d+=1)l[d].call(r,c,f,s,o,a);f+=s,h=f}!a.disableImageHead&&h>6&&(u.slice?o.imageHead=u.slice(0,h):o.imageHead=new Uint8Array(u).subarray(0,h))}else console.log("Invalid JPEG file: Missing JPEG marker.");i(o)},"readAsArrayBuffer")||i(o)},e.hasMetaOption=function(e){return e.meta};var i=e.transform;e.transform=function(t,a,o,r,n){e.hasMetaOption(a||{})?e.parseMetaData(r,function(n){i.call(e,t,a,o,r,n)},a,n):i.apply(e,arguments)}}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-meta"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-meta")):e(window.loadImage)}(function(e){"use strict";e.ExifMap=function(){return this},e.ExifMap.prototype.map={Orientation:274},e.ExifMap.prototype.get=function(e){return this[e]||this[this.map[e]]},e.getExifThumbnail=function(e,t,i){var a,o,r;if(!i||t+i>e.byteLength)return void console.log("Invalid Exif data: Invalid thumbnail data.");for(a=[],o=0;o<i;o+=1)r=e.getUint8(t+o),a.push((r<16?"0":"")+r.toString(16));return"data:image/jpeg,%"+a.join("%")},e.exifTagTypes={1:{getValue:function(e,t){return e.getUint8(t)},size:1},2:{getValue:function(e,t){return String.fromCharCode(e.getUint8(t))},size:1,ascii:!0},3:{getValue:function(e,t,i){return e.getUint16(t,i)},size:2},4:{getValue:function(e,t,i){return e.getUint32(t,i)},size:4},5:{getValue:function(e,t,i){return e.getUint32(t,i)/e.getUint32(t+4,i)},size:8},9:{getValue:function(e,t,i){return e.getInt32(t,i)},size:4},10:{getValue:function(e,t,i){return e.getInt32(t,i)/e.getInt32(t+4,i)},size:8}},e.exifTagTypes[7]=e.exifTagTypes[1],e.getExifValue=function(t,i,a,o,r,n){var s,l,d,u,c,f,g=e.exifTagTypes[o];if(!g)return void console.log("Invalid Exif data: Invalid tag type.");if(s=g.size*r,l=s>4?i+t.getUint32(a+8,n):a+8,l+s>t.byteLength)return void console.log("Invalid Exif data: Invalid data offset.");if(1===r)return g.getValue(t,l,n);for(d=[],u=0;u<r;u+=1)d[u]=g.getValue(t,l+u*g.size,n);if(g.ascii){for(c="",u=0;u<d.length&&(f=d[u],"\0"!==f);u+=1)c+=f;return c}return d},e.parseExifTag=function(t,i,a,o,r){var n=t.getUint16(a,o);r.exif[n]=e.getExifValue(t,i,a,t.getUint16(a+2,o),t.getUint32(a+4,o),o)},e.parseExifTags=function(e,t,i,a,o){var r,n,s;if(i+6>e.byteLength)return void console.log("Invalid Exif data: Invalid directory offset.");if(r=e.getUint16(i,a),n=i+2+12*r,n+4>e.byteLength)return void console.log("Invalid Exif data: Invalid directory size.");for(s=0;s<r;s+=1)this.parseExifTag(e,t,i+2+12*s,a,o);return e.getUint32(n,a)},e.parseExifData=function(t,i,a,o,r){if(!r.disableExif){var n,s,l,d=i+10;if(1165519206===t.getUint32(i+4)){if(d+8>t.byteLength)return void console.log("Invalid Exif data: Invalid segment size.");if(0!==t.getUint16(i+8))return void console.log("Invalid Exif data: Missing byte alignment offset.");switch(t.getUint16(d)){case 18761:n=!0;break;case 19789:n=!1;break;default:return void console.log("Invalid Exif data: Invalid byte alignment marker.")}if(42!==t.getUint16(d+2,n))return void console.log("Invalid Exif data: Missing TIFF marker.");s=t.getUint32(d+4,n),o.exif=new e.ExifMap,s=e.parseExifTags(t,d,d+s,n,o),s&&!r.disableExifThumbnail&&(l={exif:{}},s=e.parseExifTags(t,d,d+s,n,l),l.exif[513]&&(o.exif.Thumbnail=e.getExifThumbnail(t,d+l.exif[513],l.exif[514]))),o.exif[34665]&&!r.disableExifSub&&e.parseExifTags(t,d,d+o.exif[34665],n,o),o.exif[34853]&&!r.disableExifGps&&e.parseExifTags(t,d,d+o.exif[34853],n,o)}}},e.metaDataParsers.jpeg[65505].push(e.parseExifData)}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-exif"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-exif")):e(window.loadImage)}(function(e){"use strict";e.ExifMap.prototype.tags={256:"ImageWidth",257:"ImageHeight",34665:"ExifIFDPointer",34853:"GPSInfoIFDPointer",40965:"InteroperabilityIFDPointer",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",274:"Orientation",277:"SamplesPerPixel",284:"PlanarConfiguration",530:"YCbCrSubSampling",531:"YCbCrPositioning",282:"XResolution",283:"YResolution",296:"ResolutionUnit",273:"StripOffsets",278:"RowsPerStrip",279:"StripByteCounts",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",301:"TransferFunction",318:"WhitePoint",319:"PrimaryChromaticities",529:"YCbCrCoefficients",532:"ReferenceBlackWhite",306:"DateTime",270:"ImageDescription",271:"Make",272:"Model",305:"Software",315:"Artist",33432:"Copyright",36864:"ExifVersion",40960:"FlashpixVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",42240:"Gamma",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37500:"MakerNote",37510:"UserComment",40964:"RelatedSoundFile",36867:"DateTimeOriginal",36868:"DateTimeDigitized",37520:"SubSecTime",37521:"SubSecTimeOriginal",37522:"SubSecTimeDigitized",33434:"ExposureTime",33437:"FNumber",34850:"ExposureProgram",34852:"SpectralSensitivity",34855:"PhotographicSensitivity",34856:"OECF",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureBias",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37396:"SubjectArea",37386:"FocalLength",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41492:"SubjectLocation",41493:"ExposureIndex",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFilm",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"CameraOwnerName",42033:"BodySerialNumber",42034:"LensSpecification",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber",0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"},e.ExifMap.prototype.stringValues={ExposureProgram:{0:"Undefined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"},SensingMethod:{1:"Undefined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},SceneType:{1:"Directly photographed"},CustomRendered:{0:"Normal process",1:"Custom process"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},GainControl:{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},SubjectDistanceRange:{0:"Unknown",1:"Macro",2:"Close view",3:"Distant view"},FileSource:{3:"DSC"},ComponentsConfiguration:{0:"",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"},Orientation:{1:"top-left",2:"top-right",3:"bottom-right",4:"bottom-left",5:"left-top",6:"right-top",7:"right-bottom",8:"left-bottom"}},e.ExifMap.prototype.getText=function(e){var t=this.get(e);switch(e){case"LightSource":case"Flash":case"MeteringMode":case"ExposureProgram":case"SensingMethod":case"SceneCaptureType":case"SceneType":case"CustomRendered":case"WhiteBalance":case"GainControl":case"Contrast":case"Saturation":case"Sharpness":case"SubjectDistanceRange":case"FileSource":case"Orientation":return this.stringValues[e][t];case"ExifVersion":case"FlashpixVersion":if(!t)return;return String.fromCharCode(t[0],t[1],t[2],t[3]);case"ComponentsConfiguration":if(!t)return;return this.stringValues[e][t[0]]+this.stringValues[e][t[1]]+this.stringValues[e][t[2]]+this.stringValues[e][t[3]];case"GPSVersionID":if(!t)return;return t[0]+"."+t[1]+"."+t[2]+"."+t[3]}return String(t)},function(e){var t,i=e.tags,a=e.map;for(t in i)i.hasOwnProperty(t)&&(a[i[t]]=t)}(e.ExifMap.prototype),e.ExifMap.prototype.getAll=function(){var e,t,i={};for(e in this)this.hasOwnProperty(e)&&(t=this.tags[e],t&&(i[t]=this.getText(t)));return i}}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image"],e):e("object"==typeof module&&module.exports?require("./load-image"):window.loadImage)}(function(e){"use strict";var t=e.hasCanvasOption,i=e.hasMetaOption,a=e.transformCoordinates,o=e.getTransformedOptions;e.hasCanvasOption=function(i){return!!i.orientation||t.call(e,i)},e.hasMetaOption=function(t){return t.orientation===!0||i.call(e,t)},e.transformCoordinates=function(t,i){a.call(e,t,i);var o=t.getContext("2d"),r=t.width,n=t.height,s=t.style.width,l=t.style.height,d=i.orientation;if(d&&!(d>8))switch(d>4&&(t.width=n,t.height=r,t.style.width=l,t.style.height=s),d){case 2:o.translate(r,0),o.scale(-1,1);break;case 3:o.translate(r,n),o.rotate(Math.PI);break;case 4:o.translate(0,n),o.scale(1,-1);break;case 5:o.rotate(.5*Math.PI),o.scale(1,-1);break;case 6:o.rotate(.5*Math.PI),o.translate(0,-n);break;case 7:o.rotate(.5*Math.PI),o.translate(r,-n),o.scale(-1,1);break;case 8:o.rotate(-.5*Math.PI),o.translate(-r,0)}},e.getTransformedOptions=function(t,i,a){var r,n,s=o.call(e,t,i),l=s.orientation;if(l===!0&&a&&a.exif&&(l=a.exif.get("Orientation")),!l||l>8||1===l)return s;r={};for(n in s)s.hasOwnProperty(n)&&(r[n]=s[n]);switch(r.orientation=l,l){case 2:r.left=s.right,r.right=s.left;break;case 3:r.left=s.right,r.top=s.bottom,r.right=s.left,r.bottom=s.top;break;case 4:r.top=s.bottom,r.bottom=s.top;break;case 5:r.left=s.top,r.top=s.left,r.right=s.bottom,r.bottom=s.right;break;case 6:r.left=s.top,r.top=s.right,r.right=s.bottom,r.bottom=s.left;break;case 7:r.left=s.bottom,r.top=s.right,r.right=s.top,r.bottom=s.left;break;case 8:r.left=s.bottom,r.top=s.left,r.right=s.top,r.bottom=s.right}return r.orientation>4&&(r.maxWidth=s.maxHeight,r.maxHeight=s.maxWidth,r.minWidth=s.minHeight,r.minHeight=s.minWidth,r.sourceWidth=s.sourceHeight,r.sourceHeight=s.sourceWidth),r}});
//# sourceMappingURL=load-image.all.min.js.map;

/** JavaScript Canvas to Blob **/
(window.defineModule = (window.defineModule || {})).name = 'JavaScript Canvas to Blob';
!function(t){"use strict";var e=t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype,o=t.Blob&&function(){try{return Boolean(new Blob)}catch(t){return!1}}(),n=o&&t.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(t){return!1}}(),r=t.BlobBuilder||t.WebKitBlobBuilder||t.MozBlobBuilder||t.MSBlobBuilder,a=/^data:((.*?)(;charset=.*?)?)(;base64)?,/,i=(o||r)&&t.atob&&t.ArrayBuffer&&t.Uint8Array&&function(t){var e,i,l,u,b,c,d,B,f;if(e=t.match(a),!e)throw new Error("invalid data URI");for(i=e[2]?e[1]:"text/plain"+(e[3]||";charset=US-ASCII"),l=!!e[4],u=t.slice(e[0].length),b=l?atob(u):decodeURIComponent(u),c=new ArrayBuffer(b.length),d=new Uint8Array(c),B=0;B<b.length;B+=1)d[B]=b.charCodeAt(B);return o?new Blob([n?d:c],{type:i}):(f=new r,f.append(c),f.getBlob(i))};t.HTMLCanvasElement&&!e.toBlob&&(e.mozGetAsFile?e.toBlob=function(t,o,n){t(n&&e.toDataURL&&i?i(this.toDataURL(o,n)):this.mozGetAsFile("blob",o))}:e.toDataURL&&i&&(e.toBlob=function(t,e,o){t(i(this.toDataURL(e,o)))})),"function"==typeof define&&define.amd?define(function(){return i}):"object"==typeof module&&module.exports?module.exports=i:t.dataURLtoBlob=i}(window);
//# sourceMappingURL=canvas-to-blob.min.js.map;

/** jQuery File Upload (IFT) **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery File Upload (IFT)';
/*
 * jQuery Iframe Transport Plugin
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* global define, require, window, document, JSON */

;(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS:
        factory(require('jquery'));
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Helper variable to create unique names for the transport iframes:
    var counter = 0,
        jsonAPI = $,
        jsonParse = 'parseJSON';

    if ('JSON' in window && 'parse' in JSON) {
      jsonAPI = JSON;
      jsonParse = 'parse';
    }

    // The iframe transport accepts four additional options:
    // options.fileInput: a jQuery collection of file input fields
    // options.paramName: the parameter name for the file form data,
    //  overrides the name property of the file input field(s),
    //  can be a string or an array of strings.
    // options.formData: an array of objects with name and value properties,
    //  equivalent to the return data of .serializeArray(), e.g.:
    //  [{name: 'a', value: 1}, {name: 'b', value: 2}]
    // options.initialIframeSrc: the URL of the initial iframe src,
    //  by default set to "javascript:false;"
    $.ajaxTransport('iframe', function (options) {
        if (options.async) {
            // javascript:false as initial iframe src
            // prevents warning popups on HTTPS in IE6:
            /*jshint scripturl: true */
            var initialIframeSrc = options.initialIframeSrc || 'javascript:false;',
            /*jshint scripturl: false */
                form,
                iframe,
                addParamChar;
            return {
                send: function (_, completeCallback) {
                    form = $('<form style="display:none;"></form>');
                    form.attr('accept-charset', options.formAcceptCharset);
                    addParamChar = /\?/.test(options.url) ? '&' : '?';
                    // XDomainRequest only supports GET and POST:
                    if (options.type === 'DELETE') {
                        options.url = options.url + addParamChar + '_method=DELETE';
                        options.type = 'POST';
                    } else if (options.type === 'PUT') {
                        options.url = options.url + addParamChar + '_method=PUT';
                        options.type = 'POST';
                    } else if (options.type === 'PATCH') {
                        options.url = options.url + addParamChar + '_method=PATCH';
                        options.type = 'POST';
                    }
                    // IE versions below IE8 cannot set the name property of
                    // elements that have already been added to the DOM,
                    // so we set the name along with the iframe HTML markup:
                    counter += 1;
                    iframe = $(
                        '<iframe src="' + initialIframeSrc +
                            '" name="iframe-transport-' + counter + '"></iframe>'
                    ).bind('load', function () {
                        var fileInputClones,
                            paramNames = $.isArray(options.paramName) ?
                                    options.paramName : [options.paramName];
                        iframe
                            .unbind('load')
                            .bind('load', function () {
                                var response;
                                // Wrap in a try/catch block to catch exceptions thrown
                                // when trying to access cross-domain iframe contents:
                                try {
                                    response = iframe.contents();
                                    // Google Chrome and Firefox do not throw an
                                    // exception when calling iframe.contents() on
                                    // cross-domain requests, so we unify the response:
                                    if (!response.length || !response[0].firstChild) {
                                        throw new Error();
                                    }
                                } catch (e) {
                                    response = undefined;
                                }
                                // The complete callback returns the
                                // iframe content document as response object:
                                completeCallback(
                                    200,
                                    'success',
                                    {'iframe': response}
                                );
                                // Fix for IE endless progress bar activity bug
                                // (happens on form submits to iframe targets):
                                $('<iframe src="' + initialIframeSrc + '"></iframe>')
                                    .appendTo(form);
                                window.setTimeout(function () {
                                    // Removing the form in a setTimeout call
                                    // allows Chrome's developer tools to display
                                    // the response result
                                    form.remove();
                                }, 0);
                            });
                        form
                            .prop('target', iframe.prop('name'))
                            .prop('action', options.url)
                            .prop('method', options.type);
                        if (options.formData) {
                            $.each(options.formData, function (index, field) {
                                $('<input type="hidden"/>')
                                    .prop('name', field.name)
                                    .val(field.value)
                                    .appendTo(form);
                            });
                        }
                        if (options.fileInput && options.fileInput.length &&
                                options.type === 'POST') {
                            fileInputClones = options.fileInput.clone();
                            // Insert a clone for each file input field:
                            options.fileInput.after(function (index) {
                                return fileInputClones[index];
                            });
                            if (options.paramName) {
                                options.fileInput.each(function (index) {
                                    $(this).prop(
                                        'name',
                                        paramNames[index] || options.paramName
                                    );
                                });
                            }
                            // Appending the file input fields to the hidden form
                            // removes them from their original location:
                            form
                                .append(options.fileInput)
                                .prop('enctype', 'multipart/form-data')
                                // enctype must be set as encoding for IE:
                                .prop('encoding', 'multipart/form-data');
                            // Remove the HTML5 form attribute from the input(s):
                            options.fileInput.removeAttr('form');
                        }
                        form.submit();
                        // Insert the file input fields at their original location
                        // by replacing the clones with the originals:
                        if (fileInputClones && fileInputClones.length) {
                            options.fileInput.each(function (index, input) {
                                var clone = $(fileInputClones[index]);
                                // Restore the original name and form properties:
                                $(input)
                                    .prop('name', clone.prop('name'))
                                    .attr('form', clone.attr('form'));
                                clone.replaceWith(input);
                            });
                        }
                    });
                    form.append(iframe).appendTo(document.body);
                },
                abort: function () {
                    if (iframe) {
                        // javascript:false as iframe src aborts the request
                        // and prevents warning popups on HTTPS in IE6.
                        // concat is used to avoid the "Script URL" JSLint error:
                        iframe
                            .unbind('load')
                            .prop('src', initialIframeSrc);
                    }
                    if (form) {
                        form.remove();
                    }
                }
            };
        }
    });

    // The iframe transport returns the iframe content document as response.
    // The following adds converters from iframe to text, json, html, xml
    // and script.
    // Please note that the Content-Type for JSON responses has to be text/plain
    // or text/html, if the browser doesn't include application/json in the
    // Accept header, else IE will show a download dialog.
    // The Content-Type for XML responses on the other hand has to be always
    // application/xml or text/xml, so IE properly parses the XML response.
    // See also
    // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
    $.ajaxSetup({
        converters: {
            'iframe text': function (iframe) {
                return iframe && $(iframe[0].body).text();
            },
            'iframe json': function (iframe) {
                return iframe && jsonAPI[jsonParse]($(iframe[0].body).text());
            },
            'iframe html': function (iframe) {
                return iframe && $(iframe[0].body).html();
            },
            'iframe xml': function (iframe) {
                var xmlDoc = iframe && iframe[0];
                return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
                        $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
                            $(xmlDoc.body).html());
            },
            'iframe script': function (iframe) {
                return iframe && $.globalEval($(iframe[0].body).text());
            }
        }
    });

}));
;

/** jQuery File Upload (COR) **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery File Upload (COR)';
/*
 * jQuery File Upload Plugin
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* jshint nomen:false */
/* global define, require, window, document, location, Blob, FormData */

;(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'jquery-ui/ui/widget'
        ], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS:
        factory(
            require('jquery'),
            require('./vendor/jquery.ui.widget')
        );
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Detect file input support, based on
    // http://viljamis.com/blog/2012/file-upload-support-on-mobile/
    $.support.fileInput = !(new RegExp(
        // Handle devices which give false positives for the feature detection:
        '(Android (1\\.[0156]|2\\.[01]))' +
            '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' +
            '|(w(eb)?OSBrowser)|(webOS)' +
            '|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
    ).test(window.navigator.userAgent) ||
        // Feature detection for all other devices:
        $('<input type="file">').prop('disabled'));

    // The FileReader API is not actually used, but works as feature detection,
    // as some Safari versions (5?) support XHR file uploads via the FormData API,
    // but not non-multipart XHR file uploads.
    // window.XMLHttpRequestUpload is not available on IE10, so we check for
    // window.ProgressEvent instead to detect XHR2 file upload capability:
    $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader);
    $.support.xhrFormDataFileUpload = !!window.FormData;

    // Detect support for Blob slicing (required for chunked uploads):
    $.support.blobSlice = window.Blob && (Blob.prototype.slice ||
        Blob.prototype.webkitSlice || Blob.prototype.mozSlice);

    // Helper function to create drag handlers for dragover/dragenter/dragleave:
    function getDragHandler(type) {
        var isDragOver = type === 'dragover';
        return function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var dataTransfer = e.dataTransfer;
            if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 &&
                    this._trigger(
                        type,
                        $.Event(type, {delegatedEvent: e})
                    ) !== false) {
                e.preventDefault();
                if (isDragOver) {
                    dataTransfer.dropEffect = 'copy';
                }
            }
        };
    }

    // The fileupload widget listens for change events on file input fields defined
    // via fileInput setting and paste or drop events of the given dropZone.
    // In addition to the default jQuery Widget methods, the fileupload widget
    // exposes the "add" and "send" methods, to add or directly send files using
    // the fileupload API.
    // By default, files added via file input selection, paste, drag & drop or
    // "add" method are uploaded immediately, but it is possible to override
    // the "add" callback option to queue file uploads.
    $.widget('blueimp.fileupload', {

        options: {
            // The drop target element(s), by the default the complete document.
            // Set to null to disable drag & drop support:
            dropZone: $(document),
            // The paste target element(s), by the default undefined.
            // Set to a DOM node or jQuery object to enable file pasting:
            pasteZone: undefined,
            // The file input field(s), that are listened to for change events.
            // If undefined, it is set to the file input fields inside
            // of the widget element on plugin initialization.
            // Set to null to disable the change listener.
            fileInput: undefined,
            // By default, the file input field is replaced with a clone after
            // each input field change event. This is required for iframe transport
            // queues and allows change events to be fired for the same file
            // selection, but can be disabled by setting the following option to false:
            replaceFileInput: true,
            // The parameter name for the file form data (the request argument name).
            // If undefined or empty, the name property of the file input field is
            // used, or "files[]" if the file input name property is also empty,
            // can be a string or an array of strings:
            paramName: undefined,
            // By default, each file of a selection is uploaded using an individual
            // request for XHR type uploads. Set to false to upload file
            // selections in one request each:
            singleFileUploads: true,
            // To limit the number of files uploaded with one XHR request,
            // set the following option to an integer greater than 0:
            limitMultiFileUploads: undefined,
            // The following option limits the number of files uploaded with one
            // XHR request to keep the request size under or equal to the defined
            // limit in bytes:
            limitMultiFileUploadSize: undefined,
            // Multipart file uploads add a number of bytes to each uploaded file,
            // therefore the following option adds an overhead for each file used
            // in the limitMultiFileUploadSize configuration:
            limitMultiFileUploadSizeOverhead: 512,
            // Set the following option to true to issue all file upload requests
            // in a sequential order:
            sequentialUploads: false,
            // To limit the number of concurrent uploads,
            // set the following option to an integer greater than 0:
            limitConcurrentUploads: undefined,
            // Set the following option to true to force iframe transport uploads:
            forceIframeTransport: false,
            // Set the following option to the location of a redirect url on the
            // origin server, for cross-domain iframe transport uploads:
            redirect: undefined,
            // The parameter name for the redirect url, sent as part of the form
            // data and set to 'redirect' if this option is empty:
            redirectParamName: undefined,
            // Set the following option to the location of a postMessage window,
            // to enable postMessage transport uploads:
            postMessage: undefined,
            // By default, XHR file uploads are sent as multipart/form-data.
            // The iframe transport is always using multipart/form-data.
            // Set to false to enable non-multipart XHR uploads:
            multipart: true,
            // To upload large files in smaller chunks, set the following option
            // to a preferred maximum chunk size. If set to 0, null or undefined,
            // or the browser does not support the required Blob API, files will
            // be uploaded as a whole.
            maxChunkSize: undefined,
            // When a non-multipart upload or a chunked multipart upload has been
            // aborted, this option can be used to resume the upload by setting
            // it to the size of the already uploaded bytes. This option is most
            // useful when modifying the options object inside of the "add" or
            // "send" callbacks, as the options are cloned for each file upload.
            uploadedBytes: undefined,
            // By default, failed (abort or error) file uploads are removed from the
            // global progress calculation. Set the following option to false to
            // prevent recalculating the global progress data:
            recalculateProgress: true,
            // Interval in milliseconds to calculate and trigger progress events:
            progressInterval: 100,
            // Interval in milliseconds to calculate progress bitrate:
            bitrateInterval: 500,
            // By default, uploads are started automatically when adding files:
            autoUpload: true,

            // Error and info messages:
            messages: {
                uploadedBytes: 'Uploaded bytes exceed file size'
            },

            // Translation function, gets the message key to be translated
            // and an object with context specific data as arguments:
            i18n: function (message, context) {
                message = this.messages[message] || message.toString();
                if (context) {
                    $.each(context, function (key, value) {
                        message = message.replace('{' + key + '}', value);
                    });
                }
                return message;
            },

            // Additional form data to be sent along with the file uploads can be set
            // using this option, which accepts an array of objects with name and
            // value properties, a function returning such an array, a FormData
            // object (for XHR file uploads), or a simple object.
            // The form of the first fileInput is given as parameter to the function:
            formData: function (form) {
                return form.serializeArray();
            },

            // The add callback is invoked as soon as files are added to the fileupload
            // widget (via file input selection, drag & drop, paste or add API call).
            // If the singleFileUploads option is enabled, this callback will be
            // called once for each file in the selection for XHR file uploads, else
            // once for each file selection.
            //
            // The upload starts when the submit method is invoked on the data parameter.
            // The data object contains a files property holding the added files
            // and allows you to override plugin options as well as define ajax settings.
            //
            // Listeners for this callback can also be bound the following way:
            // .bind('fileuploadadd', func);
            //
            // data.submit() returns a Promise object and allows to attach additional
            // handlers using jQuery's Deferred callbacks:
            // data.submit().done(func).fail(func).always(func);
            add: function (e, data) {
                if (e.isDefaultPrevented()) {
                    return false;
                }
                if (data.autoUpload || (data.autoUpload !== false &&
                        $(this).fileupload('option', 'autoUpload'))) {
                    data.process().done(function () {
                        data.submit();
                    });
                }
            },

            // Other callbacks:

            // Callback for the submit event of each file upload:
            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);

            // Callback for the start of each file upload request:
            // send: function (e, data) {}, // .bind('fileuploadsend', func);

            // Callback for successful uploads:
            // done: function (e, data) {}, // .bind('fileuploaddone', func);

            // Callback for failed (abort or error) uploads:
            // fail: function (e, data) {}, // .bind('fileuploadfail', func);

            // Callback for completed (success, abort or error) requests:
            // always: function (e, data) {}, // .bind('fileuploadalways', func);

            // Callback for upload progress events:
            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);

            // Callback for global upload progress events:
            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);

            // Callback for uploads start, equivalent to the global ajaxStart event:
            // start: function (e) {}, // .bind('fileuploadstart', func);

            // Callback for uploads stop, equivalent to the global ajaxStop event:
            // stop: function (e) {}, // .bind('fileuploadstop', func);

            // Callback for change events of the fileInput(s):
            // change: function (e, data) {}, // .bind('fileuploadchange', func);

            // Callback for paste events to the pasteZone(s):
            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);

            // Callback for drop events of the dropZone(s):
            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);

            // Callback for dragover events of the dropZone(s):
            // dragover: function (e) {}, // .bind('fileuploaddragover', func);

            // Callback for the start of each chunk upload request:
            // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);

            // Callback for successful chunk uploads:
            // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);

            // Callback for failed (abort or error) chunk uploads:
            // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);

            // Callback for completed (success, abort or error) chunk upload requests:
            // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);

            // The plugin options are used as settings object for the ajax calls.
            // The following are jQuery ajax settings required for the file uploads:
            processData: false,
            contentType: false,
            cache: false,
            timeout: 0
        },

        // A list of options that require reinitializing event listeners and/or
        // special initialization code:
        _specialOptions: [
            'fileInput',
            'dropZone',
            'pasteZone',
            'multipart',
            'forceIframeTransport'
        ],

        _blobSlice: $.support.blobSlice && function () {
            var slice = this.slice || this.webkitSlice || this.mozSlice;
            return slice.apply(this, arguments);
        },

        _BitrateTimer: function () {
            this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
            this.loaded = 0;
            this.bitrate = 0;
            this.getBitrate = function (now, loaded, interval) {
                var timeDiff = now - this.timestamp;
                if (!this.bitrate || !interval || timeDiff > interval) {
                    this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
                    this.loaded = loaded;
                    this.timestamp = now;
                }
                return this.bitrate;
            };
        },

        _isXHRUpload: function (options) {
            return !options.forceIframeTransport &&
                ((!options.multipart && $.support.xhrFileUpload) ||
                $.support.xhrFormDataFileUpload);
        },

        _getFormData: function (options) {
            var formData;
            if ($.type(options.formData) === 'function') {
                return options.formData(options.form);
            }
            if ($.isArray(options.formData)) {
                return options.formData;
            }
            if ($.type(options.formData) === 'object') {
                formData = [];
                $.each(options.formData, function (name, value) {
                    formData.push({name: name, value: value});
                });
                return formData;
            }
            return [];
        },

        _getTotal: function (files) {
            var total = 0;
            $.each(files, function (index, file) {
                total += file.size || 1;
            });
            return total;
        },

        _initProgressObject: function (obj) {
            var progress = {
                loaded: 0,
                total: 0,
                bitrate: 0
            };
            if (obj._progress) {
                $.extend(obj._progress, progress);
            } else {
                obj._progress = progress;
            }
        },

        _initResponseObject: function (obj) {
            var prop;
            if (obj._response) {
                for (prop in obj._response) {
                    if (obj._response.hasOwnProperty(prop)) {
                        delete obj._response[prop];
                    }
                }
            } else {
                obj._response = {};
            }
        },

        _onProgress: function (e, data) {
            if (e.lengthComputable) {
                var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
                    loaded;
                if (data._time && data.progressInterval &&
                        (now - data._time < data.progressInterval) &&
                        e.loaded !== e.total) {
                    return;
                }
                data._time = now;
                loaded = Math.floor(
                    e.loaded / e.total * (data.chunkSize || data._progress.total)
                ) + (data.uploadedBytes || 0);
                // Add the difference from the previously loaded state
                // to the global loaded counter:
                this._progress.loaded += (loaded - data._progress.loaded);
                this._progress.bitrate = this._bitrateTimer.getBitrate(
                    now,
                    this._progress.loaded,
                    data.bitrateInterval
                );
                data._progress.loaded = data.loaded = loaded;
                data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
                    now,
                    loaded,
                    data.bitrateInterval
                );
                // Trigger a custom progress event with a total data property set
                // to the file size(s) of the current upload and a loaded data
                // property calculated accordingly:
                this._trigger(
                    'progress',
                    $.Event('progress', {delegatedEvent: e}),
                    data
                );
                // Trigger a global progress event for all current file uploads,
                // including ajax calls queued for sequential file uploads:
                this._trigger(
                    'progressall',
                    $.Event('progressall', {delegatedEvent: e}),
                    this._progress
                );
            }
        },

        _initProgressListener: function (options) {
            var that = this,
                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
            // Accesss to the native XHR object is required to add event listeners
            // for the upload progress event:
            if (xhr.upload) {
                $(xhr.upload).bind('progress', function (e) {
                    var oe = e.originalEvent;
                    // Make sure the progress event properties get copied over:
                    e.lengthComputable = oe.lengthComputable;
                    e.loaded = oe.loaded;
                    e.total = oe.total;
                    that._onProgress(e, options);
                });
                options.xhr = function () {
                    return xhr;
                };
            }
        },

        _isInstanceOf: function (type, obj) {
            // Cross-frame instanceof check
            return Object.prototype.toString.call(obj) === '[object ' + type + ']';
        },

        _initXHRData: function (options) {
            var that = this,
                formData,
                file = options.files[0],
                // Ignore non-multipart setting if not supported:
                multipart = options.multipart || !$.support.xhrFileUpload,
                paramName = $.type(options.paramName) === 'array' ?
                    options.paramName[0] : options.paramName;
            options.headers = $.extend({}, options.headers);
            if (options.contentRange) {
                options.headers['Content-Range'] = options.contentRange;
            }
            if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
                options.headers['Content-Disposition'] = 'attachment; filename="' +
                    encodeURI(file.name) + '"';
            }
            if (!multipart) {
                options.contentType = file.type || 'application/octet-stream';
                options.data = options.blob || file;
            } else if ($.support.xhrFormDataFileUpload) {
                if (options.postMessage) {
                    // window.postMessage does not allow sending FormData
                    // objects, so we just add the File/Blob objects to
                    // the formData array and let the postMessage window
                    // create the FormData object out of this array:
                    formData = this._getFormData(options);
                    if (options.blob) {
                        formData.push({
                            name: paramName,
                            value: options.blob
                        });
                    } else {
                        $.each(options.files, function (index, file) {
                            formData.push({
                                name: ($.type(options.paramName) === 'array' &&
                                    options.paramName[index]) || paramName,
                                value: file
                            });
                        });
                    }
                } else {
                    if (that._isInstanceOf('FormData', options.formData)) {
                        formData = options.formData;
                    } else {
                        formData = new FormData();
                        $.each(this._getFormData(options), function (index, field) {
                            formData.append(field.name, field.value);
                        });
                    }
                    if (options.blob) {
                        formData.append(paramName, options.blob, file.name);
                    } else {
                        $.each(options.files, function (index, file) {
                            // This check allows the tests to run with
                            // dummy objects:
                            if (that._isInstanceOf('File', file) ||
                                    that._isInstanceOf('Blob', file)) {
                                formData.append(
                                    ($.type(options.paramName) === 'array' &&
                                        options.paramName[index]) || paramName,
                                    file,
                                    file.uploadName || file.name
                                );
                            }
                        });
                    }
                }
                options.data = formData;
            }
            // Blob reference is not needed anymore, free memory:
            options.blob = null;
        },

        _initIframeSettings: function (options) {
            var targetHost = $('<a></a>').prop('href', options.url).prop('host');
            // Setting the dataType to iframe enables the iframe transport:
            options.dataType = 'iframe ' + (options.dataType || '');
            // The iframe transport accepts a serialized array as form data:
            options.formData = this._getFormData(options);
            // Add redirect url to form data on cross-domain uploads:
            if (options.redirect && targetHost && targetHost !== location.host) {
                options.formData.push({
                    name: options.redirectParamName || 'redirect',
                    value: options.redirect
                });
            }
        },

        _initDataSettings: function (options) {
            if (this._isXHRUpload(options)) {
                if (!this._chunkedUpload(options, true)) {
                    if (!options.data) {
                        this._initXHRData(options);
                    }
                    this._initProgressListener(options);
                }
                if (options.postMessage) {
                    // Setting the dataType to postmessage enables the
                    // postMessage transport:
                    options.dataType = 'postmessage ' + (options.dataType || '');
                }
            } else {
                this._initIframeSettings(options);
            }
        },

        _getParamName: function (options) {
            var fileInput = $(options.fileInput),
                paramName = options.paramName;
            if (!paramName) {
                paramName = [];
                fileInput.each(function () {
                    var input = $(this),
                        name = input.prop('name') || 'files[]',
                        i = (input.prop('files') || [1]).length;
                    while (i) {
                        paramName.push(name);
                        i -= 1;
                    }
                });
                if (!paramName.length) {
                    paramName = [fileInput.prop('name') || 'files[]'];
                }
            } else if (!$.isArray(paramName)) {
                paramName = [paramName];
            }
            return paramName;
        },

        _initFormSettings: function (options) {
            // Retrieve missing options from the input field and the
            // associated form, if available:
            if (!options.form || !options.form.length) {
                options.form = $(options.fileInput.prop('form'));
                // If the given file input doesn't have an associated form,
                // use the default widget file input's form:
                if (!options.form.length) {
                    options.form = $(this.options.fileInput.prop('form'));
                }
            }
            options.paramName = this._getParamName(options);
            if (!options.url) {
                options.url = options.form.prop('action') || location.href;
            }
            // The HTTP request method must be "POST" or "PUT":
            options.type = (options.type ||
                ($.type(options.form.prop('method')) === 'string' &&
                    options.form.prop('method')) || ''
                ).toUpperCase();
            if (options.type !== 'POST' && options.type !== 'PUT' &&
                    options.type !== 'PATCH') {
                options.type = 'POST';
            }
            if (!options.formAcceptCharset) {
                options.formAcceptCharset = options.form.attr('accept-charset');
            }
        },

        _getAJAXSettings: function (data) {
            var options = $.extend({}, this.options, data);
            this._initFormSettings(options);
            this._initDataSettings(options);
            return options;
        },

        // jQuery 1.6 doesn't provide .state(),
        // while jQuery 1.8+ removed .isRejected() and .isResolved():
        _getDeferredState: function (deferred) {
            if (deferred.state) {
                return deferred.state();
            }
            if (deferred.isResolved()) {
                return 'resolved';
            }
            if (deferred.isRejected()) {
                return 'rejected';
            }
            return 'pending';
        },

        // Maps jqXHR callbacks to the equivalent
        // methods of the given Promise object:
        _enhancePromise: function (promise) {
            promise.success = promise.done;
            promise.error = promise.fail;
            promise.complete = promise.always;
            return promise;
        },

        // Creates and returns a Promise object enhanced with
        // the jqXHR methods abort, success, error and complete:
        _getXHRPromise: function (resolveOrReject, context, args) {
            var dfd = $.Deferred(),
                promise = dfd.promise();
            context = context || this.options.context || promise;
            if (resolveOrReject === true) {
                dfd.resolveWith(context, args);
            } else if (resolveOrReject === false) {
                dfd.rejectWith(context, args);
            }
            promise.abort = dfd.promise;
            return this._enhancePromise(promise);
        },

        // Adds convenience methods to the data callback argument:
        _addConvenienceMethods: function (e, data) {
            var that = this,
                getPromise = function (args) {
                    return $.Deferred().resolveWith(that, args).promise();
                };
            data.process = function (resolveFunc, rejectFunc) {
                if (resolveFunc || rejectFunc) {
                    data._processQueue = this._processQueue =
                        (this._processQueue || getPromise([this])).then(
                            function () {
                                if (data.errorThrown) {
                                    return $.Deferred()
                                        .rejectWith(that, [data]).promise();
                                }
                                return getPromise(arguments);
                            }
                        ).then(resolveFunc, rejectFunc);
                }
                return this._processQueue || getPromise([this]);
            };
            data.submit = function () {
                if (this.state() !== 'pending') {
                    data.jqXHR = this.jqXHR =
                        (that._trigger(
                            'submit',
                            $.Event('submit', {delegatedEvent: e}),
                            this
                        ) !== false) && that._onSend(e, this);
                }
                return this.jqXHR || that._getXHRPromise();
            };
            data.abort = function () {
                if (this.jqXHR) {
                    return this.jqXHR.abort();
                }
                this.errorThrown = 'abort';
                that._trigger('fail', null, this);
                return that._getXHRPromise(false);
            };
            data.state = function () {
                if (this.jqXHR) {
                    return that._getDeferredState(this.jqXHR);
                }
                if (this._processQueue) {
                    return that._getDeferredState(this._processQueue);
                }
            };
            data.processing = function () {
                return !this.jqXHR && this._processQueue && that
                    ._getDeferredState(this._processQueue) === 'pending';
            };
            data.progress = function () {
                return this._progress;
            };
            data.response = function () {
                return this._response;
            };
        },

        // Parses the Range header from the server response
        // and returns the uploaded bytes:
        _getUploadedBytes: function (jqXHR) {
            var range = jqXHR.getResponseHeader('Range'),
                parts = range && range.split('-'),
                upperBytesPos = parts && parts.length > 1 &&
                    parseInt(parts[1], 10);
            return upperBytesPos && upperBytesPos + 1;
        },

        // Uploads a file in multiple, sequential requests
        // by splitting the file up in multiple blob chunks.
        // If the second parameter is true, only tests if the file
        // should be uploaded in chunks, but does not invoke any
        // upload requests:
        _chunkedUpload: function (options, testOnly) {
            options.uploadedBytes = options.uploadedBytes || 0;
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes,
                mcs = options.maxChunkSize || fs,
                slice = this._blobSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
                    options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = options.i18n('uploadedBytes');
                return this._getXHRPromise(
                    false,
                    options.context,
                    [null, 'error', file.error]
                );
            }
            // The chunk upload method:
            upload = function () {
                // Clone the options object for each chunk upload:
                var o = $.extend({}, options),
                    currentLoaded = o._progress.loaded;
                o.blob = slice.call(
                    file,
                    ub,
                    ub + mcs,
                    file.type
                );
                // Store the current chunk size, as the blob itself
                // will be dereferenced after data processing:
                o.chunkSize = o.blob.size;
                // Expose the chunk bytes position range:
                o.contentRange = 'bytes ' + ub + '-' +
                    (ub + o.chunkSize - 1) + '/' + fs;
                // Process the upload data (the blob and potential form data):
                that._initXHRData(o);
                // Add progress listeners for this chunk upload:
                that._initProgressListener(o);
                jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
                        that._getXHRPromise(false, o.context))
                    .done(function (result, textStatus, jqXHR) {
                        ub = that._getUploadedBytes(jqXHR) ||
                            (ub + o.chunkSize);
                        // Create a progress event if no final progress event
                        // with loaded equaling total has been triggered
                        // for this chunk:
                        if (currentLoaded + o.chunkSize - o._progress.loaded) {
                            that._onProgress($.Event('progress', {
                                lengthComputable: true,
                                loaded: ub - o.uploadedBytes,
                                total: ub - o.uploadedBytes
                            }), o);
                        }
                        options.uploadedBytes = o.uploadedBytes = ub;
                        o.result = result;
                        o.textStatus = textStatus;
                        o.jqXHR = jqXHR;
                        that._trigger('chunkdone', null, o);
                        that._trigger('chunkalways', null, o);
                        if (ub < fs) {
                            // File upload not yet complete,
                            // continue with the next chunk:
                            upload();
                        } else {
                            dfd.resolveWith(
                                o.context,
                                [result, textStatus, jqXHR]
                            );
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        o.jqXHR = jqXHR;
                        o.textStatus = textStatus;
                        o.errorThrown = errorThrown;
                        that._trigger('chunkfail', null, o);
                        that._trigger('chunkalways', null, o);
                        dfd.rejectWith(
                            o.context,
                            [jqXHR, textStatus, errorThrown]
                        );
                    });
            };
            this._enhancePromise(promise);
            promise.abort = function () {
                return jqXHR.abort();
            };
            upload();
            return promise;
        },

        _beforeSend: function (e, data) {
            if (this._active === 0) {
                // the start callback is triggered when an upload starts
                // and no other uploads are currently running,
                // equivalent to the global ajaxStart event:
                this._trigger('start');
                // Set timer for global bitrate progress calculation:
                this._bitrateTimer = new this._BitrateTimer();
                // Reset the global progress values:
                this._progress.loaded = this._progress.total = 0;
                this._progress.bitrate = 0;
            }
            // Make sure the container objects for the .response() and
            // .progress() methods on the data object are available
            // and reset to their initial state:
            this._initResponseObject(data);
            this._initProgressObject(data);
            data._progress.loaded = data.loaded = data.uploadedBytes || 0;
            data._progress.total = data.total = this._getTotal(data.files) || 1;
            data._progress.bitrate = data.bitrate = 0;
            this._active += 1;
            // Initialize the global progress values:
            this._progress.loaded += data.loaded;
            this._progress.total += data.total;
        },

        _onDone: function (result, textStatus, jqXHR, options) {
            var total = options._progress.total,
                response = options._response;
            if (options._progress.loaded < total) {
                // Create a progress event if no final progress event
                // with loaded equaling total has been triggered:
                this._onProgress($.Event('progress', {
                    lengthComputable: true,
                    loaded: total,
                    total: total
                }), options);
            }
            response.result = options.result = result;
            response.textStatus = options.textStatus = textStatus;
            response.jqXHR = options.jqXHR = jqXHR;
            this._trigger('done', null, options);
        },

        _onFail: function (jqXHR, textStatus, errorThrown, options) {
            var response = options._response;
            if (options.recalculateProgress) {
                // Remove the failed (error or abort) file upload from
                // the global progress calculation:
                this._progress.loaded -= options._progress.loaded;
                this._progress.total -= options._progress.total;
            }
            response.jqXHR = options.jqXHR = jqXHR;
            response.textStatus = options.textStatus = textStatus;
            response.errorThrown = options.errorThrown = errorThrown;
            this._trigger('fail', null, options);
        },

        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
            // jqXHRorResult, textStatus and jqXHRorError are added to the
            // options object via done and fail callbacks
            this._trigger('always', null, options);
        },

        _onSend: function (e, data) {
            if (!data.submit) {
                this._addConvenienceMethods(e, data);
            }
            var that = this,
                jqXHR,
                aborted,
                slot,
                pipe,
                options = that._getAJAXSettings(data),
                send = function () {
                    that._sending += 1;
                    // Set timer for bitrate progress calculation:
                    options._bitrateTimer = new that._BitrateTimer();
                    jqXHR = jqXHR || (
                        ((aborted || that._trigger(
                            'send',
                            $.Event('send', {delegatedEvent: e}),
                            options
                        ) === false) &&
                        that._getXHRPromise(false, options.context, aborted)) ||
                        that._chunkedUpload(options) || $.ajax(options)
                    ).done(function (result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, options);
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, options);
                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
                        that._onAlways(
                            jqXHRorResult,
                            textStatus,
                            jqXHRorError,
                            options
                        );
                        that._sending -= 1;
                        that._active -= 1;
                        if (options.limitConcurrentUploads &&
                                options.limitConcurrentUploads > that._sending) {
                            // Start the next queued upload,
                            // that has not been aborted:
                            var nextSlot = that._slots.shift();
                            while (nextSlot) {
                                if (that._getDeferredState(nextSlot) === 'pending') {
                                    nextSlot.resolve();
                                    break;
                                }
                                nextSlot = that._slots.shift();
                            }
                        }
                        if (that._active === 0) {
                            // The stop callback is triggered when all uploads have
                            // been completed, equivalent to the global ajaxStop event:
                            that._trigger('stop');
                        }
                    });
                    return jqXHR;
                };
            this._beforeSend(e, options);
            if (this.options.sequentialUploads ||
                    (this.options.limitConcurrentUploads &&
                    this.options.limitConcurrentUploads <= this._sending)) {
                if (this.options.limitConcurrentUploads > 1) {
                    slot = $.Deferred();
                    this._slots.push(slot);
                    pipe = slot.then(send);
                } else {
                    this._sequence = this._sequence.then(send, send);
                    pipe = this._sequence;
                }
                // Return the piped Promise object, enhanced with an abort method,
                // which is delegated to the jqXHR object of the current upload,
                // and jqXHR callbacks mapped to the equivalent Promise methods:
                pipe.abort = function () {
                    aborted = [undefined, 'abort', 'abort'];
                    if (!jqXHR) {
                        if (slot) {
                            slot.rejectWith(options.context, aborted);
                        }
                        return send();
                    }
                    return jqXHR.abort();
                };
                return this._enhancePromise(pipe);
            }
            return send();
        },

        _onAdd: function (e, data) {
            var that = this,
                result = true,
                options = $.extend({}, this.options, data),
                files = data.files,
                filesLength = files.length,
                limit = options.limitMultiFileUploads,
                limitSize = options.limitMultiFileUploadSize,
                overhead = options.limitMultiFileUploadSizeOverhead,
                batchSize = 0,
                paramName = this._getParamName(options),
                paramNameSet,
                paramNameSlice,
                fileSet,
                i,
                j = 0;
            if (!filesLength) {
                return false;
            }
            if (limitSize && files[0].size === undefined) {
                limitSize = undefined;
            }
            if (!(options.singleFileUploads || limit || limitSize) ||
                    !this._isXHRUpload(options)) {
                fileSet = [files];
                paramNameSet = [paramName];
            } else if (!(options.singleFileUploads || limitSize) && limit) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < filesLength; i += limit) {
                    fileSet.push(files.slice(i, i + limit));
                    paramNameSlice = paramName.slice(i, i + limit);
                    if (!paramNameSlice.length) {
                        paramNameSlice = paramName;
                    }
                    paramNameSet.push(paramNameSlice);
                }
            } else if (!options.singleFileUploads && limitSize) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < filesLength; i = i + 1) {
                    batchSize += files[i].size + overhead;
                    if (i + 1 === filesLength ||
                            ((batchSize + files[i + 1].size + overhead) > limitSize) ||
                            (limit && i + 1 - j >= limit)) {
                        fileSet.push(files.slice(j, i + 1));
                        paramNameSlice = paramName.slice(j, i + 1);
                        if (!paramNameSlice.length) {
                            paramNameSlice = paramName;
                        }
                        paramNameSet.push(paramNameSlice);
                        j = i + 1;
                        batchSize = 0;
                    }
                }
            } else {
                paramNameSet = paramName;
            }
            data.originalFiles = files;
            $.each(fileSet || files, function (index, element) {
                var newData = $.extend({}, data);
                newData.files = fileSet ? element : [element];
                newData.paramName = paramNameSet[index];
                that._initResponseObject(newData);
                that._initProgressObject(newData);
                that._addConvenienceMethods(e, newData);
                result = that._trigger(
                    'add',
                    $.Event('add', {delegatedEvent: e}),
                    newData
                );
                return result;
            });
            return result;
        },

        _replaceFileInput: function (data) {
            var input = data.fileInput,
                inputClone = input.clone(true),
                restoreFocus = input.is(document.activeElement);
            // Add a reference for the new cloned file input to the data argument:
            data.fileInputClone = inputClone;
            $('<form></form>').append(inputClone)[0].reset();
            // Detaching allows to insert the fileInput on another form
            // without loosing the file input value:
            input.after(inputClone).detach();
            // If the fileInput had focus before it was detached,
            // restore focus to the inputClone.
            if (restoreFocus) {
                inputClone.focus();
            }
            // Avoid memory leaks with the detached file input:
            $.cleanData(input.unbind('remove'));
            // Replace the original file input element in the fileInput
            // elements set with the clone, which has been copied including
            // event handlers:
            this.options.fileInput = this.options.fileInput.map(function (i, el) {
                if (el === input[0]) {
                    return inputClone[0];
                }
                return el;
            });
            // If the widget has been initialized on the file input itself,
            // override this.element with the file input clone:
            if (input[0] === this.element[0]) {
                this.element = inputClone;
            }
        },

        _handleFileTreeEntry: function (entry, path) {
            var that = this,
                dfd = $.Deferred(),
                entries = [],
                dirReader,
                errorHandler = function (e) {
                    if (e && !e.entry) {
                        e.entry = entry;
                    }
                    // Since $.when returns immediately if one
                    // Deferred is rejected, we use resolve instead.
                    // This allows valid files and invalid items
                    // to be returned together in one set:
                    dfd.resolve([e]);
                },
                successHandler = function (entries) {
                    that._handleFileTreeEntries(
                        entries,
                        path + entry.name + '/'
                    ).done(function (files) {
                        dfd.resolve(files);
                    }).fail(errorHandler);
                },
                readEntries = function () {
                    dirReader.readEntries(function (results) {
                        if (!results.length) {
                            successHandler(entries);
                        } else {
                            entries = entries.concat(results);
                            readEntries();
                        }
                    }, errorHandler);
                };
            path = path || '';
            if (entry.isFile) {
                if (entry._file) {
                    // Workaround for Chrome bug #149735
                    entry._file.relativePath = path;
                    dfd.resolve(entry._file);
                } else {
                    entry.file(function (file) {
                        file.relativePath = path;
                        dfd.resolve(file);
                    }, errorHandler);
                }
            } else if (entry.isDirectory) {
                dirReader = entry.createReader();
                readEntries();
            } else {
                // Return an empy list for file system items
                // other than files or directories:
                dfd.resolve([]);
            }
            return dfd.promise();
        },

        _handleFileTreeEntries: function (entries, path) {
            var that = this;
            return $.when.apply(
                $,
                $.map(entries, function (entry) {
                    return that._handleFileTreeEntry(entry, path);
                })
            ).then(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _getDroppedFiles: function (dataTransfer) {
            dataTransfer = dataTransfer || {};
            var items = dataTransfer.items;
            if (items && items.length && (items[0].webkitGetAsEntry ||
                    items[0].getAsEntry)) {
                return this._handleFileTreeEntries(
                    $.map(items, function (item) {
                        var entry;
                        if (item.webkitGetAsEntry) {
                            entry = item.webkitGetAsEntry();
                            if (entry) {
                                // Workaround for Chrome bug #149735:
                                entry._file = item.getAsFile();
                            }
                            return entry;
                        }
                        return item.getAsEntry();
                    })
                );
            }
            return $.Deferred().resolve(
                $.makeArray(dataTransfer.files)
            ).promise();
        },

        _getSingleFileInputFiles: function (fileInput) {
            fileInput = $(fileInput);
            var entries = fileInput.prop('webkitEntries') ||
                    fileInput.prop('entries'),
                files,
                value;
            if (entries && entries.length) {
                return this._handleFileTreeEntries(entries);
            }
            files = $.makeArray(fileInput.prop('files'));
            if (!files.length) {
                value = fileInput.prop('value');
                if (!value) {
                    return $.Deferred().resolve([]).promise();
                }
                // If the files property is not available, the browser does not
                // support the File API and we add a pseudo File object with
                // the input value as name with path information removed:
                files = [{name: value.replace(/^.*\\/, '')}];
            } else if (files[0].name === undefined && files[0].fileName) {
                // File normalization for Safari 4 and Firefox 3:
                $.each(files, function (index, file) {
                    file.name = file.fileName;
                    file.size = file.fileSize;
                });
            }
            return $.Deferred().resolve(files).promise();
        },

        _getFileInputFiles: function (fileInput) {
            if (!(fileInput instanceof $) || fileInput.length === 1) {
                return this._getSingleFileInputFiles(fileInput);
            }
            return $.when.apply(
                $,
                $.map(fileInput, this._getSingleFileInputFiles)
            ).then(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _onChange: function (e) {
            var that = this,
                data = {
                    fileInput: $(e.target),
                    form: $(e.target.form)
                };
            this._getFileInputFiles(data.fileInput).always(function (files) {
                data.files = files;
                if (that.options.replaceFileInput) {
                    that._replaceFileInput(data);
                }
                if (that._trigger(
                        'change',
                        $.Event('change', {delegatedEvent: e}),
                        data
                    ) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onPaste: function (e) {
            var items = e.originalEvent && e.originalEvent.clipboardData &&
                    e.originalEvent.clipboardData.items,
                data = {files: []};
            if (items && items.length) {
                $.each(items, function (index, item) {
                    var file = item.getAsFile && item.getAsFile();
                    if (file) {
                        data.files.push(file);
                    }
                });
                if (this._trigger(
                        'paste',
                        $.Event('paste', {delegatedEvent: e}),
                        data
                    ) !== false) {
                    this._onAdd(e, data);
                }
            }
        },

        _onDrop: function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var that = this,
                dataTransfer = e.dataTransfer,
                data = {};
            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
                e.preventDefault();
                this._getDroppedFiles(dataTransfer).always(function (files) {
                    data.files = files;
                    if (that._trigger(
                            'drop',
                            $.Event('drop', {delegatedEvent: e}),
                            data
                        ) !== false) {
                        that._onAdd(e, data);
                    }
                });
            }
        },

        _onDragOver: getDragHandler('dragover'),

        _onDragEnter: getDragHandler('dragenter'),

        _onDragLeave: getDragHandler('dragleave'),

        _initEventHandlers: function () {
            if (this._isXHRUpload(this.options)) {
                this._on(this.options.dropZone, {
                    dragover: this._onDragOver,
                    drop: this._onDrop,
                    // event.preventDefault() on dragenter is required for IE10+:
                    dragenter: this._onDragEnter,
                    // dragleave is not required, but added for completeness:
                    dragleave: this._onDragLeave
                });
                this._on(this.options.pasteZone, {
                    paste: this._onPaste
                });
            }
            if ($.support.fileInput) {
                this._on(this.options.fileInput, {
                    change: this._onChange
                });
            }
        },

        _destroyEventHandlers: function () {
            this._off(this.options.dropZone, 'dragenter dragleave dragover drop');
            this._off(this.options.pasteZone, 'paste');
            this._off(this.options.fileInput, 'change');
        },

        _destroy: function () {
            this._destroyEventHandlers();
        },

        _setOption: function (key, value) {
            var reinit = $.inArray(key, this._specialOptions) !== -1;
            if (reinit) {
                this._destroyEventHandlers();
            }
            this._super(key, value);
            if (reinit) {
                this._initSpecialOptions();
                this._initEventHandlers();
            }
        },

        _initSpecialOptions: function () {
            var options = this.options;
            if (options.fileInput === undefined) {
                options.fileInput = this.element.is('input[type="file"]') ?
                        this.element : this.element.find('input[type="file"]');
            } else if (!(options.fileInput instanceof $)) {
                options.fileInput = $(options.fileInput);
            }
            if (!(options.dropZone instanceof $)) {
                options.dropZone = $(options.dropZone);
            }
            if (!(options.pasteZone instanceof $)) {
                options.pasteZone = $(options.pasteZone);
            }
        },

        _getRegExp: function (str) {
            var parts = str.split('/'),
                modifiers = parts.pop();
            parts.shift();
            return new RegExp(parts.join('/'), modifiers);
        },

        _isRegExpOption: function (key, value) {
            return key !== 'url' && $.type(value) === 'string' &&
                /^\/.*\/[igm]{0,3}$/.test(value);
        },

        _initDataAttributes: function () {
            var that = this,
                options = this.options,
                data = this.element.data();
            // Initialize options set via HTML5 data-attributes:
            $.each(
                this.element[0].attributes,
                function (index, attr) {
                    var key = attr.name.toLowerCase(),
                        value;
                    if (/^data-/.test(key)) {
                        // Convert hyphen-ated key to camelCase:
                        key = key.slice(5).replace(/-[a-z]/g, function (str) {
                            return str.charAt(1).toUpperCase();
                        });
                        value = data[key];
                        if (that._isRegExpOption(key, value)) {
                            value = that._getRegExp(value);
                        }
                        options[key] = value;
                    }
                }
            );
        },

        _create: function () {
            this._initDataAttributes();
            this._initSpecialOptions();
            this._slots = [];
            this._sequence = this._getXHRPromise(true);
            this._sending = this._active = 0;
            this._initProgressObject(this);
            this._initEventHandlers();
        },

        // This method is exposed to the widget API and allows to query
        // the number of active uploads:
        active: function () {
            return this._active;
        },

        // This method is exposed to the widget API and allows to query
        // the widget upload progress.
        // It returns an object with loaded, total and bitrate properties
        // for the running uploads:
        progress: function () {
            return this._progress;
        },

        // This method is exposed to the widget API and allows adding files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files property and can contain additional options:
        // .fileupload('add', {files: filesList});
        add: function (data) {
            var that = this;
            if (!data || this.options.disabled) {
                return;
            }
            if (data.fileInput && !data.files) {
                this._getFileInputFiles(data.fileInput).always(function (files) {
                    data.files = files;
                    that._onAdd(null, data);
                });
            } else {
                data.files = $.makeArray(data.files);
                this._onAdd(null, data);
            }
        },

        // This method is exposed to the widget API and allows sending files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files or fileInput property and can contain additional options:
        // .fileupload('send', {files: filesList});
        // The method returns a Promise object for the file upload call.
        send: function (data) {
            if (data && !this.options.disabled) {
                if (data.fileInput && !data.files) {
                    var that = this,
                        dfd = $.Deferred(),
                        promise = dfd.promise(),
                        jqXHR,
                        aborted;
                    promise.abort = function () {
                        aborted = true;
                        if (jqXHR) {
                            return jqXHR.abort();
                        }
                        dfd.reject(null, 'abort', 'abort');
                        return promise;
                    };
                    this._getFileInputFiles(data.fileInput).always(
                        function (files) {
                            if (aborted) {
                                return;
                            }
                            if (!files.length) {
                                dfd.reject();
                                return;
                            }
                            data.files = files;
                            jqXHR = that._onSend(null, data);
                            jqXHR.then(
                                function (result, textStatus, jqXHR) {
                                    dfd.resolve(result, textStatus, jqXHR);
                                },
                                function (jqXHR, textStatus, errorThrown) {
                                    dfd.reject(jqXHR, textStatus, errorThrown);
                                }
                            );
                        }
                    );
                    return this._enhancePromise(promise);
                }
                data.files = $.makeArray(data.files);
                if (data.files.length) {
                    return this._onSend(null, data);
                }
            }
            return this._getXHRPromise(false, data && data.context);
        }

    });

}));
;

/** jQuery File Upload (PRC) **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery File Upload (PRC)';
/*
 * jQuery File Upload Processing Plugin
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2012, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* jshint nomen:false */
/* global define, require, window */

;(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            './jquery.fileupload'
        ], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS:
        factory(
            require('jquery'),
            require('./jquery.fileupload')
        );
    } else {
        // Browser globals:
        factory(
            window.jQuery
        );
    }
}(function ($) {
    'use strict';

    var originalAdd = $.blueimp.fileupload.prototype.options.add;

    // The File Upload Processing plugin extends the fileupload widget
    // with file processing functionality:
    $.widget('blueimp.fileupload', $.blueimp.fileupload, {

        options: {
            // The list of processing actions:
            processQueue: [
                /*
                {
                    action: 'log',
                    type: 'debug'
                }
                */
            ],
            add: function (e, data) {
                var $this = $(this);
                data.process(function () {
                    return $this.fileupload('process', data);
                });
                originalAdd.call(this, e, data);
            }
        },

        processActions: {
            /*
            log: function (data, options) {
                console[options.type](
                    'Processing "' + data.files[data.index].name + '"'
                );
            }
            */
        },

        _processFile: function (data, originalData) {
            var that = this,
                dfd = $.Deferred().resolveWith(that, [data]),
                chain = dfd.promise();
            this._trigger('process', null, data);
            $.each(data.processQueue, function (i, settings) {
                var func = function (data) {
                    if (originalData.errorThrown) {
                        return $.Deferred()
                                .rejectWith(that, [originalData]).promise();
                    }
                    return that.processActions[settings.action].call(
                        that,
                        data,
                        settings
                    );
                };
                chain = chain.then(func, settings.always && func);
            });
            chain
                .done(function () {
                    that._trigger('processdone', null, data);
                    that._trigger('processalways', null, data);
                })
                .fail(function () {
                    that._trigger('processfail', null, data);
                    that._trigger('processalways', null, data);
                });
            return chain;
        },

        // Replaces the settings of each processQueue item that
        // are strings starting with an "@", using the remaining
        // substring as key for the option map,
        // e.g. "@autoUpload" is replaced with options.autoUpload:
        _transformProcessQueue: function (options) {
            var processQueue = [];
            $.each(options.processQueue, function () {
                var settings = {},
                    action = this.action,
                    prefix = this.prefix === true ? action : this.prefix;
                $.each(this, function (key, value) {
                    if ($.type(value) === 'string' &&
                            value.charAt(0) === '@') {
                        settings[key] = options[
                            value.slice(1) || (prefix ? prefix +
                                key.charAt(0).toUpperCase() + key.slice(1) : key)
                        ];
                    } else {
                        settings[key] = value;
                    }

                });
                processQueue.push(settings);
            });
            options.processQueue = processQueue;
        },

        // Returns the number of files currently in the processsing queue:
        processing: function () {
            return this._processing;
        },

        // Processes the files given as files property of the data parameter,
        // returns a Promise object that allows to bind callbacks:
        process: function (data) {
            var that = this,
                options = $.extend({}, this.options, data);
            if (options.processQueue && options.processQueue.length) {
                this._transformProcessQueue(options);
                if (this._processing === 0) {
                    this._trigger('processstart');
                }
                $.each(data.files, function (index) {
                    var opts = index ? $.extend({}, options) : options,
                        func = function () {
                            if (data.errorThrown) {
                                return $.Deferred()
                                        .rejectWith(that, [data]).promise();
                            }
                            return that._processFile(opts, data);
                        };
                    opts.index = index;
                    that._processing += 1;
                    that._processingQueue = that._processingQueue.then(func, func)
                        .always(function () {
                            that._processing -= 1;
                            if (that._processing === 0) {
                                that._trigger('processstop');
                            }
                        });
                });
            }
            return this._processingQueue;
        },

        _create: function () {
            this._super();
            this._processing = 0;
            this._processingQueue = $.Deferred().resolveWith(this)
                .promise();
        }

    });

}));
;

/** jQuery File Upload (IMG) **/
(window.defineModule = (window.defineModule || {})).name = 'jQuery File Upload (IMG)';
/*
 * jQuery File Upload Image Preview & Resize Plugin
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2013, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* jshint nomen:false */
/* global define, require, window, Blob */

;(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'load-image',
            'load-image-meta',
            'load-image-exif',
            'canvas-to-blob',
            './jquery.fileupload-process'
        ], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS:
        factory(
            require('jquery'),
            require('blueimp-load-image/js/load-image'),
            require('blueimp-load-image/js/load-image-meta'),
            require('blueimp-load-image/js/load-image-exif'),
            require('blueimp-canvas-to-blob'),
            require('./jquery.fileupload-process')
        );
    } else {
        // Browser globals:
        factory(
            window.jQuery,
            window.loadImage
        );
    }
}(function ($, loadImage) {
    'use strict';

    // Prepend to the default processQueue:
    $.blueimp.fileupload.prototype.options.processQueue.unshift(
        {
            action: 'loadImageMetaData',
            disableImageHead: '@',
            disableExif: '@',
            disableExifThumbnail: '@',
            disableExifSub: '@',
            disableExifGps: '@',
            disabled: '@disableImageMetaDataLoad'
        },
        {
            action: 'loadImage',
            // Use the action as prefix for the "@" options:
            prefix: true,
            fileTypes: '@',
            maxFileSize: '@',
            noRevoke: '@',
            disabled: '@disableImageLoad'
        },
        {
            action: 'resizeImage',
            // Use "image" as prefix for the "@" options:
            prefix: 'image',
            maxWidth: '@',
            maxHeight: '@',
            minWidth: '@',
            minHeight: '@',
            crop: '@',
            orientation: '@',
            forceResize: '@',
            disabled: '@disableImageResize'
        },
        {
            action: 'saveImage',
            quality: '@imageQuality',
            type: '@imageType',
            disabled: '@disableImageResize'
        },
        {
            action: 'saveImageMetaData',
            disabled: '@disableImageMetaDataSave'
        },
        {
            action: 'resizeImage',
            // Use "preview" as prefix for the "@" options:
            prefix: 'preview',
            maxWidth: '@',
            maxHeight: '@',
            minWidth: '@',
            minHeight: '@',
            crop: '@',
            orientation: '@',
            thumbnail: '@',
            canvas: '@',
            disabled: '@disableImagePreview'
        },
        {
            action: 'setImage',
            name: '@imagePreviewName',
            disabled: '@disableImagePreview'
        },
        {
            action: 'deleteImageReferences',
            disabled: '@disableImageReferencesDeletion'
        }
    );

    // The File Upload Resize plugin extends the fileupload widget
    // with image resize functionality:
    $.widget('blueimp.fileupload', $.blueimp.fileupload, {

        options: {
            // The regular expression for the types of images to load:
            // matched against the file type:
            loadImageFileTypes: /^image\/(gif|jpeg|png|svg\+xml)$/,
            // The maximum file size of images to load:
            loadImageMaxFileSize: 10000000, // 10MB
            // The maximum width of resized images:
            imageMaxWidth: 1920,
            // The maximum height of resized images:
            imageMaxHeight: 1080,
            // Defines the image orientation (1-8) or takes the orientation
            // value from Exif data if set to true:
            imageOrientation: false,
            // Define if resized images should be cropped or only scaled:
            imageCrop: false,
            // Disable the resize image functionality by default:
            disableImageResize: true,
            // The maximum width of the preview images:
            previewMaxWidth: 80,
            // The maximum height of the preview images:
            previewMaxHeight: 80,
            // Defines the preview orientation (1-8) or takes the orientation
            // value from Exif data if set to true:
            previewOrientation: true,
            // Create the preview using the Exif data thumbnail:
            previewThumbnail: true,
            // Define if preview images should be cropped or only scaled:
            previewCrop: false,
            // Define if preview images should be resized as canvas elements:
            previewCanvas: true
        },

        processActions: {

            // Loads the image given via data.files and data.index
            // as img element, if the browser supports the File API.
            // Accepts the options fileTypes (regular expression)
            // and maxFileSize (integer) to limit the files to load:
            loadImage: function (data, options) {
                if (options.disabled) {
                    return data;
                }
                var that = this,
                    file = data.files[data.index],
                    dfd = $.Deferred();
                if (($.type(options.maxFileSize) === 'number' &&
                            file.size > options.maxFileSize) ||
                        (options.fileTypes &&
                            !options.fileTypes.test(file.type)) ||
                        !loadImage(
                            file,
                            function (img) {
                                if (img.src) {
                                    data.img = img;
                                }
                                dfd.resolveWith(that, [data]);
                            },
                            options
                        )) {
                    return data;
                }
                return dfd.promise();
            },

            // Resizes the image given as data.canvas or data.img
            // and updates data.canvas or data.img with the resized image.
            // Also stores the resized image as preview property.
            // Accepts the options maxWidth, maxHeight, minWidth,
            // minHeight, canvas and crop:
            resizeImage: function (data, options) {
                if (options.disabled || !(data.canvas || data.img)) {
                    return data;
                }
                options = $.extend({canvas: true}, options);
                var that = this,
                    dfd = $.Deferred(),
                    img = (options.canvas && data.canvas) || data.img,
                    resolve = function (newImg) {
                        if (newImg && (newImg.width !== img.width ||
                                newImg.height !== img.height ||
                                options.forceResize)) {
                            data[newImg.getContext ? 'canvas' : 'img'] = newImg;
                        }
                        data.preview = newImg;
                        dfd.resolveWith(that, [data]);
                    },
                    thumbnail;
                if (data.exif) {
                    if (options.orientation === true) {
                        options.orientation = data.exif.get('Orientation');
                    }
                    if (options.thumbnail) {
                        thumbnail = data.exif.get('Thumbnail');
                        if (thumbnail) {
                            loadImage(thumbnail, resolve, options);
                            return dfd.promise();
                        }
                    }
                    // Prevent orienting the same image twice:
                    if (data.orientation) {
                        delete options.orientation;
                    } else {
                        data.orientation = options.orientation;
                    }
                }
                if (img) {
                    resolve(loadImage.scale(img, options));
                    return dfd.promise();
                }
                return data;
            },

            // Saves the processed image given as data.canvas
            // inplace at data.index of data.files:
            saveImage: function (data, options) {
                if (!data.canvas || options.disabled) {
                    return data;
                }
                var that = this,
                    file = data.files[data.index],
                    dfd = $.Deferred();
                if (data.canvas.toBlob) {
                    data.canvas.toBlob(
                        function (blob) {
                            if (!blob.name) {
                                if (file.type === blob.type) {
                                    blob.name = file.name;
                                } else if (file.name) {
                                    blob.name = file.name.replace(
                                        /\.\w+$/,
                                        '.' + blob.type.substr(6)
                                    );
                                }
                            }
                            // Don't restore invalid meta data:
                            if (file.type !== blob.type) {
                                delete data.imageHead;
                            }
                            // Store the created blob at the position
                            // of the original file in the files list:
                            data.files[data.index] = blob;
                            dfd.resolveWith(that, [data]);
                        },
                        options.type || file.type,
                        options.quality
                    );
                } else {
                    return data;
                }
                return dfd.promise();
            },

            loadImageMetaData: function (data, options) {
                if (options.disabled) {
                    return data;
                }
                var that = this,
                    dfd = $.Deferred();
                loadImage.parseMetaData(data.files[data.index], function (result) {
                    $.extend(data, result);
                    dfd.resolveWith(that, [data]);
                }, options);
                return dfd.promise();
            },

            saveImageMetaData: function (data, options) {
                if (!(data.imageHead && data.canvas &&
                        data.canvas.toBlob && !options.disabled)) {
                    return data;
                }
                var file = data.files[data.index],
                    blob = new Blob([
                        data.imageHead,
                        // Resized images always have a head size of 20 bytes,
                        // including the JPEG marker and a minimal JFIF header:
                        this._blobSlice.call(file, 20)
                    ], {type: file.type});
                blob.name = file.name;
                data.files[data.index] = blob;
                return data;
            },

            // Sets the resized version of the image as a property of the
            // file object, must be called after "saveImage":
            setImage: function (data, options) {
                if (data.preview && !options.disabled) {
                    data.files[data.index][options.name || 'preview'] = data.preview;
                }
                return data;
            },

            deleteImageReferences: function (data, options) {
                if (!options.disabled) {
                    delete data.img;
                    delete data.canvas;
                    delete data.preview;
                    delete data.imageHead;
                }
                return data;
            }

        }

    });

}));
;

/** Auto Scale Uploaded Image **/
(window.defineModule = (window.defineModule || {})).name = 'Auto Scale Uploaded Image';
(function(win) {
	var originalScale = window.loadImage.scale;

	/**
	 * Wrapper for scale() method of jQuery Load Image library.
	 * @param {HTMLElement} img
	 * @param {object} options
	 * @return {HTMLElement}
	 */
	window.loadImage.scale = function (img, options) {
		if( ('action' in options) && ('imageType' in options) && wb_builder.maxUploadImageSize && wb_builder.maxUploadImageFileSize && options.action == 'resizeImage' ) {
			if( options.imageType == 'image/gif' || options.imageType == 'image/svg' || options.imageType == 'image/svg+xml' )
				return img;
			var w = img.naturalWidth || img.width;
			var h = img.naturalHeight || img.height;
			if( w && h ) {
				if( !options.imageQuality )
					options.imageQuality = 100;
				var maxPixels = wb_builder.maxUploadImageSize, maxWidth, maxHeight, newImg;
				for( var i = 0; i < 5; i++ ) {
					maxHeight = Math.sqrt(h * maxPixels / w);
					maxWidth = w * maxHeight / h;
					options.maxWidth = Math.floor(maxWidth);
					options.maxHeight = Math.floor(maxHeight);
					options.cover = w > options.maxWidth || h > options.maxHeight;
					if( options.maxWidth >= w || options.maxHeight >= h ) {
						options.maxWidth = w;
						options.maxHeight = h;
						options.forceResize = true;
					}

					newImg = originalScale.apply(this, arguments);
					var size;
					if( typeof newImg.toDataURL == 'function' ) {
						size = newImg.toDataURL(options.imageType, options.imageQuality).length * 0.75; // base64 encoded string is 33% bigger than binary.
						size *= 1.1; // add extra 10%
					}
					else
						break;

					if( size <= wb_builder.maxUploadImageFileSize )
						break;
					maxPixels *= wb_builder.maxUploadImageFileSize / size;
				}
				return newImg;
			}

			options.maxWidth = 1920;
			options.maxHeight = 1080;
			options.cover = false;
		}
		return originalScale.apply(this, arguments);
	};

	/**
	 * This method must be used as a "fileuploadprocess" event handler in order for automatic resizing to work.
	 * @param {Event} e
	 * @param {object} data
	 */
	win.prepareAutoScaleOptions = function(e, data) {
		// find out image quality
		var imageQuality;
		var imageType = data.files[0].type;
		$.each(data.processQueue, function(i, options) {
			if( options.action == 'saveImage' && !options.action.disabled ) {
				imageQuality = options.quality;
				imageType = options.type || imageType;
				return false; // break
			}
		});
		// add additional options required by wrapper to resize the image automatically
		$.each(data.processQueue, function(i, options) {
			if( options.action == 'resizeImage' && !options.action.disabled ) {
				options.imageType = imageType;
				options.imageQuality = imageQuality;
				return false; // break
			}
		});
	};
})(window);
;

/** CKEitor **/
(window.defineModule = (window.defineModule || {})).name = 'CKEitor';
﻿/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
(function(){if(window.CKEDITOR&&window.CKEDITOR.dom)return;window.CKEDITOR||(window.CKEDITOR=function(){var a=/(^|.*[\\\/])ckeditor\.js(?:\?.*|;.*)?$/i,d={timestamp:"I8BG",version:"4.10.1",revision:"59246e9",rnd:Math.floor(900*Math.random())+100,_:{pending:[],basePathSrcPattern:a},status:"unloaded",basePath:function(){var b=window.CKEDITOR_BASEPATH||"";if(!b)for(var c=document.getElementsByTagName("script"),d=0;d<c.length;d++){var g=c[d].src.match(a);if(g){b=g[1];break}}-1==b.indexOf(":/")&&"//"!=b.slice(0,2)&&(b=0===b.indexOf("/")?location.href.match(/^.*?:\/\/[^\/]*/)[0]+
b:location.href.match(/^[^\?]*\/(?:)/)[0]+b);if(!b)throw'The CKEditor installation path could not be automatically detected. Please set the global variable "CKEDITOR_BASEPATH" before creating editor instances.';return b}(),getUrl:function(a){-1==a.indexOf(":/")&&0!==a.indexOf("/")&&(a=this.basePath+a);this.timestamp&&"/"!=a.charAt(a.length-1)&&!/[&?]t=/.test(a)&&(a+=(0<=a.indexOf("?")?"\x26":"?")+"t\x3d"+this.timestamp);return a},domReady:function(){function a(){try{document.addEventListener?(document.removeEventListener("DOMContentLoaded",
a,!1),b()):document.attachEvent&&"complete"===document.readyState&&(document.detachEvent("onreadystatechange",a),b())}catch(c){}}function b(){for(var a;a=c.shift();)a()}var c=[];return function(b){function n(){try{document.documentElement.doScroll("left")}catch(e){setTimeout(n,1);return}a()}c.push(b);"complete"===document.readyState&&setTimeout(a,1);if(1==c.length)if(document.addEventListener)document.addEventListener("DOMContentLoaded",a,!1),window.addEventListener("load",a,!1);else if(document.attachEvent){document.attachEvent("onreadystatechange",
a);window.attachEvent("onload",a);b=!1;try{b=!window.frameElement}catch(r){}document.documentElement.doScroll&&b&&n()}}}()},b=window.CKEDITOR_GETURL;if(b){var c=d.getUrl;d.getUrl=function(a){return b.call(d,a)||c.call(d,a)}}return d}());
CKEDITOR.event||(CKEDITOR.event=function(){},CKEDITOR.event.implementOn=function(a){var d=CKEDITOR.event.prototype,b;for(b in d)null==a[b]&&(a[b]=d[b])},CKEDITOR.event.prototype=function(){function a(a){var f=d(this);return f[a]||(f[a]=new b(a))}var d=function(a){a=a.getPrivate&&a.getPrivate()||a._||(a._={});return a.events||(a.events={})},b=function(a){this.name=a;this.listeners=[]};b.prototype={getListenerIndex:function(a){for(var b=0,d=this.listeners;b<d.length;b++)if(d[b].fn==a)return b;return-1}};
return{define:function(b,d){var h=a.call(this,b);CKEDITOR.tools.extend(h,d,!0)},on:function(b,d,h,k,g){function n(e,a,y,v){e={name:b,sender:this,editor:e,data:a,listenerData:k,stop:y,cancel:v,removeListener:r};return!1===d.call(h,e)?!1:e.data}function r(){y.removeListener(b,d)}var e=a.call(this,b);if(0>e.getListenerIndex(d)){e=e.listeners;h||(h=this);isNaN(g)&&(g=10);var y=this;n.fn=d;n.priority=g;for(var v=e.length-1;0<=v;v--)if(e[v].priority<=g)return e.splice(v+1,0,n),{removeListener:r};e.unshift(n)}return{removeListener:r}},
once:function(){var a=Array.prototype.slice.call(arguments),b=a[1];a[1]=function(a){a.removeListener();return b.apply(this,arguments)};return this.on.apply(this,a)},capture:function(){CKEDITOR.event.useCapture=1;var a=this.on.apply(this,arguments);CKEDITOR.event.useCapture=0;return a},fire:function(){var a=0,b=function(){a=1},h=0,k=function(){h=1};return function(g,n,r){var e=d(this)[g];g=a;var y=h;a=h=0;if(e){var v=e.listeners;if(v.length)for(var v=v.slice(0),B,D=0;D<v.length;D++){if(e.errorProof)try{B=
v[D].call(this,r,n,b,k)}catch(x){}else B=v[D].call(this,r,n,b,k);!1===B?h=1:"undefined"!=typeof B&&(n=B);if(a||h)break}}n=h?!1:"undefined"==typeof n?!0:n;a=g;h=y;return n}}(),fireOnce:function(a,b,h){b=this.fire(a,b,h);delete d(this)[a];return b},removeListener:function(a,b){var h=d(this)[a];if(h){var k=h.getListenerIndex(b);0<=k&&h.listeners.splice(k,1)}},removeAllListeners:function(){var a=d(this),b;for(b in a)delete a[b]},hasListeners:function(a){return(a=d(this)[a])&&0<a.listeners.length}}}());
CKEDITOR.editor||(CKEDITOR.editor=function(){CKEDITOR._.pending.push([this,arguments]);CKEDITOR.event.call(this)},CKEDITOR.editor.prototype.fire=function(a,d){a in{instanceReady:1,loaded:1}&&(this[a]=!0);return CKEDITOR.event.prototype.fire.call(this,a,d,this)},CKEDITOR.editor.prototype.fireOnce=function(a,d){a in{instanceReady:1,loaded:1}&&(this[a]=!0);return CKEDITOR.event.prototype.fireOnce.call(this,a,d,this)},CKEDITOR.event.implementOn(CKEDITOR.editor.prototype));
CKEDITOR.env||(CKEDITOR.env=function(){var a=navigator.userAgent.toLowerCase(),d=a.match(/edge[ \/](\d+.?\d*)/),b=-1<a.indexOf("trident/"),b=!(!d&&!b),b={ie:b,edge:!!d,webkit:!b&&-1<a.indexOf(" applewebkit/"),air:-1<a.indexOf(" adobeair/"),mac:-1<a.indexOf("macintosh"),quirks:"BackCompat"==document.compatMode&&(!document.documentMode||10>document.documentMode),mobile:-1<a.indexOf("mobile"),iOS:/(ipad|iphone|ipod)/.test(a),isCustomDomain:function(){if(!this.ie)return!1;var a=document.domain,b=window.location.hostname;
return a!=b&&a!="["+b+"]"},secure:"https:"==location.protocol};b.gecko="Gecko"==navigator.product&&!b.webkit&&!b.ie;b.webkit&&(-1<a.indexOf("chrome")?b.chrome=!0:b.safari=!0);var c=0;b.ie&&(c=d?parseFloat(d[1]):b.quirks||!document.documentMode?parseFloat((a.match(/msie (\d+)/))&&RegExp.$1?RegExp.$1:0):document.documentMode,b.ie9Compat=9==c,b.ie8Compat=8==c,b.ie7Compat=7==c,b.ie6Compat=7>c||b.quirks);b.gecko&&(d=a.match(/rv:([\d\.]+)/))&&(d=d[1].split("."),c=1E4*d[0]+100*(d[1]||0)+1*(d[2]||0));b.air&&(c=parseFloat(a.match(/ adobeair\/(\d+)/)[1]));
b.webkit&&(c=parseFloat(a.match(/ applewebkit\/(\d+)/)[1]));b.version=c;b.isCompatible=!(b.ie&&7>c)&&!(b.gecko&&4E4>c)&&!(b.webkit&&534>c);b.hidpi=2<=window.devicePixelRatio;b.needsBrFiller=b.gecko||b.webkit||b.ie&&10<c;b.needsNbspFiller=b.ie&&11>c;b.cssClass="cke_browser_"+(b.ie?"ie":b.gecko?"gecko":b.webkit?"webkit":"unknown");b.quirks&&(b.cssClass+=" cke_browser_quirks");b.ie&&(b.cssClass+=" cke_browser_ie"+(b.quirks?"6 cke_browser_iequirks":b.version));b.air&&(b.cssClass+=" cke_browser_air");
b.iOS&&(b.cssClass+=" cke_browser_ios");b.hidpi&&(b.cssClass+=" cke_hidpi");return b}());
"unloaded"==CKEDITOR.status&&function(){CKEDITOR.event.implementOn(CKEDITOR);CKEDITOR.loadFullCore=function(){if("basic_ready"!=CKEDITOR.status)CKEDITOR.loadFullCore._load=1;else{delete CKEDITOR.loadFullCore;var a=document.createElement("script");a.type="text/javascript";a.src=CKEDITOR.basePath+"ckeditor.js";document.getElementsByTagName("head")[0].appendChild(a)}};CKEDITOR.loadFullCoreTimeout=0;CKEDITOR.add=function(a){(this._.pending||(this._.pending=[])).push(a)};(function(){CKEDITOR.domReady(function(){var a=
CKEDITOR.loadFullCore,d=CKEDITOR.loadFullCoreTimeout;a&&(CKEDITOR.status="basic_ready",a&&a._load?a():d&&setTimeout(function(){CKEDITOR.loadFullCore&&CKEDITOR.loadFullCore()},1E3*d))})})();CKEDITOR.status="basic_loaded"}();"use strict";CKEDITOR.VERBOSITY_WARN=1;CKEDITOR.VERBOSITY_ERROR=2;CKEDITOR.verbosity=CKEDITOR.VERBOSITY_WARN|CKEDITOR.VERBOSITY_ERROR;CKEDITOR.warn=function(a,d){CKEDITOR.verbosity&CKEDITOR.VERBOSITY_WARN&&CKEDITOR.fire("log",{type:"warn",errorCode:a,additionalData:d})};
CKEDITOR.error=function(a,d){CKEDITOR.verbosity&CKEDITOR.VERBOSITY_ERROR&&CKEDITOR.fire("log",{type:"error",errorCode:a,additionalData:d})};
CKEDITOR.on("log",function(a){if(window.console&&window.console.log){var d=console[a.data.type]?a.data.type:"log",b=a.data.errorCode;if(a=a.data.additionalData)console[d]("[CKEDITOR] Error code: "+b+".",a);else console[d]("[CKEDITOR] Error code: "+b+".");console[d]("[CKEDITOR] For more information about this error go to https://ckeditor.com/docs/ckeditor4/latest/guide/dev_errors.html#"+b)}},null,null,999);CKEDITOR.dom={};
(function(){var a=[],d=CKEDITOR.env.gecko?"-moz-":CKEDITOR.env.webkit?"-webkit-":CKEDITOR.env.ie?"-ms-":"",b=/&/g,c=/>/g,f=/</g,h=/"/g,k=/&(lt|gt|amp|quot|nbsp|shy|#\d{1,5});/g,g={lt:"\x3c",gt:"\x3e",amp:"\x26",quot:'"',nbsp:" ",shy:"­"},n=function(a,e){return"#"==e[0]?String.fromCharCode(parseInt(e.slice(1),10)):g[e]};CKEDITOR.on("reset",function(){a=[]});CKEDITOR.tools={arrayCompare:function(a,e){if(!a&&!e)return!0;if(!a||!e||a.length!=e.length)return!1;for(var b=0;b<a.length;b++)if(a[b]!=e[b])return!1;
return!0},getIndex:function(a,e){for(var b=0;b<a.length;++b)if(e(a[b]))return b;return-1},clone:function(a){var e;if(a&&a instanceof Array){e=[];for(var b=0;b<a.length;b++)e[b]=CKEDITOR.tools.clone(a[b]);return e}if(null===a||"object"!=typeof a||a instanceof String||a instanceof Number||a instanceof Boolean||a instanceof Date||a instanceof RegExp||a.nodeType||a.window===a)return a;e=new a.constructor;for(b in a)e[b]=CKEDITOR.tools.clone(a[b]);return e},capitalize:function(a,e){return a.charAt(0).toUpperCase()+
(e?a.slice(1):a.slice(1).toLowerCase())},extend:function(a){var e=arguments.length,b,v;"boolean"==typeof(b=arguments[e-1])?e--:"boolean"==typeof(b=arguments[e-2])&&(v=arguments[e-1],e-=2);for(var c=1;c<e;c++){var g=arguments[c],d;for(d in g)if(!0===b||null==a[d])if(!v||d in v)a[d]=g[d]}return a},prototypedCopy:function(a){var e=function(){};e.prototype=a;return new e},copy:function(a){var e={},b;for(b in a)e[b]=a[b];return e},isArray:function(a){return"[object Array]"==Object.prototype.toString.call(a)},
isEmpty:function(a){for(var e in a)if(a.hasOwnProperty(e))return!1;return!0},cssVendorPrefix:function(a,e,b){if(b)return d+a+":"+e+";"+a+":"+e;b={};b[a]=e;b[d+a]=e;return b},cssStyleToDomStyle:function(){var a=document.createElement("div").style,e="undefined"!=typeof a.cssFloat?"cssFloat":"undefined"!=typeof a.styleFloat?"styleFloat":"float";return function(a){return"float"==a?e:a.replace(/-./g,function(a){return a.substr(1).toUpperCase()})}}(),buildStyleHtml:function(a){a=[].concat(a);for(var e,
b=[],v=0;v<a.length;v++)if(e=a[v])/@import|[{}]/.test(e)?b.push("\x3cstyle\x3e"+e+"\x3c/style\x3e"):b.push('\x3clink type\x3d"text/css" rel\x3dstylesheet href\x3d"'+e+'"\x3e');return b.join("")},htmlEncode:function(a){return void 0===a||null===a?"":String(a).replace(b,"\x26amp;").replace(c,"\x26gt;").replace(f,"\x26lt;")},htmlDecode:function(a){return a.replace(k,n)},htmlEncodeAttr:function(a){return CKEDITOR.tools.htmlEncode(a).replace(h,"\x26quot;")},htmlDecodeAttr:function(a){return CKEDITOR.tools.htmlDecode(a)},
transformPlainTextToHtml:function(a,e){var b=e==CKEDITOR.ENTER_BR,v=this.htmlEncode(a.replace(/\r\n/g,"\n")),v=v.replace(/\t/g,"\x26nbsp;\x26nbsp; \x26nbsp;"),c=e==CKEDITOR.ENTER_P?"p":"div";if(!b){var g=/\n{2}/g;if(g.test(v))var d="\x3c"+c+"\x3e",m="\x3c/"+c+"\x3e",v=d+v.replace(g,function(){return m+d})+m}v=v.replace(/\n/g,"\x3cbr\x3e");b||(v=v.replace(new RegExp("\x3cbr\x3e(?\x3d\x3c/"+c+"\x3e)"),function(a){return CKEDITOR.tools.repeat(a,2)}));v=v.replace(/^ | $/g,"\x26nbsp;");return v=v.replace(/(>|\s) /g,
function(a,e){return e+"\x26nbsp;"}).replace(/ (?=<)/g,"\x26nbsp;")},getNextNumber:function(){var a=0;return function(){return++a}}(),getNextId:function(){return"cke_"+this.getNextNumber()},getUniqueId:function(){for(var a="e",e=0;8>e;e++)a+=Math.floor(65536*(1+Math.random())).toString(16).substring(1);return a},override:function(a,e){var b=e(a);b.prototype=a.prototype;return b},setTimeout:function(a,e,b,c,g){g||(g=window);b||(b=g);return g.setTimeout(function(){c?a.apply(b,[].concat(c)):a.apply(b)},
e||0)},throttle:function(a,e,b){var c,g=0;b=b||{};return{input:function(){function d(){g=(new Date).getTime();c=!1;e.apply(b,n)}var n=Array.prototype.slice.call(arguments);c&&(clearTimeout(c),c=0);var m=(new Date).getTime()-g;m<a?c=setTimeout(d,a-m):d()},reset:function(){c&&(clearTimeout(c),c=g=0)}}},trim:function(){var a=/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g;return function(e){return e.replace(a,"")}}(),ltrim:function(){var a=/^[ \t\n\r]+/g;return function(e){return e.replace(a,"")}}(),rtrim:function(){var a=
/[ \t\n\r]+$/g;return function(e){return e.replace(a,"")}}(),indexOf:function(a,e){if("function"==typeof e)for(var b=0,c=a.length;b<c;b++){if(e(a[b]))return b}else{if(a.indexOf)return a.indexOf(e);b=0;for(c=a.length;b<c;b++)if(a[b]===e)return b}return-1},search:function(a,e){var b=CKEDITOR.tools.indexOf(a,e);return 0<=b?a[b]:null},bind:function(a,e){return function(){return a.apply(e,arguments)}},createClass:function(a){var e=a.$,b=a.base,c=a.privates||a._,g=a.proto;a=a.statics;!e&&(e=function(){b&&
this.base.apply(this,arguments)});if(c)var d=e,e=function(){var a=this._||(this._={}),e;for(e in c){var b=c[e];a[e]="function"==typeof b?CKEDITOR.tools.bind(b,this):b}d.apply(this,arguments)};b&&(e.prototype=this.prototypedCopy(b.prototype),e.prototype.constructor=e,e.base=b,e.baseProto=b.prototype,e.prototype.base=function(){this.base=b.prototype.base;b.apply(this,arguments);this.base=arguments.callee});g&&this.extend(e.prototype,g,!0);a&&this.extend(e,a,!0);return e},addFunction:function(b,e){return a.push(function(){return b.apply(e||
this,arguments)})-1},removeFunction:function(b){a[b]=null},callFunction:function(b){var e=a[b];return e&&e.apply(window,Array.prototype.slice.call(arguments,1))},cssLength:function(){var a=/^-?\d+\.?\d*px$/,e;return function(b){e=CKEDITOR.tools.trim(b+"")+"px";return a.test(e)?e:b||""}}(),convertToPx:function(){var a;return function(e){a||(a=CKEDITOR.dom.element.createFromHtml('\x3cdiv style\x3d"position:absolute;left:-9999px;top:-9999px;margin:0px;padding:0px;border:0px;"\x3e\x3c/div\x3e',CKEDITOR.document),
CKEDITOR.document.getBody().append(a));return/%$/.test(e)?e:(a.setStyle("width",e),a.$.clientWidth)}}(),repeat:function(a,e){return Array(e+1).join(a)},tryThese:function(){for(var a,e=0,b=arguments.length;e<b;e++){var c=arguments[e];try{a=c();break}catch(g){}}return a},genKey:function(){return Array.prototype.slice.call(arguments).join("-")},defer:function(a){return function(){var e=arguments,b=this;window.setTimeout(function(){a.apply(b,e)},0)}},normalizeCssText:function(a,e){var b=[],c,g=CKEDITOR.tools.parseCssText(a,
!0,e);for(c in g)b.push(c+":"+g[c]);b.sort();return b.length?b.join(";")+";":""},convertRgbToHex:function(a){return a.replace(/(?:rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\))/gi,function(a,b,c,g){a=[b,c,g];for(b=0;3>b;b++)a[b]=("0"+parseInt(a[b],10).toString(16)).slice(-2);return"#"+a.join("")})},normalizeHex:function(a){return a.replace(/#(([0-9a-f]{3}){1,2})($|;|\s+)/gi,function(a,b,c,g){a=b.toLowerCase();3==a.length&&(a=a.split(""),a=[a[0],a[0],a[1],a[1],a[2],a[2]].join(""));return"#"+a+g})},parseCssText:function(a,
e,b){var c={};b&&(a=(new CKEDITOR.dom.element("span")).setAttribute("style",a).getAttribute("style")||"");a&&(a=CKEDITOR.tools.normalizeHex(CKEDITOR.tools.convertRgbToHex(a)));if(!a||";"==a)return c;a.replace(/&quot;/g,'"').replace(/\s*([^:;\s]+)\s*:\s*([^;]+)\s*(?=;|$)/g,function(a,b,g){e&&(b=b.toLowerCase(),"font-family"==b&&(g=g.replace(/\s*,\s*/g,",")),g=CKEDITOR.tools.trim(g));c[b]=g});return c},writeCssText:function(a,e){var b,c=[];for(b in a)c.push(b+":"+a[b]);e&&c.sort();return c.join("; ")},
objectCompare:function(a,e,b){var c;if(!a&&!e)return!0;if(!a||!e)return!1;for(c in a)if(a[c]!=e[c])return!1;if(!b)for(c in e)if(a[c]!=e[c])return!1;return!0},objectKeys:function(a){var e=[],b;for(b in a)e.push(b);return e},convertArrayToObject:function(a,e){var b={};1==arguments.length&&(e=!0);for(var c=0,g=a.length;c<g;++c)b[a[c]]=e;return b},fixDomain:function(){for(var a;;)try{a=window.parent.document.domain;break}catch(e){a=a?a.replace(/.+?(?:\.|$)/,""):document.domain;if(!a)break;document.domain=
a}return!!a},eventsBuffer:function(a,e,b){function c(){d=(new Date).getTime();g=!1;b?e.call(b):e()}var g,d=0;return{input:function(){if(!g){var e=(new Date).getTime()-d;e<a?g=setTimeout(c,a-e):c()}},reset:function(){g&&clearTimeout(g);g=d=0}}},enableHtml5Elements:function(a,e){for(var b="abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video".split(" "),c=b.length,g;c--;)g=a.createElement(b[c]),
e&&a.appendChild(g)},checkIfAnyArrayItemMatches:function(a,e){for(var b=0,c=a.length;b<c;++b)if(a[b].match(e))return!0;return!1},checkIfAnyObjectPropertyMatches:function(a,e){for(var b in a)if(b.match(e))return!0;return!1},keystrokeToString:function(a,e){var b=this.keystrokeToArray(a,e);b.display=b.display.join("+");b.aria=b.aria.join("+");return b},keystrokeToArray:function(a,e){var b=e&16711680,c=e&65535,g=CKEDITOR.env.mac,d=[],n=[];b&CKEDITOR.CTRL&&(d.push(g?"⌘":a[17]),n.push(g?a[224]:a[17]));
b&CKEDITOR.ALT&&(d.push(g?"⌥":a[18]),n.push(a[18]));b&CKEDITOR.SHIFT&&(d.push(g?"⇧":a[16]),n.push(a[16]));c&&(a[c]?(d.push(a[c]),n.push(a[c])):(d.push(String.fromCharCode(c)),n.push(String.fromCharCode(c))));return{display:d,aria:n}},transparentImageData:"data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw\x3d\x3d",getCookie:function(a){a=a.toLowerCase();for(var e=document.cookie.split(";"),b,c,g=0;g<e.length;g++)if(b=e[g].split("\x3d"),c=decodeURIComponent(CKEDITOR.tools.trim(b[0]).toLowerCase()),
c===a)return decodeURIComponent(1<b.length?b[1]:"");return null},setCookie:function(a,e){document.cookie=encodeURIComponent(a)+"\x3d"+encodeURIComponent(e)+";path\x3d/"},getCsrfToken:function(){var a=CKEDITOR.tools.getCookie("ckCsrfToken");if(!a||40!=a.length){var a=[],e="";if(window.crypto&&window.crypto.getRandomValues)a=new Uint8Array(40),window.crypto.getRandomValues(a);else for(var b=0;40>b;b++)a.push(Math.floor(256*Math.random()));for(b=0;b<a.length;b++)var c="abcdefghijklmnopqrstuvwxyz0123456789".charAt(a[b]%
36),e=e+(.5<Math.random()?c.toUpperCase():c);a=e;CKEDITOR.tools.setCookie("ckCsrfToken",a)}return a},escapeCss:function(a){return a?window.CSS&&CSS.escape?CSS.escape(a):isNaN(parseInt(a.charAt(0),10))?a:"\\3"+a.charAt(0)+" "+a.substring(1,a.length):""},getMouseButton:function(a){var b=(a=a.data)&&a.$;return a&&b?CKEDITOR.env.ie&&9>CKEDITOR.env.version?4===b.button?CKEDITOR.MOUSE_BUTTON_MIDDLE:1===b.button?CKEDITOR.MOUSE_BUTTON_LEFT:CKEDITOR.MOUSE_BUTTON_RIGHT:b.button:!1},convertHexStringToBytes:function(a){var b=
[],c=a.length/2,g;for(g=0;g<c;g++)b.push(parseInt(a.substr(2*g,2),16));return b},convertBytesToBase64:function(a){var b="",c=a.length,g;for(g=0;g<c;g+=3){var d=a.slice(g,g+3),n=d.length,f=[],m;if(3>n)for(m=n;3>m;m++)d[m]=0;f[0]=(d[0]&252)>>2;f[1]=(d[0]&3)<<4|d[1]>>4;f[2]=(d[1]&15)<<2|(d[2]&192)>>6;f[3]=d[2]&63;for(m=0;4>m;m++)b=m<=n?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(f[m]):b+"\x3d"}return b},style:{parse:{_colors:{aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",
aqua:"#00FFFF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",blue:"#0000FF",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#00FFFF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgreen:"#006400",darkgrey:"#A9A9A9",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",
darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#FF00FF",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",
gray:"#808080",green:"#008000",greenyellow:"#ADFF2F",grey:"#808080",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgreen:"#90EE90",lightgrey:"#D3D3D3",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",
lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#00FF00",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",
navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#663399",red:"#FF0000",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",
sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFFFFF",whitesmoke:"#F5F5F5",yellow:"#FFFF00",yellowgreen:"#9ACD32"},_borderStyle:"none hidden dotted dashed solid double groove ridge inset outset".split(" "),_widthRegExp:/^(thin|medium|thick|[\+-]?\d+(\.\d+)?[a-z%]+|[\+-]?0+(\.0+)?|\.\d+[a-z%]+)$/,
_rgbaRegExp:/rgba?\(\s*\d+%?\s*,\s*\d+%?\s*,\s*\d+%?\s*(?:,\s*[0-9.]+\s*)?\)/gi,_hslaRegExp:/hsla?\(\s*[0-9.]+\s*,\s*\d+%\s*,\s*\d+%\s*(?:,\s*[0-9.]+\s*)?\)/gi,background:function(a){var b={},c=this._findColor(a);c.length&&(b.color=c[0],CKEDITOR.tools.array.forEach(c,function(b){a=a.replace(b,"")}));if(a=CKEDITOR.tools.trim(a))b.unprocessed=a;return b},margin:function(a){function b(a){c.top=g[a[0]];c.right=g[a[1]];c.bottom=g[a[2]];c.left=g[a[3]]}var c={},g=a.match(/(?:\-?[\.\d]+(?:%|\w*)|auto|inherit|initial|unset)/g)||
["0px"];switch(g.length){case 1:b([0,0,0,0]);break;case 2:b([0,1,0,1]);break;case 3:b([0,1,2,1]);break;case 4:b([0,1,2,3])}return c},border:function(a){var b={},c=a.split(/\s+/g);a=CKEDITOR.tools.style.parse._findColor(a);a.length&&(b.color=a[0]);CKEDITOR.tools.array.forEach(c,function(a){b.style||-1===CKEDITOR.tools.indexOf(CKEDITOR.tools.style.parse._borderStyle,a)?!b.width&&CKEDITOR.tools.style.parse._widthRegExp.test(a)&&(b.width=a):b.style=a});return b},_findColor:function(a){var b=[],c=CKEDITOR.tools.array,
b=b.concat(a.match(this._rgbaRegExp)||[]),b=b.concat(a.match(this._hslaRegExp)||[]);return b=b.concat(c.filter(a.split(/\s+/),function(a){return a.match(/^\#[a-f0-9]{3}(?:[a-f0-9]{3})?$/gi)?!0:a.toLowerCase()in CKEDITOR.tools.style.parse._colors}))}}},array:{filter:function(a,b,c){var g=[];this.forEach(a,function(d,n){b.call(c,d,n,a)&&g.push(d)});return g},forEach:function(a,b,c){var g=a.length,d;for(d=0;d<g;d++)b.call(c,a[d],d,a)},map:function(a,b,c){for(var g=[],d=0;d<a.length;d++)g.push(b.call(c,
a[d],d,a));return g},reduce:function(a,b,c,g){for(var d=0;d<a.length;d++)c=b.call(g,c,a[d],d,a);return c},every:function(a,b,c){if(!a.length)return!0;b=this.filter(a,b,c);return a.length===b.length}},object:{findKey:function(a,b){if("object"!==typeof a)return null;for(var c in a)if(a[c]===b)return c;return null},merge:function(a,b){var c=CKEDITOR.tools,g=c.clone(a),d=c.clone(b);c.array.forEach(c.objectKeys(d),function(a){g[a]="object"===typeof d[a]&&"object"===typeof g[a]?c.object.merge(g[a],d[a]):
d[a]});return g}},getAbsoluteRectPosition:function(a,b){function c(a){if(a){var b=a.getClientRect();g.top+=b.top;g.left+=b.left;"x"in g&&"y"in g&&(g.x+=b.x,g.y+=b.y);c(a.getWindow().getFrame())}}var g=CKEDITOR.tools.copy(b);c(a.getFrame());var d=CKEDITOR.document.getWindow().getScrollPosition();g.top+=d.y;g.left+=d.x;"x"in g&&"y"in g&&(g.y+=d.y,g.x+=d.x);g.right=g.left+g.width;g.bottom=g.top+g.height;return g}};CKEDITOR.tools.array.indexOf=CKEDITOR.tools.indexOf;CKEDITOR.tools.array.isArray=CKEDITOR.tools.isArray;
CKEDITOR.MOUSE_BUTTON_LEFT=0;CKEDITOR.MOUSE_BUTTON_MIDDLE=1;CKEDITOR.MOUSE_BUTTON_RIGHT=2})();
CKEDITOR.dtd=function(){var a=CKEDITOR.tools.extend,d=function(a,b){for(var c=CKEDITOR.tools.clone(a),g=1;g<arguments.length;g++){b=arguments[g];for(var d in b)delete c[d]}return c},b={},c={},f={address:1,article:1,aside:1,blockquote:1,details:1,div:1,dl:1,fieldset:1,figure:1,footer:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,header:1,hgroup:1,hr:1,main:1,menu:1,nav:1,ol:1,p:1,pre:1,section:1,table:1,ul:1},h={command:1,link:1,meta:1,noscript:1,script:1,style:1},k={},g={"#":1},n={center:1,dir:1,noframes:1};
a(b,{a:1,abbr:1,area:1,audio:1,b:1,bdi:1,bdo:1,br:1,button:1,canvas:1,cite:1,code:1,command:1,datalist:1,del:1,dfn:1,em:1,embed:1,i:1,iframe:1,img:1,input:1,ins:1,kbd:1,keygen:1,label:1,map:1,mark:1,meter:1,noscript:1,object:1,output:1,progress:1,q:1,ruby:1,s:1,samp:1,script:1,select:1,small:1,span:1,strong:1,sub:1,sup:1,textarea:1,time:1,u:1,"var":1,video:1,wbr:1},g,{acronym:1,applet:1,basefont:1,big:1,font:1,isindex:1,strike:1,style:1,tt:1});a(c,f,b,n);d={a:d(b,{a:1,button:1}),abbr:b,address:c,
area:k,article:c,aside:c,audio:a({source:1,track:1},c),b:b,base:k,bdi:b,bdo:b,blockquote:c,body:c,br:k,button:d(b,{a:1,button:1}),canvas:b,caption:c,cite:b,code:b,col:k,colgroup:{col:1},command:k,datalist:a({option:1},b),dd:c,del:b,details:a({summary:1},c),dfn:b,div:c,dl:{dt:1,dd:1},dt:c,em:b,embed:k,fieldset:a({legend:1},c),figcaption:c,figure:a({figcaption:1},c),footer:c,form:c,h1:b,h2:b,h3:b,h4:b,h5:b,h6:b,head:a({title:1,base:1},h),header:c,hgroup:{h1:1,h2:1,h3:1,h4:1,h5:1,h6:1},hr:k,html:a({head:1,
body:1},c,h),i:b,iframe:g,img:k,input:k,ins:b,kbd:b,keygen:k,label:b,legend:b,li:c,link:k,main:c,map:c,mark:b,menu:a({li:1},c),meta:k,meter:d(b,{meter:1}),nav:c,noscript:a({link:1,meta:1,style:1},b),object:a({param:1},b),ol:{li:1},optgroup:{option:1},option:g,output:b,p:b,param:k,pre:b,progress:d(b,{progress:1}),q:b,rp:b,rt:b,ruby:a({rp:1,rt:1},b),s:b,samp:b,script:g,section:c,select:{optgroup:1,option:1},small:b,source:k,span:b,strong:b,style:g,sub:b,summary:a({h1:1,h2:1,h3:1,h4:1,h5:1,h6:1},b),
sup:b,table:{caption:1,colgroup:1,thead:1,tfoot:1,tbody:1,tr:1},tbody:{tr:1},td:c,textarea:g,tfoot:{tr:1},th:c,thead:{tr:1},time:d(b,{time:1}),title:g,tr:{th:1,td:1},track:k,u:b,ul:{li:1},"var":b,video:a({source:1,track:1},c),wbr:k,acronym:b,applet:a({param:1},c),basefont:k,big:b,center:c,dialog:k,dir:{li:1},font:b,isindex:k,noframes:c,strike:b,tt:b};a(d,{$block:a({audio:1,dd:1,dt:1,figcaption:1,li:1,video:1},f,n),$blockLimit:{article:1,aside:1,audio:1,body:1,caption:1,details:1,dir:1,div:1,dl:1,
fieldset:1,figcaption:1,figure:1,footer:1,form:1,header:1,hgroup:1,main:1,menu:1,nav:1,ol:1,section:1,table:1,td:1,th:1,tr:1,ul:1,video:1},$cdata:{script:1,style:1},$editable:{address:1,article:1,aside:1,blockquote:1,body:1,details:1,div:1,fieldset:1,figcaption:1,footer:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,header:1,hgroup:1,main:1,nav:1,p:1,pre:1,section:1},$empty:{area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,
track:1,wbr:1},$inline:b,$list:{dl:1,ol:1,ul:1},$listItem:{dd:1,dt:1,li:1},$nonBodyContent:a({body:1,head:1,html:1},d.head),$nonEditable:{applet:1,audio:1,button:1,embed:1,iframe:1,map:1,object:1,option:1,param:1,script:1,textarea:1,video:1},$object:{applet:1,audio:1,button:1,hr:1,iframe:1,img:1,input:1,object:1,select:1,table:1,textarea:1,video:1},$removeEmpty:{abbr:1,acronym:1,b:1,bdi:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,mark:1,meter:1,output:1,q:1,ruby:1,
s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,time:1,tt:1,u:1,"var":1},$tabIndex:{a:1,area:1,button:1,input:1,object:1,select:1,textarea:1},$tableContent:{caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1},$transparent:{a:1,audio:1,canvas:1,del:1,ins:1,map:1,noscript:1,object:1,video:1},$intermediate:{caption:1,colgroup:1,dd:1,dt:1,figcaption:1,legend:1,li:1,optgroup:1,option:1,rp:1,rt:1,summary:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1}});return d}();
CKEDITOR.dom.event=function(a){this.$=a};
CKEDITOR.dom.event.prototype={getKey:function(){return this.$.keyCode||this.$.which},getKeystroke:function(){var a=this.getKey();if(this.$.ctrlKey||this.$.metaKey)a+=CKEDITOR.CTRL;this.$.shiftKey&&(a+=CKEDITOR.SHIFT);this.$.altKey&&(a+=CKEDITOR.ALT);return a},preventDefault:function(a){var d=this.$;d.preventDefault?d.preventDefault():d.returnValue=!1;a&&this.stopPropagation()},stopPropagation:function(){var a=this.$;a.stopPropagation?a.stopPropagation():a.cancelBubble=!0},getTarget:function(){var a=
this.$.target||this.$.srcElement;return a?new CKEDITOR.dom.node(a):null},getPhase:function(){return this.$.eventPhase||2},getPageOffset:function(){var a=this.getTarget().getDocument().$;return{x:this.$.pageX||this.$.clientX+(a.documentElement.scrollLeft||a.body.scrollLeft),y:this.$.pageY||this.$.clientY+(a.documentElement.scrollTop||a.body.scrollTop)}}};CKEDITOR.CTRL=1114112;CKEDITOR.SHIFT=2228224;CKEDITOR.ALT=4456448;CKEDITOR.EVENT_PHASE_CAPTURING=1;CKEDITOR.EVENT_PHASE_AT_TARGET=2;
CKEDITOR.EVENT_PHASE_BUBBLING=3;CKEDITOR.dom.domObject=function(a){a&&(this.$=a)};
CKEDITOR.dom.domObject.prototype=function(){var a=function(a,b){return function(c){"undefined"!=typeof CKEDITOR&&a.fire(b,new CKEDITOR.dom.event(c))}};return{getPrivate:function(){var a;(a=this.getCustomData("_"))||this.setCustomData("_",a={});return a},on:function(d){var b=this.getCustomData("_cke_nativeListeners");b||(b={},this.setCustomData("_cke_nativeListeners",b));b[d]||(b=b[d]=a(this,d),this.$.addEventListener?this.$.addEventListener(d,b,!!CKEDITOR.event.useCapture):this.$.attachEvent&&this.$.attachEvent("on"+
d,b));return CKEDITOR.event.prototype.on.apply(this,arguments)},removeListener:function(a){CKEDITOR.event.prototype.removeListener.apply(this,arguments);if(!this.hasListeners(a)){var b=this.getCustomData("_cke_nativeListeners"),c=b&&b[a];c&&(this.$.removeEventListener?this.$.removeEventListener(a,c,!1):this.$.detachEvent&&this.$.detachEvent("on"+a,c),delete b[a])}},removeAllListeners:function(){var a=this.getCustomData("_cke_nativeListeners"),b;for(b in a){var c=a[b];this.$.detachEvent?this.$.detachEvent("on"+
b,c):this.$.removeEventListener&&this.$.removeEventListener(b,c,!1);delete a[b]}CKEDITOR.event.prototype.removeAllListeners.call(this)}}}();
(function(a){var d={};CKEDITOR.on("reset",function(){d={}});a.equals=function(a){try{return a&&a.$===this.$}catch(c){return!1}};a.setCustomData=function(a,c){var f=this.getUniqueId();(d[f]||(d[f]={}))[a]=c;return this};a.getCustomData=function(a){var c=this.$["data-cke-expando"];return(c=c&&d[c])&&a in c?c[a]:null};a.removeCustomData=function(a){var c=this.$["data-cke-expando"],c=c&&d[c],f,h;c&&(f=c[a],h=a in c,delete c[a]);return h?f:null};a.clearCustomData=function(){this.removeAllListeners();var a=
this.$["data-cke-expando"];a&&delete d[a]};a.getUniqueId=function(){return this.$["data-cke-expando"]||(this.$["data-cke-expando"]=CKEDITOR.tools.getNextNumber())};CKEDITOR.event.implementOn(a)})(CKEDITOR.dom.domObject.prototype);
CKEDITOR.dom.node=function(a){return a?new CKEDITOR.dom[a.nodeType==CKEDITOR.NODE_DOCUMENT?"document":a.nodeType==CKEDITOR.NODE_ELEMENT?"element":a.nodeType==CKEDITOR.NODE_TEXT?"text":a.nodeType==CKEDITOR.NODE_COMMENT?"comment":a.nodeType==CKEDITOR.NODE_DOCUMENT_FRAGMENT?"documentFragment":"domObject"](a):this};CKEDITOR.dom.node.prototype=new CKEDITOR.dom.domObject;CKEDITOR.NODE_ELEMENT=1;CKEDITOR.NODE_DOCUMENT=9;CKEDITOR.NODE_TEXT=3;CKEDITOR.NODE_COMMENT=8;CKEDITOR.NODE_DOCUMENT_FRAGMENT=11;
CKEDITOR.POSITION_IDENTICAL=0;CKEDITOR.POSITION_DISCONNECTED=1;CKEDITOR.POSITION_FOLLOWING=2;CKEDITOR.POSITION_PRECEDING=4;CKEDITOR.POSITION_IS_CONTAINED=8;CKEDITOR.POSITION_CONTAINS=16;
CKEDITOR.tools.extend(CKEDITOR.dom.node.prototype,{appendTo:function(a,d){a.append(this,d);return a},clone:function(a,d){function b(c){c["data-cke-expando"]&&(c["data-cke-expando"]=!1);if(c.nodeType==CKEDITOR.NODE_ELEMENT||c.nodeType==CKEDITOR.NODE_DOCUMENT_FRAGMENT)if(d||c.nodeType!=CKEDITOR.NODE_ELEMENT||c.removeAttribute("id",!1),a){c=c.childNodes;for(var f=0;f<c.length;f++)b(c[f])}}function c(b){if(b.type==CKEDITOR.NODE_ELEMENT||b.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT){if(b.type!=CKEDITOR.NODE_DOCUMENT_FRAGMENT){var d=
b.getName();":"==d[0]&&b.renameNode(d.substring(1))}if(a)for(d=0;d<b.getChildCount();d++)c(b.getChild(d))}}var f=this.$.cloneNode(a);b(f);f=new CKEDITOR.dom.node(f);CKEDITOR.env.ie&&9>CKEDITOR.env.version&&(this.type==CKEDITOR.NODE_ELEMENT||this.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT)&&c(f);return f},hasPrevious:function(){return!!this.$.previousSibling},hasNext:function(){return!!this.$.nextSibling},insertAfter:function(a){a.$.parentNode.insertBefore(this.$,a.$.nextSibling);return a},insertBefore:function(a){a.$.parentNode.insertBefore(this.$,
a.$);return a},insertBeforeMe:function(a){this.$.parentNode.insertBefore(a.$,this.$);return a},getAddress:function(a){for(var d=[],b=this.getDocument().$.documentElement,c=this.$;c&&c!=b;){var f=c.parentNode;f&&d.unshift(this.getIndex.call({$:c},a));c=f}return d},getDocument:function(){return new CKEDITOR.dom.document(this.$.ownerDocument||this.$.parentNode.ownerDocument)},getIndex:function(a){function d(a,c){var n=c?a.nextSibling:a.previousSibling;return n&&n.nodeType==CKEDITOR.NODE_TEXT?b(n)?d(n,
c):n:null}function b(a){return!a.nodeValue||a.nodeValue==CKEDITOR.dom.selection.FILLING_CHAR_SEQUENCE}var c=this.$,f=-1,h;if(!this.$.parentNode||a&&c.nodeType==CKEDITOR.NODE_TEXT&&b(c)&&!d(c)&&!d(c,!0))return-1;do a&&c!=this.$&&c.nodeType==CKEDITOR.NODE_TEXT&&(h||b(c))||(f++,h=c.nodeType==CKEDITOR.NODE_TEXT);while(c=c.previousSibling);return f},getNextSourceNode:function(a,d,b){if(b&&!b.call){var c=b;b=function(a){return!a.equals(c)}}a=!a&&this.getFirst&&this.getFirst();var f;if(!a){if(this.type==
CKEDITOR.NODE_ELEMENT&&b&&!1===b(this,!0))return null;a=this.getNext()}for(;!a&&(f=(f||this).getParent());){if(b&&!1===b(f,!0))return null;a=f.getNext()}return!a||b&&!1===b(a)?null:d&&d!=a.type?a.getNextSourceNode(!1,d,b):a},getPreviousSourceNode:function(a,d,b){if(b&&!b.call){var c=b;b=function(a){return!a.equals(c)}}a=!a&&this.getLast&&this.getLast();var f;if(!a){if(this.type==CKEDITOR.NODE_ELEMENT&&b&&!1===b(this,!0))return null;a=this.getPrevious()}for(;!a&&(f=(f||this).getParent());){if(b&&!1===
b(f,!0))return null;a=f.getPrevious()}return!a||b&&!1===b(a)?null:d&&a.type!=d?a.getPreviousSourceNode(!1,d,b):a},getPrevious:function(a){var d=this.$,b;do b=(d=d.previousSibling)&&10!=d.nodeType&&new CKEDITOR.dom.node(d);while(b&&a&&!a(b));return b},getNext:function(a){var d=this.$,b;do b=(d=d.nextSibling)&&new CKEDITOR.dom.node(d);while(b&&a&&!a(b));return b},getParent:function(a){var d=this.$.parentNode;return d&&(d.nodeType==CKEDITOR.NODE_ELEMENT||a&&d.nodeType==CKEDITOR.NODE_DOCUMENT_FRAGMENT)?
new CKEDITOR.dom.node(d):null},getParents:function(a){var d=this,b=[];do b[a?"push":"unshift"](d);while(d=d.getParent());return b},getCommonAncestor:function(a){if(a.equals(this))return this;if(a.contains&&a.contains(this))return a;var d=this.contains?this:this.getParent();do if(d.contains(a))return d;while(d=d.getParent());return null},getPosition:function(a){var d=this.$,b=a.$;if(d.compareDocumentPosition)return d.compareDocumentPosition(b);if(d==b)return CKEDITOR.POSITION_IDENTICAL;if(this.type==
CKEDITOR.NODE_ELEMENT&&a.type==CKEDITOR.NODE_ELEMENT){if(d.contains){if(d.contains(b))return CKEDITOR.POSITION_CONTAINS+CKEDITOR.POSITION_PRECEDING;if(b.contains(d))return CKEDITOR.POSITION_IS_CONTAINED+CKEDITOR.POSITION_FOLLOWING}if("sourceIndex"in d)return 0>d.sourceIndex||0>b.sourceIndex?CKEDITOR.POSITION_DISCONNECTED:d.sourceIndex<b.sourceIndex?CKEDITOR.POSITION_PRECEDING:CKEDITOR.POSITION_FOLLOWING}d=this.getAddress();a=a.getAddress();for(var b=Math.min(d.length,a.length),c=0;c<b;c++)if(d[c]!=
a[c])return d[c]<a[c]?CKEDITOR.POSITION_PRECEDING:CKEDITOR.POSITION_FOLLOWING;return d.length<a.length?CKEDITOR.POSITION_CONTAINS+CKEDITOR.POSITION_PRECEDING:CKEDITOR.POSITION_IS_CONTAINED+CKEDITOR.POSITION_FOLLOWING},getAscendant:function(a,d){var b=this.$,c,f;d||(b=b.parentNode);"function"==typeof a?(f=!0,c=a):(f=!1,c=function(b){b="string"==typeof b.nodeName?b.nodeName.toLowerCase():"";return"string"==typeof a?b==a:b in a});for(;b;){if(c(f?new CKEDITOR.dom.node(b):b))return new CKEDITOR.dom.node(b);
try{b=b.parentNode}catch(h){b=null}}return null},hasAscendant:function(a,d){var b=this.$;d||(b=b.parentNode);for(;b;){if(b.nodeName&&b.nodeName.toLowerCase()==a)return!0;b=b.parentNode}return!1},move:function(a,d){a.append(this.remove(),d)},remove:function(a){var d=this.$,b=d.parentNode;if(b){if(a)for(;a=d.firstChild;)b.insertBefore(d.removeChild(a),d);b.removeChild(d)}return this},replace:function(a){this.insertBefore(a);a.remove()},trim:function(){this.ltrim();this.rtrim()},ltrim:function(){for(var a;this.getFirst&&
(a=this.getFirst());){if(a.type==CKEDITOR.NODE_TEXT){var d=CKEDITOR.tools.ltrim(a.getText()),b=a.getLength();if(d)d.length<b&&(a.split(b-d.length),this.$.removeChild(this.$.firstChild));else{a.remove();continue}}break}},rtrim:function(){for(var a;this.getLast&&(a=this.getLast());){if(a.type==CKEDITOR.NODE_TEXT){var d=CKEDITOR.tools.rtrim(a.getText()),b=a.getLength();if(d)d.length<b&&(a.split(d.length),this.$.lastChild.parentNode.removeChild(this.$.lastChild));else{a.remove();continue}}break}CKEDITOR.env.needsBrFiller&&
(a=this.$.lastChild)&&1==a.type&&"br"==a.nodeName.toLowerCase()&&a.parentNode.removeChild(a)},isReadOnly:function(a){var d=this;this.type!=CKEDITOR.NODE_ELEMENT&&(d=this.getParent());CKEDITOR.env.edge&&d&&d.is("textarea","input")&&(a=!0);if(!a&&d&&"undefined"!=typeof d.$.isContentEditable)return!(d.$.isContentEditable||d.data("cke-editable"));for(;d;){if(d.data("cke-editable"))return!1;if(d.hasAttribute("contenteditable"))return"false"==d.getAttribute("contenteditable");d=d.getParent()}return!0}});
CKEDITOR.dom.window=function(a){CKEDITOR.dom.domObject.call(this,a)};CKEDITOR.dom.window.prototype=new CKEDITOR.dom.domObject;
CKEDITOR.tools.extend(CKEDITOR.dom.window.prototype,{focus:function(){this.$.focus()},getViewPaneSize:function(){var a=this.$.document,d="CSS1Compat"==a.compatMode;return{width:(d?a.documentElement.clientWidth:a.body.clientWidth)||0,height:(d?a.documentElement.clientHeight:a.body.clientHeight)||0}},getScrollPosition:function(){var a=this.$;if("pageXOffset"in a)return{x:a.pageXOffset||0,y:a.pageYOffset||0};a=a.document;return{x:a.documentElement.scrollLeft||a.body.scrollLeft||0,y:a.documentElement.scrollTop||
a.body.scrollTop||0}},getFrame:function(){var a=this.$.frameElement;return a?new CKEDITOR.dom.element.get(a):null}});CKEDITOR.dom.document=function(a){CKEDITOR.dom.domObject.call(this,a)};CKEDITOR.dom.document.prototype=new CKEDITOR.dom.domObject;
CKEDITOR.tools.extend(CKEDITOR.dom.document.prototype,{type:CKEDITOR.NODE_DOCUMENT,appendStyleSheet:function(a){if(this.$.createStyleSheet)this.$.createStyleSheet(a);else{var d=new CKEDITOR.dom.element("link");d.setAttributes({rel:"stylesheet",type:"text/css",href:a});this.getHead().append(d)}},appendStyleText:function(a){if(this.$.createStyleSheet){var d=this.$.createStyleSheet("");d.cssText=a}else{var b=new CKEDITOR.dom.element("style",this);b.append(new CKEDITOR.dom.text(a,this));this.getHead().append(b)}return d||
b.$.sheet},createElement:function(a,d){var b=new CKEDITOR.dom.element(a,this);d&&(d.attributes&&b.setAttributes(d.attributes),d.styles&&b.setStyles(d.styles));return b},createText:function(a){return new CKEDITOR.dom.text(a,this)},focus:function(){this.getWindow().focus()},getActive:function(){var a;try{a=this.$.activeElement}catch(d){return null}return new CKEDITOR.dom.element(a)},getById:function(a){return(a=this.$.getElementById(a))?new CKEDITOR.dom.element(a):null},getByAddress:function(a,d){for(var b=
this.$.documentElement,c=0;b&&c<a.length;c++){var f=a[c];if(d)for(var h=-1,k=0;k<b.childNodes.length;k++){var g=b.childNodes[k];if(!0!==d||3!=g.nodeType||!g.previousSibling||3!=g.previousSibling.nodeType)if(h++,h==f){b=g;break}}else b=b.childNodes[f]}return b?new CKEDITOR.dom.node(b):null},getElementsByTag:function(a,d){CKEDITOR.env.ie&&8>=document.documentMode||!d||(a=d+":"+a);return new CKEDITOR.dom.nodeList(this.$.getElementsByTagName(a))},getHead:function(){var a=this.$.getElementsByTagName("head")[0];
return a=a?new CKEDITOR.dom.element(a):this.getDocumentElement().append(new CKEDITOR.dom.element("head"),!0)},getBody:function(){return new CKEDITOR.dom.element(this.$.body)},getDocumentElement:function(){return new CKEDITOR.dom.element(this.$.documentElement)},getWindow:function(){return new CKEDITOR.dom.window(this.$.parentWindow||this.$.defaultView)},write:function(a){this.$.open("text/html","replace");CKEDITOR.env.ie&&(a=a.replace(/(?:^\s*<!DOCTYPE[^>]*?>)|^/i,'$\x26\n\x3cscript data-cke-temp\x3d"1"\x3e('+
CKEDITOR.tools.fixDomain+")();\x3c/script\x3e"));this.$.write(a);this.$.close()},find:function(a){return new CKEDITOR.dom.nodeList(this.$.querySelectorAll(a))},findOne:function(a){return(a=this.$.querySelector(a))?new CKEDITOR.dom.element(a):null},_getHtml5ShivFrag:function(){var a=this.getCustomData("html5ShivFrag");a||(a=this.$.createDocumentFragment(),CKEDITOR.tools.enableHtml5Elements(a,!0),this.setCustomData("html5ShivFrag",a));return a}});CKEDITOR.dom.nodeList=function(a){this.$=a};
CKEDITOR.dom.nodeList.prototype={count:function(){return this.$.length},getItem:function(a){return 0>a||a>=this.$.length?null:(a=this.$[a])?new CKEDITOR.dom.node(a):null},toArray:function(){return CKEDITOR.tools.array.map(this.$,function(a){return new CKEDITOR.dom.node(a)})}};CKEDITOR.dom.element=function(a,d){"string"==typeof a&&(a=(d?d.$:document).createElement(a));CKEDITOR.dom.domObject.call(this,a)};
CKEDITOR.dom.element.get=function(a){return(a="string"==typeof a?document.getElementById(a)||document.getElementsByName(a)[0]:a)&&(a.$?a:new CKEDITOR.dom.element(a))};CKEDITOR.dom.element.prototype=new CKEDITOR.dom.node;CKEDITOR.dom.element.createFromHtml=function(a,d){var b=new CKEDITOR.dom.element("div",d);b.setHtml(a);return b.getFirst().remove()};
CKEDITOR.dom.element.setMarker=function(a,d,b,c){var f=d.getCustomData("list_marker_id")||d.setCustomData("list_marker_id",CKEDITOR.tools.getNextNumber()).getCustomData("list_marker_id"),h=d.getCustomData("list_marker_names")||d.setCustomData("list_marker_names",{}).getCustomData("list_marker_names");a[f]=d;h[b]=1;return d.setCustomData(b,c)};CKEDITOR.dom.element.clearAllMarkers=function(a){for(var d in a)CKEDITOR.dom.element.clearMarkers(a,a[d],1)};
CKEDITOR.dom.element.clearMarkers=function(a,d,b){var c=d.getCustomData("list_marker_names"),f=d.getCustomData("list_marker_id"),h;for(h in c)d.removeCustomData(h);d.removeCustomData("list_marker_names");b&&(d.removeCustomData("list_marker_id"),delete a[f])};
(function(){function a(a,b){return-1<(" "+a+" ").replace(h," ").indexOf(" "+b+" ")}function d(a){var b=!0;a.$.id||(a.$.id="cke_tmp_"+CKEDITOR.tools.getNextNumber(),b=!1);return function(){b||a.removeAttribute("id")}}function b(a,b){var c=CKEDITOR.tools.escapeCss(a.$.id);return"#"+c+" "+b.split(/,\s*/).join(", #"+c+" ")}function c(a){for(var b=0,c=0,e=k[a].length;c<e;c++)b+=parseFloat(this.getComputedStyle(k[a][c])||0,10)||0;return b}var f=document.createElement("_").classList,f="undefined"!==typeof f&&
null!==String(f.add).match(/\[Native code\]/gi),h=/[\n\t\r]/g;CKEDITOR.tools.extend(CKEDITOR.dom.element.prototype,{type:CKEDITOR.NODE_ELEMENT,addClass:f?function(a){this.$.classList.add(a);return this}:function(b){var c=this.$.className;c&&(a(c,b)||(c+=" "+b));this.$.className=c||b;return this},removeClass:f?function(a){var b=this.$;b.classList.remove(a);b.className||b.removeAttribute("class");return this}:function(b){var c=this.getAttribute("class");c&&a(c,b)&&((c=c.replace(new RegExp("(?:^|\\s+)"+
b+"(?\x3d\\s|$)"),"").replace(/^\s+/,""))?this.setAttribute("class",c):this.removeAttribute("class"));return this},hasClass:function(b){return a(this.$.className,b)},append:function(a,b){"string"==typeof a&&(a=this.getDocument().createElement(a));b?this.$.insertBefore(a.$,this.$.firstChild):this.$.appendChild(a.$);return a},appendHtml:function(a){if(this.$.childNodes.length){var b=new CKEDITOR.dom.element("div",this.getDocument());b.setHtml(a);b.moveChildren(this)}else this.setHtml(a)},appendText:function(a){null!=
this.$.text&&CKEDITOR.env.ie&&9>CKEDITOR.env.version?this.$.text+=a:this.append(new CKEDITOR.dom.text(a))},appendBogus:function(a){if(a||CKEDITOR.env.needsBrFiller){for(a=this.getLast();a&&a.type==CKEDITOR.NODE_TEXT&&!CKEDITOR.tools.rtrim(a.getText());)a=a.getPrevious();a&&a.is&&a.is("br")||(a=this.getDocument().createElement("br"),CKEDITOR.env.gecko&&a.setAttribute("type","_moz"),this.append(a))}},breakParent:function(a,b){var c=new CKEDITOR.dom.range(this.getDocument());c.setStartAfter(this);c.setEndAfter(a);
var e=c.extractContents(!1,b||!1),d;c.insertNode(this.remove());if(CKEDITOR.env.ie&&!CKEDITOR.env.edge){for(c=new CKEDITOR.dom.element("div");d=e.getFirst();)d.$.style.backgroundColor&&(d.$.style.backgroundColor=d.$.style.backgroundColor),c.append(d);c.insertAfter(this);c.remove(!0)}else e.insertAfterNode(this)},contains:document.compareDocumentPosition?function(a){return!!(this.$.compareDocumentPosition(a.$)&16)}:function(a){var b=this.$;return a.type!=CKEDITOR.NODE_ELEMENT?b.contains(a.getParent().$):
b!=a.$&&b.contains(a.$)},focus:function(){function a(){try{this.$.focus()}catch(b){}}return function(b){b?CKEDITOR.tools.setTimeout(a,100,this):a.call(this)}}(),getHtml:function(){var a=this.$.innerHTML;return CKEDITOR.env.ie?a.replace(/<\?[^>]*>/g,""):a},getOuterHtml:function(){if(this.$.outerHTML)return this.$.outerHTML.replace(/<\?[^>]*>/,"");var a=this.$.ownerDocument.createElement("div");a.appendChild(this.$.cloneNode(!0));return a.innerHTML},getClientRect:function(a){var b=CKEDITOR.tools.extend({},
this.$.getBoundingClientRect());!b.width&&(b.width=b.right-b.left);!b.height&&(b.height=b.bottom-b.top);return a?CKEDITOR.tools.getAbsoluteRectPosition(this.getWindow(),b):b},setHtml:CKEDITOR.env.ie&&9>CKEDITOR.env.version?function(a){try{var b=this.$;if(this.getParent())return b.innerHTML=a;var c=this.getDocument()._getHtml5ShivFrag();c.appendChild(b);b.innerHTML=a;c.removeChild(b);return a}catch(e){this.$.innerHTML="";b=new CKEDITOR.dom.element("body",this.getDocument());b.$.innerHTML=a;for(b=b.getChildren();b.count();)this.append(b.getItem(0));
return a}}:function(a){return this.$.innerHTML=a},setText:function(){var a=document.createElement("p");a.innerHTML="x";a=a.textContent;return function(b){this.$[a?"textContent":"innerText"]=b}}(),getAttribute:function(){var a=function(a){return this.$.getAttribute(a,2)};return CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks)?function(a){switch(a){case "class":a="className";break;case "http-equiv":a="httpEquiv";break;case "name":return this.$.name;case "tabindex":return a=this.$.getAttribute(a,
2),0!==a&&0===this.$.tabIndex&&(a=null),a;case "checked":return a=this.$.attributes.getNamedItem(a),(a.specified?a.nodeValue:this.$.checked)?"checked":null;case "hspace":case "value":return this.$[a];case "style":return this.$.style.cssText;case "contenteditable":case "contentEditable":return this.$.attributes.getNamedItem("contentEditable").specified?this.$.getAttribute("contentEditable"):null}return this.$.getAttribute(a,2)}:a}(),getAttributes:function(a){var b={},c=this.$.attributes,e;a=CKEDITOR.tools.isArray(a)?
a:[];for(e=0;e<c.length;e++)-1===CKEDITOR.tools.indexOf(a,c[e].name)&&(b[c[e].name]=c[e].value);return b},getChildren:function(){return new CKEDITOR.dom.nodeList(this.$.childNodes)},getComputedStyle:document.defaultView&&document.defaultView.getComputedStyle?function(a){var b=this.getWindow().$.getComputedStyle(this.$,null);return b?b.getPropertyValue(a):""}:function(a){return this.$.currentStyle[CKEDITOR.tools.cssStyleToDomStyle(a)]},getDtd:function(){var a=CKEDITOR.dtd[this.getName()];this.getDtd=
function(){return a};return a},getElementsByTag:CKEDITOR.dom.document.prototype.getElementsByTag,getTabIndex:function(){var a=this.$.tabIndex;return 0!==a||CKEDITOR.dtd.$tabIndex[this.getName()]||0===parseInt(this.getAttribute("tabindex"),10)?a:-1},getText:function(){return this.$.textContent||this.$.innerText||""},getWindow:function(){return this.getDocument().getWindow()},getId:function(){return this.$.id||null},getNameAtt:function(){return this.$.name||null},getName:function(){var a=this.$.nodeName.toLowerCase();
if(CKEDITOR.env.ie&&8>=document.documentMode){var b=this.$.scopeName;"HTML"!=b&&(a=b.toLowerCase()+":"+a)}this.getName=function(){return a};return this.getName()},getValue:function(){return this.$.value},getFirst:function(a){var b=this.$.firstChild;(b=b&&new CKEDITOR.dom.node(b))&&a&&!a(b)&&(b=b.getNext(a));return b},getLast:function(a){var b=this.$.lastChild;(b=b&&new CKEDITOR.dom.node(b))&&a&&!a(b)&&(b=b.getPrevious(a));return b},getStyle:function(a){return this.$.style[CKEDITOR.tools.cssStyleToDomStyle(a)]},
is:function(){var a=this.getName();if("object"==typeof arguments[0])return!!arguments[0][a];for(var b=0;b<arguments.length;b++)if(arguments[b]==a)return!0;return!1},isEditable:function(a){var b=this.getName();return this.isReadOnly()||"none"==this.getComputedStyle("display")||"hidden"==this.getComputedStyle("visibility")||CKEDITOR.dtd.$nonEditable[b]||CKEDITOR.dtd.$empty[b]||this.is("a")&&(this.data("cke-saved-name")||this.hasAttribute("name"))&&!this.getChildCount()?!1:!1!==a?(a=CKEDITOR.dtd[b]||
CKEDITOR.dtd.span,!(!a||!a["#"])):!0},isIdentical:function(a){var b=this.clone(0,1);a=a.clone(0,1);b.removeAttributes(["_moz_dirty","data-cke-expando","data-cke-saved-href","data-cke-saved-name"]);a.removeAttributes(["_moz_dirty","data-cke-expando","data-cke-saved-href","data-cke-saved-name"]);if(b.$.isEqualNode)return b.$.style.cssText=CKEDITOR.tools.normalizeCssText(b.$.style.cssText),a.$.style.cssText=CKEDITOR.tools.normalizeCssText(a.$.style.cssText),b.$.isEqualNode(a.$);b=b.getOuterHtml();a=
a.getOuterHtml();if(CKEDITOR.env.ie&&9>CKEDITOR.env.version&&this.is("a")){var c=this.getParent();c.type==CKEDITOR.NODE_ELEMENT&&(c=c.clone(),c.setHtml(b),b=c.getHtml(),c.setHtml(a),a=c.getHtml())}return b==a},isVisible:function(){var a=(this.$.offsetHeight||this.$.offsetWidth)&&"hidden"!=this.getComputedStyle("visibility"),b,c;a&&CKEDITOR.env.webkit&&(b=this.getWindow(),!b.equals(CKEDITOR.document.getWindow())&&(c=b.$.frameElement)&&(a=(new CKEDITOR.dom.element(c)).isVisible()));return!!a},isEmptyInlineRemoveable:function(){if(!CKEDITOR.dtd.$removeEmpty[this.getName()])return!1;
for(var a=this.getChildren(),b=0,c=a.count();b<c;b++){var e=a.getItem(b);if(e.type!=CKEDITOR.NODE_ELEMENT||!e.data("cke-bookmark"))if(e.type==CKEDITOR.NODE_ELEMENT&&!e.isEmptyInlineRemoveable()||e.type==CKEDITOR.NODE_TEXT&&CKEDITOR.tools.trim(e.getText()))return!1}return!0},hasAttributes:CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks)?function(){for(var a=this.$.attributes,b=0;b<a.length;b++){var c=a[b];switch(c.nodeName){case "class":if(this.getAttribute("class"))return!0;case "data-cke-expando":continue;
default:if(c.specified)return!0}}return!1}:function(){var a=this.$.attributes,b=a.length,c={"data-cke-expando":1,_moz_dirty:1};return 0<b&&(2<b||!c[a[0].nodeName]||2==b&&!c[a[1].nodeName])},hasAttribute:function(){function a(b){var c=this.$.attributes.getNamedItem(b);if("input"==this.getName())switch(b){case "class":return 0<this.$.className.length;case "checked":return!!this.$.checked;case "value":return b=this.getAttribute("type"),"checkbox"==b||"radio"==b?"on"!=this.$.value:!!this.$.value}return c?
c.specified:!1}return CKEDITOR.env.ie?8>CKEDITOR.env.version?function(b){return"name"==b?!!this.$.name:a.call(this,b)}:a:function(a){return!!this.$.attributes.getNamedItem(a)}}(),hide:function(){this.setStyle("display","none")},moveChildren:function(a,b){var c=this.$;a=a.$;if(c!=a){var e;if(b)for(;e=c.lastChild;)a.insertBefore(c.removeChild(e),a.firstChild);else for(;e=c.firstChild;)a.appendChild(c.removeChild(e))}},mergeSiblings:function(){function a(b,c,e){if(c&&c.type==CKEDITOR.NODE_ELEMENT){for(var d=
[];c.data("cke-bookmark")||c.isEmptyInlineRemoveable();)if(d.push(c),c=e?c.getNext():c.getPrevious(),!c||c.type!=CKEDITOR.NODE_ELEMENT)return;if(b.isIdentical(c)){for(var g=e?b.getLast():b.getFirst();d.length;)d.shift().move(b,!e);c.moveChildren(b,!e);c.remove();g&&g.type==CKEDITOR.NODE_ELEMENT&&g.mergeSiblings()}}}return function(b){if(!1===b||CKEDITOR.dtd.$removeEmpty[this.getName()]||this.is("a"))a(this,this.getNext(),!0),a(this,this.getPrevious())}}(),show:function(){this.setStyles({display:"",
visibility:""})},setAttribute:function(){var a=function(a,b){this.$.setAttribute(a,b);return this};return CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks)?function(b,c){"class"==b?this.$.className=c:"style"==b?this.$.style.cssText=c:"tabindex"==b?this.$.tabIndex=c:"checked"==b?this.$.checked=c:"contenteditable"==b?a.call(this,"contentEditable",c):a.apply(this,arguments);return this}:CKEDITOR.env.ie8Compat&&CKEDITOR.env.secure?function(b,c){if("src"==b&&c.match(/^http:\/\//))try{a.apply(this,
arguments)}catch(e){}else a.apply(this,arguments);return this}:a}(),setAttributes:function(a){for(var b in a)this.setAttribute(b,a[b]);return this},setValue:function(a){this.$.value=a;return this},removeAttribute:function(){var a=function(a){this.$.removeAttribute(a)};return CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks)?function(a){"class"==a?a="className":"tabindex"==a?a="tabIndex":"contenteditable"==a&&(a="contentEditable");this.$.removeAttribute(a)}:a}(),removeAttributes:function(a){if(CKEDITOR.tools.isArray(a))for(var b=
0;b<a.length;b++)this.removeAttribute(a[b]);else for(b in a=a||this.getAttributes(),a)a.hasOwnProperty(b)&&this.removeAttribute(b)},removeStyle:function(a){var b=this.$.style;if(b.removeProperty||"border"!=a&&"margin"!=a&&"padding"!=a)b.removeProperty?b.removeProperty(a):b.removeAttribute(CKEDITOR.tools.cssStyleToDomStyle(a)),this.$.style.cssText||this.removeAttribute("style");else{var c=["top","left","right","bottom"],e;"border"==a&&(e=["color","style","width"]);for(var b=[],d=0;d<c.length;d++)if(e)for(var v=
0;v<e.length;v++)b.push([a,c[d],e[v]].join("-"));else b.push([a,c[d]].join("-"));for(a=0;a<b.length;a++)this.removeStyle(b[a])}},setStyle:function(a,b){this.$.style[CKEDITOR.tools.cssStyleToDomStyle(a)]=b;return this},setStyles:function(a){for(var b in a)this.setStyle(b,a[b]);return this},setOpacity:function(a){CKEDITOR.env.ie&&9>CKEDITOR.env.version?(a=Math.round(100*a),this.setStyle("filter",100<=a?"":"progid:DXImageTransform.Microsoft.Alpha(opacity\x3d"+a+")")):this.setStyle("opacity",a)},unselectable:function(){this.setStyles(CKEDITOR.tools.cssVendorPrefix("user-select",
"none"));if(CKEDITOR.env.ie){this.setAttribute("unselectable","on");for(var a,b=this.getElementsByTag("*"),c=0,e=b.count();c<e;c++)a=b.getItem(c),a.setAttribute("unselectable","on")}},getPositionedAncestor:function(){for(var a=this;"html"!=a.getName();){if("static"!=a.getComputedStyle("position"))return a;a=a.getParent()}return null},getDocumentPosition:function(a){var b=0,c=0,e=this.getDocument(),d=e.getBody(),v="BackCompat"==e.$.compatMode;if(document.documentElement.getBoundingClientRect&&(CKEDITOR.env.ie?
8!==CKEDITOR.env.version:1)){var f=this.$.getBoundingClientRect(),h=e.$.documentElement,x=h.clientTop||d.$.clientTop||0,m=h.clientLeft||d.$.clientLeft||0,k=!0;CKEDITOR.env.ie&&(k=e.getDocumentElement().contains(this),e=e.getBody().contains(this),k=v&&e||!v&&k);k&&(CKEDITOR.env.webkit||CKEDITOR.env.ie&&12<=CKEDITOR.env.version?(b=d.$.scrollLeft||h.scrollLeft,c=d.$.scrollTop||h.scrollTop):(c=v?d.$:h,b=c.scrollLeft,c=c.scrollTop),b=f.left+b-m,c=f.top+c-x)}else for(x=this,m=null;x&&"body"!=x.getName()&&
"html"!=x.getName();){b+=x.$.offsetLeft-x.$.scrollLeft;c+=x.$.offsetTop-x.$.scrollTop;x.equals(this)||(b+=x.$.clientLeft||0,c+=x.$.clientTop||0);for(;m&&!m.equals(x);)b-=m.$.scrollLeft,c-=m.$.scrollTop,m=m.getParent();m=x;x=(f=x.$.offsetParent)?new CKEDITOR.dom.element(f):null}a&&(f=this.getWindow(),x=a.getWindow(),!f.equals(x)&&f.$.frameElement&&(a=(new CKEDITOR.dom.element(f.$.frameElement)).getDocumentPosition(a),b+=a.x,c+=a.y));document.documentElement.getBoundingClientRect||!CKEDITOR.env.gecko||
v||(b+=this.$.clientLeft?1:0,c+=this.$.clientTop?1:0);return{x:b,y:c}},scrollIntoView:function(a){var b=this.getParent();if(b){do if((b.$.clientWidth&&b.$.clientWidth<b.$.scrollWidth||b.$.clientHeight&&b.$.clientHeight<b.$.scrollHeight)&&!b.is("body")&&this.scrollIntoParent(b,a,1),b.is("html")){var c=b.getWindow();try{var e=c.$.frameElement;e&&(b=new CKEDITOR.dom.element(e))}catch(d){}}while(b=b.getParent())}},scrollIntoParent:function(a,b,c){var e,d,v,f;function h(b,c){/body|html/.test(a.getName())?
a.getWindow().$.scrollBy(b,c):(a.$.scrollLeft+=b,a.$.scrollTop+=c)}function x(a,b){var c={x:0,y:0};if(!a.is(k?"body":"html")){var e=a.$.getBoundingClientRect();c.x=e.left;c.y=e.top}e=a.getWindow();e.equals(b)||(e=x(CKEDITOR.dom.element.get(e.$.frameElement),b),c.x+=e.x,c.y+=e.y);return c}function m(a,b){return parseInt(a.getComputedStyle("margin-"+b)||0,10)||0}!a&&(a=this.getWindow());v=a.getDocument();var k="BackCompat"==v.$.compatMode;a instanceof CKEDITOR.dom.window&&(a=k?v.getBody():v.getDocumentElement());
CKEDITOR.env.webkit&&(v=this.getEditor(!1))&&(v._.previousScrollTop=null);v=a.getWindow();d=x(this,v);var u=x(a,v),K=this.$.offsetHeight;e=this.$.offsetWidth;var l=a.$.clientHeight,t=a.$.clientWidth;v=d.x-m(this,"left")-u.x||0;f=d.y-m(this,"top")-u.y||0;e=d.x+e+m(this,"right")-(u.x+t)||0;d=d.y+K+m(this,"bottom")-(u.y+l)||0;(0>f||0<d)&&h(0,!0===b?f:!1===b?d:0>f?f:d);c&&(0>v||0<e)&&h(0>v?v:e,0)},setState:function(a,b,c){b=b||"cke";switch(a){case CKEDITOR.TRISTATE_ON:this.addClass(b+"_on");this.removeClass(b+
"_off");this.removeClass(b+"_disabled");c&&this.setAttribute("aria-pressed",!0);c&&this.removeAttribute("aria-disabled");break;case CKEDITOR.TRISTATE_DISABLED:this.addClass(b+"_disabled");this.removeClass(b+"_off");this.removeClass(b+"_on");c&&this.setAttribute("aria-disabled",!0);c&&this.removeAttribute("aria-pressed");break;default:this.addClass(b+"_off"),this.removeClass(b+"_on"),this.removeClass(b+"_disabled"),c&&this.removeAttribute("aria-pressed"),c&&this.removeAttribute("aria-disabled")}},
getFrameDocument:function(){var a=this.$;try{a.contentWindow.document}catch(b){a.src=a.src}return a&&new CKEDITOR.dom.document(a.contentWindow.document)},copyAttributes:function(a,b){var c=this.$.attributes;b=b||{};for(var e=0;e<c.length;e++){var d=c[e],v=d.nodeName.toLowerCase(),f;if(!(v in b))if("checked"==v&&(f=this.getAttribute(v)))a.setAttribute(v,f);else if(!CKEDITOR.env.ie||this.hasAttribute(v))f=this.getAttribute(v),null===f&&(f=d.nodeValue),a.setAttribute(v,f)}""!==this.$.style.cssText&&
(a.$.style.cssText=this.$.style.cssText)},renameNode:function(a){if(this.getName()!=a){var b=this.getDocument();a=new CKEDITOR.dom.element(a,b);this.copyAttributes(a);this.moveChildren(a);this.getParent(!0)&&this.$.parentNode.replaceChild(a.$,this.$);a.$["data-cke-expando"]=this.$["data-cke-expando"];this.$=a.$;delete this.getName}},getChild:function(){function a(b,c){var e=b.childNodes;if(0<=c&&c<e.length)return e[c]}return function(b){var c=this.$;if(b.slice)for(b=b.slice();0<b.length&&c;)c=a(c,
b.shift());else c=a(c,b);return c?new CKEDITOR.dom.node(c):null}}(),getChildCount:function(){return this.$.childNodes.length},disableContextMenu:function(){function a(b){return b.type==CKEDITOR.NODE_ELEMENT&&b.hasClass("cke_enable_context_menu")}this.on("contextmenu",function(b){b.data.getTarget().getAscendant(a,!0)||b.data.preventDefault()})},getDirection:function(a){return a?this.getComputedStyle("direction")||this.getDirection()||this.getParent()&&this.getParent().getDirection(1)||this.getDocument().$.dir||
"ltr":this.getStyle("direction")||this.getAttribute("dir")},data:function(a,b){a="data-"+a;if(void 0===b)return this.getAttribute(a);!1===b?this.removeAttribute(a):this.setAttribute(a,b);return null},getEditor:function(a){var b=CKEDITOR.instances,c,e,d;a=a||void 0===a;for(c in b)if(e=b[c],e.element.equals(this)&&e.elementMode!=CKEDITOR.ELEMENT_MODE_APPENDTO||!a&&(d=e.editable())&&(d.equals(this)||d.contains(this)))return e;return null},find:function(a){var c=d(this);a=new CKEDITOR.dom.nodeList(this.$.querySelectorAll(b(this,
a)));c();return a},findOne:function(a){var c=d(this);a=this.$.querySelector(b(this,a));c();return a?new CKEDITOR.dom.element(a):null},forEach:function(a,b,c){if(!(c||b&&this.type!=b))var e=a(this);if(!1!==e){c=this.getChildren();for(var d=0;d<c.count();d++)e=c.getItem(d),e.type==CKEDITOR.NODE_ELEMENT?e.forEach(a,b):b&&e.type!=b||a(e)}}});var k={width:["border-left-width","border-right-width","padding-left","padding-right"],height:["border-top-width","border-bottom-width","padding-top","padding-bottom"]};
CKEDITOR.dom.element.prototype.setSize=function(a,b,d){"number"==typeof b&&(!d||CKEDITOR.env.ie&&CKEDITOR.env.quirks||(b-=c.call(this,a)),this.setStyle(a,b+"px"))};CKEDITOR.dom.element.prototype.getSize=function(a,b){var d=Math.max(this.$["offset"+CKEDITOR.tools.capitalize(a)],this.$["client"+CKEDITOR.tools.capitalize(a)])||0;b&&(d-=c.call(this,a));return d}})();CKEDITOR.dom.documentFragment=function(a){a=a||CKEDITOR.document;this.$=a.type==CKEDITOR.NODE_DOCUMENT?a.$.createDocumentFragment():a};
CKEDITOR.tools.extend(CKEDITOR.dom.documentFragment.prototype,CKEDITOR.dom.element.prototype,{type:CKEDITOR.NODE_DOCUMENT_FRAGMENT,insertAfterNode:function(a){a=a.$;a.parentNode.insertBefore(this.$,a.nextSibling)},getHtml:function(){var a=new CKEDITOR.dom.element("div");this.clone(1,1).appendTo(a);return a.getHtml().replace(/\s*data-cke-expando=".*?"/g,"")}},!0,{append:1,appendBogus:1,clone:1,getFirst:1,getHtml:1,getLast:1,getParent:1,getNext:1,getPrevious:1,appendTo:1,moveChildren:1,insertBefore:1,
insertAfterNode:1,replace:1,trim:1,type:1,ltrim:1,rtrim:1,getDocument:1,getChildCount:1,getChild:1,getChildren:1});
(function(){function a(a,b){var c=this.range;if(this._.end)return null;if(!this._.start){this._.start=1;if(c.collapsed)return this.end(),null;c.optimize()}var e,d=c.startContainer;e=c.endContainer;var f=c.startOffset,y=c.endOffset,h,l=this.guard,t=this.type,g=a?"getPreviousSourceNode":"getNextSourceNode";if(!a&&!this._.guardLTR){var L=e.type==CKEDITOR.NODE_ELEMENT?e:e.getParent(),C=e.type==CKEDITOR.NODE_ELEMENT?e.getChild(y):e.getNext();this._.guardLTR=function(a,b){return(!b||!L.equals(a))&&(!C||
!a.equals(C))&&(a.type!=CKEDITOR.NODE_ELEMENT||!b||!a.equals(c.root))}}if(a&&!this._.guardRTL){var k=d.type==CKEDITOR.NODE_ELEMENT?d:d.getParent(),q=d.type==CKEDITOR.NODE_ELEMENT?f?d.getChild(f-1):null:d.getPrevious();this._.guardRTL=function(a,b){return(!b||!k.equals(a))&&(!q||!a.equals(q))&&(a.type!=CKEDITOR.NODE_ELEMENT||!b||!a.equals(c.root))}}var E=a?this._.guardRTL:this._.guardLTR;h=l?function(a,b){return!1===E(a,b)?!1:l(a,b)}:E;this.current?e=this.current[g](!1,t,h):(a?e.type==CKEDITOR.NODE_ELEMENT&&
(e=0<y?e.getChild(y-1):!1===h(e,!0)?null:e.getPreviousSourceNode(!0,t,h)):(e=d,e.type==CKEDITOR.NODE_ELEMENT&&((e=e.getChild(f))||(e=!1===h(d,!0)?null:d.getNextSourceNode(!0,t,h)))),e&&!1===h(e)&&(e=null));for(;e&&!this._.end;){this.current=e;if(!this.evaluator||!1!==this.evaluator(e)){if(!b)return e}else if(b&&this.evaluator)return!1;e=e[g](!1,t,h)}this.end();return this.current=null}function d(b){for(var c,e=null;c=a.call(this,b);)e=c;return e}CKEDITOR.dom.walker=CKEDITOR.tools.createClass({$:function(a){this.range=
a;this._={}},proto:{end:function(){this._.end=1},next:function(){return a.call(this)},previous:function(){return a.call(this,1)},checkForward:function(){return!1!==a.call(this,0,1)},checkBackward:function(){return!1!==a.call(this,1,1)},lastForward:function(){return d.call(this)},lastBackward:function(){return d.call(this,1)},reset:function(){delete this.current;this._={}}}});var b={block:1,"list-item":1,table:1,"table-row-group":1,"table-header-group":1,"table-footer-group":1,"table-row":1,"table-column-group":1,
"table-column":1,"table-cell":1,"table-caption":1},c={absolute:1,fixed:1};CKEDITOR.dom.element.prototype.isBlockBoundary=function(a){return"none"!=this.getComputedStyle("float")||this.getComputedStyle("position")in c||!b[this.getComputedStyle("display")]?!!(this.is(CKEDITOR.dtd.$block)||a&&this.is(a)):!0};CKEDITOR.dom.walker.blockBoundary=function(a){return function(b){return!(b.type==CKEDITOR.NODE_ELEMENT&&b.isBlockBoundary(a))}};CKEDITOR.dom.walker.listItemBoundary=function(){return this.blockBoundary({br:1})};
CKEDITOR.dom.walker.bookmark=function(a,b){function c(a){return a&&a.getName&&"span"==a.getName()&&a.data("cke-bookmark")}return function(e){var d,f;d=e&&e.type!=CKEDITOR.NODE_ELEMENT&&(f=e.getParent())&&c(f);d=a?d:d||c(e);return!!(b^d)}};CKEDITOR.dom.walker.whitespaces=function(a){return function(b){var c;b&&b.type==CKEDITOR.NODE_TEXT&&(c=!CKEDITOR.tools.trim(b.getText())||CKEDITOR.env.webkit&&b.getText()==CKEDITOR.dom.selection.FILLING_CHAR_SEQUENCE);return!!(a^c)}};CKEDITOR.dom.walker.invisible=
function(a){var b=CKEDITOR.dom.walker.whitespaces(),c=CKEDITOR.env.webkit?1:0;return function(e){b(e)?e=1:(e.type==CKEDITOR.NODE_TEXT&&(e=e.getParent()),e=e.$.offsetWidth<=c);return!!(a^e)}};CKEDITOR.dom.walker.nodeType=function(a,b){return function(c){return!!(b^c.type==a)}};CKEDITOR.dom.walker.bogus=function(a){function b(a){return!h(a)&&!k(a)}return function(c){var e=CKEDITOR.env.needsBrFiller?c.is&&c.is("br"):c.getText&&f.test(c.getText());e&&(e=c.getParent(),c=c.getNext(b),e=e.isBlockBoundary()&&
(!c||c.type==CKEDITOR.NODE_ELEMENT&&c.isBlockBoundary()));return!!(a^e)}};CKEDITOR.dom.walker.temp=function(a){return function(b){b.type!=CKEDITOR.NODE_ELEMENT&&(b=b.getParent());b=b&&b.hasAttribute("data-cke-temp");return!!(a^b)}};var f=/^[\t\r\n ]*(?:&nbsp;|\xa0)$/,h=CKEDITOR.dom.walker.whitespaces(),k=CKEDITOR.dom.walker.bookmark(),g=CKEDITOR.dom.walker.temp(),n=function(a){return k(a)||h(a)||a.type==CKEDITOR.NODE_ELEMENT&&a.is(CKEDITOR.dtd.$inline)&&!a.is(CKEDITOR.dtd.$empty)};CKEDITOR.dom.walker.ignored=
function(a){return function(b){b=h(b)||k(b)||g(b);return!!(a^b)}};var r=CKEDITOR.dom.walker.ignored();CKEDITOR.dom.walker.empty=function(a){return function(b){for(var c=0,e=b.getChildCount();c<e;++c)if(!r(b.getChild(c)))return!!a;return!a}};var e=CKEDITOR.dom.walker.empty(),y=CKEDITOR.dom.walker.validEmptyBlockContainers=CKEDITOR.tools.extend(function(a){var b={},c;for(c in a)CKEDITOR.dtd[c]["#"]&&(b[c]=1);return b}(CKEDITOR.dtd.$block),{caption:1,td:1,th:1});CKEDITOR.dom.walker.editable=function(a){return function(b){b=
r(b)?!1:b.type==CKEDITOR.NODE_TEXT||b.type==CKEDITOR.NODE_ELEMENT&&(b.is(CKEDITOR.dtd.$inline)||b.is("hr")||"false"==b.getAttribute("contenteditable")||!CKEDITOR.env.needsBrFiller&&b.is(y)&&e(b))?!0:!1;return!!(a^b)}};CKEDITOR.dom.element.prototype.getBogus=function(){var a=this;do a=a.getPreviousSourceNode();while(n(a));return a&&(CKEDITOR.env.needsBrFiller?a.is&&a.is("br"):a.getText&&f.test(a.getText()))?a:!1}})();
CKEDITOR.dom.range=function(a){this.endOffset=this.endContainer=this.startOffset=this.startContainer=null;this.collapsed=!0;var d=a instanceof CKEDITOR.dom.document;this.document=d?a:a.getDocument();this.root=d?a.getBody():a};
(function(){function a(a){a.collapsed=a.startContainer&&a.endContainer&&a.startContainer.equals(a.endContainer)&&a.startOffset==a.endOffset}function d(a,b,c,d,f){function h(a,b,c,e){var d=c?a.getPrevious():a.getNext();if(e&&k)return d;l||e?b.append(a.clone(!0,f),c):(a.remove(),r&&b.append(a,c));return d}function m(){var a,b,c,e=Math.min(O.length,p.length);for(a=0;a<e;a++)if(b=O[a],c=p[a],!b.equals(c))return a;return a-1}function g(){var b=N-1,c=E&&z&&!t.equals(F);b<w-1||b<A-1||c?(c?a.moveToPosition(F,
CKEDITOR.POSITION_BEFORE_START):A==b+1&&q?a.moveToPosition(p[b],CKEDITOR.POSITION_BEFORE_END):a.moveToPosition(p[b+1],CKEDITOR.POSITION_BEFORE_START),d&&(b=O[b+1])&&b.type==CKEDITOR.NODE_ELEMENT&&(c=CKEDITOR.dom.element.createFromHtml('\x3cspan data-cke-bookmark\x3d"1" style\x3d"display:none"\x3e\x26nbsp;\x3c/span\x3e',a.document),c.insertAfter(b),b.mergeSiblings(!1),a.moveToBookmark({startNode:c}))):a.collapse(!0)}a.optimizeBookmark();var k=0===b,r=1==b,l=2==b;b=l||r;var t=a.startContainer,F=a.endContainer,
L=a.startOffset,C=a.endOffset,M,q,E,z,H,P;if(l&&F.type==CKEDITOR.NODE_TEXT&&(t.equals(F)||t.type===CKEDITOR.NODE_ELEMENT&&t.getFirst().equals(F)))c.append(a.document.createText(F.substring(L,C)));else{F.type==CKEDITOR.NODE_TEXT?l?P=!0:F=F.split(C):0<F.getChildCount()?C>=F.getChildCount()?(F=F.getChild(C-1),q=!0):F=F.getChild(C):z=q=!0;t.type==CKEDITOR.NODE_TEXT?l?H=!0:t.split(L):0<t.getChildCount()?0===L?(t=t.getChild(L),M=!0):t=t.getChild(L-1):E=M=!0;for(var O=t.getParents(),p=F.getParents(),N=m(),
w=O.length-1,A=p.length-1,G=c,I,X,V,da=-1,Q=N;Q<=w;Q++){X=O[Q];V=X.getNext();for(Q!=w||X.equals(p[Q])&&w<A?b&&(I=G.append(X.clone(0,f))):M?h(X,G,!1,E):H&&G.append(a.document.createText(X.substring(L)));V;){if(V.equals(p[Q])){da=Q;break}V=h(V,G)}G=I}G=c;for(Q=N;Q<=A;Q++)if(c=p[Q],V=c.getPrevious(),c.equals(O[Q]))b&&(G=G.getChild(0));else{Q!=A||c.equals(O[Q])&&A<w?b&&(I=G.append(c.clone(0,f))):q?h(c,G,!1,z):P&&G.append(a.document.createText(c.substring(0,C)));if(Q>da)for(;V;)V=h(V,G,!0);G=I}l||g()}}
function b(){var a=!1,b=CKEDITOR.dom.walker.whitespaces(),c=CKEDITOR.dom.walker.bookmark(!0),d=CKEDITOR.dom.walker.bogus();return function(f){return c(f)||b(f)?!0:d(f)&&!a?a=!0:f.type==CKEDITOR.NODE_TEXT&&(f.hasAscendant("pre")||CKEDITOR.tools.trim(f.getText()).length)||f.type==CKEDITOR.NODE_ELEMENT&&!f.is(h)?!1:!0}}function c(a){var b=CKEDITOR.dom.walker.whitespaces(),c=CKEDITOR.dom.walker.bookmark(1);return function(d){return c(d)||b(d)?!0:!a&&k(d)||d.type==CKEDITOR.NODE_ELEMENT&&d.is(CKEDITOR.dtd.$removeEmpty)}}
function f(a){return function(){var b;return this[a?"getPreviousNode":"getNextNode"](function(a){!b&&r(a)&&(b=a);return n(a)&&!(k(a)&&a.equals(b))})}}var h={abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,"var":1},k=CKEDITOR.dom.walker.bogus(),g=/^[\t\r\n ]*(?:&nbsp;|\xa0)$/,n=CKEDITOR.dom.walker.editable(),r=CKEDITOR.dom.walker.ignored(!0);CKEDITOR.dom.range.prototype={clone:function(){var a=
new CKEDITOR.dom.range(this.root);a._setStartContainer(this.startContainer);a.startOffset=this.startOffset;a._setEndContainer(this.endContainer);a.endOffset=this.endOffset;a.collapsed=this.collapsed;return a},collapse:function(a){a?(this._setEndContainer(this.startContainer),this.endOffset=this.startOffset):(this._setStartContainer(this.endContainer),this.startOffset=this.endOffset);this.collapsed=!0},cloneContents:function(a){var b=new CKEDITOR.dom.documentFragment(this.document);this.collapsed||
d(this,2,b,!1,"undefined"==typeof a?!0:a);return b},deleteContents:function(a){this.collapsed||d(this,0,null,a)},extractContents:function(a,b){var c=new CKEDITOR.dom.documentFragment(this.document);this.collapsed||d(this,1,c,a,"undefined"==typeof b?!0:b);return c},createBookmark:function(a){var b,c,d,f,h=this.collapsed;b=this.document.createElement("span");b.data("cke-bookmark",1);b.setStyle("display","none");b.setHtml("\x26nbsp;");a&&(d="cke_bm_"+CKEDITOR.tools.getNextNumber(),b.setAttribute("id",
d+(h?"C":"S")));h||(c=b.clone(),c.setHtml("\x26nbsp;"),a&&c.setAttribute("id",d+"E"),f=this.clone(),f.collapse(),f.insertNode(c));f=this.clone();f.collapse(!0);f.insertNode(b);c?(this.setStartAfter(b),this.setEndBefore(c)):this.moveToPosition(b,CKEDITOR.POSITION_AFTER_END);return{startNode:a?d+(h?"C":"S"):b,endNode:a?d+"E":c,serializable:a,collapsed:h}},createBookmark2:function(){function a(b){var e=b.container,d=b.offset,m;m=e;var f=d;m=m.type!=CKEDITOR.NODE_ELEMENT||0===f||f==m.getChildCount()?
0:m.getChild(f-1).type==CKEDITOR.NODE_TEXT&&m.getChild(f).type==CKEDITOR.NODE_TEXT;m&&(e=e.getChild(d-1),d=e.getLength());if(e.type==CKEDITOR.NODE_ELEMENT&&0<d){a:{for(m=e;d--;)if(f=m.getChild(d).getIndex(!0),0<=f){d=f;break a}d=-1}d+=1}if(e.type==CKEDITOR.NODE_TEXT){m=e;for(f=0;(m=m.getPrevious())&&m.type==CKEDITOR.NODE_TEXT;)f+=m.getText().replace(CKEDITOR.dom.selection.FILLING_CHAR_SEQUENCE,"").length;m=f;e.getText()?d+=m:(f=e.getPrevious(c),m?(d=m,e=f?f.getNext():e.getParent().getFirst()):(e=
e.getParent(),d=f?f.getIndex(!0)+1:0))}b.container=e;b.offset=d}function b(a,c){var e=c.getCustomData("cke-fillingChar");if(e){var d=a.container;e.equals(d)&&(a.offset-=CKEDITOR.dom.selection.FILLING_CHAR_SEQUENCE.length,0>=a.offset&&(a.offset=d.getIndex(),a.container=d.getParent()))}}var c=CKEDITOR.dom.walker.nodeType(CKEDITOR.NODE_TEXT,!0);return function(c){var d=this.collapsed,f={container:this.startContainer,offset:this.startOffset},m={container:this.endContainer,offset:this.endOffset};c&&(a(f),
b(f,this.root),d||(a(m),b(m,this.root)));return{start:f.container.getAddress(c),end:d?null:m.container.getAddress(c),startOffset:f.offset,endOffset:m.offset,normalized:c,collapsed:d,is2:!0}}}(),moveToBookmark:function(a){if(a.is2){var b=this.document.getByAddress(a.start,a.normalized),c=a.startOffset,d=a.end&&this.document.getByAddress(a.end,a.normalized);a=a.endOffset;this.setStart(b,c);d?this.setEnd(d,a):this.collapse(!0)}else b=(c=a.serializable)?this.document.getById(a.startNode):a.startNode,
a=c?this.document.getById(a.endNode):a.endNode,this.setStartBefore(b),b.remove(),a?(this.setEndBefore(a),a.remove()):this.collapse(!0)},getBoundaryNodes:function(){var a=this.startContainer,b=this.endContainer,c=this.startOffset,d=this.endOffset,f;if(a.type==CKEDITOR.NODE_ELEMENT)if(f=a.getChildCount(),f>c)a=a.getChild(c);else if(1>f)a=a.getPreviousSourceNode();else{for(a=a.$;a.lastChild;)a=a.lastChild;a=new CKEDITOR.dom.node(a);a=a.getNextSourceNode()||a}if(b.type==CKEDITOR.NODE_ELEMENT)if(f=b.getChildCount(),
f>d)b=b.getChild(d).getPreviousSourceNode(!0);else if(1>f)b=b.getPreviousSourceNode();else{for(b=b.$;b.lastChild;)b=b.lastChild;b=new CKEDITOR.dom.node(b)}a.getPosition(b)&CKEDITOR.POSITION_FOLLOWING&&(a=b);return{startNode:a,endNode:b}},getCommonAncestor:function(a,b){var c=this.startContainer,d=this.endContainer,c=c.equals(d)?a&&c.type==CKEDITOR.NODE_ELEMENT&&this.startOffset==this.endOffset-1?c.getChild(this.startOffset):c:c.getCommonAncestor(d);return b&&!c.is?c.getParent():c},optimize:function(){var a=
this.startContainer,b=this.startOffset;a.type!=CKEDITOR.NODE_ELEMENT&&(b?b>=a.getLength()&&this.setStartAfter(a):this.setStartBefore(a));a=this.endContainer;b=this.endOffset;a.type!=CKEDITOR.NODE_ELEMENT&&(b?b>=a.getLength()&&this.setEndAfter(a):this.setEndBefore(a))},optimizeBookmark:function(){var a=this.startContainer,b=this.endContainer;a.is&&a.is("span")&&a.data("cke-bookmark")&&this.setStartAt(a,CKEDITOR.POSITION_BEFORE_START);b&&b.is&&b.is("span")&&b.data("cke-bookmark")&&this.setEndAt(b,CKEDITOR.POSITION_AFTER_END)},
trim:function(a,b){var c=this.startContainer,d=this.startOffset,f=this.collapsed;if((!a||f)&&c&&c.type==CKEDITOR.NODE_TEXT){if(d)if(d>=c.getLength())d=c.getIndex()+1,c=c.getParent();else{var h=c.split(d),d=c.getIndex()+1,c=c.getParent();this.startContainer.equals(this.endContainer)?this.setEnd(h,this.endOffset-this.startOffset):c.equals(this.endContainer)&&(this.endOffset+=1)}else d=c.getIndex(),c=c.getParent();this.setStart(c,d);if(f){this.collapse(!0);return}}c=this.endContainer;d=this.endOffset;
b||f||!c||c.type!=CKEDITOR.NODE_TEXT||(d?(d>=c.getLength()||c.split(d),d=c.getIndex()+1):d=c.getIndex(),c=c.getParent(),this.setEnd(c,d))},enlarge:function(a,b){function c(a){return a&&a.type==CKEDITOR.NODE_ELEMENT&&a.hasAttribute("contenteditable")?null:a}var d=new RegExp(/[^\s\ufeff]/);switch(a){case CKEDITOR.ENLARGE_INLINE:var f=1;case CKEDITOR.ENLARGE_ELEMENT:var h=function(a,b){var c=new CKEDITOR.dom.range(g);c.setStart(a,b);c.setEndAt(g,CKEDITOR.POSITION_BEFORE_END);var c=new CKEDITOR.dom.walker(c),
e;for(c.guard=function(a){return!(a.type==CKEDITOR.NODE_ELEMENT&&a.isBlockBoundary())};e=c.next();){if(e.type!=CKEDITOR.NODE_TEXT)return!1;M=e!=a?e.getText():e.substring(b);if(d.test(M))return!1}return!0};if(this.collapsed)break;var m=this.getCommonAncestor(),g=this.root,k,r,l,t,F,L=!1,C,M;C=this.startContainer;var q=this.startOffset;C.type==CKEDITOR.NODE_TEXT?(q&&(C=!CKEDITOR.tools.trim(C.substring(0,q)).length&&C,L=!!C),C&&((t=C.getPrevious())||(l=C.getParent()))):(q&&(t=C.getChild(q-1)||C.getLast()),
t||(l=C));for(l=c(l);l||t;){if(l&&!t){!F&&l.equals(m)&&(F=!0);if(f?l.isBlockBoundary():!g.contains(l))break;L&&"inline"==l.getComputedStyle("display")||(L=!1,F?k=l:this.setStartBefore(l));t=l.getPrevious()}for(;t;)if(C=!1,t.type==CKEDITOR.NODE_COMMENT)t=t.getPrevious();else{if(t.type==CKEDITOR.NODE_TEXT)M=t.getText(),d.test(M)&&(t=null),C=/[\s\ufeff]$/.test(M);else if((t.$.offsetWidth>(CKEDITOR.env.webkit?1:0)||b&&t.is("br"))&&!t.data("cke-bookmark"))if(L&&CKEDITOR.dtd.$removeEmpty[t.getName()]){M=
t.getText();if(d.test(M))t=null;else for(var q=t.$.getElementsByTagName("*"),E=0,z;z=q[E++];)if(!CKEDITOR.dtd.$removeEmpty[z.nodeName.toLowerCase()]){t=null;break}t&&(C=!!M.length)}else t=null;C&&(L?F?k=l:l&&this.setStartBefore(l):L=!0);if(t){C=t.getPrevious();if(!l&&!C){l=t;t=null;break}t=C}else l=null}l&&(l=c(l.getParent()))}C=this.endContainer;q=this.endOffset;l=t=null;F=L=!1;C.type==CKEDITOR.NODE_TEXT?CKEDITOR.tools.trim(C.substring(q)).length?L=!0:(L=!C.getLength(),q==C.getLength()?(t=C.getNext())||
(l=C.getParent()):h(C,q)&&(l=C.getParent())):(t=C.getChild(q))||(l=C);for(;l||t;){if(l&&!t){!F&&l.equals(m)&&(F=!0);if(f?l.isBlockBoundary():!g.contains(l))break;L&&"inline"==l.getComputedStyle("display")||(L=!1,F?r=l:l&&this.setEndAfter(l));t=l.getNext()}for(;t;){C=!1;if(t.type==CKEDITOR.NODE_TEXT)M=t.getText(),h(t,0)||(t=null),C=/^[\s\ufeff]/.test(M);else if(t.type==CKEDITOR.NODE_ELEMENT){if((0<t.$.offsetWidth||b&&t.is("br"))&&!t.data("cke-bookmark"))if(L&&CKEDITOR.dtd.$removeEmpty[t.getName()]){M=
t.getText();if(d.test(M))t=null;else for(q=t.$.getElementsByTagName("*"),E=0;z=q[E++];)if(!CKEDITOR.dtd.$removeEmpty[z.nodeName.toLowerCase()]){t=null;break}t&&(C=!!M.length)}else t=null}else C=1;C&&L&&(F?r=l:this.setEndAfter(l));if(t){C=t.getNext();if(!l&&!C){l=t;t=null;break}t=C}else l=null}l&&(l=c(l.getParent()))}k&&r&&(m=k.contains(r)?r:k,this.setStartBefore(m),this.setEndAfter(m));break;case CKEDITOR.ENLARGE_BLOCK_CONTENTS:case CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS:l=new CKEDITOR.dom.range(this.root);
g=this.root;l.setStartAt(g,CKEDITOR.POSITION_AFTER_START);l.setEnd(this.startContainer,this.startOffset);l=new CKEDITOR.dom.walker(l);var H,P,O=CKEDITOR.dom.walker.blockBoundary(a==CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS?{br:1}:null),p=null,N=function(a){if(a.type==CKEDITOR.NODE_ELEMENT&&"false"==a.getAttribute("contenteditable"))if(p){if(p.equals(a)){p=null;return}}else p=a;else if(p)return;var b=O(a);b||(H=a);return b},f=function(a){var b=N(a);!b&&a.is&&a.is("br")&&(P=a);return b};l.guard=N;l=l.lastBackward();
H=H||g;this.setStartAt(H,!H.is("br")&&(!l&&this.checkStartOfBlock()||l&&H.contains(l))?CKEDITOR.POSITION_AFTER_START:CKEDITOR.POSITION_AFTER_END);if(a==CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS){l=this.clone();l=new CKEDITOR.dom.walker(l);var w=CKEDITOR.dom.walker.whitespaces(),A=CKEDITOR.dom.walker.bookmark();l.evaluator=function(a){return!w(a)&&!A(a)};if((l=l.previous())&&l.type==CKEDITOR.NODE_ELEMENT&&l.is("br"))break}l=this.clone();l.collapse();l.setEndAt(g,CKEDITOR.POSITION_BEFORE_END);l=new CKEDITOR.dom.walker(l);
l.guard=a==CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS?f:N;H=p=P=null;l=l.lastForward();H=H||g;this.setEndAt(H,!l&&this.checkEndOfBlock()||l&&H.contains(l)?CKEDITOR.POSITION_BEFORE_END:CKEDITOR.POSITION_BEFORE_START);P&&this.setEndAfter(P)}},shrink:function(a,b,c){var d="boolean"===typeof c?c:c&&"boolean"===typeof c.shrinkOnBlockBoundary?c.shrinkOnBlockBoundary:!0,f=c&&c.skipBogus;if(!this.collapsed){a=a||CKEDITOR.SHRINK_TEXT;var h=this.clone(),m=this.startContainer,g=this.endContainer,k=this.startOffset,
r=this.endOffset,l=c=1;m&&m.type==CKEDITOR.NODE_TEXT&&(k?k>=m.getLength()?h.setStartAfter(m):(h.setStartBefore(m),c=0):h.setStartBefore(m));g&&g.type==CKEDITOR.NODE_TEXT&&(r?r>=g.getLength()?h.setEndAfter(g):(h.setEndAfter(g),l=0):h.setEndBefore(g));var h=new CKEDITOR.dom.walker(h),t=CKEDITOR.dom.walker.bookmark(),F=CKEDITOR.dom.walker.bogus();h.evaluator=function(b){return b.type==(a==CKEDITOR.SHRINK_ELEMENT?CKEDITOR.NODE_ELEMENT:CKEDITOR.NODE_TEXT)};var L;h.guard=function(b,c){if(f&&F(b)||t(b))return!0;
if(a==CKEDITOR.SHRINK_ELEMENT&&b.type==CKEDITOR.NODE_TEXT||c&&b.equals(L)||!1===d&&b.type==CKEDITOR.NODE_ELEMENT&&b.isBlockBoundary()||b.type==CKEDITOR.NODE_ELEMENT&&b.hasAttribute("contenteditable"))return!1;c||b.type!=CKEDITOR.NODE_ELEMENT||(L=b);return!0};c&&(m=h[a==CKEDITOR.SHRINK_ELEMENT?"lastForward":"next"]())&&this.setStartAt(m,b?CKEDITOR.POSITION_AFTER_START:CKEDITOR.POSITION_BEFORE_START);l&&(h.reset(),(h=h[a==CKEDITOR.SHRINK_ELEMENT?"lastBackward":"previous"]())&&this.setEndAt(h,b?CKEDITOR.POSITION_BEFORE_END:
CKEDITOR.POSITION_AFTER_END));return!(!c&&!l)}},insertNode:function(a){this.optimizeBookmark();this.trim(!1,!0);var b=this.startContainer,c=b.getChild(this.startOffset);c?a.insertBefore(c):b.append(a);a.getParent()&&a.getParent().equals(this.endContainer)&&this.endOffset++;this.setStartBefore(a)},moveToPosition:function(a,b){this.setStartAt(a,b);this.collapse(!0)},moveToRange:function(a){this.setStart(a.startContainer,a.startOffset);this.setEnd(a.endContainer,a.endOffset)},selectNodeContents:function(a){this.setStart(a,
0);this.setEnd(a,a.type==CKEDITOR.NODE_TEXT?a.getLength():a.getChildCount())},setStart:function(b,c){b.type==CKEDITOR.NODE_ELEMENT&&CKEDITOR.dtd.$empty[b.getName()]&&(c=b.getIndex(),b=b.getParent());this._setStartContainer(b);this.startOffset=c;this.endContainer||(this._setEndContainer(b),this.endOffset=c);a(this)},setEnd:function(b,c){b.type==CKEDITOR.NODE_ELEMENT&&CKEDITOR.dtd.$empty[b.getName()]&&(c=b.getIndex()+1,b=b.getParent());this._setEndContainer(b);this.endOffset=c;this.startContainer||
(this._setStartContainer(b),this.startOffset=c);a(this)},setStartAfter:function(a){this.setStart(a.getParent(),a.getIndex()+1)},setStartBefore:function(a){this.setStart(a.getParent(),a.getIndex())},setEndAfter:function(a){this.setEnd(a.getParent(),a.getIndex()+1)},setEndBefore:function(a){this.setEnd(a.getParent(),a.getIndex())},setStartAt:function(b,c){switch(c){case CKEDITOR.POSITION_AFTER_START:this.setStart(b,0);break;case CKEDITOR.POSITION_BEFORE_END:b.type==CKEDITOR.NODE_TEXT?this.setStart(b,
b.getLength()):this.setStart(b,b.getChildCount());break;case CKEDITOR.POSITION_BEFORE_START:this.setStartBefore(b);break;case CKEDITOR.POSITION_AFTER_END:this.setStartAfter(b)}a(this)},setEndAt:function(b,c){switch(c){case CKEDITOR.POSITION_AFTER_START:this.setEnd(b,0);break;case CKEDITOR.POSITION_BEFORE_END:b.type==CKEDITOR.NODE_TEXT?this.setEnd(b,b.getLength()):this.setEnd(b,b.getChildCount());break;case CKEDITOR.POSITION_BEFORE_START:this.setEndBefore(b);break;case CKEDITOR.POSITION_AFTER_END:this.setEndAfter(b)}a(this)},
fixBlock:function(a,b){var c=this.createBookmark(),d=this.document.createElement(b);this.collapse(a);this.enlarge(CKEDITOR.ENLARGE_BLOCK_CONTENTS);this.extractContents().appendTo(d);d.trim();this.insertNode(d);var f=d.getBogus();f&&f.remove();d.appendBogus();this.moveToBookmark(c);return d},splitBlock:function(a,b){var c=new CKEDITOR.dom.elementPath(this.startContainer,this.root),d=new CKEDITOR.dom.elementPath(this.endContainer,this.root),f=c.block,h=d.block,m=null;if(!c.blockLimit.equals(d.blockLimit))return null;
"br"!=a&&(f||(f=this.fixBlock(!0,a),h=(new CKEDITOR.dom.elementPath(this.endContainer,this.root)).block),h||(h=this.fixBlock(!1,a)));c=f&&this.checkStartOfBlock();d=h&&this.checkEndOfBlock();this.deleteContents();f&&f.equals(h)&&(d?(m=new CKEDITOR.dom.elementPath(this.startContainer,this.root),this.moveToPosition(h,CKEDITOR.POSITION_AFTER_END),h=null):c?(m=new CKEDITOR.dom.elementPath(this.startContainer,this.root),this.moveToPosition(f,CKEDITOR.POSITION_BEFORE_START),f=null):(h=this.splitElement(f,
b||!1),f.is("ul","ol")||f.appendBogus()));return{previousBlock:f,nextBlock:h,wasStartOfBlock:c,wasEndOfBlock:d,elementPath:m}},splitElement:function(a,b){if(!this.collapsed)return null;this.setEndAt(a,CKEDITOR.POSITION_BEFORE_END);var c=this.extractContents(!1,b||!1),d=a.clone(!1,b||!1);c.appendTo(d);d.insertAfter(a);this.moveToPosition(a,CKEDITOR.POSITION_AFTER_END);return d},removeEmptyBlocksAtEnd:function(){function a(d){return function(a){return b(a)||c(a)||a.type==CKEDITOR.NODE_ELEMENT&&a.isEmptyInlineRemoveable()||
d.is("table")&&a.is("caption")?!1:!0}}var b=CKEDITOR.dom.walker.whitespaces(),c=CKEDITOR.dom.walker.bookmark(!1);return function(b){for(var c=this.createBookmark(),d=this[b?"endPath":"startPath"](),f=d.block||d.blockLimit,h;f&&!f.equals(d.root)&&!f.getFirst(a(f));)h=f.getParent(),this[b?"setEndAt":"setStartAt"](f,CKEDITOR.POSITION_AFTER_END),f.remove(1),f=h;this.moveToBookmark(c)}}(),startPath:function(){return new CKEDITOR.dom.elementPath(this.startContainer,this.root)},endPath:function(){return new CKEDITOR.dom.elementPath(this.endContainer,
this.root)},checkBoundaryOfElement:function(a,b){var d=b==CKEDITOR.START,f=this.clone();f.collapse(d);f[d?"setStartAt":"setEndAt"](a,d?CKEDITOR.POSITION_AFTER_START:CKEDITOR.POSITION_BEFORE_END);f=new CKEDITOR.dom.walker(f);f.evaluator=c(d);return f[d?"checkBackward":"checkForward"]()},checkStartOfBlock:function(){var a=this.startContainer,c=this.startOffset;CKEDITOR.env.ie&&c&&a.type==CKEDITOR.NODE_TEXT&&(a=CKEDITOR.tools.ltrim(a.substring(0,c)),g.test(a)&&this.trim(0,1));this.trim();a=new CKEDITOR.dom.elementPath(this.startContainer,
this.root);c=this.clone();c.collapse(!0);c.setStartAt(a.block||a.blockLimit,CKEDITOR.POSITION_AFTER_START);a=new CKEDITOR.dom.walker(c);a.evaluator=b();return a.checkBackward()},checkEndOfBlock:function(){var a=this.endContainer,c=this.endOffset;CKEDITOR.env.ie&&a.type==CKEDITOR.NODE_TEXT&&(a=CKEDITOR.tools.rtrim(a.substring(c)),g.test(a)&&this.trim(1,0));this.trim();a=new CKEDITOR.dom.elementPath(this.endContainer,this.root);c=this.clone();c.collapse(!1);c.setEndAt(a.block||a.blockLimit,CKEDITOR.POSITION_BEFORE_END);
a=new CKEDITOR.dom.walker(c);a.evaluator=b();return a.checkForward()},getPreviousNode:function(a,b,c){var d=this.clone();d.collapse(1);d.setStartAt(c||this.root,CKEDITOR.POSITION_AFTER_START);c=new CKEDITOR.dom.walker(d);c.evaluator=a;c.guard=b;return c.previous()},getNextNode:function(a,b,c){var d=this.clone();d.collapse();d.setEndAt(c||this.root,CKEDITOR.POSITION_BEFORE_END);c=new CKEDITOR.dom.walker(d);c.evaluator=a;c.guard=b;return c.next()},checkReadOnly:function(){function a(b,c){for(;b;){if(b.type==
CKEDITOR.NODE_ELEMENT){if("false"==b.getAttribute("contentEditable")&&!b.data("cke-editable"))return 0;if(b.is("html")||"true"==b.getAttribute("contentEditable")&&(b.contains(c)||b.equals(c)))break}b=b.getParent()}return 1}return function(){var b=this.startContainer,c=this.endContainer;return!(a(b,c)&&a(c,b))}}(),moveToElementEditablePosition:function(a,b){if(a.type==CKEDITOR.NODE_ELEMENT&&!a.isEditable(!1))return this.moveToPosition(a,b?CKEDITOR.POSITION_AFTER_END:CKEDITOR.POSITION_BEFORE_START),
!0;for(var c=0;a;){if(a.type==CKEDITOR.NODE_TEXT){b&&this.endContainer&&this.checkEndOfBlock()&&g.test(a.getText())?this.moveToPosition(a,CKEDITOR.POSITION_BEFORE_START):this.moveToPosition(a,b?CKEDITOR.POSITION_AFTER_END:CKEDITOR.POSITION_BEFORE_START);c=1;break}if(a.type==CKEDITOR.NODE_ELEMENT)if(a.isEditable())this.moveToPosition(a,b?CKEDITOR.POSITION_BEFORE_END:CKEDITOR.POSITION_AFTER_START),c=1;else if(b&&a.is("br")&&this.endContainer&&this.checkEndOfBlock())this.moveToPosition(a,CKEDITOR.POSITION_BEFORE_START);
else if("false"==a.getAttribute("contenteditable")&&a.is(CKEDITOR.dtd.$block))return this.setStartBefore(a),this.setEndAfter(a),!0;var d=a,f=c,h=void 0;d.type==CKEDITOR.NODE_ELEMENT&&d.isEditable(!1)&&(h=d[b?"getLast":"getFirst"](r));f||h||(h=d[b?"getPrevious":"getNext"](r));a=h}return!!c},moveToClosestEditablePosition:function(a,b){var c,d=0,f,h,m=[CKEDITOR.POSITION_AFTER_END,CKEDITOR.POSITION_BEFORE_START];a?(c=new CKEDITOR.dom.range(this.root),c.moveToPosition(a,m[b?0:1])):c=this.clone();if(a&&
!a.is(CKEDITOR.dtd.$block))d=1;else if(f=c[b?"getNextEditableNode":"getPreviousEditableNode"]())d=1,(h=f.type==CKEDITOR.NODE_ELEMENT)&&f.is(CKEDITOR.dtd.$block)&&"false"==f.getAttribute("contenteditable")?(c.setStartAt(f,CKEDITOR.POSITION_BEFORE_START),c.setEndAt(f,CKEDITOR.POSITION_AFTER_END)):!CKEDITOR.env.needsBrFiller&&h&&f.is(CKEDITOR.dom.walker.validEmptyBlockContainers)?(c.setEnd(f,0),c.collapse()):c.moveToPosition(f,m[b?1:0]);d&&this.moveToRange(c);return!!d},moveToElementEditStart:function(a){return this.moveToElementEditablePosition(a)},
moveToElementEditEnd:function(a){return this.moveToElementEditablePosition(a,!0)},getEnclosedNode:function(){var a=this.clone();a.optimize();if(a.startContainer.type!=CKEDITOR.NODE_ELEMENT||a.endContainer.type!=CKEDITOR.NODE_ELEMENT)return null;var a=new CKEDITOR.dom.walker(a),b=CKEDITOR.dom.walker.bookmark(!1,!0),c=CKEDITOR.dom.walker.whitespaces(!0);a.evaluator=function(a){return c(a)&&b(a)};var d=a.next();a.reset();return d&&d.equals(a.previous())?d:null},getTouchedStartNode:function(){var a=this.startContainer;
return this.collapsed||a.type!=CKEDITOR.NODE_ELEMENT?a:a.getChild(this.startOffset)||a},getTouchedEndNode:function(){var a=this.endContainer;return this.collapsed||a.type!=CKEDITOR.NODE_ELEMENT?a:a.getChild(this.endOffset-1)||a},getNextEditableNode:f(),getPreviousEditableNode:f(1),_getTableElement:function(a){a=a||{td:1,th:1,tr:1,tbody:1,thead:1,tfoot:1,table:1};var b=this.startContainer,c=this.endContainer,d=b.getAscendant("table",!0),f=c.getAscendant("table",!0);return CKEDITOR.env.safari&&d&&c.equals(this.root)?
b.getAscendant(a,!0):this.getEnclosedNode()?this.getEnclosedNode().getAscendant(a,!0):d&&f&&(d.equals(f)||d.contains(f)||f.contains(d))?b.getAscendant(a,!0):null},scrollIntoView:function(){var a=new CKEDITOR.dom.element.createFromHtml("\x3cspan\x3e\x26nbsp;\x3c/span\x3e",this.document),b,c,d,f=this.clone();f.optimize();(d=f.startContainer.type==CKEDITOR.NODE_TEXT)?(c=f.startContainer.getText(),b=f.startContainer.split(f.startOffset),a.insertAfter(f.startContainer)):f.insertNode(a);a.scrollIntoView();
d&&(f.startContainer.setText(c),b.remove());a.remove()},getClientRects:function(){function a(b,c){var d=CKEDITOR.tools.array.map(b,function(a){return a}),e=new CKEDITOR.dom.range(c.root),f,h,l;c.startContainer instanceof CKEDITOR.dom.element&&(h=0===c.startOffset&&c.startContainer.hasAttribute("data-widget"));c.endContainer instanceof CKEDITOR.dom.element&&(l=(l=c.endOffset===(c.endContainer.getChildCount?c.endContainer.getChildCount():c.endContainer.length))&&c.endContainer.hasAttribute("data-widget"));
h&&e.setStart(c.startContainer.getParent(),c.startContainer.getIndex());l&&e.setEnd(c.endContainer.getParent(),c.endContainer.getIndex()+1);if(h||l)c=e;e=c.cloneContents();e=CKEDITOR.dom.document.prototype.find.call(e,"[data-cke-widget-id]").toArray();if(e=CKEDITOR.tools.array.map(e,function(a){var b=c.root.editor;a=a.getAttribute("data-cke-widget-id");return b.widgets.instances[a].element}))return e=CKEDITOR.tools.array.map(e,function(a){var b;b=a.getParent().hasClass("cke_widget_wrapper")?a.getParent():
a;f=this.root.getDocument().$.createRange();f.setStart(b.getParent().$,b.getIndex());f.setEnd(b.getParent().$,b.getIndex()+1);b=f.getClientRects();b.widgetRect=a.getClientRect();return b},c),CKEDITOR.tools.array.forEach(e,function(a){function b(e){CKEDITOR.tools.array.forEach(d,function(b,f){var l=CKEDITOR.tools.objectCompare(a[e],b);l||(l=CKEDITOR.tools.objectCompare(a.widgetRect,b));l&&(Array.prototype.splice.call(d,f,a.length-e,a.widgetRect),c=!0)});c||(e<d.length-1?b(e+1):d.push(a.widgetRect))}
var c;b(0)}),d}function b(a,c,e){var f;c.collapsed?e.startContainer instanceof CKEDITOR.dom.element?(a=e.checkStartOfBlock(),f=new CKEDITOR.dom.text("​"),a?e.startContainer.append(f,!0):0===e.startOffset?f.insertBefore(e.startContainer.getFirst()):(e=e.startContainer.getChildren().getItem(e.startOffset-1),f.insertAfter(e)),c.setStart(f.$,0),c.setEnd(f.$,0),a=c.getClientRects(),f.remove()):e.startContainer instanceof CKEDITOR.dom.text&&(""===e.startContainer.getText()?(e.startContainer.setText("​"),
a=c.getClientRects(),e.startContainer.setText("")):a=[d(e.createBookmark())]):a=[d(e.createBookmark())];return a}function c(a,b,d){a=CKEDITOR.tools.extend({},a);b&&(a=CKEDITOR.tools.getAbsoluteRectPosition(d.document.getWindow(),a));!a.width&&(a.width=a.right-a.left);!a.height&&(a.height=a.bottom-a.top);return a}function d(a){var b=a.startNode;a=a.endNode;var c;b.setText("​");b.removeStyle("display");a?(a.setText("​"),a.removeStyle("display"),c=[b.getClientRect(),a.getClientRect()],a.remove()):c=
[b.getClientRect(),b.getClientRect()];b.remove();return{right:Math.max(c[0].right,c[1].right),bottom:Math.max(c[0].bottom,c[1].bottom),left:Math.min(c[0].left,c[1].left),top:Math.min(c[0].top,c[1].top),width:Math.abs(c[0].left-c[1].left),height:Math.max(c[0].bottom,c[1].bottom)-Math.min(c[0].top,c[1].top)}}return void 0!==this.document.getSelection?function(d){var f=this.root.getDocument().$.createRange(),m;f.setStart(this.startContainer.$,this.startOffset);f.setEnd(this.endContainer.$,this.endOffset);
m=f.getClientRects();m=a(m,this);m.length||(m=b(m,f,this));return CKEDITOR.tools.array.map(m,function(a){return c(a,d,this)},this)}:function(a){return[c(d(this.createBookmark()),a,this)]}}(),_setStartContainer:function(a){this.startContainer=a},_setEndContainer:function(a){this.endContainer=a},_find:function(a,b){var c=this.getCommonAncestor(),d=this.getBoundaryNodes(),f=[],h,m,g,k;if(c&&c.find)for(m=c.find(a),h=0;h<m.count();h++)if(c=m.getItem(h),b||!c.isReadOnly())g=c.getPosition(d.startNode)&CKEDITOR.POSITION_FOLLOWING||
d.startNode.equals(c),k=c.getPosition(d.endNode)&CKEDITOR.POSITION_PRECEDING+CKEDITOR.POSITION_IS_CONTAINED||d.endNode.equals(c),g&&k&&f.push(c);return f}};CKEDITOR.dom.range.mergeRanges=function(a){return CKEDITOR.tools.array.reduce(a,function(a,b){var c=a[a.length-1],d=!1;b=b.clone();b.enlarge(CKEDITOR.ENLARGE_ELEMENT);if(c){var e=new CKEDITOR.dom.range(b.root),d=new CKEDITOR.dom.walker(e),f=CKEDITOR.dom.walker.whitespaces();e.setStart(c.endContainer,c.endOffset);e.setEnd(b.startContainer,b.startOffset);
for(e=d.next();f(e)||b.endContainer.equals(e);)e=d.next();d=!e}d?c.setEnd(b.endContainer,b.endOffset):a.push(b);return a},[])}})();CKEDITOR.POSITION_AFTER_START=1;CKEDITOR.POSITION_BEFORE_END=2;CKEDITOR.POSITION_BEFORE_START=3;CKEDITOR.POSITION_AFTER_END=4;CKEDITOR.ENLARGE_ELEMENT=1;CKEDITOR.ENLARGE_BLOCK_CONTENTS=2;CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS=3;CKEDITOR.ENLARGE_INLINE=4;CKEDITOR.START=1;CKEDITOR.END=2;CKEDITOR.SHRINK_ELEMENT=1;CKEDITOR.SHRINK_TEXT=2;"use strict";
(function(){function a(a){1>arguments.length||(this.range=a,this.forceBrBreak=0,this.enlargeBr=1,this.enforceRealBlocks=0,this._||(this._={}))}function d(a){var b=[];a.forEach(function(a){if("true"==a.getAttribute("contenteditable"))return b.push(a),!1},CKEDITOR.NODE_ELEMENT,!0);return b}function b(a,c,f,h){a:{null==h&&(h=d(f));for(var g;g=h.shift();)if(g.getDtd().p){h={element:g,remaining:h};break a}h=null}if(!h)return 0;if((g=CKEDITOR.filter.instances[h.element.data("cke-filter")])&&!g.check(c))return b(a,
c,f,h.remaining);c=new CKEDITOR.dom.range(h.element);c.selectNodeContents(h.element);c=c.createIterator();c.enlargeBr=a.enlargeBr;c.enforceRealBlocks=a.enforceRealBlocks;c.activeFilter=c.filter=g;a._.nestedEditable={element:h.element,container:f,remaining:h.remaining,iterator:c};return 1}function c(a,b,c){if(!b)return!1;a=a.clone();a.collapse(!c);return a.checkBoundaryOfElement(b,c?CKEDITOR.START:CKEDITOR.END)}var f=/^[\r\n\t ]+$/,h=CKEDITOR.dom.walker.bookmark(!1,!0),k=CKEDITOR.dom.walker.whitespaces(!0),
g=function(a){return h(a)&&k(a)},n={dd:1,dt:1,li:1};a.prototype={getNextParagraph:function(a){var d,k,v,B,D;a=a||"p";if(this._.nestedEditable){if(d=this._.nestedEditable.iterator.getNextParagraph(a))return this.activeFilter=this._.nestedEditable.iterator.activeFilter,d;this.activeFilter=this.filter;if(b(this,a,this._.nestedEditable.container,this._.nestedEditable.remaining))return this.activeFilter=this._.nestedEditable.iterator.activeFilter,this._.nestedEditable.iterator.getNextParagraph(a);this._.nestedEditable=
null}if(!this.range.root.getDtd()[a])return null;if(!this._.started){var x=this.range.clone();k=x.startPath();var m=x.endPath(),J=!x.collapsed&&c(x,k.block),u=!x.collapsed&&c(x,m.block,1);x.shrink(CKEDITOR.SHRINK_ELEMENT,!0);J&&x.setStartAt(k.block,CKEDITOR.POSITION_BEFORE_END);u&&x.setEndAt(m.block,CKEDITOR.POSITION_AFTER_START);k=x.endContainer.hasAscendant("pre",!0)||x.startContainer.hasAscendant("pre",!0);x.enlarge(this.forceBrBreak&&!k||!this.enlargeBr?CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS:CKEDITOR.ENLARGE_BLOCK_CONTENTS);
x.collapsed||(k=new CKEDITOR.dom.walker(x.clone()),m=CKEDITOR.dom.walker.bookmark(!0,!0),k.evaluator=m,this._.nextNode=k.next(),k=new CKEDITOR.dom.walker(x.clone()),k.evaluator=m,k=k.previous(),this._.lastNode=k.getNextSourceNode(!0,null,x.root),this._.lastNode&&this._.lastNode.type==CKEDITOR.NODE_TEXT&&!CKEDITOR.tools.trim(this._.lastNode.getText())&&this._.lastNode.getParent().isBlockBoundary()&&(m=this.range.clone(),m.moveToPosition(this._.lastNode,CKEDITOR.POSITION_AFTER_END),m.checkEndOfBlock()&&
(m=new CKEDITOR.dom.elementPath(m.endContainer,m.root),this._.lastNode=(m.block||m.blockLimit).getNextSourceNode(!0))),this._.lastNode&&x.root.contains(this._.lastNode)||(this._.lastNode=this._.docEndMarker=x.document.createText(""),this._.lastNode.insertAfter(k)),x=null);this._.started=1;k=x}m=this._.nextNode;x=this._.lastNode;for(this._.nextNode=null;m;){var J=0,u=m.hasAscendant("pre"),K=m.type!=CKEDITOR.NODE_ELEMENT,l=0;if(K)m.type==CKEDITOR.NODE_TEXT&&f.test(m.getText())&&(K=0);else{var t=m.getName();
if(CKEDITOR.dtd.$block[t]&&"false"==m.getAttribute("contenteditable")){d=m;b(this,a,d);break}else if(m.isBlockBoundary(this.forceBrBreak&&!u&&{br:1})){if("br"==t)K=1;else if(!k&&!m.getChildCount()&&"hr"!=t){d=m;v=m.equals(x);break}k&&(k.setEndAt(m,CKEDITOR.POSITION_BEFORE_START),"br"!=t&&(this._.nextNode=m));J=1}else{if(m.getFirst()){k||(k=this.range.clone(),k.setStartAt(m,CKEDITOR.POSITION_BEFORE_START));m=m.getFirst();continue}K=1}}K&&!k&&(k=this.range.clone(),k.setStartAt(m,CKEDITOR.POSITION_BEFORE_START));
v=(!J||K)&&m.equals(x);if(k&&!J)for(;!m.getNext(g)&&!v;){t=m.getParent();if(t.isBlockBoundary(this.forceBrBreak&&!u&&{br:1})){J=1;K=0;v||t.equals(x);k.setEndAt(t,CKEDITOR.POSITION_BEFORE_END);break}m=t;K=1;v=m.equals(x);l=1}K&&k.setEndAt(m,CKEDITOR.POSITION_AFTER_END);m=this._getNextSourceNode(m,l,x);if((v=!m)||J&&k)break}if(!d){if(!k)return this._.docEndMarker&&this._.docEndMarker.remove(),this._.nextNode=null;d=new CKEDITOR.dom.elementPath(k.startContainer,k.root);m=d.blockLimit;J={div:1,th:1,td:1};
d=d.block;!d&&m&&!this.enforceRealBlocks&&J[m.getName()]&&k.checkStartOfBlock()&&k.checkEndOfBlock()&&!m.equals(k.root)?d=m:!d||this.enforceRealBlocks&&d.is(n)?(d=this.range.document.createElement(a),k.extractContents().appendTo(d),d.trim(),k.insertNode(d),B=D=!0):"li"!=d.getName()?k.checkStartOfBlock()&&k.checkEndOfBlock()||(d=d.clone(!1),k.extractContents().appendTo(d),d.trim(),D=k.splitBlock(),B=!D.wasStartOfBlock,D=!D.wasEndOfBlock,k.insertNode(d)):v||(this._.nextNode=d.equals(x)?null:this._getNextSourceNode(k.getBoundaryNodes().endNode,
1,x))}B&&(B=d.getPrevious())&&B.type==CKEDITOR.NODE_ELEMENT&&("br"==B.getName()?B.remove():B.getLast()&&"br"==B.getLast().$.nodeName.toLowerCase()&&B.getLast().remove());D&&(B=d.getLast())&&B.type==CKEDITOR.NODE_ELEMENT&&"br"==B.getName()&&(!CKEDITOR.env.needsBrFiller||B.getPrevious(h)||B.getNext(h))&&B.remove();this._.nextNode||(this._.nextNode=v||d.equals(x)||!x?null:this._getNextSourceNode(d,1,x));return d},_getNextSourceNode:function(a,b,c){function d(a){return!(a.equals(c)||a.equals(f))}var f=
this.range.root;for(a=a.getNextSourceNode(b,null,d);!h(a);)a=a.getNextSourceNode(b,null,d);return a}};CKEDITOR.dom.range.prototype.createIterator=function(){return new a(this)}})();
CKEDITOR.command=function(a,d){this.uiItems=[];this.exec=function(b){if(this.state==CKEDITOR.TRISTATE_DISABLED||!this.checkAllowed())return!1;this.editorFocus&&a.focus();return!1===this.fire("exec")?!0:!1!==d.exec.call(this,a,b)};this.refresh=function(a,b){if(!this.readOnly&&a.readOnly)return!0;if(this.context&&!b.isContextFor(this.context)||!this.checkAllowed(!0))return this.disable(),!0;this.startDisabled||this.enable();this.modes&&!this.modes[a.mode]&&this.disable();return!1===this.fire("refresh",
{editor:a,path:b})?!0:d.refresh&&!1!==d.refresh.apply(this,arguments)};var b;this.checkAllowed=function(c){return c||"boolean"!=typeof b?b=a.activeFilter.checkFeature(this):b};CKEDITOR.tools.extend(this,d,{modes:{wysiwyg:1},editorFocus:1,contextSensitive:!!d.context,state:CKEDITOR.TRISTATE_DISABLED});CKEDITOR.event.call(this)};
CKEDITOR.command.prototype={enable:function(){this.state==CKEDITOR.TRISTATE_DISABLED&&this.checkAllowed()&&this.setState(this.preserveState&&"undefined"!=typeof this.previousState?this.previousState:CKEDITOR.TRISTATE_OFF)},disable:function(){this.setState(CKEDITOR.TRISTATE_DISABLED)},setState:function(a){if(this.state==a||a!=CKEDITOR.TRISTATE_DISABLED&&!this.checkAllowed())return!1;this.previousState=this.state;this.state=a;this.fire("state");return!0},toggleState:function(){this.state==CKEDITOR.TRISTATE_OFF?
this.setState(CKEDITOR.TRISTATE_ON):this.state==CKEDITOR.TRISTATE_ON&&this.setState(CKEDITOR.TRISTATE_OFF)}};CKEDITOR.event.implementOn(CKEDITOR.command.prototype);CKEDITOR.ENTER_P=1;CKEDITOR.ENTER_BR=2;CKEDITOR.ENTER_DIV=3;
CKEDITOR.config={customConfig:"config.js",autoUpdateElement:!0,language:"",defaultLanguage:"en",contentsLangDirection:"",enterMode:CKEDITOR.ENTER_P,forceEnterMode:!1,shiftEnterMode:CKEDITOR.ENTER_BR,docType:"\x3c!DOCTYPE html\x3e",bodyId:"",bodyClass:"",fullPage:!1,height:200,contentsCss:CKEDITOR.getUrl("contents.css"),extraPlugins:"",removePlugins:"",protectedSource:[],tabIndex:0,width:"",baseFloatZIndex:1E4,blockedKeystrokes:[CKEDITOR.CTRL+66,CKEDITOR.CTRL+73,CKEDITOR.CTRL+85]};
(function(){function a(a,b,c,d,f){var e,w;a=[];for(e in b){w=b[e];w="boolean"==typeof w?{}:"function"==typeof w?{match:w}:E(w);"$"!=e.charAt(0)&&(w.elements=e);c&&(w.featureName=c.toLowerCase());var l=w;l.elements=k(l.elements,/\s+/)||null;l.propertiesOnly=l.propertiesOnly||!0===l.elements;var p=/\s*,\s*/,m=void 0;for(m in P){l[m]=k(l[m],p)||null;var h=l,t=O[m],q=k(l[O[m]],p),A=l[m],z=[],g=!0,H=void 0;q?g=!1:q={};for(H in A)"!"==H.charAt(0)&&(H=H.slice(1),z.push(H),q[H]=!0,g=!1);for(;H=z.pop();)A[H]=
A["!"+H],delete A["!"+H];h[t]=(g?!1:q)||null}l.match=l.match||null;d.push(w);a.push(w)}b=f.elements;f=f.generic;var F;c=0;for(d=a.length;c<d;++c){e=E(a[c]);w=!0===e.classes||!0===e.styles||!0===e.attributes;l=e;m=t=p=void 0;for(p in P)l[p]=J(l[p]);h=!0;for(m in O){p=O[m];t=l[p];q=[];A=void 0;for(A in t)-1<A.indexOf("*")?q.push(new RegExp("^"+A.replace(/\*/g,".*")+"$")):q.push(A);t=q;t.length&&(l[p]=t,h=!1)}l.nothingRequired=h;l.noProperties=!(l.attributes||l.classes||l.styles);if(!0===e.elements||
null===e.elements)f[w?"unshift":"push"](e);else for(F in l=e.elements,delete e.elements,l)if(b[F])b[F][w?"unshift":"push"](e);else b[F]=[e]}}function d(a,c,d,f){if(!a.match||a.match(c))if(f||g(a,c))if(a.propertiesOnly||(d.valid=!0),d.allAttributes||(d.allAttributes=b(a.attributes,c.attributes,d.validAttributes)),d.allStyles||(d.allStyles=b(a.styles,c.styles,d.validStyles)),!d.allClasses){a=a.classes;c=c.classes;f=d.validClasses;if(a)if(!0===a)a=!0;else{for(var e=0,w=c.length,l;e<w;++e)l=c[e],f[l]||
(f[l]=a(l));a=!1}else a=!1;d.allClasses=a}}function b(a,b,c){if(!a)return!1;if(!0===a)return!0;for(var d in b)c[d]||(c[d]=a(d));return!1}function c(a,b,c){if(!a.match||a.match(b)){if(a.noProperties)return!1;c.hadInvalidAttribute=f(a.attributes,b.attributes)||c.hadInvalidAttribute;c.hadInvalidStyle=f(a.styles,b.styles)||c.hadInvalidStyle;a=a.classes;b=b.classes;if(a){for(var d=!1,e=!0===a,l=b.length;l--;)if(e||a(b[l]))b.splice(l,1),d=!0;a=d}else a=!1;c.hadInvalidClass=a||c.hadInvalidClass}}function f(a,
b){if(!a)return!1;var c=!1,d=!0===a,f;for(f in b)if(d||a(f))delete b[f],c=!0;return c}function h(a,b,c){if(a.disabled||a.customConfig&&!c||!b)return!1;a._.cachedChecks={};return!0}function k(a,b){if(!a)return!1;if(!0===a)return a;if("string"==typeof a)return a=z(a),"*"==a?!0:CKEDITOR.tools.convertArrayToObject(a.split(b));if(CKEDITOR.tools.isArray(a))return a.length?CKEDITOR.tools.convertArrayToObject(a):!1;var c={},d=0,f;for(f in a)c[f]=a[f],d++;return d?c:!1}function g(a,b){if(a.nothingRequired)return!0;
var c,d,f,e;if(f=a.requiredClasses)for(e=b.classes,c=0;c<f.length;++c)if(d=f[c],"string"==typeof d){if(-1==CKEDITOR.tools.indexOf(e,d))return!1}else if(!CKEDITOR.tools.checkIfAnyArrayItemMatches(e,d))return!1;return n(b.styles,a.requiredStyles)&&n(b.attributes,a.requiredAttributes)}function n(a,b){if(!b)return!0;for(var c=0,d;c<b.length;++c)if(d=b[c],"string"==typeof d){if(!(d in a))return!1}else if(!CKEDITOR.tools.checkIfAnyObjectPropertyMatches(a,d))return!1;return!0}function r(a){if(!a)return{};
a=a.split(/\s*,\s*/).sort();for(var b={};a.length;)b[a.shift()]="cke-test";return b}function e(a){var b,c,d,f,e={},l=1;for(a=z(a);b=a.match(p);)(c=b[2])?(d=y(c,"styles"),f=y(c,"attrs"),c=y(c,"classes")):d=f=c=null,e["$"+l++]={elements:b[1],classes:c,styles:d,attributes:f},a=a.slice(b[0].length);return e}function y(a,b){var c=a.match(N[b]);return c?z(c[1]):null}function v(a){var b=a.styleBackup=a.attributes.style,c=a.classBackup=a.attributes["class"];a.styles||(a.styles=CKEDITOR.tools.parseCssText(b||
"",1));a.classes||(a.classes=c?c.split(/\s+/):[])}function B(a,b,f,e){var l=0,p;e.toHtml&&(b.name=b.name.replace(w,"$1"));if(e.doCallbacks&&a.elementCallbacks){a:{p=a.elementCallbacks;for(var h=0,q=p.length,E;h<q;++h)if(E=p[h](b)){p=E;break a}p=void 0}if(p)return p}if(e.doTransform&&(p=a._.transformations[b.name])){v(b);for(h=0;h<p.length;++h)t(a,b,p[h]);x(b)}if(e.doFilter){a:{h=b.name;q=a._;a=q.allowedRules.elements[h];p=q.allowedRules.generic;h=q.disallowedRules.elements[h];q=q.disallowedRules.generic;
E=e.skipRequired;var z={valid:!1,validAttributes:{},validClasses:{},validStyles:{},allAttributes:!1,allClasses:!1,allStyles:!1,hadInvalidAttribute:!1,hadInvalidClass:!1,hadInvalidStyle:!1},g,k;if(a||p){v(b);if(h)for(g=0,k=h.length;g<k;++g)if(!1===c(h[g],b,z)){a=null;break a}if(q)for(g=0,k=q.length;g<k;++g)c(q[g],b,z);if(a)for(g=0,k=a.length;g<k;++g)d(a[g],b,z,E);if(p)for(g=0,k=p.length;g<k;++g)d(p[g],b,z,E);a=z}else a=null}if(!a||!a.valid)return f.push(b),1;k=a.validAttributes;var H=a.validStyles;
p=a.validClasses;var h=b.attributes,F=b.styles,q=b.classes;E=b.classBackup;var L=b.styleBackup,G,N,C=[],z=[],O=/^data-cke-/;g=!1;delete h.style;delete h["class"];delete b.classBackup;delete b.styleBackup;if(!a.allAttributes)for(G in h)k[G]||(O.test(G)?G==(N=G.replace(/^data-cke-saved-/,""))||k[N]||(delete h[G],g=!0):(delete h[G],g=!0));if(!a.allStyles||a.hadInvalidStyle){for(G in F)a.allStyles||H[G]?C.push(G+":"+F[G]):g=!0;C.length&&(h.style=C.sort().join("; "))}else L&&(h.style=L);if(!a.allClasses||
a.hadInvalidClass){for(G=0;G<q.length;++G)(a.allClasses||p[q[G]])&&z.push(q[G]);z.length&&(h["class"]=z.sort().join(" "));E&&z.length<E.split(/\s+/).length&&(g=!0)}else E&&(h["class"]=E);g&&(l=1);if(!e.skipFinalValidation&&!m(b))return f.push(b),1}e.toHtml&&(b.name=b.name.replace(A,"cke:$1"));return l}function D(a){var b=[],c;for(c in a)-1<c.indexOf("*")&&b.push(c.replace(/\*/g,".*"));return b.length?new RegExp("^(?:"+b.join("|")+")$"):null}function x(a){var b=a.attributes,c;delete b.style;delete b["class"];
if(c=CKEDITOR.tools.writeCssText(a.styles,!0))b.style=c;a.classes.length&&(b["class"]=a.classes.sort().join(" "))}function m(a){switch(a.name){case "a":if(!(a.children.length||a.attributes.name||a.attributes.id))return!1;break;case "img":if(!a.attributes.src)return!1}return!0}function J(a){if(!a)return!1;if(!0===a)return!0;var b=D(a);return function(c){return c in a||b&&c.match(b)}}function u(){return new CKEDITOR.htmlParser.element("br")}function K(a){return a.type==CKEDITOR.NODE_ELEMENT&&("br"==
a.name||q.$block[a.name])}function l(a,b,c){var d=a.name;if(q.$empty[d]||!a.children.length)"hr"==d&&"br"==b?a.replaceWith(u()):(a.parent&&c.push({check:"it",el:a.parent}),a.remove());else if(q.$block[d]||"tr"==d)if("br"==b)a.previous&&!K(a.previous)&&(b=u(),b.insertBefore(a)),a.next&&!K(a.next)&&(b=u(),b.insertAfter(a)),a.replaceWithChildren();else{var d=a.children,f;b:{f=q[b];for(var e=0,l=d.length,w;e<l;++e)if(w=d[e],w.type==CKEDITOR.NODE_ELEMENT&&!f[w.name]){f=!1;break b}f=!0}if(f)a.name=b,a.attributes=
{},c.push({check:"parent-down",el:a});else{f=a.parent;for(var e=f.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT||"body"==f.name,p,h,l=d.length;0<l;)w=d[--l],e&&(w.type==CKEDITOR.NODE_TEXT||w.type==CKEDITOR.NODE_ELEMENT&&q.$inline[w.name])?(p||(p=new CKEDITOR.htmlParser.element(b),p.insertAfter(a),c.push({check:"parent-down",el:p})),p.add(w,0)):(p=null,h=q[f.name]||q.span,w.insertAfter(a),f.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT||w.type!=CKEDITOR.NODE_ELEMENT||h[w.name]||c.push({check:"el-up",el:w}));a.remove()}}else d in
{style:1,script:1}?a.remove():(a.parent&&c.push({check:"it",el:a.parent}),a.replaceWithChildren())}function t(a,b,c){var d,f;for(d=0;d<c.length;++d)if(f=c[d],!(f.check&&!a.check(f.check,!1)||f.left&&!f.left(b))){f.right(b,G);break}}function F(a,b){var c=b.getDefinition(),d=c.attributes,f=c.styles,e,l,w,p;if(a.name!=c.element)return!1;for(e in d)if("class"==e)for(c=d[e].split(/\s+/),w=a.classes.join("|");p=c.pop();){if(-1==w.indexOf(p))return!1}else if(a.attributes[e]!=d[e])return!1;for(l in f)if(a.styles[l]!=
f[l])return!1;return!0}function L(a,b){var c,d;"string"==typeof a?c=a:a instanceof CKEDITOR.style?d=a:(c=a[0],d=a[1]);return[{element:c,left:d,right:function(a,c){c.transform(a,b)}}]}function C(a){return function(b){return F(b,a)}}function M(a){return function(b,c){c[a](b)}}var q=CKEDITOR.dtd,E=CKEDITOR.tools.copy,z=CKEDITOR.tools.trim,H=["","p","br","div"];CKEDITOR.FILTER_SKIP_TREE=2;CKEDITOR.filter=function(a){this.allowedContent=[];this.disallowedContent=[];this.elementCallbacks=null;this.disabled=
!1;this.editor=null;this.id=CKEDITOR.tools.getNextNumber();this._={allowedRules:{elements:{},generic:[]},disallowedRules:{elements:{},generic:[]},transformations:{},cachedTests:{},cachedChecks:{}};CKEDITOR.filter.instances[this.id]=this;if(a instanceof CKEDITOR.editor){a=this.editor=a;this.customConfig=!0;var b=a.config.allowedContent;!0===b?this.disabled=!0:(b||(this.customConfig=!1),this.allow(b,"config",1),this.allow(a.config.extraAllowedContent,"extra",1),this.allow(H[a.enterMode]+" "+H[a.shiftEnterMode],
"default",1),this.disallow(a.config.disallowedContent))}else this.customConfig=!1,this.allow(a,"default",1)};CKEDITOR.filter.instances={};CKEDITOR.filter.prototype={allow:function(b,c,d){if(!h(this,b,d))return!1;var f,l;if("string"==typeof b)b=e(b);else if(b instanceof CKEDITOR.style){if(b.toAllowedContentRules)return this.allow(b.toAllowedContentRules(this.editor),c,d);f=b.getDefinition();b={};d=f.attributes;b[f.element]=f={styles:f.styles,requiredStyles:f.styles&&CKEDITOR.tools.objectKeys(f.styles)};
d&&(d=E(d),f.classes=d["class"]?d["class"].split(/\s+/):null,f.requiredClasses=f.classes,delete d["class"],f.attributes=d,f.requiredAttributes=d&&CKEDITOR.tools.objectKeys(d))}else if(CKEDITOR.tools.isArray(b)){for(f=0;f<b.length;++f)l=this.allow(b[f],c,d);return l}a(this,b,c,this.allowedContent,this._.allowedRules);return!0},applyTo:function(a,b,c,d){if(this.disabled)return!1;var f=this,e=[],w=this.editor&&this.editor.config.protectedSource,p,h=!1,t={doFilter:!c,doTransform:!0,doCallbacks:!0,toHtml:b};
a.forEach(function(a){if(a.type==CKEDITOR.NODE_ELEMENT){if("off"==a.attributes["data-cke-filter"])return!1;if(!b||"span"!=a.name||!~CKEDITOR.tools.objectKeys(a.attributes).join("|").indexOf("data-cke-"))if(p=B(f,a,e,t),p&1)h=!0;else if(p&2)return!1}else if(a.type==CKEDITOR.NODE_COMMENT&&a.value.match(/^\{cke_protected\}(?!\{C\})/)){var c;a:{var d=decodeURIComponent(a.value.replace(/^\{cke_protected\}/,""));c=[];var l,m,q;if(w)for(m=0;m<w.length;++m)if((q=d.match(w[m]))&&q[0].length==d.length){c=!0;
break a}d=CKEDITOR.htmlParser.fragment.fromHtml(d);1==d.children.length&&(l=d.children[0]).type==CKEDITOR.NODE_ELEMENT&&B(f,l,c,t);c=!c.length}c||e.push(a)}},null,!0);e.length&&(h=!0);var E;a=[];d=H[d||(this.editor?this.editor.enterMode:CKEDITOR.ENTER_P)];for(var z;c=e.pop();)c.type==CKEDITOR.NODE_ELEMENT?l(c,d,a):c.remove();for(;E=a.pop();)if(c=E.el,c.parent)switch(z=q[c.parent.name]||q.span,E.check){case "it":q.$removeEmpty[c.name]&&!c.children.length?l(c,d,a):m(c)||l(c,d,a);break;case "el-up":c.parent.type==
CKEDITOR.NODE_DOCUMENT_FRAGMENT||z[c.name]||l(c,d,a);break;case "parent-down":c.parent.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT||z[c.name]||l(c.parent,d,a)}return h},checkFeature:function(a){if(this.disabled||!a)return!0;a.toFeature&&(a=a.toFeature(this.editor));return!a.requiredContent||this.check(a.requiredContent)},disable:function(){this.disabled=!0},disallow:function(b){if(!h(this,b,!0))return!1;"string"==typeof b&&(b=e(b));a(this,b,null,this.disallowedContent,this._.disallowedRules);return!0},
addContentForms:function(a){if(!this.disabled&&a){var b,c,d=[],f;for(b=0;b<a.length&&!f;++b)c=a[b],("string"==typeof c||c instanceof CKEDITOR.style)&&this.check(c)&&(f=c);if(f){for(b=0;b<a.length;++b)d.push(L(a[b],f));this.addTransformations(d)}}},addElementCallback:function(a){this.elementCallbacks||(this.elementCallbacks=[]);this.elementCallbacks.push(a)},addFeature:function(a){if(this.disabled||!a)return!0;a.toFeature&&(a=a.toFeature(this.editor));this.allow(a.allowedContent,a.name);this.addTransformations(a.contentTransformations);
this.addContentForms(a.contentForms);return a.requiredContent&&(this.customConfig||this.disallowedContent.length)?this.check(a.requiredContent):!0},addTransformations:function(a){var b,c;if(!this.disabled&&a){var d=this._.transformations,f;for(f=0;f<a.length;++f){b=a[f];var e=void 0,l=void 0,w=void 0,p=void 0,h=void 0,m=void 0;c=[];for(l=0;l<b.length;++l)w=b[l],"string"==typeof w?(w=w.split(/\s*:\s*/),p=w[0],h=null,m=w[1]):(p=w.check,h=w.left,m=w.right),e||(e=w,e=e.element?e.element:p?p.match(/^([a-z0-9]+)/i)[0]:
e.left.getDefinition().element),h instanceof CKEDITOR.style&&(h=C(h)),c.push({check:p==e?null:p,left:h,right:"string"==typeof m?M(m):m});b=e;d[b]||(d[b]=[]);d[b].push(c)}}},check:function(a,b,c){if(this.disabled)return!0;if(CKEDITOR.tools.isArray(a)){for(var d=a.length;d--;)if(this.check(a[d],b,c))return!0;return!1}var f,w;if("string"==typeof a){w=a+"\x3c"+(!1===b?"0":"1")+(c?"1":"0")+"\x3e";if(w in this._.cachedChecks)return this._.cachedChecks[w];f=e(a).$1;var l=f.styles,d=f.classes;f.name=f.elements;
f.classes=d=d?d.split(/\s*,\s*/):[];f.styles=r(l);f.attributes=r(f.attributes);f.children=[];d.length&&(f.attributes["class"]=d.join(" "));l&&(f.attributes.style=CKEDITOR.tools.writeCssText(f.styles))}else f=a.getDefinition(),l=f.styles,d=f.attributes||{},l&&!CKEDITOR.tools.isEmpty(l)?(l=E(l),d.style=CKEDITOR.tools.writeCssText(l,!0)):l={},f={name:f.element,attributes:d,classes:d["class"]?d["class"].split(/\s+/):[],styles:l,children:[]};var l=CKEDITOR.tools.clone(f),p=[],h;if(!1!==b&&(h=this._.transformations[f.name])){for(d=
0;d<h.length;++d)t(this,f,h[d]);x(f)}B(this,l,p,{doFilter:!0,doTransform:!1!==b,skipRequired:!c,skipFinalValidation:!c});0<p.length?c=!1:((b=f.attributes["class"])&&(f.attributes["class"]=f.attributes["class"].split(" ").sort().join(" ")),c=CKEDITOR.tools.objectCompare(f.attributes,l.attributes,!0),b&&(f.attributes["class"]=b));"string"==typeof a&&(this._.cachedChecks[w]=c);return c},getAllowedEnterMode:function(){var a=["p","div","br"],b={p:CKEDITOR.ENTER_P,div:CKEDITOR.ENTER_DIV,br:CKEDITOR.ENTER_BR};
return function(c,d){var f=a.slice(),e;if(this.check(H[c]))return c;for(d||(f=f.reverse());e=f.pop();)if(this.check(e))return b[e];return CKEDITOR.ENTER_BR}}(),clone:function(){var a=new CKEDITOR.filter,b=CKEDITOR.tools.clone;a.allowedContent=b(this.allowedContent);a._.allowedRules=b(this._.allowedRules);a.disallowedContent=b(this.disallowedContent);a._.disallowedRules=b(this._.disallowedRules);a._.transformations=b(this._.transformations);a.disabled=this.disabled;a.editor=this.editor;return a},destroy:function(){delete CKEDITOR.filter.instances[this.id];
delete this._;delete this.allowedContent;delete this.disallowedContent}};var P={styles:1,attributes:1,classes:1},O={styles:"requiredStyles",attributes:"requiredAttributes",classes:"requiredClasses"},p=/^([a-z0-9\-*\s]+)((?:\s*\{[!\w\-,\s\*]+\}\s*|\s*\[[!\w\-,\s\*]+\]\s*|\s*\([!\w\-,\s\*]+\)\s*){0,3})(?:;\s*|$)/i,N={styles:/{([^}]+)}/,attrs:/\[([^\]]+)\]/,classes:/\(([^\)]+)\)/},w=/^cke:(object|embed|param)$/,A=/^(object|embed|param)$/,G;G=CKEDITOR.filter.transformationsTools={sizeToStyle:function(a){this.lengthToStyle(a,
"width");this.lengthToStyle(a,"height")},sizeToAttribute:function(a){this.lengthToAttribute(a,"width");this.lengthToAttribute(a,"height")},lengthToStyle:function(a,b,c){c=c||b;if(!(c in a.styles)){var d=a.attributes[b];d&&(/^\d+$/.test(d)&&(d+="px"),a.styles[c]=d)}delete a.attributes[b]},lengthToAttribute:function(a,b,c){c=c||b;if(!(c in a.attributes)){var d=a.styles[b],f=d&&d.match(/^(\d+)(?:\.\d*)?px$/);f?a.attributes[c]=f[1]:"cke-test"==d&&(a.attributes[c]="cke-test")}delete a.styles[b]},alignmentToStyle:function(a){if(!("float"in
a.styles)){var b=a.attributes.align;if("left"==b||"right"==b)a.styles["float"]=b}delete a.attributes.align},alignmentToAttribute:function(a){if(!("align"in a.attributes)){var b=a.styles["float"];if("left"==b||"right"==b)a.attributes.align=b}delete a.styles["float"]},splitBorderShorthand:function(a){if(a.styles.border){var b=CKEDITOR.tools.style.parse.border(a.styles.border);b.color&&(a.styles["border-color"]=b.color);b.style&&(a.styles["border-style"]=b.style);b.width&&(a.styles["border-width"]=b.width);
delete a.styles.border}},listTypeToStyle:function(a){if(a.attributes.type)switch(a.attributes.type){case "a":a.styles["list-style-type"]="lower-alpha";break;case "A":a.styles["list-style-type"]="upper-alpha";break;case "i":a.styles["list-style-type"]="lower-roman";break;case "I":a.styles["list-style-type"]="upper-roman";break;case "1":a.styles["list-style-type"]="decimal";break;default:a.styles["list-style-type"]=a.attributes.type}},splitMarginShorthand:function(a){function b(d){a.styles["margin-top"]=
c[d[0]];a.styles["margin-right"]=c[d[1]];a.styles["margin-bottom"]=c[d[2]];a.styles["margin-left"]=c[d[3]]}if(a.styles.margin){var c=a.styles.margin.match(/(\-?[\.\d]+\w+)/g)||["0px"];switch(c.length){case 1:b([0,0,0,0]);break;case 2:b([0,1,0,1]);break;case 3:b([0,1,2,1]);break;case 4:b([0,1,2,3])}delete a.styles.margin}},matchesStyle:F,transform:function(a,b){if("string"==typeof b)a.name=b;else{var c=b.getDefinition(),d=c.styles,f=c.attributes,e,l,w,p;a.name=c.element;for(e in f)if("class"==e)for(c=
a.classes.join("|"),w=f[e].split(/\s+/);p=w.pop();)-1==c.indexOf(p)&&a.classes.push(p);else a.attributes[e]=f[e];for(l in d)a.styles[l]=d[l]}}}})();
(function(){CKEDITOR.focusManager=function(a){if(a.focusManager)return a.focusManager;this.hasFocus=!1;this.currentActive=null;this._={editor:a};return this};CKEDITOR.focusManager._={blurDelay:200};CKEDITOR.focusManager.prototype={focus:function(a){this._.timer&&clearTimeout(this._.timer);a&&(this.currentActive=a);this.hasFocus||this._.locked||((a=CKEDITOR.currentInstance)&&a.focusManager.blur(1),this.hasFocus=!0,(a=this._.editor.container)&&a.addClass("cke_focus"),this._.editor.fire("focus"))},lock:function(){this._.locked=
1},unlock:function(){delete this._.locked},blur:function(a){function d(){if(this.hasFocus){this.hasFocus=!1;var a=this._.editor.container;a&&a.removeClass("cke_focus");this._.editor.fire("blur")}}if(!this._.locked){this._.timer&&clearTimeout(this._.timer);var b=CKEDITOR.focusManager._.blurDelay;a||!b?d.call(this):this._.timer=CKEDITOR.tools.setTimeout(function(){delete this._.timer;d.call(this)},b,this)}},add:function(a,d){var b=a.getCustomData("focusmanager");if(!b||b!=this){b&&b.remove(a);var b=
"focus",c="blur";d&&(CKEDITOR.env.ie?(b="focusin",c="focusout"):CKEDITOR.event.useCapture=1);var f={blur:function(){a.equals(this.currentActive)&&this.blur()},focus:function(){this.focus(a)}};a.on(b,f.focus,this);a.on(c,f.blur,this);d&&(CKEDITOR.event.useCapture=0);a.setCustomData("focusmanager",this);a.setCustomData("focusmanager_handlers",f)}},remove:function(a){a.removeCustomData("focusmanager");var d=a.removeCustomData("focusmanager_handlers");a.removeListener("blur",d.blur);a.removeListener("focus",
d.focus)}}})();CKEDITOR.keystrokeHandler=function(a){if(a.keystrokeHandler)return a.keystrokeHandler;this.keystrokes={};this.blockedKeystrokes={};this._={editor:a};return this};
(function(){var a,d=function(b){b=b.data;var d=b.getKeystroke(),h=this.keystrokes[d],k=this._.editor;a=!1===k.fire("key",{keyCode:d,domEvent:b});a||(h&&(a=!1!==k.execCommand(h,{from:"keystrokeHandler"})),a||(a=!!this.blockedKeystrokes[d]));a&&b.preventDefault(!0);return!a},b=function(b){a&&(a=!1,b.data.preventDefault(!0))};CKEDITOR.keystrokeHandler.prototype={attach:function(a){a.on("keydown",d,this);if(CKEDITOR.env.gecko&&CKEDITOR.env.mac)a.on("keypress",b,this)}}})();
(function(){CKEDITOR.lang={languages:{af:1,ar:1,az:1,bg:1,bn:1,bs:1,ca:1,cs:1,cy:1,da:1,de:1,"de-ch":1,el:1,"en-au":1,"en-ca":1,"en-gb":1,en:1,eo:1,es:1,"es-mx":1,et:1,eu:1,fa:1,fi:1,fo:1,"fr-ca":1,fr:1,gl:1,gu:1,he:1,hi:1,hr:1,hu:1,id:1,is:1,it:1,ja:1,ka:1,km:1,ko:1,ku:1,lt:1,lv:1,mk:1,mn:1,ms:1,nb:1,nl:1,no:1,oc:1,pl:1,"pt-br":1,pt:1,ro:1,ru:1,si:1,sk:1,sl:1,sq:1,"sr-latn":1,sr:1,sv:1,th:1,tr:1,tt:1,ug:1,uk:1,vi:1,"zh-cn":1,zh:1},rtl:{ar:1,fa:1,he:1,ku:1,ug:1},load:function(a,d,b){a&&CKEDITOR.lang.languages[a]||
(a=this.detect(d,a));var c=this;d=function(){c[a].dir=c.rtl[a]?"rtl":"ltr";b(a,c[a])};this[a]?d():CKEDITOR.scriptLoader.load(CKEDITOR.getUrl("lang/"+a+".js"),d,this)},detect:function(a,d){var b=this.languages;d=d||navigator.userLanguage||navigator.language||a;var c=d.toLowerCase().match(/([a-z]+)(?:-([a-z]+))?/),f=c[1],c=c[2];b[f+"-"+c]?f=f+"-"+c:b[f]||(f=null);CKEDITOR.lang.detect=f?function(){return f}:function(a){return a};return f||a}}})();
CKEDITOR.scriptLoader=function(){var a={},d={};return{load:function(b,c,f,h){var k="string"==typeof b;k&&(b=[b]);f||(f=CKEDITOR);var g=b.length,n=[],r=[],e=function(a){c&&(k?c.call(f,a):c.call(f,n,r))};if(0===g)e(!0);else{var y=function(a,b){(b?n:r).push(a);0>=--g&&(h&&CKEDITOR.document.getDocumentElement().removeStyle("cursor"),e(b))},v=function(b,c){a[b]=1;var f=d[b];delete d[b];for(var e=0;e<f.length;e++)f[e](b,c)},B=function(b){if(a[b])y(b,!0);else{var f=d[b]||(d[b]=[]);f.push(y);if(!(1<f.length)){var e=
new CKEDITOR.dom.element("script");e.setAttributes({type:"text/javascript",src:b});c&&(CKEDITOR.env.ie&&(8>=CKEDITOR.env.version||CKEDITOR.env.ie9Compat)?e.$.onreadystatechange=function(){if("loaded"==e.$.readyState||"complete"==e.$.readyState)e.$.onreadystatechange=null,v(b,!0)}:(e.$.onload=function(){setTimeout(function(){v(b,!0)},0)},e.$.onerror=function(){v(b,!1)}));e.appendTo(CKEDITOR.document.getHead())}}};h&&CKEDITOR.document.getDocumentElement().setStyle("cursor","wait");for(var D=0;D<g;D++)B(b[D])}},
queue:function(){function a(){var b;(b=c[0])&&this.load(b.scriptUrl,b.callback,CKEDITOR,0)}var c=[];return function(d,h){var k=this;c.push({scriptUrl:d,callback:function(){h&&h.apply(this,arguments);c.shift();a.call(k)}});1==c.length&&a.call(this)}}()}}();CKEDITOR.resourceManager=function(a,d){this.basePath=a;this.fileName=d;this.registered={};this.loaded={};this.externals={};this._={waitingList:{}}};
CKEDITOR.resourceManager.prototype={add:function(a,d){if(this.registered[a])throw Error('[CKEDITOR.resourceManager.add] The resource name "'+a+'" is already registered.');var b=this.registered[a]=d||{};b.name=a;b.path=this.getPath(a);CKEDITOR.fire(a+CKEDITOR.tools.capitalize(this.fileName)+"Ready",b);return this.get(a)},get:function(a){return this.registered[a]||null},getPath:function(a){var d=this.externals[a];return CKEDITOR.getUrl(d&&d.dir||this.basePath+a+"/")},getFilePath:function(a){var d=this.externals[a];
return CKEDITOR.getUrl(this.getPath(a)+(d?d.file:this.fileName+".js"))},addExternal:function(a,d,b){a=a.split(",");for(var c=0;c<a.length;c++){var f=a[c];b||(d=d.replace(/[^\/]+$/,function(a){b=a;return""}));this.externals[f]={dir:d,file:b||this.fileName+".js"}}},load:function(a,d,b){CKEDITOR.tools.isArray(a)||(a=a?[a]:[]);for(var c=this.loaded,f=this.registered,h=[],k={},g={},n=0;n<a.length;n++){var r=a[n];if(r)if(c[r]||f[r])g[r]=this.get(r);else{var e=this.getFilePath(r);h.push(e);e in k||(k[e]=
[]);k[e].push(r)}}CKEDITOR.scriptLoader.load(h,function(a,f){if(f.length)throw Error('[CKEDITOR.resourceManager.load] Resource name "'+k[f[0]].join(",")+'" was not found at "'+f[0]+'".');for(var e=0;e<a.length;e++)for(var h=k[a[e]],n=0;n<h.length;n++){var m=h[n];g[m]=this.get(m);c[m]=1}d.call(b,g)},this)}};CKEDITOR.plugins=new CKEDITOR.resourceManager("plugins/","plugin");
CKEDITOR.plugins.load=CKEDITOR.tools.override(CKEDITOR.plugins.load,function(a){var d={};return function(b,c,f){var h={},k=function(b){a.call(this,b,function(a){CKEDITOR.tools.extend(h,a);var b=[],e;for(e in a){var g=a[e],v=g&&g.requires;if(!d[e]){if(g.icons)for(var B=g.icons.split(","),D=B.length;D--;)CKEDITOR.skin.addIcon(B[D],g.path+"icons/"+(CKEDITOR.env.hidpi&&g.hidpi?"hidpi/":"")+B[D]+".png");d[e]=1}if(v)for(v.split&&(v=v.split(",")),g=0;g<v.length;g++)h[v[g]]||b.push(v[g])}if(b.length)k.call(this,
b);else{for(e in h)g=h[e],g.onLoad&&!g.onLoad._called&&(!1===g.onLoad()&&delete h[e],g.onLoad._called=1);c&&c.call(f||window,h)}},this)};k.call(this,b)}});CKEDITOR.plugins.setLang=function(a,d,b){var c=this.get(a);a=c.langEntries||(c.langEntries={});c=c.lang||(c.lang=[]);c.split&&(c=c.split(","));-1==CKEDITOR.tools.indexOf(c,d)&&c.push(d);a[d]=b};CKEDITOR.ui=function(a){if(a.ui)return a.ui;this.items={};this.instances={};this.editor=a;this._={handlers:{}};return this};
CKEDITOR.ui.prototype={add:function(a,d,b){b.name=a.toLowerCase();var c=this.items[a]={type:d,command:b.command||null,args:Array.prototype.slice.call(arguments,2)};CKEDITOR.tools.extend(c,b)},get:function(a){return this.instances[a]},create:function(a){var d=this.items[a],b=d&&this._.handlers[d.type],c=d&&d.command&&this.editor.getCommand(d.command),b=b&&b.create.apply(this,d.args);this.instances[a]=b;c&&c.uiItems.push(b);b&&!b.type&&(b.type=d.type);return b},addHandler:function(a,d){this._.handlers[a]=
d},space:function(a){return CKEDITOR.document.getById(this.spaceId(a))},spaceId:function(a){return this.editor.id+"_"+a}};CKEDITOR.event.implementOn(CKEDITOR.ui);
(function(){function a(a,f,e){CKEDITOR.event.call(this);a=a&&CKEDITOR.tools.clone(a);if(void 0!==f){if(!(f instanceof CKEDITOR.dom.element))throw Error("Expect element of type CKEDITOR.dom.element.");if(!e)throw Error("One of the element modes must be specified.");if(CKEDITOR.env.ie&&CKEDITOR.env.quirks&&e==CKEDITOR.ELEMENT_MODE_INLINE)throw Error("Inline element mode is not supported on IE quirks.");if(!b(f,e))throw Error('The specified element mode is not supported on element: "'+f.getName()+'".');
this.element=f;this.elementMode=e;this.name=this.elementMode!=CKEDITOR.ELEMENT_MODE_APPENDTO&&(f.getId()||f.getNameAtt())}else this.elementMode=CKEDITOR.ELEMENT_MODE_NONE;this._={};this.commands={};this.templates={};this.name=this.name||d();this.id=CKEDITOR.tools.getNextId();this.status="unloaded";this.config=CKEDITOR.tools.prototypedCopy(CKEDITOR.config);this.ui=new CKEDITOR.ui(this);this.focusManager=new CKEDITOR.focusManager(this);this.keystrokeHandler=new CKEDITOR.keystrokeHandler(this);this.on("readOnly",
c);this.on("selectionChange",function(a){h(this,a.data.path)});this.on("activeFilterChange",function(){h(this,this.elementPath(),!0)});this.on("mode",c);this.on("instanceReady",function(){if(this.config.startupFocus){if("end"===this.config.startupFocus){var a=this.createRange();a.selectNodeContents(this.editable());a.shrink(CKEDITOR.SHRINK_ELEMENT,!0);a.collapse();this.getSelection().selectRanges([a])}this.focus()}});CKEDITOR.fire("instanceCreated",null,this);CKEDITOR.add(this);CKEDITOR.tools.setTimeout(function(){"destroyed"!==
this.status?g(this,a):CKEDITOR.warn("editor-incorrect-destroy")},0,this)}function d(){do var a="editor"+ ++D;while(CKEDITOR.instances[a]);return a}function b(a,b){return b==CKEDITOR.ELEMENT_MODE_INLINE?a.is(CKEDITOR.dtd.$editable)||a.is("textarea"):b==CKEDITOR.ELEMENT_MODE_REPLACE?!a.is(CKEDITOR.dtd.$nonBodyContent):1}function c(){var a=this.commands,b;for(b in a)f(this,a[b])}function f(a,b){b[b.startDisabled?"disable":a.readOnly&&!b.readOnly?"disable":b.modes[a.mode]?"enable":"disable"]()}function h(a,
b,c){if(b){var d,f,e=a.commands;for(f in e)d=e[f],(c||d.contextSensitive)&&d.refresh(a,b)}}function k(a){var b=a.config.customConfig;if(!b)return!1;var b=CKEDITOR.getUrl(b),c=x[b]||(x[b]={});c.fn?(c.fn.call(a,a.config),CKEDITOR.getUrl(a.config.customConfig)!=b&&k(a)||a.fireOnce("customConfigLoaded")):CKEDITOR.scriptLoader.queue(b,function(){c.fn=CKEDITOR.editorConfig?CKEDITOR.editorConfig:function(){};k(a)});return!0}function g(a,b){a.on("customConfigLoaded",function(){if(b){if(b.on)for(var c in b.on)a.on(c,
b.on[c]);CKEDITOR.tools.extend(a.config,b,!0);delete a.config.on}c=a.config;a.readOnly=c.readOnly?!0:a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE?a.element.is("textarea")?a.element.hasAttribute("disabled")||a.element.hasAttribute("readonly"):a.element.isReadOnly():a.elementMode==CKEDITOR.ELEMENT_MODE_REPLACE?a.element.hasAttribute("disabled")||a.element.hasAttribute("readonly"):!1;a.blockless=a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE?!(a.element.is("textarea")||CKEDITOR.dtd[a.element.getName()].p):
!1;a.tabIndex=c.tabIndex||a.element&&a.element.getAttribute("tabindex")||0;a.activeEnterMode=a.enterMode=a.blockless?CKEDITOR.ENTER_BR:c.enterMode;a.activeShiftEnterMode=a.shiftEnterMode=a.blockless?CKEDITOR.ENTER_BR:c.shiftEnterMode;c.skin&&(CKEDITOR.skinName=c.skin);a.fireOnce("configLoaded");a.dataProcessor=new CKEDITOR.htmlDataProcessor(a);a.filter=a.activeFilter=new CKEDITOR.filter(a);n(a)});b&&null!=b.customConfig&&(a.config.customConfig=b.customConfig);k(a)||a.fireOnce("customConfigLoaded")}
function n(a){CKEDITOR.skin.loadPart("editor",function(){r(a)})}function r(a){CKEDITOR.lang.load(a.config.language,a.config.defaultLanguage,function(b,c){var d=a.config.title;a.langCode=b;a.lang=CKEDITOR.tools.prototypedCopy(c);a.title="string"==typeof d||!1===d?d:[a.lang.editor,a.name].join(", ");a.config.contentsLangDirection||(a.config.contentsLangDirection=a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE?a.element.getDirection(1):a.lang.dir);a.fire("langLoaded");e(a)})}function e(a){a.getStylesSet(function(b){a.once("loaded",
function(){a.fire("stylesSet",{styles:b})},null,null,1);y(a)})}function y(a){function b(a){if(!a)return"";CKEDITOR.tools.isArray(a)&&(a=a.join(","));return a.replace(/\s/g,"")}var c=a.config,d=b(c.plugins),f=b(c.extraPlugins),e=b(c.removePlugins);if(f)var h=new RegExp("(?:^|,)(?:"+f.replace(/,/g,"|")+")(?\x3d,|$)","g"),d=d.replace(h,""),d=d+(","+f);if(e)var g=new RegExp("(?:^|,)(?:"+e.replace(/,/g,"|")+")(?\x3d,|$)","g"),d=d.replace(g,"");CKEDITOR.env.air&&(d+=",adobeair");CKEDITOR.plugins.load(d.split(","),
function(b){var d=[],f=[],e=[];a.plugins=CKEDITOR.tools.extend({},a.plugins,b);for(var l in b){var h=b[l],t=h.lang,k=null,p=h.requires,F;CKEDITOR.tools.isArray(p)&&(p=p.join(","));if(p&&(F=p.match(g)))for(;p=F.pop();)CKEDITOR.error("editor-plugin-required",{plugin:p.replace(",",""),requiredBy:l});t&&!a.lang[l]&&(t.split&&(t=t.split(",")),0<=CKEDITOR.tools.indexOf(t,a.langCode)?k=a.langCode:(k=a.langCode.replace(/-.*/,""),k=k!=a.langCode&&0<=CKEDITOR.tools.indexOf(t,k)?k:0<=CKEDITOR.tools.indexOf(t,
"en")?"en":t[0]),h.langEntries&&h.langEntries[k]?(a.lang[l]=h.langEntries[k],k=null):e.push(CKEDITOR.getUrl(h.path+"lang/"+k+".js")));f.push(k);d.push(h)}CKEDITOR.scriptLoader.load(e,function(){for(var b=["beforeInit","init","afterInit"],e=0;e<b.length;e++)for(var l=0;l<d.length;l++){var p=d[l];0===e&&f[l]&&p.lang&&p.langEntries&&(a.lang[p.name]=p.langEntries[f[l]]);if(p[b[e]])p[b[e]](a)}a.fireOnce("pluginsLoaded");c.keystrokes&&a.setKeystroke(a.config.keystrokes);for(l=0;l<a.config.blockedKeystrokes.length;l++)a.keystrokeHandler.blockedKeystrokes[a.config.blockedKeystrokes[l]]=
1;a.status="loaded";a.fireOnce("loaded");CKEDITOR.fire("instanceLoaded",null,a)})})}function v(){var a=this.element;if(a&&this.elementMode!=CKEDITOR.ELEMENT_MODE_APPENDTO){var b=this.getData();this.config.htmlEncodeOutput&&(b=CKEDITOR.tools.htmlEncode(b));a.is("textarea")?a.setValue(b):a.setHtml(b);return!0}return!1}function B(a,b){function c(a){var b=a.startContainer,d=a.endContainer;return b.is&&(b.is("tr")||b.is("td")&&b.equals(d)&&a.endOffset===b.getChildCount())?!0:!1}function d(a){var b=a.startContainer;
return b.is("tr")?a.cloneContents():b.clone(!0)}for(var f=new CKEDITOR.dom.documentFragment,e,h,g,k=0;k<a.length;k++){var M=a[k],q=M.startContainer.getAscendant("tr",!0);c(M)?(e||(e=q.getAscendant("table").clone(),e.append(q.getAscendant({thead:1,tbody:1,tfoot:1}).clone()),f.append(e),e=e.findOne("thead, tbody, tfoot")),h&&h.equals(q)||(h=q,g=q.clone(),e.append(g)),g.append(d(M))):f.append(M.cloneContents())}return e?f:b.getHtmlFromRange(a[0])}a.prototype=CKEDITOR.editor.prototype;CKEDITOR.editor=
a;var D=0,x={};CKEDITOR.tools.extend(CKEDITOR.editor.prototype,{plugins:{detectConflict:function(a,b){for(var c=0;c<b.length;c++){var d=b[c];if(this[d])return CKEDITOR.warn("editor-plugin-conflict",{plugin:a,replacedWith:d}),!0}return!1}},addCommand:function(a,b){b.name=a.toLowerCase();var c=b instanceof CKEDITOR.command?b:new CKEDITOR.command(this,b);this.mode&&f(this,c);return this.commands[a]=c},_attachToForm:function(){function a(b){c.updateElement();c._.required&&!d.getValue()&&!1===c.fire("required")&&
b.data.preventDefault()}function b(a){return!!(a&&a.call&&a.apply)}var c=this,d=c.element,f=new CKEDITOR.dom.element(d.$.form);d.is("textarea")&&f&&(f.on("submit",a),b(f.$.submit)&&(f.$.submit=CKEDITOR.tools.override(f.$.submit,function(b){return function(){a();b.apply?b.apply(this):b()}})),c.on("destroy",function(){f.removeListener("submit",a)}))},destroy:function(a){this.fire("beforeDestroy");!a&&v.call(this);this.editable(null);this.filter&&(this.filter.destroy(),delete this.filter);delete this.activeFilter;
this.status="destroyed";this.fire("destroy");this.removeAllListeners();CKEDITOR.remove(this);CKEDITOR.fire("instanceDestroyed",null,this)},elementPath:function(a){if(!a){a=this.getSelection();if(!a)return null;a=a.getStartElement()}return a?new CKEDITOR.dom.elementPath(a,this.editable()):null},createRange:function(){var a=this.editable();return a?new CKEDITOR.dom.range(a):null},execCommand:function(a,b){var c=this.getCommand(a),d={name:a,commandData:b||{},command:c};return c&&c.state!=CKEDITOR.TRISTATE_DISABLED&&
!1!==this.fire("beforeCommandExec",d)&&(d.returnValue=c.exec(d.commandData),!c.async&&!1!==this.fire("afterCommandExec",d))?d.returnValue:!1},getCommand:function(a){return this.commands[a]},getData:function(a){!a&&this.fire("beforeGetData");var b=this._.data;"string"!=typeof b&&(b=(b=this.element)&&this.elementMode==CKEDITOR.ELEMENT_MODE_REPLACE?b.is("textarea")?b.getValue():b.getHtml():"");b={dataValue:b};!a&&this.fire("getData",b);return b.dataValue},getSnapshot:function(){var a=this.fire("getSnapshot");
"string"!=typeof a&&(a=(a=this.element)&&this.elementMode==CKEDITOR.ELEMENT_MODE_REPLACE?a.is("textarea")?a.getValue():a.getHtml():"");return a},loadSnapshot:function(a){this.fire("loadSnapshot",a)},setData:function(a,b,c){var d=!0,f=b;b&&"object"==typeof b&&(c=b.internal,f=b.callback,d=!b.noSnapshot);!c&&d&&this.fire("saveSnapshot");if(f||!c)this.once("dataReady",function(a){!c&&d&&this.fire("saveSnapshot");f&&f.call(a.editor)});a={dataValue:a};!c&&this.fire("setData",a);this._.data=a.dataValue;
!c&&this.fire("afterSetData",a)},setReadOnly:function(a){a=null==a||a;this.readOnly!=a&&(this.readOnly=a,this.keystrokeHandler.blockedKeystrokes[8]=+a,this.editable().setReadOnly(a),this.fire("readOnly"))},insertHtml:function(a,b,c){this.fire("insertHtml",{dataValue:a,mode:b,range:c})},insertText:function(a){this.fire("insertText",a)},insertElement:function(a){this.fire("insertElement",a)},getSelectedHtml:function(a){var b=this.editable(),c=this.getSelection(),c=c&&c.getRanges();if(!b||!c||0===c.length)return null;
b=B(c,b);return a?b.getHtml():b},extractSelectedHtml:function(a,b){var c=this.editable(),d=this.getSelection().getRanges(),f=new CKEDITOR.dom.documentFragment,e;if(!c||0===d.length)return null;for(e=0;e<d.length;e++)f.append(c.extractHtmlFromRange(d[e],b));b||this.getSelection().selectRanges([d[0]]);return a?f.getHtml():f},focus:function(){this.fire("beforeFocus")},checkDirty:function(){return"ready"==this.status&&this._.previousValue!==this.getSnapshot()},resetDirty:function(){this._.previousValue=
this.getSnapshot()},updateElement:function(){return v.call(this)},setKeystroke:function(){for(var a=this.keystrokeHandler.keystrokes,b=CKEDITOR.tools.isArray(arguments[0])?arguments[0]:[[].slice.call(arguments,0)],c,d,f=b.length;f--;)c=b[f],d=0,CKEDITOR.tools.isArray(c)&&(d=c[1],c=c[0]),d?a[c]=d:delete a[c]},getCommandKeystroke:function(a){if(a="string"===typeof a?this.getCommand(a):a){var b=CKEDITOR.tools.object.findKey(this.commands,a),c=this.keystrokeHandler.keystrokes,d;if(a.fakeKeystroke)return a.fakeKeystroke;
for(d in c)if(c.hasOwnProperty(d)&&c[d]==b)return d}return null},addFeature:function(a){return this.filter.addFeature(a)},setActiveFilter:function(a){a||(a=this.filter);this.activeFilter!==a&&(this.activeFilter=a,this.fire("activeFilterChange"),a===this.filter?this.setActiveEnterMode(null,null):this.setActiveEnterMode(a.getAllowedEnterMode(this.enterMode),a.getAllowedEnterMode(this.shiftEnterMode,!0)))},setActiveEnterMode:function(a,b){a=a?this.blockless?CKEDITOR.ENTER_BR:a:this.enterMode;b=b?this.blockless?
CKEDITOR.ENTER_BR:b:this.shiftEnterMode;if(this.activeEnterMode!=a||this.activeShiftEnterMode!=b)this.activeEnterMode=a,this.activeShiftEnterMode=b,this.fire("activeEnterModeChange")},showNotification:function(a){alert(a)}})})();CKEDITOR.ELEMENT_MODE_NONE=0;CKEDITOR.ELEMENT_MODE_REPLACE=1;CKEDITOR.ELEMENT_MODE_APPENDTO=2;CKEDITOR.ELEMENT_MODE_INLINE=3;CKEDITOR.htmlParser=function(){this._={htmlPartsRegex:/<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)--\x3e)|(?:([^\/\s>]+)((?:\s+[\w\-:.]+(?:\s*=\s*?(?:(?:"[^"]*")|(?:'[^']*')|[^\s"'\/>]+))?)*)[\S\s]*?(\/?)>))/g}};
(function(){var a=/([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g,d={checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1,readonly:1,selected:1};CKEDITOR.htmlParser.prototype={onTagOpen:function(){},onTagClose:function(){},onText:function(){},onCDATA:function(){},onComment:function(){},parse:function(b){for(var c,f,h=0,k;c=this._.htmlPartsRegex.exec(b);){f=c.index;if(f>h)if(h=b.substring(h,f),k)k.push(h);else this.onText(h);
h=this._.htmlPartsRegex.lastIndex;if(f=c[1])if(f=f.toLowerCase(),k&&CKEDITOR.dtd.$cdata[f]&&(this.onCDATA(k.join("")),k=null),!k){this.onTagClose(f);continue}if(k)k.push(c[0]);else if(f=c[3]){if(f=f.toLowerCase(),!/="/.test(f)){var g={},n,r=c[4];c=!!c[5];if(r)for(;n=a.exec(r);){var e=n[1].toLowerCase();n=n[2]||n[3]||n[4]||"";g[e]=!n&&d[e]?e:CKEDITOR.tools.htmlDecodeAttr(n)}this.onTagOpen(f,g,c);!k&&CKEDITOR.dtd.$cdata[f]&&(k=[])}}else if(f=c[2])this.onComment(f)}if(b.length>h)this.onText(b.substring(h,
b.length))}}})();
CKEDITOR.htmlParser.basicWriter=CKEDITOR.tools.createClass({$:function(){this._={output:[]}},proto:{openTag:function(a){this._.output.push("\x3c",a)},openTagClose:function(a,d){d?this._.output.push(" /\x3e"):this._.output.push("\x3e")},attribute:function(a,d){"string"==typeof d&&(d=CKEDITOR.tools.htmlEncodeAttr(d));this._.output.push(" ",a,'\x3d"',d,'"')},closeTag:function(a){this._.output.push("\x3c/",a,"\x3e")},text:function(a){this._.output.push(a)},comment:function(a){this._.output.push("\x3c!--",a,
"--\x3e")},write:function(a){this._.output.push(a)},reset:function(){this._.output=[];this._.indent=!1},getHtml:function(a){var d=this._.output.join("");a&&this.reset();return d}}});"use strict";
(function(){CKEDITOR.htmlParser.node=function(){};CKEDITOR.htmlParser.node.prototype={remove:function(){var a=this.parent.children,d=CKEDITOR.tools.indexOf(a,this),b=this.previous,c=this.next;b&&(b.next=c);c&&(c.previous=b);a.splice(d,1);this.parent=null},replaceWith:function(a){var d=this.parent.children,b=CKEDITOR.tools.indexOf(d,this),c=a.previous=this.previous,f=a.next=this.next;c&&(c.next=a);f&&(f.previous=a);d[b]=a;a.parent=this.parent;this.parent=null},insertAfter:function(a){var d=a.parent.children,
b=CKEDITOR.tools.indexOf(d,a),c=a.next;d.splice(b+1,0,this);this.next=a.next;this.previous=a;a.next=this;c&&(c.previous=this);this.parent=a.parent},insertBefore:function(a){var d=a.parent.children,b=CKEDITOR.tools.indexOf(d,a);d.splice(b,0,this);this.next=a;(this.previous=a.previous)&&(a.previous.next=this);a.previous=this;this.parent=a.parent},getAscendant:function(a){var d="function"==typeof a?a:"string"==typeof a?function(b){return b.name==a}:function(b){return b.name in a},b=this.parent;for(;b&&
b.type==CKEDITOR.NODE_ELEMENT;){if(d(b))return b;b=b.parent}return null},wrapWith:function(a){this.replaceWith(a);a.add(this);return a},getIndex:function(){return CKEDITOR.tools.indexOf(this.parent.children,this)},getFilterContext:function(a){return a||{}}}})();"use strict";CKEDITOR.htmlParser.comment=function(a){this.value=a;this._={isBlockLike:!1}};
CKEDITOR.htmlParser.comment.prototype=CKEDITOR.tools.extend(new CKEDITOR.htmlParser.node,{type:CKEDITOR.NODE_COMMENT,filter:function(a,d){var b=this.value;if(!(b=a.onComment(d,b,this)))return this.remove(),!1;if("string"!=typeof b)return this.replaceWith(b),!1;this.value=b;return!0},writeHtml:function(a,d){d&&this.filter(d);a.comment(this.value)}});"use strict";
(function(){CKEDITOR.htmlParser.text=function(a){this.value=a;this._={isBlockLike:!1}};CKEDITOR.htmlParser.text.prototype=CKEDITOR.tools.extend(new CKEDITOR.htmlParser.node,{type:CKEDITOR.NODE_TEXT,filter:function(a,d){if(!(this.value=a.onText(d,this.value,this)))return this.remove(),!1},writeHtml:function(a,d){d&&this.filter(d);a.text(this.value)}})})();"use strict";
(function(){CKEDITOR.htmlParser.cdata=function(a){this.value=a};CKEDITOR.htmlParser.cdata.prototype=CKEDITOR.tools.extend(new CKEDITOR.htmlParser.node,{type:CKEDITOR.NODE_TEXT,filter:function(){},writeHtml:function(a){a.write(this.value)}})})();"use strict";CKEDITOR.htmlParser.fragment=function(){this.children=[];this.parent=null;this._={isBlockLike:!0,hasInlineStarted:!1}};
(function(){function a(a){return a.attributes["data-cke-survive"]?!1:"a"==a.name&&a.attributes.href||CKEDITOR.dtd.$removeEmpty[a.name]}var d=CKEDITOR.tools.extend({table:1,ul:1,ol:1,dl:1},CKEDITOR.dtd.table,CKEDITOR.dtd.ul,CKEDITOR.dtd.ol,CKEDITOR.dtd.dl),b={ol:1,ul:1},c=CKEDITOR.tools.extend({},{html:1},CKEDITOR.dtd.html,CKEDITOR.dtd.body,CKEDITOR.dtd.head,{style:1,script:1}),f={ul:"li",ol:"li",dl:"dd",table:"tbody",tbody:"tr",thead:"tr",tfoot:"tr",tr:"td"};CKEDITOR.htmlParser.fragment.fromHtml=
function(h,k,g){function n(a){var b;if(0<m.length)for(var c=0;c<m.length;c++){var d=m[c],f=d.name,e=CKEDITOR.dtd[f],l=u.name&&CKEDITOR.dtd[u.name];l&&!l[f]||a&&e&&!e[a]&&CKEDITOR.dtd[a]?f==u.name&&(y(u,u.parent,1),c--):(b||(r(),b=1),d=d.clone(),d.parent=u,u=d,m.splice(c,1),c--)}}function r(){for(;J.length;)y(J.shift(),u)}function e(a){if(a._.isBlockLike&&"pre"!=a.name&&"textarea"!=a.name){var b=a.children.length,c=a.children[b-1],d;c&&c.type==CKEDITOR.NODE_TEXT&&((d=CKEDITOR.tools.rtrim(c.value))?
c.value=d:a.children.length=b-1)}}function y(b,c,d){c=c||u||x;var f=u;void 0===b.previous&&(v(c,b)&&(u=c,D.onTagOpen(g,{}),b.returnPoint=c=u),e(b),a(b)&&!b.children.length||c.add(b),"pre"==b.name&&(l=!1),"textarea"==b.name&&(K=!1));b.returnPoint?(u=b.returnPoint,delete b.returnPoint):u=d?c:f}function v(a,b){if((a==x||"body"==a.name)&&g&&(!a.name||CKEDITOR.dtd[a.name][g])){var c,d;return(c=b.attributes&&(d=b.attributes["data-cke-real-element-type"])?d:b.name)&&c in CKEDITOR.dtd.$inline&&!(c in CKEDITOR.dtd.head)&&
!b.isOrphan||b.type==CKEDITOR.NODE_TEXT}}function B(a,b){return a in CKEDITOR.dtd.$listItem||a in CKEDITOR.dtd.$tableContent?a==b||"dt"==a&&"dd"==b||"dd"==a&&"dt"==b:!1}var D=new CKEDITOR.htmlParser,x=k instanceof CKEDITOR.htmlParser.element?k:"string"==typeof k?new CKEDITOR.htmlParser.element(k):new CKEDITOR.htmlParser.fragment,m=[],J=[],u=x,K="textarea"==x.name,l="pre"==x.name;D.onTagOpen=function(f,e,h,g){e=new CKEDITOR.htmlParser.element(f,e);e.isUnknown&&h&&(e.isEmpty=!0);e.isOptionalClose=g;
if(a(e))m.push(e);else{if("pre"==f)l=!0;else{if("br"==f&&l){u.add(new CKEDITOR.htmlParser.text("\n"));return}"textarea"==f&&(K=!0)}if("br"==f)J.push(e);else{for(;!(g=(h=u.name)?CKEDITOR.dtd[h]||(u._.isBlockLike?CKEDITOR.dtd.div:CKEDITOR.dtd.span):c,e.isUnknown||u.isUnknown||g[f]);)if(u.isOptionalClose)D.onTagClose(h);else if(f in b&&h in b)h=u.children,(h=h[h.length-1])&&"li"==h.name||y(h=new CKEDITOR.htmlParser.element("li"),u),!e.returnPoint&&(e.returnPoint=u),u=h;else if(f in CKEDITOR.dtd.$listItem&&
!B(f,h))D.onTagOpen("li"==f?"ul":"dl",{},0,1);else if(h in d&&!B(f,h))!e.returnPoint&&(e.returnPoint=u),u=u.parent;else if(h in CKEDITOR.dtd.$inline&&m.unshift(u),u.parent)y(u,u.parent,1);else{e.isOrphan=1;break}n(f);r();e.parent=u;e.isEmpty?y(e):u=e}}};D.onTagClose=function(a){for(var b=m.length-1;0<=b;b--)if(a==m[b].name){m.splice(b,1);return}for(var c=[],d=[],f=u;f!=x&&f.name!=a;)f._.isBlockLike||d.unshift(f),c.push(f),f=f.returnPoint||f.parent;if(f!=x){for(b=0;b<c.length;b++){var e=c[b];y(e,e.parent)}u=
f;f._.isBlockLike&&r();y(f,f.parent);f==u&&(u=u.parent);m=m.concat(d)}"body"==a&&(g=!1)};D.onText=function(a){if(!(u._.hasInlineStarted&&!J.length||l||K)&&(a=CKEDITOR.tools.ltrim(a),0===a.length))return;var b=u.name,e=b?CKEDITOR.dtd[b]||(u._.isBlockLike?CKEDITOR.dtd.div:CKEDITOR.dtd.span):c;if(!K&&!e["#"]&&b in d)D.onTagOpen(f[b]||""),D.onText(a);else{r();n();l||K||(a=a.replace(/[\t\r\n ]{2,}|[\t\r\n]/g," "));a=new CKEDITOR.htmlParser.text(a);if(v(u,a))this.onTagOpen(g,{},0,1);u.add(a)}};D.onCDATA=
function(a){u.add(new CKEDITOR.htmlParser.cdata(a))};D.onComment=function(a){r();n();u.add(new CKEDITOR.htmlParser.comment(a))};D.parse(h);for(r();u!=x;)y(u,u.parent,1);e(x);return x};CKEDITOR.htmlParser.fragment.prototype={type:CKEDITOR.NODE_DOCUMENT_FRAGMENT,add:function(a,b){isNaN(b)&&(b=this.children.length);var c=0<b?this.children[b-1]:null;if(c){if(a._.isBlockLike&&c.type==CKEDITOR.NODE_TEXT&&(c.value=CKEDITOR.tools.rtrim(c.value),0===c.value.length)){this.children.pop();this.add(a);return}c.next=
a}a.previous=c;a.parent=this;this.children.splice(b,0,a);this._.hasInlineStarted||(this._.hasInlineStarted=a.type==CKEDITOR.NODE_TEXT||a.type==CKEDITOR.NODE_ELEMENT&&!a._.isBlockLike)},filter:function(a,b){b=this.getFilterContext(b);a.onRoot(b,this);this.filterChildren(a,!1,b)},filterChildren:function(a,b,c){if(this.childrenFilteredBy!=a.id){c=this.getFilterContext(c);if(b&&!this.parent)a.onRoot(c,this);this.childrenFilteredBy=a.id;for(b=0;b<this.children.length;b++)!1===this.children[b].filter(a,
c)&&b--}},writeHtml:function(a,b){b&&this.filter(b);this.writeChildrenHtml(a)},writeChildrenHtml:function(a,b,c){var d=this.getFilterContext();if(c&&!this.parent&&b)b.onRoot(d,this);b&&this.filterChildren(b,!1,d);b=0;c=this.children;for(d=c.length;b<d;b++)c[b].writeHtml(a)},forEach:function(a,b,c){if(!(c||b&&this.type!=b))var d=a(this);if(!1!==d){c=this.children;for(var f=0;f<c.length;f++)d=c[f],d.type==CKEDITOR.NODE_ELEMENT?d.forEach(a,b):b&&d.type!=b||a(d)}},getFilterContext:function(a){return a||
{}}}})();"use strict";
(function(){function a(){this.rules=[]}function d(b,c,d,h){var k,g;for(k in c)(g=b[k])||(g=b[k]=new a),g.add(c[k],d,h)}CKEDITOR.htmlParser.filter=CKEDITOR.tools.createClass({$:function(b){this.id=CKEDITOR.tools.getNextNumber();this.elementNameRules=new a;this.attributeNameRules=new a;this.elementsRules={};this.attributesRules={};this.textRules=new a;this.commentRules=new a;this.rootRules=new a;b&&this.addRules(b,10)},proto:{addRules:function(a,c){var f;"number"==typeof c?f=c:c&&"priority"in c&&(f=
c.priority);"number"!=typeof f&&(f=10);"object"!=typeof c&&(c={});a.elementNames&&this.elementNameRules.addMany(a.elementNames,f,c);a.attributeNames&&this.attributeNameRules.addMany(a.attributeNames,f,c);a.elements&&d(this.elementsRules,a.elements,f,c);a.attributes&&d(this.attributesRules,a.attributes,f,c);a.text&&this.textRules.add(a.text,f,c);a.comment&&this.commentRules.add(a.comment,f,c);a.root&&this.rootRules.add(a.root,f,c)},applyTo:function(a){a.filter(this)},onElementName:function(a,c){return this.elementNameRules.execOnName(a,
c)},onAttributeName:function(a,c){return this.attributeNameRules.execOnName(a,c)},onText:function(a,c,d){return this.textRules.exec(a,c,d)},onComment:function(a,c,d){return this.commentRules.exec(a,c,d)},onRoot:function(a,c){return this.rootRules.exec(a,c)},onElement:function(a,c){for(var d=[this.elementsRules["^"],this.elementsRules[c.name],this.elementsRules.$],h,k=0;3>k;k++)if(h=d[k]){h=h.exec(a,c,this);if(!1===h)return null;if(h&&h!=c)return this.onNode(a,h);if(c.parent&&!c.name)break}return c},
onNode:function(a,c){var d=c.type;return d==CKEDITOR.NODE_ELEMENT?this.onElement(a,c):d==CKEDITOR.NODE_TEXT?new CKEDITOR.htmlParser.text(this.onText(a,c.value)):d==CKEDITOR.NODE_COMMENT?new CKEDITOR.htmlParser.comment(this.onComment(a,c.value)):null},onAttribute:function(a,c,d,h){return(d=this.attributesRules[d])?d.exec(a,h,c,this):h}}});CKEDITOR.htmlParser.filterRulesGroup=a;a.prototype={add:function(a,c,d){this.rules.splice(this.findIndex(c),0,{value:a,priority:c,options:d})},addMany:function(a,
c,d){for(var h=[this.findIndex(c),0],k=0,g=a.length;k<g;k++)h.push({value:a[k],priority:c,options:d});this.rules.splice.apply(this.rules,h)},findIndex:function(a){for(var c=this.rules,d=c.length-1;0<=d&&a<c[d].priority;)d--;return d+1},exec:function(a,c){var d=c instanceof CKEDITOR.htmlParser.node||c instanceof CKEDITOR.htmlParser.fragment,h=Array.prototype.slice.call(arguments,1),k=this.rules,g=k.length,n,r,e,y;for(y=0;y<g;y++)if(d&&(n=c.type,r=c.name),e=k[y],!(a.nonEditable&&!e.options.applyToAll||
a.nestedEditable&&e.options.excludeNestedEditable)){e=e.value.apply(null,h);if(!1===e||d&&e&&(e.name!=r||e.type!=n))return e;null!=e&&(h[0]=c=e)}return c},execOnName:function(a,c){for(var d=0,h=this.rules,k=h.length,g;c&&d<k;d++)g=h[d],a.nonEditable&&!g.options.applyToAll||a.nestedEditable&&g.options.excludeNestedEditable||(c=c.replace(g.value[0],g.value[1]));return c}}})();
(function(){function a(a,d){function e(a){return a||CKEDITOR.env.needsNbspFiller?new CKEDITOR.htmlParser.text(" "):new CKEDITOR.htmlParser.element("br",{"data-cke-bogus":1})}function p(a,d){return function(f){if(f.type!=CKEDITOR.NODE_DOCUMENT_FRAGMENT){var l=[],w=b(f),p,E;if(w)for(q(w,1)&&l.push(w);w;)h(w)&&(p=c(w))&&q(p)&&((E=c(p))&&!h(E)?l.push(p):(e(z).insertAfter(p),p.remove())),w=w.previous;for(w=0;w<l.length;w++)l[w].remove();if(l=!a||!1!==("function"==typeof d?d(f):d))z||CKEDITOR.env.needsBrFiller||
f.type!=CKEDITOR.NODE_DOCUMENT_FRAGMENT?z||CKEDITOR.env.needsBrFiller||!(7<document.documentMode||f.name in CKEDITOR.dtd.tr||f.name in CKEDITOR.dtd.$listItem)?(l=b(f),l=!l||"form"==f.name&&"input"==l.name):l=!1:l=!1;l&&f.add(e(a))}}}function q(a,b){if((!z||CKEDITOR.env.needsBrFiller)&&a.type==CKEDITOR.NODE_ELEMENT&&"br"==a.name&&!a.attributes["data-cke-eol"])return!0;var c;return a.type==CKEDITOR.NODE_TEXT&&(c=a.value.match(m))&&(c.index&&((new CKEDITOR.htmlParser.text(a.value.substring(0,c.index))).insertBefore(a),
a.value=c[0]),!CKEDITOR.env.needsBrFiller&&z&&(!b||a.parent.name in g)||!z&&((c=a.previous)&&"br"==c.name||!c||h(c)))?!0:!1}var E={elements:{}},z="html"==d,g=CKEDITOR.tools.extend({},l),t;for(t in g)"#"in u[t]||delete g[t];for(t in g)E.elements[t]=p(z,a.config.fillEmptyBlocks);E.root=p(z,!1);E.elements.br=function(a){return function(b){if(b.parent.type!=CKEDITOR.NODE_DOCUMENT_FRAGMENT){var d=b.attributes;if("data-cke-bogus"in d||"data-cke-eol"in d)delete d["data-cke-bogus"];else{for(d=b.next;d&&f(d);)d=
d.next;var l=c(b);!d&&h(b.parent)?k(b.parent,e(a)):h(d)&&l&&!h(l)&&e(a).insertBefore(d)}}}}(z);return E}function d(a,b){return a!=CKEDITOR.ENTER_BR&&!1!==b?a==CKEDITOR.ENTER_DIV?"div":"p":!1}function b(a){for(a=a.children[a.children.length-1];a&&f(a);)a=a.previous;return a}function c(a){for(a=a.previous;a&&f(a);)a=a.previous;return a}function f(a){return a.type==CKEDITOR.NODE_TEXT&&!CKEDITOR.tools.trim(a.value)||a.type==CKEDITOR.NODE_ELEMENT&&a.attributes["data-cke-bookmark"]}function h(a){return a&&
(a.type==CKEDITOR.NODE_ELEMENT&&a.name in l||a.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT)}function k(a,b){var c=a.children[a.children.length-1];a.children.push(b);b.parent=a;c&&(c.next=b,b.previous=c)}function g(a){a=a.attributes;"false"!=a.contenteditable&&(a["data-cke-editable"]=a.contenteditable?"true":1);a.contenteditable="false"}function n(a){a=a.attributes;switch(a["data-cke-editable"]){case "true":a.contenteditable="true";break;case "1":delete a.contenteditable}}function r(a){return a.replace(M,
function(a,b,c){return"\x3c"+b+c.replace(q,function(a,b){return E.test(b)&&-1==c.indexOf("data-cke-saved-"+b)?" data-cke-saved-"+a+" data-cke-"+CKEDITOR.rnd+"-"+a:a})+"\x3e"})}function e(a,b){return a.replace(b,function(a,b,c){0===a.indexOf("\x3ctextarea")&&(a=b+B(c).replace(/</g,"\x26lt;").replace(/>/g,"\x26gt;")+"\x3c/textarea\x3e");return"\x3ccke:encoded\x3e"+encodeURIComponent(a)+"\x3c/cke:encoded\x3e"})}function y(a){return a.replace(P,function(a,b){return decodeURIComponent(b)})}function v(a){return a.replace(/\x3c!--(?!{cke_protected})[\s\S]+?--\x3e/g,
function(a){return"\x3c!--"+J+"{C}"+encodeURIComponent(a).replace(/--/g,"%2D%2D")+"--\x3e"})}function B(a){return a.replace(/\x3c!--\{cke_protected\}\{C\}([\s\S]+?)--\x3e/g,function(a,b){return decodeURIComponent(b)})}function D(a,b){var c=b._.dataStore;return a.replace(/\x3c!--\{cke_protected\}([\s\S]+?)--\x3e/g,function(a,b){return decodeURIComponent(b)}).replace(/\{cke_protected_(\d+)\}/g,function(a,b){return c&&c[b]||""})}function x(a,b){var c=[],d=b.config.protectedSource,f=b._.dataStore||(b._.dataStore=
{id:1}),e=/<\!--\{cke_temp(comment)?\}(\d*?)--\x3e/g,d=[/<script[\s\S]*?(<\/script>|$)/gi,/<noscript[\s\S]*?<\/noscript>/gi,/<meta[\s\S]*?\/?>/gi].concat(d);a=a.replace(/\x3c!--[\s\S]*?--\x3e/g,function(a){return"\x3c!--{cke_tempcomment}"+(c.push(a)-1)+"--\x3e"});for(var l=0;l<d.length;l++)a=a.replace(d[l],function(a){a=a.replace(e,function(a,b,d){return c[d]});return/cke_temp(comment)?/.test(a)?a:"\x3c!--{cke_temp}"+(c.push(a)-1)+"--\x3e"});a=a.replace(e,function(a,b,d){return"\x3c!--"+J+(b?"{C}":
"")+encodeURIComponent(c[d]).replace(/--/g,"%2D%2D")+"--\x3e"});a=a.replace(/<\w+(?:\s+(?:(?:[^\s=>]+\s*=\s*(?:[^'"\s>]+|'[^']*'|"[^"]*"))|[^\s=\/>]+))+\s*\/?>/g,function(a){return a.replace(/\x3c!--\{cke_protected\}([^>]*)--\x3e/g,function(a,b){f[f.id]=decodeURIComponent(b);return"{cke_protected_"+f.id++ +"}"})});return a=a.replace(/<(title|iframe|textarea)([^>]*)>([\s\S]*?)<\/\1>/g,function(a,c,d,f){return"\x3c"+c+d+"\x3e"+D(B(f),b)+"\x3c/"+c+"\x3e"})}CKEDITOR.htmlDataProcessor=function(b){var c,
f,l=this;this.editor=b;this.dataFilter=c=new CKEDITOR.htmlParser.filter;this.htmlFilter=f=new CKEDITOR.htmlParser.filter;this.writer=new CKEDITOR.htmlParser.basicWriter;c.addRules(t);c.addRules(F,{applyToAll:!0});c.addRules(a(b,"data"),{applyToAll:!0});f.addRules(L);f.addRules(C,{applyToAll:!0});f.addRules(a(b,"html"),{applyToAll:!0});b.on("toHtml",function(a){a=a.data;var c=a.dataValue,f,c=x(c,b),c=e(c,H),c=r(c),c=e(c,z),c=c.replace(O,"$1cke:$2"),c=c.replace(N,"\x3ccke:$1$2\x3e\x3c/cke:$1\x3e"),
c=c.replace(/(<pre\b[^>]*>)(\r\n|\n)/g,"$1$2$2"),c=c.replace(/([^a-z0-9<\-])(on\w{3,})(?!>)/gi,"$1data-cke-"+CKEDITOR.rnd+"-$2");f=a.context||b.editable().getName();var l;CKEDITOR.env.ie&&9>CKEDITOR.env.version&&"pre"==f&&(f="div",c="\x3cpre\x3e"+c+"\x3c/pre\x3e",l=1);f=b.document.createElement(f);f.setHtml("a"+c);c=f.getHtml().substr(1);c=c.replace(new RegExp("data-cke-"+CKEDITOR.rnd+"-","ig"),"");l&&(c=c.replace(/^<pre>|<\/pre>$/gi,""));c=c.replace(p,"$1$2");c=y(c);c=B(c);f=!1===a.fixForBody?!1:
d(a.enterMode,b.config.autoParagraph);c=CKEDITOR.htmlParser.fragment.fromHtml(c,a.context,f);f&&(l=c,!l.children.length&&CKEDITOR.dtd[l.name][f]&&(f=new CKEDITOR.htmlParser.element(f),l.add(f)));a.dataValue=c},null,null,5);b.on("toHtml",function(a){a.data.filter.applyTo(a.data.dataValue,!0,a.data.dontFilter,a.data.enterMode)&&b.fire("dataFiltered")},null,null,6);b.on("toHtml",function(a){a.data.dataValue.filterChildren(l.dataFilter,!0)},null,null,10);b.on("toHtml",function(a){a=a.data;var b=a.dataValue,
c=new CKEDITOR.htmlParser.basicWriter;b.writeChildrenHtml(c);b=c.getHtml(!0);a.dataValue=v(b)},null,null,15);b.on("toDataFormat",function(a){var c=a.data.dataValue;a.data.enterMode!=CKEDITOR.ENTER_BR&&(c=c.replace(/^<br *\/?>/i,""));a.data.dataValue=CKEDITOR.htmlParser.fragment.fromHtml(c,a.data.context,d(a.data.enterMode,b.config.autoParagraph))},null,null,5);b.on("toDataFormat",function(a){a.data.dataValue.filterChildren(l.htmlFilter,!0)},null,null,10);b.on("toDataFormat",function(a){a.data.filter.applyTo(a.data.dataValue,
!1,!0)},null,null,11);b.on("toDataFormat",function(a){var c=a.data.dataValue,d=l.writer;d.reset();c.writeChildrenHtml(d);c=d.getHtml(!0);c=B(c);c=D(c,b);a.data.dataValue=c},null,null,15)};CKEDITOR.htmlDataProcessor.prototype={toHtml:function(a,b,c,d){var f=this.editor,e,l,p,h;b&&"object"==typeof b?(e=b.context,c=b.fixForBody,d=b.dontFilter,l=b.filter,p=b.enterMode,h=b.protectedWhitespaces):e=b;e||null===e||(e=f.editable().getName());return f.fire("toHtml",{dataValue:a,context:e,fixForBody:c,dontFilter:d,
filter:l||f.filter,enterMode:p||f.enterMode,protectedWhitespaces:h}).dataValue},toDataFormat:function(a,b){var c,d,f;b&&(c=b.context,d=b.filter,f=b.enterMode);c||null===c||(c=this.editor.editable().getName());return this.editor.fire("toDataFormat",{dataValue:a,filter:d||this.editor.filter,context:c,enterMode:f||this.editor.enterMode}).dataValue}};var m=/(?:&nbsp;|\xa0)$/,J="{cke_protected}",u=CKEDITOR.dtd,K="caption colgroup col thead tfoot tbody".split(" "),l=CKEDITOR.tools.extend({},u.$blockLimit,
u.$block),t={elements:{input:g,textarea:g}},F={attributeNames:[[/^on/,"data-cke-pa-on"],[/^srcdoc/,"data-cke-pa-srcdoc"],[/^data-cke-expando$/,""]],elements:{iframe:function(a){if(a.attributes&&a.attributes.src){var b=a.attributes.src.toLowerCase().replace(/[^a-z]/gi,"");if(0===b.indexOf("javascript")||0===b.indexOf("data"))a.attributes["data-cke-pa-src"]=a.attributes.src,delete a.attributes.src}}}},L={elements:{embed:function(a){var b=a.parent;if(b&&"object"==b.name){var c=b.attributes.width,b=b.attributes.height;
c&&(a.attributes.width=c);b&&(a.attributes.height=b)}},a:function(a){var b=a.attributes;if(!(a.children.length||b.name||b.id||a.attributes["data-cke-saved-name"]))return!1}}},C={elementNames:[[/^cke:/,""],[/^\?xml:namespace$/,""]],attributeNames:[[/^data-cke-(saved|pa)-/,""],[/^data-cke-.*/,""],["hidefocus",""]],elements:{$:function(a){var b=a.attributes;if(b){if(b["data-cke-temp"])return!1;for(var c=["name","href","src"],d,f=0;f<c.length;f++)d="data-cke-saved-"+c[f],d in b&&delete b[c[f]]}return a},
table:function(a){a.children.slice(0).sort(function(a,b){var c,d;a.type==CKEDITOR.NODE_ELEMENT&&b.type==a.type&&(c=CKEDITOR.tools.indexOf(K,a.name),d=CKEDITOR.tools.indexOf(K,b.name));-1<c&&-1<d&&c!=d||(c=a.parent?a.getIndex():-1,d=b.parent?b.getIndex():-1);return c>d?1:-1})},param:function(a){a.children=[];a.isEmpty=!0;return a},span:function(a){"Apple-style-span"==a.attributes["class"]&&delete a.name},html:function(a){delete a.attributes.contenteditable;delete a.attributes["class"]},body:function(a){delete a.attributes.spellcheck;
delete a.attributes.contenteditable},style:function(a){var b=a.children[0];b&&b.value&&(b.value=CKEDITOR.tools.trim(b.value));a.attributes.type||(a.attributes.type="text/css")},title:function(a){var b=a.children[0];!b&&k(a,b=new CKEDITOR.htmlParser.text);b.value=a.attributes["data-cke-title"]||""},input:n,textarea:n},attributes:{"class":function(a){return CKEDITOR.tools.ltrim(a.replace(/(?:^|\s+)cke_[^\s]*/g,""))||!1}}};CKEDITOR.env.ie&&(C.attributes.style=function(a){return a.replace(/(^|;)([^\:]+)/g,
function(a){return a.toLowerCase()})});var M=/<(a|area|img|input|source)\b([^>]*)>/gi,q=/([\w-:]+)\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|(?:[^ "'>]+))/gi,E=/^(href|src|name)$/i,z=/(?:<style(?=[ >])[^>]*>[\s\S]*?<\/style>)|(?:<(:?link|meta|base)[^>]*>)/gi,H=/(<textarea(?=[ >])[^>]*>)([\s\S]*?)(?:<\/textarea>)/gi,P=/<cke:encoded>([^<]*)<\/cke:encoded>/gi,O=/(<\/?)((?:object|embed|param|html|body|head|title)([\s][^>]*)?>)/gi,p=/(<\/?)cke:((?:html|body|head|title)[^>]*>)/gi,N=/<cke:(param|embed)([^>]*?)\/?>(?!\s*<\/cke:\1)/gi})();
"use strict";CKEDITOR.htmlParser.element=function(a,d){this.name=a;this.attributes=d||{};this.children=[];var b=a||"",c=b.match(/^cke:(.*)/);c&&(b=c[1]);b=!!(CKEDITOR.dtd.$nonBodyContent[b]||CKEDITOR.dtd.$block[b]||CKEDITOR.dtd.$listItem[b]||CKEDITOR.dtd.$tableContent[b]||CKEDITOR.dtd.$nonEditable[b]||"br"==b);this.isEmpty=!!CKEDITOR.dtd.$empty[a];this.isUnknown=!CKEDITOR.dtd[a];this._={isBlockLike:b,hasInlineStarted:this.isEmpty||!b}};
CKEDITOR.htmlParser.cssStyle=function(a){var d={};((a instanceof CKEDITOR.htmlParser.element?a.attributes.style:a)||"").replace(/&quot;/g,'"').replace(/\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g,function(a,c,f){"font-family"==c&&(f=f.replace(/["']/g,""));d[c.toLowerCase()]=f});return{rules:d,populate:function(a){var c=this.toString();c&&(a instanceof CKEDITOR.dom.element?a.setAttribute("style",c):a instanceof CKEDITOR.htmlParser.element?a.attributes.style=c:a.style=c)},toString:function(){var a=[],c;
for(c in d)d[c]&&a.push(c,":",d[c],";");return a.join("")}}};
(function(){function a(a){return function(b){return b.type==CKEDITOR.NODE_ELEMENT&&("string"==typeof a?b.name==a:b.name in a)}}var d=function(a,b){a=a[0];b=b[0];return a<b?-1:a>b?1:0},b=CKEDITOR.htmlParser.fragment.prototype;CKEDITOR.htmlParser.element.prototype=CKEDITOR.tools.extend(new CKEDITOR.htmlParser.node,{type:CKEDITOR.NODE_ELEMENT,add:b.add,clone:function(){return new CKEDITOR.htmlParser.element(this.name,this.attributes)},filter:function(a,b){var d=this,k,g;b=d.getFilterContext(b);if(b.off)return!0;
if(!d.parent)a.onRoot(b,d);for(;;){k=d.name;if(!(g=a.onElementName(b,k)))return this.remove(),!1;d.name=g;if(!(d=a.onElement(b,d)))return this.remove(),!1;if(d!==this)return this.replaceWith(d),!1;if(d.name==k)break;if(d.type!=CKEDITOR.NODE_ELEMENT)return this.replaceWith(d),!1;if(!d.name)return this.replaceWithChildren(),!1}k=d.attributes;var n,r;for(n in k){for(g=k[n];;)if(r=a.onAttributeName(b,n))if(r!=n)delete k[n],n=r;else break;else{delete k[n];break}r&&(!1===(g=a.onAttribute(b,d,r,g))?delete k[r]:
k[r]=g)}d.isEmpty||this.filterChildren(a,!1,b);return!0},filterChildren:b.filterChildren,writeHtml:function(a,b){b&&this.filter(b);var h=this.name,k=[],g=this.attributes,n,r;a.openTag(h,g);for(n in g)k.push([n,g[n]]);a.sortAttributes&&k.sort(d);n=0;for(r=k.length;n<r;n++)g=k[n],a.attribute(g[0],g[1]);a.openTagClose(h,this.isEmpty);this.writeChildrenHtml(a);this.isEmpty||a.closeTag(h)},writeChildrenHtml:b.writeChildrenHtml,replaceWithChildren:function(){for(var a=this.children,b=a.length;b;)a[--b].insertAfter(this);
this.remove()},forEach:b.forEach,getFirst:function(b){if(!b)return this.children.length?this.children[0]:null;"function"!=typeof b&&(b=a(b));for(var d=0,h=this.children.length;d<h;++d)if(b(this.children[d]))return this.children[d];return null},getHtml:function(){var a=new CKEDITOR.htmlParser.basicWriter;this.writeChildrenHtml(a);return a.getHtml()},setHtml:function(a){a=this.children=CKEDITOR.htmlParser.fragment.fromHtml(a).children;for(var b=0,d=a.length;b<d;++b)a[b].parent=this},getOuterHtml:function(){var a=
new CKEDITOR.htmlParser.basicWriter;this.writeHtml(a);return a.getHtml()},split:function(a){for(var b=this.children.splice(a,this.children.length-a),d=this.clone(),k=0;k<b.length;++k)b[k].parent=d;d.children=b;b[0]&&(b[0].previous=null);0<a&&(this.children[a-1].next=null);this.parent.add(d,this.getIndex()+1);return d},find:function(a,b){void 0===b&&(b=!1);var d=[],k;for(k=0;k<this.children.length;k++){var g=this.children[k];"function"==typeof a&&a(g)?d.push(g):"string"==typeof a&&g.name===a&&d.push(g);
b&&g.find&&(d=d.concat(g.find(a,b)))}return d},addClass:function(a){if(!this.hasClass(a)){var b=this.attributes["class"]||"";this.attributes["class"]=b+(b?" ":"")+a}},removeClass:function(a){var b=this.attributes["class"];b&&((b=CKEDITOR.tools.trim(b.replace(new RegExp("(?:\\s+|^)"+a+"(?:\\s+|$)")," ")))?this.attributes["class"]=b:delete this.attributes["class"])},hasClass:function(a){var b=this.attributes["class"];return b?(new RegExp("(?:^|\\s)"+a+"(?\x3d\\s|$)")).test(b):!1},getFilterContext:function(a){var b=
[];a||(a={off:!1,nonEditable:!1,nestedEditable:!1});a.off||"off"!=this.attributes["data-cke-processor"]||b.push("off",!0);a.nonEditable||"false"!=this.attributes.contenteditable?a.nonEditable&&!a.nestedEditable&&"true"==this.attributes.contenteditable&&b.push("nestedEditable",!0):b.push("nonEditable",!0);if(b.length){a=CKEDITOR.tools.copy(a);for(var d=0;d<b.length;d+=2)a[b[d]]=b[d+1]}return a}},!0)})();
(function(){var a=/{([^}]+)}/g;CKEDITOR.template=function(a){this.source=String(a)};CKEDITOR.template.prototype.output=function(d,b){var c=this.source.replace(a,function(a,b){return void 0!==d[b]?d[b]:a});return b?b.push(c):c}})();delete CKEDITOR.loadFullCore;CKEDITOR.instances={};CKEDITOR.document=new CKEDITOR.dom.document(document);
CKEDITOR.add=function(a){CKEDITOR.instances[a.name]=a;a.on("focus",function(){CKEDITOR.currentInstance!=a&&(CKEDITOR.currentInstance=a,CKEDITOR.fire("currentInstance"))});a.on("blur",function(){CKEDITOR.currentInstance==a&&(CKEDITOR.currentInstance=null,CKEDITOR.fire("currentInstance"))});CKEDITOR.fire("instance",null,a)};CKEDITOR.remove=function(a){delete CKEDITOR.instances[a.name]};
(function(){var a={};CKEDITOR.addTemplate=function(d,b){var c=a[d];if(c)return c;c={name:d,source:b};CKEDITOR.fire("template",c);return a[d]=new CKEDITOR.template(c.source)};CKEDITOR.getTemplate=function(d){return a[d]}})();(function(){var a=[];CKEDITOR.addCss=function(d){a.push(d)};CKEDITOR.getCss=function(){return a.join("\n")}})();CKEDITOR.on("instanceDestroyed",function(){CKEDITOR.tools.isEmpty(this.instances)&&CKEDITOR.fire("reset")});CKEDITOR.TRISTATE_ON=1;CKEDITOR.TRISTATE_OFF=2;
CKEDITOR.TRISTATE_DISABLED=0;
(function(){CKEDITOR.inline=function(a,d){if(!CKEDITOR.env.isCompatible)return null;a=CKEDITOR.dom.element.get(a);if(a.getEditor())throw'The editor instance "'+a.getEditor().name+'" is already attached to the provided element.';var b=new CKEDITOR.editor(d,a,CKEDITOR.ELEMENT_MODE_INLINE),c=a.is("textarea")?a:null;c?(b.setData(c.getValue(),null,!0),a=CKEDITOR.dom.element.createFromHtml('\x3cdiv contenteditable\x3d"'+!!b.readOnly+'" class\x3d"cke_textarea_inline"\x3e'+c.getValue()+"\x3c/div\x3e",CKEDITOR.document),
a.insertAfter(c),c.hide(),c.$.form&&b._attachToForm()):b.setData(a.getHtml(),null,!0);b.on("loaded",function(){b.fire("uiReady");b.editable(a);b.container=a;b.ui.contentsElement=a;b.setData(b.getData(1));b.resetDirty();b.fire("contentDom");b.mode="wysiwyg";b.fire("mode");b.status="ready";b.fireOnce("instanceReady");CKEDITOR.fire("instanceReady",null,b)},null,null,1E4);b.on("destroy",function(){c&&(b.container.clearCustomData(),b.container.remove(),c.show());b.element.clearCustomData();delete b.element});
return b};CKEDITOR.inlineAll=function(){var a,d,b;for(b in CKEDITOR.dtd.$editable)for(var c=CKEDITOR.document.getElementsByTag(b),f=0,h=c.count();f<h;f++)a=c.getItem(f),"true"==a.getAttribute("contenteditable")&&(d={element:a,config:{}},!1!==CKEDITOR.fire("inline",d)&&CKEDITOR.inline(a,d.config))};CKEDITOR.domReady(function(){!CKEDITOR.disableAutoInline&&CKEDITOR.inlineAll()})})();CKEDITOR.replaceClass="ckeditor";
(function(){function a(a,f,h,k){if(!CKEDITOR.env.isCompatible)return null;a=CKEDITOR.dom.element.get(a);if(a.getEditor())throw'The editor instance "'+a.getEditor().name+'" is already attached to the provided element.';var g=new CKEDITOR.editor(f,a,k);k==CKEDITOR.ELEMENT_MODE_REPLACE&&(a.setStyle("visibility","hidden"),g._.required=a.hasAttribute("required"),a.removeAttribute("required"));h&&g.setData(h,null,!0);g.on("loaded",function(){b(g);k==CKEDITOR.ELEMENT_MODE_REPLACE&&g.config.autoUpdateElement&&
a.$.form&&g._attachToForm();g.setMode(g.config.startupMode,function(){g.resetDirty();g.status="ready";g.fireOnce("instanceReady");CKEDITOR.fire("instanceReady",null,g)})});g.on("destroy",d);return g}function d(){var a=this.container,b=this.element;a&&(a.clearCustomData(),a.remove());b&&(b.clearCustomData(),this.elementMode==CKEDITOR.ELEMENT_MODE_REPLACE&&(b.show(),this._.required&&b.setAttribute("required","required")),delete this.element)}function b(a){var b=a.name,d=a.element,k=a.elementMode,g=
a.fire("uiSpace",{space:"top",html:""}).html,n=a.fire("uiSpace",{space:"bottom",html:""}).html,r=new CKEDITOR.template('\x3c{outerEl} id\x3d"cke_{name}" class\x3d"{id} cke cke_reset cke_chrome cke_editor_{name} cke_{langDir} '+CKEDITOR.env.cssClass+'"  dir\x3d"{langDir}" lang\x3d"{langCode}" role\x3d"application"'+(a.title?' aria-labelledby\x3d"cke_{name}_arialbl"':"")+"\x3e"+(a.title?'\x3cspan id\x3d"cke_{name}_arialbl" class\x3d"cke_voice_label"\x3e{voiceLabel}\x3c/span\x3e':"")+'\x3c{outerEl} class\x3d"cke_inner cke_reset" role\x3d"presentation"\x3e{topHtml}\x3c{outerEl} id\x3d"{contentId}" class\x3d"cke_contents cke_reset" role\x3d"presentation"\x3e\x3c/{outerEl}\x3e{bottomHtml}\x3c/{outerEl}\x3e\x3c/{outerEl}\x3e'),
b=CKEDITOR.dom.element.createFromHtml(r.output({id:a.id,name:b,langDir:a.lang.dir,langCode:a.langCode,voiceLabel:a.title,topHtml:g?'\x3cspan id\x3d"'+a.ui.spaceId("top")+'" class\x3d"cke_top cke_reset_all" role\x3d"presentation" style\x3d"height:auto"\x3e'+g+"\x3c/span\x3e":"",contentId:a.ui.spaceId("contents"),bottomHtml:n?'\x3cspan id\x3d"'+a.ui.spaceId("bottom")+'" class\x3d"cke_bottom cke_reset_all" role\x3d"presentation"\x3e'+n+"\x3c/span\x3e":"",outerEl:CKEDITOR.env.ie?"span":"div"}));k==CKEDITOR.ELEMENT_MODE_REPLACE?
(d.hide(),b.insertAfter(d)):d.append(b);a.container=b;a.ui.contentsElement=a.ui.space("contents");g&&a.ui.space("top").unselectable();n&&a.ui.space("bottom").unselectable();d=a.config.width;k=a.config.height;d&&b.setStyle("width",CKEDITOR.tools.cssLength(d));k&&a.ui.space("contents").setStyle("height",CKEDITOR.tools.cssLength(k));b.disableContextMenu();CKEDITOR.env.webkit&&b.on("focus",function(){a.focus()});a.fireOnce("uiReady")}CKEDITOR.replace=function(b,d){return a(b,d,null,CKEDITOR.ELEMENT_MODE_REPLACE)};
CKEDITOR.appendTo=function(b,d,h){return a(b,d,h,CKEDITOR.ELEMENT_MODE_APPENDTO)};CKEDITOR.replaceAll=function(){for(var a=document.getElementsByTagName("textarea"),b=0;b<a.length;b++){var d=null,k=a[b];if(k.name||k.id){if("string"==typeof arguments[0]){if(!(new RegExp("(?:^|\\s)"+arguments[0]+"(?:$|\\s)")).test(k.className))continue}else if("function"==typeof arguments[0]&&(d={},!1===arguments[0](k,d)))continue;this.replace(k,d)}}};CKEDITOR.editor.prototype.addMode=function(a,b){(this._.modes||(this._.modes=
{}))[a]=b};CKEDITOR.editor.prototype.setMode=function(a,b){var d=this,k=this._.modes;if(a!=d.mode&&k&&k[a]){d.fire("beforeSetMode",a);if(d.mode){var g=d.checkDirty(),k=d._.previousModeData,n,r=0;d.fire("beforeModeUnload");d.editable(0);d._.previousMode=d.mode;d._.previousModeData=n=d.getData(1);"source"==d.mode&&k==n&&(d.fire("lockSnapshot",{forceUpdate:!0}),r=1);d.ui.space("contents").setHtml("");d.mode=""}else d._.previousModeData=d.getData(1);this._.modes[a](function(){d.mode=a;void 0!==g&&!g&&
d.resetDirty();r?d.fire("unlockSnapshot"):"wysiwyg"==a&&d.fire("saveSnapshot");setTimeout(function(){d.fire("mode");b&&b.call(d)},0)})}};CKEDITOR.editor.prototype.resize=function(a,b,d,k){var g=this.container,n=this.ui.space("contents"),r=CKEDITOR.env.webkit&&this.document&&this.document.getWindow().$.frameElement;k=k?this.container.getFirst(function(a){return a.type==CKEDITOR.NODE_ELEMENT&&a.hasClass("cke_inner")}):g;k.setSize("width",a,!0);r&&(r.style.width="1%");var e=(k.$.offsetHeight||0)-(n.$.clientHeight||
0),g=Math.max(b-(d?0:e),0);b=d?b+e:b;n.setStyle("height",g+"px");r&&(r.style.width="100%");this.fire("resize",{outerHeight:b,contentsHeight:g,outerWidth:a||k.getSize("width")})};CKEDITOR.editor.prototype.getResizable=function(a){return a?this.ui.space("contents"):this.container};CKEDITOR.domReady(function(){CKEDITOR.replaceClass&&CKEDITOR.replaceAll(CKEDITOR.replaceClass)})})();CKEDITOR.config.startupMode="wysiwyg";
(function(){function a(a){var b=a.editor,e=a.data.path,f=e.blockLimit,g=a.data.selection,h=g.getRanges()[0],q;if(CKEDITOR.env.gecko||CKEDITOR.env.ie&&CKEDITOR.env.needsBrFiller)if(g=d(g,e))g.appendBogus(),q=CKEDITOR.env.ie;k(b,e.block,f)&&h.collapsed&&!h.getCommonAncestor().isReadOnly()&&(e=h.clone(),e.enlarge(CKEDITOR.ENLARGE_BLOCK_CONTENTS),f=new CKEDITOR.dom.walker(e),f.guard=function(a){return!c(a)||a.type==CKEDITOR.NODE_COMMENT||a.isReadOnly()},!f.checkForward()||e.checkStartOfBlock()&&e.checkEndOfBlock())&&
(b=h.fixBlock(!0,b.activeEnterMode==CKEDITOR.ENTER_DIV?"div":"p"),CKEDITOR.env.needsBrFiller||(b=b.getFirst(c))&&b.type==CKEDITOR.NODE_TEXT&&CKEDITOR.tools.trim(b.getText()).match(/^(?:&nbsp;|\xa0)$/)&&b.remove(),q=1,a.cancel());q&&h.select()}function d(a,b){if(a.isFake)return 0;var d=b.block||b.blockLimit,e=d&&d.getLast(c);if(!(!d||!d.isBlockBoundary()||e&&e.type==CKEDITOR.NODE_ELEMENT&&e.isBlockBoundary()||d.is("pre")||d.getBogus()))return d}function b(a){var b=a.data.getTarget();b.is("input")&&
(b=b.getAttribute("type"),"submit"!=b&&"reset"!=b||a.data.preventDefault())}function c(a){return e(a)&&y(a)}function f(a,b){return function(c){var d=c.data.$.toElement||c.data.$.fromElement||c.data.$.relatedTarget;(d=d&&d.nodeType==CKEDITOR.NODE_ELEMENT?new CKEDITOR.dom.element(d):null)&&(b.equals(d)||b.contains(d))||a.call(this,c)}}function h(a){function b(a){return function(b,e){e&&b.type==CKEDITOR.NODE_ELEMENT&&b.is(f)&&(d=b);if(!(e||!c(b)||a&&B(b)))return!1}}var d,e=a.getRanges()[0];a=a.root;
var f={table:1,ul:1,ol:1,dl:1};if(e.startPath().contains(f)){var g=e.clone();g.collapse(1);g.setStartAt(a,CKEDITOR.POSITION_AFTER_START);a=new CKEDITOR.dom.walker(g);a.guard=b();a.checkBackward();if(d)return g=e.clone(),g.collapse(),g.setEndAt(d,CKEDITOR.POSITION_AFTER_END),a=new CKEDITOR.dom.walker(g),a.guard=b(!0),d=!1,a.checkForward(),d}return null}function k(a,b,c){return!1!==a.config.autoParagraph&&a.activeEnterMode!=CKEDITOR.ENTER_BR&&(a.editable().equals(c)&&!b||b&&"true"==b.getAttribute("contenteditable"))}
function g(a){return a.activeEnterMode!=CKEDITOR.ENTER_BR&&!1!==a.config.autoParagraph?a.activeEnterMode==CKEDITOR.ENTER_DIV?"div":"p":!1}function n(a){var b=a.editor;b.getSelection().scrollIntoView();setTimeout(function(){b.fire("saveSnapshot")},0)}function r(a,b,c){var d=a.getCommonAncestor(b);for(b=a=c?b:a;(a=a.getParent())&&!d.equals(a)&&1==a.getChildCount();)b=a;b.remove()}var e,y,v,B,D,x,m,J,u,K;CKEDITOR.editable=CKEDITOR.tools.createClass({base:CKEDITOR.dom.element,$:function(a,b){this.base(b.$||
b);this.editor=a;this.status="unloaded";this.hasFocus=!1;this.setup()},proto:{focus:function(){var a;if(CKEDITOR.env.webkit&&!this.hasFocus&&(a=this.editor._.previousActive||this.getDocument().getActive(),this.contains(a))){a.focus();return}CKEDITOR.env.edge&&14<CKEDITOR.env.version&&!this.hasFocus&&this.getDocument().equals(CKEDITOR.document)&&(this.editor._.previousScrollTop=this.$.scrollTop);try{if(!CKEDITOR.env.ie||CKEDITOR.env.edge&&14<CKEDITOR.env.version||!this.getDocument().equals(CKEDITOR.document))if(CKEDITOR.env.chrome){var b=
this.$.scrollTop;this.$.focus();this.$.scrollTop=b}else this.$.focus();else this.$.setActive()}catch(c){if(!CKEDITOR.env.ie)throw c;}CKEDITOR.env.safari&&!this.isInline()&&(a=CKEDITOR.document.getActive(),a.equals(this.getWindow().getFrame())||this.getWindow().focus())},on:function(a,b){var c=Array.prototype.slice.call(arguments,0);CKEDITOR.env.ie&&/^focus|blur$/.exec(a)&&(a="focus"==a?"focusin":"focusout",b=f(b,this),c[0]=a,c[1]=b);return CKEDITOR.dom.element.prototype.on.apply(this,c)},attachListener:function(a){!this._.listeners&&
(this._.listeners=[]);var b=Array.prototype.slice.call(arguments,1),b=a.on.apply(a,b);this._.listeners.push(b);return b},clearListeners:function(){var a=this._.listeners;try{for(;a.length;)a.pop().removeListener()}catch(b){}},restoreAttrs:function(){var a=this._.attrChanges,b,c;for(c in a)a.hasOwnProperty(c)&&(b=a[c],null!==b?this.setAttribute(c,b):this.removeAttribute(c))},attachClass:function(a){var b=this.getCustomData("classes");this.hasClass(a)||(!b&&(b=[]),b.push(a),this.setCustomData("classes",
b),this.addClass(a))},changeAttr:function(a,b){var c=this.getAttribute(a);b!==c&&(!this._.attrChanges&&(this._.attrChanges={}),a in this._.attrChanges||(this._.attrChanges[a]=c),this.setAttribute(a,b))},insertText:function(a){this.editor.focus();this.insertHtml(this.transformPlainTextToHtml(a),"text")},transformPlainTextToHtml:function(a){var b=this.editor.getSelection().getStartElement().hasAscendant("pre",!0)?CKEDITOR.ENTER_BR:this.editor.activeEnterMode;return CKEDITOR.tools.transformPlainTextToHtml(a,
b)},insertHtml:function(a,b,c){var d=this.editor;d.focus();d.fire("saveSnapshot");c||(c=d.getSelection().getRanges()[0]);x(this,b||"html",a,c);c.select();n(this);this.editor.fire("afterInsertHtml",{})},insertHtmlIntoRange:function(a,b,c){x(this,c||"html",a,b);this.editor.fire("afterInsertHtml",{intoRange:b})},insertElement:function(a,b){var d=this.editor;d.focus();d.fire("saveSnapshot");var e=d.activeEnterMode,d=d.getSelection(),f=a.getName(),f=CKEDITOR.dtd.$block[f];b||(b=d.getRanges()[0]);this.insertElementIntoRange(a,
b)&&(b.moveToPosition(a,CKEDITOR.POSITION_AFTER_END),f&&((f=a.getNext(function(a){return c(a)&&!B(a)}))&&f.type==CKEDITOR.NODE_ELEMENT&&f.is(CKEDITOR.dtd.$block)?f.getDtd()["#"]?b.moveToElementEditStart(f):b.moveToElementEditEnd(a):f||e==CKEDITOR.ENTER_BR||(f=b.fixBlock(!0,e==CKEDITOR.ENTER_DIV?"div":"p"),b.moveToElementEditStart(f))));d.selectRanges([b]);n(this)},insertElementIntoSelection:function(a){this.insertElement(a)},insertElementIntoRange:function(a,b){var c=this.editor,d=c.config.enterMode,
e=a.getName(),f=CKEDITOR.dtd.$block[e];if(b.checkReadOnly())return!1;b.deleteContents(1);b.startContainer.type==CKEDITOR.NODE_ELEMENT&&(b.startContainer.is({tr:1,table:1,tbody:1,thead:1,tfoot:1})?m(b):b.startContainer.is(CKEDITOR.dtd.$list)&&J(b));var q,g;if(f)for(;(q=b.getCommonAncestor(0,1))&&(g=CKEDITOR.dtd[q.getName()])&&(!g||!g[e]);)q.getName()in CKEDITOR.dtd.span?b.splitElement(q):b.checkStartOfBlock()&&b.checkEndOfBlock()?(b.setStartBefore(q),b.collapse(!0),q.remove()):b.splitBlock(d==CKEDITOR.ENTER_DIV?
"div":"p",c.editable());b.insertNode(a);return!0},setData:function(a,b){b||(a=this.editor.dataProcessor.toHtml(a));this.setHtml(a);this.fixInitialSelection();"unloaded"==this.status&&(this.status="ready");this.editor.fire("dataReady")},getData:function(a){var b=this.getHtml();a||(b=this.editor.dataProcessor.toDataFormat(b));return b},setReadOnly:function(a){this.setAttribute("contenteditable",!a)},detach:function(){this.removeClass("cke_editable");this.status="detached";var a=this.editor;this._.detach();
delete a.document;delete a.window},isInline:function(){return this.getDocument().equals(CKEDITOR.document)},fixInitialSelection:function(){function a(){var b=c.getDocument().$,d=b.getSelection(),e;a:if(d.anchorNode&&d.anchorNode==c.$)e=!0;else{if(CKEDITOR.env.webkit&&(e=c.getDocument().getActive())&&e.equals(c)&&!d.anchorNode){e=!0;break a}e=void 0}e&&(e=new CKEDITOR.dom.range(c),e.moveToElementEditStart(c),b=b.createRange(),b.setStart(e.startContainer.$,e.startOffset),b.collapse(!0),d.removeAllRanges(),
d.addRange(b))}function b(){var a=c.getDocument().$,d=a.selection,e=c.getDocument().getActive();"None"==d.type&&e.equals(c)&&(d=new CKEDITOR.dom.range(c),a=a.body.createTextRange(),d.moveToElementEditStart(c),d=d.startContainer,d.type!=CKEDITOR.NODE_ELEMENT&&(d=d.getParent()),a.moveToElementText(d.$),a.collapse(!0),a.select())}var c=this;if(CKEDITOR.env.ie&&(9>CKEDITOR.env.version||CKEDITOR.env.quirks))this.hasFocus&&(this.focus(),b());else if(this.hasFocus)this.focus(),a();else this.once("focus",
function(){a()},null,null,-999)},getHtmlFromRange:function(a){if(a.collapsed)return new CKEDITOR.dom.documentFragment(a.document);a={doc:this.getDocument(),range:a.clone()};u.eol.detect(a,this);u.bogus.exclude(a);u.cell.shrink(a);a.fragment=a.range.cloneContents();u.tree.rebuild(a,this);u.eol.fix(a,this);return new CKEDITOR.dom.documentFragment(a.fragment.$)},extractHtmlFromRange:function(a,b){var c=K,d={range:a,doc:a.document},e=this.getHtmlFromRange(a);if(a.collapsed)return a.optimize(),e;a.enlarge(CKEDITOR.ENLARGE_INLINE,
1);c.table.detectPurge(d);d.bookmark=a.createBookmark();delete d.range;var f=this.editor.createRange();f.moveToPosition(d.bookmark.startNode,CKEDITOR.POSITION_BEFORE_START);d.targetBookmark=f.createBookmark();c.list.detectMerge(d,this);c.table.detectRanges(d,this);c.block.detectMerge(d,this);d.tableContentsRanges?(c.table.deleteRanges(d),a.moveToBookmark(d.bookmark),d.range=a):(a.moveToBookmark(d.bookmark),d.range=a,a.extractContents(c.detectExtractMerge(d)));a.moveToBookmark(d.targetBookmark);a.optimize();
c.fixUneditableRangePosition(a);c.list.merge(d,this);c.table.purge(d,this);c.block.merge(d,this);if(b){c=a.startPath();if(d=a.checkStartOfBlock()&&a.checkEndOfBlock()&&c.block&&!a.root.equals(c.block)){a:{var d=c.block.getElementsByTag("span"),f=0,q;if(d)for(;q=d.getItem(f++);)if(!y(q)){d=!0;break a}d=!1}d=!d}d&&(a.moveToPosition(c.block,CKEDITOR.POSITION_BEFORE_START),c.block.remove())}else c.autoParagraph(this.editor,a),v(a.startContainer)&&a.startContainer.appendBogus();a.startContainer.mergeSiblings();
return e},setup:function(){var a=this.editor;this.attachListener(a,"beforeGetData",function(){var b=this.getData();this.is("textarea")||!1!==a.config.ignoreEmptyParagraph&&(b=b.replace(D,function(a,b){return b}));a.setData(b,null,1)},this);this.attachListener(a,"getSnapshot",function(a){a.data=this.getData(1)},this);this.attachListener(a,"afterSetData",function(){this.setData(a.getData(1))},this);this.attachListener(a,"loadSnapshot",function(a){this.setData(a.data,1)},this);this.attachListener(a,
"beforeFocus",function(){var b=a.getSelection();(b=b&&b.getNative())&&"Control"==b.type||this.focus()},this);this.attachListener(a,"insertHtml",function(a){this.insertHtml(a.data.dataValue,a.data.mode,a.data.range)},this);this.attachListener(a,"insertElement",function(a){this.insertElement(a.data)},this);this.attachListener(a,"insertText",function(a){this.insertText(a.data)},this);this.setReadOnly(a.readOnly);this.attachClass("cke_editable");a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE?this.attachClass("cke_editable_inline"):
a.elementMode!=CKEDITOR.ELEMENT_MODE_REPLACE&&a.elementMode!=CKEDITOR.ELEMENT_MODE_APPENDTO||this.attachClass("cke_editable_themed");this.attachClass("cke_contents_"+a.config.contentsLangDirection);a.keystrokeHandler.blockedKeystrokes[8]=+a.readOnly;a.keystrokeHandler.attach(this);this.on("blur",function(){this.hasFocus=!1},null,null,-1);this.on("focus",function(){this.hasFocus=!0},null,null,-1);if(CKEDITOR.env.webkit)this.on("scroll",function(){a._.previousScrollTop=a.editable().$.scrollTop},null,
null,-1);if(CKEDITOR.env.edge&&14<CKEDITOR.env.version){var d=function(){var b=a.editable();null!=a._.previousScrollTop&&b.getDocument().equals(CKEDITOR.document)&&(b.$.scrollTop=a._.previousScrollTop,a._.previousScrollTop=null,this.removeListener("scroll",d))};this.on("scroll",d)}a.focusManager.add(this);this.equals(CKEDITOR.document.getActive())&&(this.hasFocus=!0,a.once("contentDom",function(){a.focusManager.focus(this)},this));this.isInline()&&this.changeAttr("tabindex",a.tabIndex);if(!this.is("textarea")){a.document=
this.getDocument();a.window=this.getWindow();var f=a.document;this.changeAttr("spellcheck",!a.config.disableNativeSpellChecker);var g=a.config.contentsLangDirection;this.getDirection(1)!=g&&this.changeAttr("dir",g);var k=CKEDITOR.getCss();if(k){var g=f.getHead(),m=g.getCustomData("stylesheet");m?k!=m.getText()&&(CKEDITOR.env.ie&&9>CKEDITOR.env.version?m.$.styleSheet.cssText=k:m.setText(k)):(k=f.appendStyleText(k),k=new CKEDITOR.dom.element(k.ownerNode||k.owningElement),g.setCustomData("stylesheet",
k),k.data("cke-temp",1))}g=f.getCustomData("stylesheet_ref")||0;f.setCustomData("stylesheet_ref",g+1);this.setCustomData("cke_includeReadonly",!a.config.disableReadonlyStyling);this.attachListener(this,"click",function(a){a=a.data;var b=(new CKEDITOR.dom.elementPath(a.getTarget(),this)).contains("a");b&&2!=a.$.button&&b.isReadOnly()&&a.preventDefault()});var q={8:1,46:1};this.attachListener(a,"key",function(b){if(a.readOnly)return!0;var c=b.data.domEvent.getKey(),d;b=a.getSelection();if(0!==b.getRanges().length){if(c in
q){var f,g=b.getRanges()[0],p=g.startPath(),k,w,A,c=8==c;CKEDITOR.env.ie&&11>CKEDITOR.env.version&&(f=b.getSelectedElement())||(f=h(b))?(a.fire("saveSnapshot"),g.moveToPosition(f,CKEDITOR.POSITION_BEFORE_START),f.remove(),g.select(),a.fire("saveSnapshot"),d=1):g.collapsed&&((k=p.block)&&(A=k[c?"getPrevious":"getNext"](e))&&A.type==CKEDITOR.NODE_ELEMENT&&A.is("table")&&g[c?"checkStartOfBlock":"checkEndOfBlock"]()?(a.fire("saveSnapshot"),g[c?"checkEndOfBlock":"checkStartOfBlock"]()&&k.remove(),g["moveToElementEdit"+
(c?"End":"Start")](A),g.select(),a.fire("saveSnapshot"),d=1):p.blockLimit&&p.blockLimit.is("td")&&(w=p.blockLimit.getAscendant("table"))&&g.checkBoundaryOfElement(w,c?CKEDITOR.START:CKEDITOR.END)&&(A=w[c?"getPrevious":"getNext"](e))?(a.fire("saveSnapshot"),g["moveToElementEdit"+(c?"End":"Start")](A),g.checkStartOfBlock()&&g.checkEndOfBlock()?A.remove():g.select(),a.fire("saveSnapshot"),d=1):(w=p.contains(["td","th","caption"]))&&g.checkBoundaryOfElement(w,c?CKEDITOR.START:CKEDITOR.END)&&(d=1))}return!d}});
a.blockless&&CKEDITOR.env.ie&&CKEDITOR.env.needsBrFiller&&this.attachListener(this,"keyup",function(b){b.data.getKeystroke()in q&&!this.getFirst(c)&&(this.appendBogus(),b=a.createRange(),b.moveToPosition(this,CKEDITOR.POSITION_AFTER_START),b.select())});this.attachListener(this,"dblclick",function(b){if(a.readOnly)return!1;b={element:b.data.getTarget()};a.fire("doubleclick",b)});CKEDITOR.env.ie&&this.attachListener(this,"click",b);CKEDITOR.env.ie&&!CKEDITOR.env.edge||this.attachListener(this,"mousedown",
function(b){var c=b.data.getTarget();c.is("img","hr","input","textarea","select")&&!c.isReadOnly()&&(a.getSelection().selectElement(c),c.is("input","textarea","select")&&b.data.preventDefault())});CKEDITOR.env.edge&&this.attachListener(this,"mouseup",function(b){(b=b.data.getTarget())&&b.is("img")&&!b.isReadOnly()&&a.getSelection().selectElement(b)});CKEDITOR.env.gecko&&this.attachListener(this,"mouseup",function(b){if(2==b.data.$.button&&(b=b.data.getTarget(),!b.getAscendant("table")&&!b.getOuterHtml().replace(D,
""))){var c=a.createRange();c.moveToElementEditStart(b);c.select(!0)}});CKEDITOR.env.webkit&&(this.attachListener(this,"click",function(a){a.data.getTarget().is("input","select")&&a.data.preventDefault()}),this.attachListener(this,"mouseup",function(a){a.data.getTarget().is("input","textarea")&&a.data.preventDefault()}));CKEDITOR.env.webkit&&this.attachListener(a,"key",function(b){if(a.readOnly)return!0;var c=b.data.domEvent.getKey();if(c in q&&(b=a.getSelection(),0!==b.getRanges().length)){var c=
8==c,d=b.getRanges()[0];b=d.startPath();if(d.collapsed)a:{var e=b.block;if(e&&d[c?"checkStartOfBlock":"checkEndOfBlock"]()&&d.moveToClosestEditablePosition(e,!c)&&d.collapsed){if(d.startContainer.type==CKEDITOR.NODE_ELEMENT){var f=d.startContainer.getChild(d.startOffset-(c?1:0));if(f&&f.type==CKEDITOR.NODE_ELEMENT&&f.is("hr")){a.fire("saveSnapshot");f.remove();b=!0;break a}}d=d.startPath().block;if(!d||d&&d.contains(e))b=void 0;else{a.fire("saveSnapshot");var p;(p=(c?d:e).getBogus())&&p.remove();
p=a.getSelection();f=p.createBookmarks();(c?e:d).moveChildren(c?d:e,!1);b.lastElement.mergeSiblings();r(e,d,!c);p.selectBookmarks(f);b=!0}}else b=!1}else c=d,p=b.block,d=c.endPath().block,p&&d&&!p.equals(d)?(a.fire("saveSnapshot"),(e=p.getBogus())&&e.remove(),c.enlarge(CKEDITOR.ENLARGE_INLINE),c.deleteContents(),d.getParent()&&(d.moveChildren(p,!1),b.lastElement.mergeSiblings(),r(p,d,!0)),c=a.getSelection().getRanges()[0],c.collapse(1),c.optimize(),""===c.startContainer.getHtml()&&c.startContainer.appendBogus(),
c.select(),b=!0):b=!1;if(!b)return;a.getSelection().scrollIntoView();a.fire("saveSnapshot");return!1}},this,null,100)}}},_:{detach:function(){this.editor.setData(this.editor.getData(),0,1);this.clearListeners();this.restoreAttrs();var a;if(a=this.removeCustomData("classes"))for(;a.length;)this.removeClass(a.pop());if(!this.is("textarea")){a=this.getDocument();var b=a.getHead();if(b.getCustomData("stylesheet")){var c=a.getCustomData("stylesheet_ref");--c?a.setCustomData("stylesheet_ref",c):(a.removeCustomData("stylesheet_ref"),
b.removeCustomData("stylesheet").remove())}}this.editor.fire("contentDomUnload");delete this.editor}}});CKEDITOR.editor.prototype.editable=function(a){var b=this._.editable;if(b&&a)return 0;arguments.length&&(b=this._.editable=a?a instanceof CKEDITOR.editable?a:new CKEDITOR.editable(this,a):(b&&b.detach(),null));return b};CKEDITOR.on("instanceLoaded",function(b){var c=b.editor;c.on("insertElement",function(a){a=a.data;a.type==CKEDITOR.NODE_ELEMENT&&(a.is("input")||a.is("textarea"))&&("false"!=a.getAttribute("contentEditable")&&
a.data("cke-editable",a.hasAttribute("contenteditable")?"true":"1"),a.setAttribute("contentEditable",!1))});c.on("selectionChange",function(b){if(!c.readOnly){var d=c.getSelection();d&&!d.isLocked&&(d=c.checkDirty(),c.fire("lockSnapshot"),a(b),c.fire("unlockSnapshot"),!d&&c.resetDirty())}})});CKEDITOR.on("instanceCreated",function(a){var b=a.editor;b.on("mode",function(){var a=b.editable();if(a&&a.isInline()){var c=b.title;a.changeAttr("role","textbox");a.changeAttr("aria-multiline","true");a.changeAttr("aria-label",
c);c&&a.changeAttr("title",c);var d=b.fire("ariaEditorHelpLabel",{}).label;if(d&&(c=this.ui.space(this.elementMode==CKEDITOR.ELEMENT_MODE_INLINE?"top":"contents"))){var e=CKEDITOR.tools.getNextId(),d=CKEDITOR.dom.element.createFromHtml('\x3cspan id\x3d"'+e+'" class\x3d"cke_voice_label"\x3e'+d+"\x3c/span\x3e");c.append(d);a.changeAttr("aria-describedby",e)}}})});CKEDITOR.addCss(".cke_editable{cursor:text}.cke_editable img,.cke_editable input,.cke_editable textarea{cursor:default}");e=CKEDITOR.dom.walker.whitespaces(!0);
y=CKEDITOR.dom.walker.bookmark(!1,!0);v=CKEDITOR.dom.walker.empty();B=CKEDITOR.dom.walker.bogus();D=/(^|<body\b[^>]*>)\s*<(p|div|address|h\d|center|pre)[^>]*>\s*(?:<br[^>]*>|&nbsp;|\u00A0|&#160;)?\s*(:?<\/\2>)?\s*(?=$|<\/body>)/gi;x=function(){function a(b){return b.type==CKEDITOR.NODE_ELEMENT}function b(c,d){var e,f,g,q,h=[],z=d.range.startContainer;e=d.range.startPath();for(var z=E[z.getName()],k=0,H=c.getChildren(),m=H.count(),n=-1,r=-1,C=0,P=e.contains(E.$list);k<m;++k)e=H.getItem(k),a(e)?(g=
e.getName(),P&&g in CKEDITOR.dtd.$list?h=h.concat(b(e,d)):(q=!!z[g],"br"!=g||!e.data("cke-eol")||k&&k!=m-1||(C=(f=k?h[k-1].node:H.getItem(k+1))&&(!a(f)||!f.is("br")),f=f&&a(f)&&E.$block[f.getName()]),-1!=n||q||(n=k),q||(r=k),h.push({isElement:1,isLineBreak:C,isBlock:e.isBlockBoundary(),hasBlockSibling:f,node:e,name:g,allowed:q}),f=C=0)):h.push({isElement:0,node:e,allowed:1});-1<n&&(h[n].firstNotAllowed=1);-1<r&&(h[r].lastNotAllowed=1);return h}function d(b,c){var e=[],f=b.getChildren(),g=f.count(),
q,h=0,z=E[c],k=!b.is(E.$inline)||b.is("br");for(k&&e.push(" ");h<g;h++)q=f.getItem(h),a(q)&&!q.is(z)?e=e.concat(d(q,c)):e.push(q);k&&e.push(" ");return e}function e(b){return a(b.startContainer)&&b.startContainer.getChild(b.startOffset-1)}function f(b){return b&&a(b)&&(b.is(E.$removeEmpty)||b.is("a")&&!b.isBlockBoundary())}function h(b,c,d,e){var f=b.clone(),g,q;f.setEndAt(c,CKEDITOR.POSITION_BEFORE_END);(g=(new CKEDITOR.dom.walker(f)).next())&&a(g)&&z[g.getName()]&&(q=g.getPrevious())&&a(q)&&!q.getParent().equals(b.startContainer)&&
d.contains(q)&&e.contains(g)&&g.isIdentical(q)&&(g.moveChildren(q),g.remove(),h(b,c,d,e))}function q(b,c){function d(b,c){if(c.isBlock&&c.isElement&&!c.node.is("br")&&a(b)&&b.is("br"))return b.remove(),1}var e=c.endContainer.getChild(c.endOffset),f=c.endContainer.getChild(c.endOffset-1);e&&d(e,b[b.length-1]);f&&d(f,b[0])&&(c.setEnd(c.endContainer,c.endOffset-1),c.collapse())}var E=CKEDITOR.dtd,z={p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,ul:1,ol:1,li:1,pre:1,dl:1,blockquote:1},H={p:1,div:1,h1:1,h2:1,
h3:1,h4:1,h5:1,h6:1},m=CKEDITOR.tools.extend({},E.$inline);delete m.br;return function(z,p,N,w){var A=z.editor,G=!1;"unfiltered_html"==p&&(p="html",G=!0);if(!w.checkReadOnly()){var I=(new CKEDITOR.dom.elementPath(w.startContainer,w.root)).blockLimit||w.root;z={type:p,dontFilter:G,editable:z,editor:A,range:w,blockLimit:I,mergeCandidates:[],zombies:[]};p=z.range;w=z.mergeCandidates;var n,r;"text"==z.type&&p.shrink(CKEDITOR.SHRINK_ELEMENT,!0,!1)&&(n=CKEDITOR.dom.element.createFromHtml("\x3cspan\x3e\x26nbsp;\x3c/span\x3e",
p.document),p.insertNode(n),p.setStartAfter(n));G=new CKEDITOR.dom.elementPath(p.startContainer);z.endPath=I=new CKEDITOR.dom.elementPath(p.endContainer);if(!p.collapsed){var A=I.block||I.blockLimit,v=p.getCommonAncestor();A&&!A.equals(v)&&!A.contains(v)&&p.checkEndOfBlock()&&z.zombies.push(A);p.deleteContents()}for(;(r=e(p))&&a(r)&&r.isBlockBoundary()&&G.contains(r);)p.moveToPosition(r,CKEDITOR.POSITION_BEFORE_END);h(p,z.blockLimit,G,I);n&&(p.setEndBefore(n),p.collapse(),n.remove());n=p.startPath();
if(A=n.contains(f,!1,1))p.splitElement(A),z.inlineStylesRoot=A,z.inlineStylesPeak=n.lastElement;n=p.createBookmark();(A=n.startNode.getPrevious(c))&&a(A)&&f(A)&&w.push(A);(A=n.startNode.getNext(c))&&a(A)&&f(A)&&w.push(A);for(A=n.startNode;(A=A.getParent())&&f(A);)w.push(A);p.moveToBookmark(n);if(n=N){n=z.range;if("text"==z.type&&z.inlineStylesRoot){r=z.inlineStylesPeak;p=r.getDocument().createText("{cke-peak}");for(w=z.inlineStylesRoot.getParent();!r.equals(w);)p=p.appendTo(r.clone()),r=r.getParent();
N=p.getOuterHtml().split("{cke-peak}").join(N)}r=z.blockLimit.getName();if(/^\s+|\s+$/.test(N)&&"span"in CKEDITOR.dtd[r]){var x='\x3cspan data-cke-marker\x3d"1"\x3e\x26nbsp;\x3c/span\x3e';N=x+N+x}N=z.editor.dataProcessor.toHtml(N,{context:null,fixForBody:!1,protectedWhitespaces:!!x,dontFilter:z.dontFilter,filter:z.editor.activeFilter,enterMode:z.editor.activeEnterMode});r=n.document.createElement("body");r.setHtml(N);x&&(r.getFirst().remove(),r.getLast().remove());if((x=n.startPath().block)&&(1!=
x.getChildCount()||!x.getBogus()))a:{var y;if(1==r.getChildCount()&&a(y=r.getFirst())&&y.is(H)&&!y.hasAttribute("contenteditable")){x=y.getElementsByTag("*");n=0;for(w=x.count();n<w;n++)if(p=x.getItem(n),!p.is(m))break a;y.moveChildren(y.getParent(1));y.remove()}}z.dataWrapper=r;n=N}if(n){y=z.range;n=y.document;var u;r=z.blockLimit;w=0;var B,x=[],D,T;N=A=0;var J,K;p=y.startContainer;var G=z.endPath.elements[0],W,I=G.getPosition(p),v=!!G.getCommonAncestor(p)&&I!=CKEDITOR.POSITION_IDENTICAL&&!(I&CKEDITOR.POSITION_CONTAINS+
CKEDITOR.POSITION_IS_CONTAINED);p=b(z.dataWrapper,z);for(q(p,y);w<p.length;w++){I=p[w];if(u=I.isLineBreak){u=y;J=r;var S=void 0,Y=void 0;I.hasBlockSibling?u=1:(S=u.startContainer.getAscendant(E.$block,1))&&S.is({div:1,p:1})?(Y=S.getPosition(J),Y==CKEDITOR.POSITION_IDENTICAL||Y==CKEDITOR.POSITION_CONTAINS?u=0:(J=u.splitElement(S),u.moveToPosition(J,CKEDITOR.POSITION_AFTER_START),u=1)):u=0}if(u)N=0<w;else{u=y.startPath();!I.isBlock&&k(z.editor,u.block,u.blockLimit)&&(T=g(z.editor))&&(T=n.createElement(T),
T.appendBogus(),y.insertNode(T),CKEDITOR.env.needsBrFiller&&(B=T.getBogus())&&B.remove(),y.moveToPosition(T,CKEDITOR.POSITION_BEFORE_END));if((u=y.startPath().block)&&!u.equals(D)){if(B=u.getBogus())B.remove(),x.push(u);D=u}I.firstNotAllowed&&(A=1);if(A&&I.isElement){u=y.startContainer;for(J=null;u&&!E[u.getName()][I.name];){if(u.equals(r)){u=null;break}J=u;u=u.getParent()}if(u)J&&(K=y.splitElement(J),z.zombies.push(K),z.zombies.push(J));else{J=r.getName();W=!w;u=w==p.length-1;J=d(I.node,J);for(var S=
[],Y=J.length,Z=0,ba=void 0,ca=0,U=-1;Z<Y;Z++)ba=J[Z]," "==ba?(ca||W&&!Z||(S.push(new CKEDITOR.dom.text(" ")),U=S.length),ca=1):(S.push(ba),ca=0);u&&U==S.length&&S.pop();W=S}}if(W){for(;u=W.pop();)y.insertNode(u);W=0}else y.insertNode(I.node);I.lastNotAllowed&&w<p.length-1&&((K=v?G:K)&&y.setEndAt(K,CKEDITOR.POSITION_AFTER_START),A=0);y.collapse()}}1!=p.length?B=!1:(B=p[0],B=B.isElement&&"false"==B.node.getAttribute("contenteditable"));B&&(N=!0,u=p[0].node,y.setStartAt(u,CKEDITOR.POSITION_BEFORE_START),
y.setEndAt(u,CKEDITOR.POSITION_AFTER_END));z.dontMoveCaret=N;z.bogusNeededBlocks=x}B=z.range;var R;K=z.bogusNeededBlocks;for(W=B.createBookmark();D=z.zombies.pop();)D.getParent()&&(T=B.clone(),T.moveToElementEditStart(D),T.removeEmptyBlocksAtEnd());if(K)for(;D=K.pop();)CKEDITOR.env.needsBrFiller?D.appendBogus():D.append(B.document.createText(" "));for(;D=z.mergeCandidates.pop();)D.mergeSiblings();B.moveToBookmark(W);if(!z.dontMoveCaret){for(D=e(B);D&&a(D)&&!D.is(E.$empty);){if(D.isBlockBoundary())B.moveToPosition(D,
CKEDITOR.POSITION_BEFORE_END);else{if(f(D)&&D.getHtml().match(/(\s|&nbsp;)$/g)){R=null;break}R=B.clone();R.moveToPosition(D,CKEDITOR.POSITION_BEFORE_END)}D=D.getLast(c)}R&&B.moveToRange(R)}}}}();m=function(){function a(b){b=new CKEDITOR.dom.walker(b);b.guard=function(a,b){if(b)return!1;if(a.type==CKEDITOR.NODE_ELEMENT)return a.is(CKEDITOR.dtd.$tableContent)};b.evaluator=function(a){return a.type==CKEDITOR.NODE_ELEMENT};return b}function b(a,c,d){c=a.getDocument().createElement(c);a.append(c,d);return c}
function c(a){var b=a.count(),d;for(b;0<b--;)d=a.getItem(b),CKEDITOR.tools.trim(d.getHtml())||(d.appendBogus(),CKEDITOR.env.ie&&9>CKEDITOR.env.version&&d.getChildCount()&&d.getFirst().remove())}return function(d){var e=d.startContainer,f=e.getAscendant("table",1),g=!1;c(f.getElementsByTag("td"));c(f.getElementsByTag("th"));f=d.clone();f.setStart(e,0);f=a(f).lastBackward();f||(f=d.clone(),f.setEndAt(e,CKEDITOR.POSITION_BEFORE_END),f=a(f).lastForward(),g=!0);f||(f=e);f.is("table")?(d.setStartAt(f,CKEDITOR.POSITION_BEFORE_START),
d.collapse(!0),f.remove()):(f.is({tbody:1,thead:1,tfoot:1})&&(f=b(f,"tr",g)),f.is("tr")&&(f=b(f,f.getParent().is("thead")?"th":"td",g)),(e=f.getBogus())&&e.remove(),d.moveToPosition(f,g?CKEDITOR.POSITION_AFTER_START:CKEDITOR.POSITION_BEFORE_END))}}();J=function(){function a(b){b=new CKEDITOR.dom.walker(b);b.guard=function(a,b){if(b)return!1;if(a.type==CKEDITOR.NODE_ELEMENT)return a.is(CKEDITOR.dtd.$list)||a.is(CKEDITOR.dtd.$listItem)};b.evaluator=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&
a.is(CKEDITOR.dtd.$listItem)};return b}return function(b){var c=b.startContainer,d=!1,e;e=b.clone();e.setStart(c,0);e=a(e).lastBackward();e||(e=b.clone(),e.setEndAt(c,CKEDITOR.POSITION_BEFORE_END),e=a(e).lastForward(),d=!0);e||(e=c);e.is(CKEDITOR.dtd.$list)?(b.setStartAt(e,CKEDITOR.POSITION_BEFORE_START),b.collapse(!0),e.remove()):((c=e.getBogus())&&c.remove(),b.moveToPosition(e,d?CKEDITOR.POSITION_AFTER_START:CKEDITOR.POSITION_BEFORE_END),b.select())}}();u={eol:{detect:function(a,b){var c=a.range,
d=c.clone(),e=c.clone(),f=new CKEDITOR.dom.elementPath(c.startContainer,b),g=new CKEDITOR.dom.elementPath(c.endContainer,b);d.collapse(1);e.collapse();f.block&&d.checkBoundaryOfElement(f.block,CKEDITOR.END)&&(c.setStartAfter(f.block),a.prependEolBr=1);g.block&&e.checkBoundaryOfElement(g.block,CKEDITOR.START)&&(c.setEndBefore(g.block),a.appendEolBr=1)},fix:function(a,b){var c=b.getDocument(),d;a.appendEolBr&&(d=this.createEolBr(c),a.fragment.append(d));!a.prependEolBr||d&&!d.getPrevious()||a.fragment.append(this.createEolBr(c),
1)},createEolBr:function(a){return a.createElement("br",{attributes:{"data-cke-eol":1}})}},bogus:{exclude:function(a){var b=a.range.getBoundaryNodes(),c=b.startNode,b=b.endNode;!b||!B(b)||c&&c.equals(b)||a.range.setEndBefore(b)}},tree:{rebuild:function(a,b){var c=a.range,d=c.getCommonAncestor(),e=new CKEDITOR.dom.elementPath(d,b),f=new CKEDITOR.dom.elementPath(c.startContainer,b),c=new CKEDITOR.dom.elementPath(c.endContainer,b),g;d.type==CKEDITOR.NODE_TEXT&&(d=d.getParent());if(e.blockLimit.is({tr:1,
table:1})){var h=e.contains("table").getParent();g=function(a){return!a.equals(h)}}else if(e.block&&e.block.is(CKEDITOR.dtd.$listItem)&&(f=f.contains(CKEDITOR.dtd.$list),c=c.contains(CKEDITOR.dtd.$list),!f.equals(c))){var z=e.contains(CKEDITOR.dtd.$list).getParent();g=function(a){return!a.equals(z)}}g||(g=function(a){return!a.equals(e.block)&&!a.equals(e.blockLimit)});this.rebuildFragment(a,b,d,g)},rebuildFragment:function(a,b,c,d){for(var e;c&&!c.equals(b)&&d(c);)e=c.clone(0,1),a.fragment.appendTo(e),
a.fragment=e,c=c.getParent()}},cell:{shrink:function(a){a=a.range;var b=a.startContainer,c=a.endContainer,d=a.startOffset,e=a.endOffset;b.type==CKEDITOR.NODE_ELEMENT&&b.equals(c)&&b.is("tr")&&++d==e&&a.shrink(CKEDITOR.SHRINK_TEXT)}}};K=function(){function a(b,c){var d=b.getParent();if(d.is(CKEDITOR.dtd.$inline))b[c?"insertBefore":"insertAfter"](d)}function b(c,d,e){a(d);a(e,1);for(var f;f=e.getNext();)f.insertAfter(d),d=f;v(c)&&c.remove()}function c(a,b){var d=new CKEDITOR.dom.range(a);d.setStartAfter(b.startNode);
d.setEndBefore(b.endNode);return d}return{list:{detectMerge:function(a,b){var d=c(b,a.bookmark),e=d.startPath(),f=d.endPath(),g=e.contains(CKEDITOR.dtd.$list),h=f.contains(CKEDITOR.dtd.$list);a.mergeList=g&&h&&g.getParent().equals(h.getParent())&&!g.equals(h);a.mergeListItems=e.block&&f.block&&e.block.is(CKEDITOR.dtd.$listItem)&&f.block.is(CKEDITOR.dtd.$listItem);if(a.mergeList||a.mergeListItems)d=d.clone(),d.setStartBefore(a.bookmark.startNode),d.setEndAfter(a.bookmark.endNode),a.mergeListBookmark=
d.createBookmark()},merge:function(a,c){if(a.mergeListBookmark){var d=a.mergeListBookmark.startNode,e=a.mergeListBookmark.endNode,f=new CKEDITOR.dom.elementPath(d,c),g=new CKEDITOR.dom.elementPath(e,c);if(a.mergeList){var h=f.contains(CKEDITOR.dtd.$list),k=g.contains(CKEDITOR.dtd.$list);h.equals(k)||(k.moveChildren(h),k.remove())}a.mergeListItems&&(f=f.contains(CKEDITOR.dtd.$listItem),g=g.contains(CKEDITOR.dtd.$listItem),f.equals(g)||b(g,d,e));d.remove();e.remove()}}},block:{detectMerge:function(a,
b){if(!a.tableContentsRanges&&!a.mergeListBookmark){var c=new CKEDITOR.dom.range(b);c.setStartBefore(a.bookmark.startNode);c.setEndAfter(a.bookmark.endNode);a.mergeBlockBookmark=c.createBookmark()}},merge:function(a,c){if(a.mergeBlockBookmark&&!a.purgeTableBookmark){var d=a.mergeBlockBookmark.startNode,e=a.mergeBlockBookmark.endNode,f=new CKEDITOR.dom.elementPath(d,c),g=new CKEDITOR.dom.elementPath(e,c),f=f.block,g=g.block;f&&g&&!f.equals(g)&&b(g,d,e);d.remove();e.remove()}}},table:function(){function a(c){var e=
[],f,g=new CKEDITOR.dom.walker(c),h=c.startPath().contains(d),k=c.endPath().contains(d),p={};g.guard=function(a,g){if(a.type==CKEDITOR.NODE_ELEMENT){var A="visited_"+(g?"out":"in");if(a.getCustomData(A))return;CKEDITOR.dom.element.setMarker(p,a,A,1)}if(g&&h&&a.equals(h))f=c.clone(),f.setEndAt(h,CKEDITOR.POSITION_BEFORE_END),e.push(f);else if(!g&&k&&a.equals(k))f=c.clone(),f.setStartAt(k,CKEDITOR.POSITION_AFTER_START),e.push(f);else{if(A=!g)A=a.type==CKEDITOR.NODE_ELEMENT&&a.is(d)&&(!h||b(a,h))&&(!k||
b(a,k));if(!A&&(A=g))if(a.is(d))var A=h&&h.getAscendant("table",!0),l=k&&k.getAscendant("table",!0),H=a.getAscendant("table",!0),A=A&&A.contains(H)||l&&l.contains(H);else A=void 0;A&&(f=c.clone(),f.selectNodeContents(a),e.push(f))}};g.lastForward();CKEDITOR.dom.element.clearAllMarkers(p);return e}function b(a,c){var d=CKEDITOR.POSITION_CONTAINS+CKEDITOR.POSITION_IS_CONTAINED,e=a.getPosition(c);return e===CKEDITOR.POSITION_IDENTICAL?!1:0===(e&d)}var d={td:1,th:1,caption:1};return{detectPurge:function(a){var b=
a.range,c=b.clone();c.enlarge(CKEDITOR.ENLARGE_ELEMENT);var c=new CKEDITOR.dom.walker(c),e=0;c.evaluator=function(a){a.type==CKEDITOR.NODE_ELEMENT&&a.is(d)&&++e};c.checkForward();if(1<e){var c=b.startPath().contains("table"),f=b.endPath().contains("table");c&&f&&b.checkBoundaryOfElement(c,CKEDITOR.START)&&b.checkBoundaryOfElement(f,CKEDITOR.END)&&(b=a.range.clone(),b.setStartBefore(c),b.setEndAfter(f),a.purgeTableBookmark=b.createBookmark())}},detectRanges:function(e,f){var g=c(f,e.bookmark),h=g.clone(),
k,l,p=g.getCommonAncestor();p.is(CKEDITOR.dtd.$tableContent)&&!p.is(d)&&(p=p.getAscendant("table",!0));l=p;p=new CKEDITOR.dom.elementPath(g.startContainer,l);l=new CKEDITOR.dom.elementPath(g.endContainer,l);p=p.contains("table");l=l.contains("table");if(p||l)p&&l&&b(p,l)?(e.tableSurroundingRange=h,h.setStartAt(p,CKEDITOR.POSITION_AFTER_END),h.setEndAt(l,CKEDITOR.POSITION_BEFORE_START),h=g.clone(),h.setEndAt(p,CKEDITOR.POSITION_AFTER_END),k=g.clone(),k.setStartAt(l,CKEDITOR.POSITION_BEFORE_START),
k=a(h).concat(a(k))):p?l||(e.tableSurroundingRange=h,h.setStartAt(p,CKEDITOR.POSITION_AFTER_END),g.setEndAt(p,CKEDITOR.POSITION_AFTER_END)):(e.tableSurroundingRange=h,h.setEndAt(l,CKEDITOR.POSITION_BEFORE_START),g.setStartAt(l,CKEDITOR.POSITION_AFTER_START)),e.tableContentsRanges=k?k:a(g)},deleteRanges:function(a){for(var b;b=a.tableContentsRanges.pop();)b.extractContents(),v(b.startContainer)&&b.startContainer.appendBogus();a.tableSurroundingRange&&a.tableSurroundingRange.extractContents()},purge:function(a){if(a.purgeTableBookmark){var b=
a.doc,c=a.range.clone(),b=b.createElement("p");b.insertBefore(a.purgeTableBookmark.startNode);c.moveToBookmark(a.purgeTableBookmark);c.deleteContents();a.range.moveToPosition(b,CKEDITOR.POSITION_AFTER_START)}}}}(),detectExtractMerge:function(a){return!(a.range.startPath().contains(CKEDITOR.dtd.$listItem)&&a.range.endPath().contains(CKEDITOR.dtd.$listItem))},fixUneditableRangePosition:function(a){a.startContainer.getDtd()["#"]||a.moveToClosestEditablePosition(null,!0)},autoParagraph:function(a,b){var c=
b.startPath(),d;k(a,c.block,c.blockLimit)&&(d=g(a))&&(d=b.document.createElement(d),d.appendBogus(),b.insertNode(d),b.moveToPosition(d,CKEDITOR.POSITION_AFTER_START))}}}()})();
(function(){function a(a){return CKEDITOR.plugins.widget&&CKEDITOR.plugins.widget.isDomWidget(a)}function d(b,c){if(0===b.length||a(b[0].getEnclosedNode()))return!1;var d,e;if((d=!c&&1===b.length)&&!(d=b[0].collapsed)){var f=b[0];d=f.startContainer.getAscendant({td:1,th:1},!0);var g=f.endContainer.getAscendant({td:1,th:1},!0);e=CKEDITOR.tools.trim;d&&d.equals(g)&&!d.findOne("td, th, tr, tbody, table")?(f=f.cloneContents(),d=f.getFirst()?e(f.getFirst().getText())!==e(d.getText()):!0):d=!1}if(d)return!1;
for(e=0;e<b.length;e++)if(d=b[e]._getTableElement(),!d)return!1;return!0}function b(a){function b(a){a=a.find("td, th");var c=[],d;for(d=0;d<a.count();d++)c.push(a.getItem(d));return c}var c=[],d,e;for(e=0;e<a.length;e++)d=a[e]._getTableElement(),d.is&&d.is({td:1,th:1})?c.push(d):c=c.concat(b(d));return c}function c(a){a=b(a);var c="",d=[],e,f;for(f=0;f<a.length;f++)e&&!e.equals(a[f].getAscendant("tr"))?(c+=d.join("\t")+"\n",e=a[f].getAscendant("tr"),d=[]):0===f&&(e=a[f].getAscendant("tr")),d.push(a[f].getText());
return c+=d.join("\t")}function f(a){var b=this.root.editor,d=b.getSelection(1);this.reset();l=!0;d.root.once("selectionchange",function(a){a.cancel()},null,null,0);d.selectRanges([a[0]]);d=this._.cache;d.ranges=new CKEDITOR.dom.rangeList(a);d.type=CKEDITOR.SELECTION_TEXT;d.selectedElement=a[0]._getTableElement();d.selectedText=c(a);d.nativeSel=null;this.isFake=1;this.rev=J++;b._.fakeSelection=this;l=!1;this.root.fire("selectionchange")}function h(){var b=this._.fakeSelection,c;if(b){c=this.getSelection(1);
var e;if(!(e=!c)&&(e=!c.isHidden())){e=b;var f=c.getRanges(),g=e.getRanges(),h=f.length&&f[0]._getTableElement()&&f[0]._getTableElement().getAscendant("table",!0),p=g.length&&g[0]._getTableElement()&&g[0]._getTableElement().getAscendant("table",!0),k=1===f.length&&f[0]._getTableElement()&&f[0]._getTableElement().is("table"),w=1===g.length&&g[0]._getTableElement()&&g[0]._getTableElement().is("table");if(a(e.getSelectedElement()))e=!1;else{var l=1===f.length&&f[0].collapsed,g=d(f,!!CKEDITOR.env.webkit)&&
d(g);h=h&&p?h.equals(p)||p.contains(h):!1;h&&(l||g)?(k&&!w&&e.selectRanges(f),e=!0):e=!1}e=!e}e&&(b.reset(),b=0)}if(!b&&(b=c||this.getSelection(1),!b||b.getType()==CKEDITOR.SELECTION_NONE))return;this.fire("selectionCheck",b);c=this.elementPath();c.compare(this._.selectionPreviousPath)||(e=this._.selectionPreviousPath&&this._.selectionPreviousPath.blockLimit.equals(c.blockLimit),CKEDITOR.env.webkit&&!e&&(this._.previousActive=this.document.getActive()),this._.selectionPreviousPath=c,this.fire("selectionChange",
{selection:b,path:c}))}function k(){F=!0;t||(g.call(this),t=CKEDITOR.tools.setTimeout(g,200,this))}function g(){t=null;F&&(CKEDITOR.tools.setTimeout(h,0,this),F=!1)}function n(a){return L(a)||a.type==CKEDITOR.NODE_ELEMENT&&!a.is(CKEDITOR.dtd.$empty)?!0:!1}function r(a){function b(c,d){return c&&c.type!=CKEDITOR.NODE_TEXT?a.clone()["moveToElementEdit"+(d?"End":"Start")](c):!1}if(!(a.root instanceof CKEDITOR.editable))return!1;var c=a.startContainer,d=a.getPreviousNode(n,null,c),e=a.getNextNode(n,null,
c);return b(d)||b(e,1)||!(d||e||c.type==CKEDITOR.NODE_ELEMENT&&c.isBlockBoundary()&&c.getBogus())?!0:!1}function e(a){y(a,!1);var b=a.getDocument().createText(u);a.setCustomData("cke-fillingChar",b);return b}function y(a,b){var c=a&&a.removeCustomData("cke-fillingChar");if(c){if(!1!==b){var d=a.getDocument().getSelection().getNative(),e=d&&"None"!=d.type&&d.getRangeAt(0),f=u.length;if(c.getLength()>f&&e&&e.intersectsNode(c.$)){var g=[{node:d.anchorNode,offset:d.anchorOffset},{node:d.focusNode,offset:d.focusOffset}];
d.anchorNode==c.$&&d.anchorOffset>f&&(g[0].offset-=f);d.focusNode==c.$&&d.focusOffset>f&&(g[1].offset-=f)}}c.setText(v(c.getText(),1));g&&(c=a.getDocument().$,d=c.getSelection(),c=c.createRange(),c.setStart(g[0].node,g[0].offset),c.collapse(!0),d.removeAllRanges(),d.addRange(c),d.extend(g[1].node,g[1].offset))}}function v(a,b){return b?a.replace(K,function(a,b){return b?" ":""}):a.replace(u,"")}function B(a,b){var c=b&&CKEDITOR.tools.htmlEncode(b)||"\x26nbsp;",c=CKEDITOR.dom.element.createFromHtml('\x3cdiv data-cke-hidden-sel\x3d"1" data-cke-temp\x3d"1" style\x3d"'+
(CKEDITOR.env.ie&&14>CKEDITOR.env.version?"display:none":"position:fixed;top:0;left:-1000px")+'"\x3e'+c+"\x3c/div\x3e",a.document);a.fire("lockSnapshot");a.editable().append(c);var d=a.getSelection(1),e=a.createRange(),f=d.root.on("selectionchange",function(a){a.cancel()},null,null,0);e.setStartAt(c,CKEDITOR.POSITION_AFTER_START);e.setEndAt(c,CKEDITOR.POSITION_BEFORE_END);d.selectRanges([e]);f.removeListener();a.fire("unlockSnapshot");a._.hiddenSelectionContainer=c}function D(a){var b={37:1,39:1,
8:1,46:1};return function(c){var d=c.data.getKeystroke();if(b[d]){var e=a.getSelection().getRanges(),f=e[0];1==e.length&&f.collapsed&&(d=f[38>d?"getPreviousEditableNode":"getNextEditableNode"]())&&d.type==CKEDITOR.NODE_ELEMENT&&"false"==d.getAttribute("contenteditable")&&(a.getSelection().fake(d),c.data.preventDefault(),c.cancel())}}}function x(a){for(var b=0;b<a.length;b++){var c=a[b];c.getCommonAncestor().isReadOnly()&&a.splice(b,1);if(!c.collapsed){if(c.startContainer.isReadOnly())for(var d=c.startContainer,
e;d&&!((e=d.type==CKEDITOR.NODE_ELEMENT)&&d.is("body")||!d.isReadOnly());)e&&"false"==d.getAttribute("contentEditable")&&c.setStartAfter(d),d=d.getParent();d=c.startContainer;e=c.endContainer;var f=c.startOffset,g=c.endOffset,h=c.clone();d&&d.type==CKEDITOR.NODE_TEXT&&(f>=d.getLength()?h.setStartAfter(d):h.setStartBefore(d));e&&e.type==CKEDITOR.NODE_TEXT&&(g?h.setEndAfter(e):h.setEndBefore(e));d=new CKEDITOR.dom.walker(h);d.evaluator=function(d){if(d.type==CKEDITOR.NODE_ELEMENT&&d.isReadOnly()){var e=
c.clone();c.setEndBefore(d);c.collapsed&&a.splice(b--,1);d.getPosition(h.endContainer)&CKEDITOR.POSITION_CONTAINS||(e.setStartAfter(d),e.collapsed||a.splice(b+1,0,e));return!0}return!1};d.next()}}return a}var m="function"!=typeof window.getSelection,J=1,u=CKEDITOR.tools.repeat("​",7),K=new RegExp(u+"( )?","g"),l,t,F,L=CKEDITOR.dom.walker.invisible(1),C=function(){function a(b){return function(a){var c=a.editor.createRange();c.moveToClosestEditablePosition(a.selected,b)&&a.editor.getSelection().selectRanges([c]);
return!1}}function b(a){return function(b){var c=b.editor,d=c.createRange(),e;if(!c.readOnly)return(e=d.moveToClosestEditablePosition(b.selected,a))||(e=d.moveToClosestEditablePosition(b.selected,!a)),e&&c.getSelection().selectRanges([d]),c.fire("saveSnapshot"),b.selected.remove(),e||(d.moveToElementEditablePosition(c.editable()),c.getSelection().selectRanges([d])),c.fire("saveSnapshot"),!1}}var c=a(),d=a(1);return{37:c,38:c,39:d,40:d,8:b(),46:b(1)}}();CKEDITOR.on("instanceCreated",function(a){function b(){var a=
c.getSelection();a&&a.removeAllRanges()}var c=a.editor;c.on("contentDom",function(){function a(){r=new CKEDITOR.dom.selection(c.getSelection());r.lock()}function b(){f.removeListener("mouseup",b);q.removeListener("mouseup",b);var a=CKEDITOR.document.$.selection,c=a.createRange();"None"!=a.type&&c.parentElement()&&c.parentElement().ownerDocument==e.$&&c.select()}function d(a){a=a.getRanges()[0];return a?(a=a.startContainer.getAscendant(function(a){return a.type==CKEDITOR.NODE_ELEMENT&&a.hasAttribute("contenteditable")},
!0))&&"false"===a.getAttribute("contenteditable")?a:null:null}var e=c.document,f=CKEDITOR.document,g=c.editable(),l=e.getBody(),q=e.getDocumentElement(),E=g.isInline(),n,r;CKEDITOR.env.gecko&&g.attachListener(g,"focus",function(a){a.removeListener();0!==n&&(a=c.getSelection().getNative())&&a.isCollapsed&&a.anchorNode==g.$&&(a=c.createRange(),a.moveToElementEditStart(g),a.select())},null,null,-2);g.attachListener(g,CKEDITOR.env.webkit?"DOMFocusIn":"focus",function(){n&&CKEDITOR.env.webkit&&(n=c._.previousActive&&
c._.previousActive.equals(e.getActive()))&&null!=c._.previousScrollTop&&c._.previousScrollTop!=g.$.scrollTop&&(g.$.scrollTop=c._.previousScrollTop);c.unlockSelection(n);n=0},null,null,-1);g.attachListener(g,"mousedown",function(){n=0});if(CKEDITOR.env.ie||E)m?g.attachListener(g,"beforedeactivate",a,null,null,-1):g.attachListener(c,"selectionCheck",a,null,null,-1),g.attachListener(g,CKEDITOR.env.webkit?"DOMFocusOut":"blur",function(){c.lockSelection(r);n=1},null,null,-1),g.attachListener(g,"mousedown",
function(){n=0});if(CKEDITOR.env.ie&&!E){var v;g.attachListener(g,"mousedown",function(a){2==a.data.$.button&&((a=c.document.getSelection())&&a.getType()!=CKEDITOR.SELECTION_NONE||(v=c.window.getScrollPosition()))});g.attachListener(g,"mouseup",function(a){2==a.data.$.button&&v&&(c.document.$.documentElement.scrollLeft=v.x,c.document.$.documentElement.scrollTop=v.y);v=null});if("BackCompat"!=e.$.compatMode){if(CKEDITOR.env.ie7Compat||CKEDITOR.env.ie6Compat){var t,u;q.on("mousedown",function(a){function b(a){a=
a.data.$;if(t){var c=l.$.createTextRange();try{c.moveToPoint(a.clientX,a.clientY)}catch(d){}t.setEndPoint(0>u.compareEndPoints("StartToStart",c)?"EndToEnd":"StartToStart",c);t.select()}}function c(){q.removeListener("mousemove",b);f.removeListener("mouseup",c);q.removeListener("mouseup",c);t.select()}a=a.data;if(a.getTarget().is("html")&&a.$.y<q.$.clientHeight&&a.$.x<q.$.clientWidth){t=l.$.createTextRange();try{t.moveToPoint(a.$.clientX,a.$.clientY)}catch(d){}u=t.duplicate();q.on("mousemove",b);f.on("mouseup",
c);q.on("mouseup",c)}})}if(7<CKEDITOR.env.version&&11>CKEDITOR.env.version)q.on("mousedown",function(a){a.data.getTarget().is("html")&&(f.on("mouseup",b),q.on("mouseup",b))})}}g.attachListener(g,"selectionchange",h,c);g.attachListener(g,"keyup",k,c);CKEDITOR.env.ie&&g.attachListener(g,"keydown",function(a){var b=this.getSelection(1),c=d(b);c&&!c.equals(g)&&(b.selectElement(c),a.data.preventDefault())},c);g.attachListener(g,CKEDITOR.env.webkit?"DOMFocusIn":"focus",function(){c.forceNextSelectionCheck();
c.selectionChange(1)});if(E&&(CKEDITOR.env.webkit||CKEDITOR.env.gecko)){var x;g.attachListener(g,"mousedown",function(){x=1});g.attachListener(e.getDocumentElement(),"mouseup",function(){x&&k.call(c);x=0})}else g.attachListener(CKEDITOR.env.ie?g:e.getDocumentElement(),"mouseup",k,c);CKEDITOR.env.webkit&&g.attachListener(e,"keydown",function(a){switch(a.data.getKey()){case 13:case 33:case 34:case 35:case 36:case 37:case 39:case 8:case 45:case 46:g.hasFocus&&y(g)}},null,null,-1);g.attachListener(g,
"keydown",D(c),null,null,-1)});c.on("setData",function(){c.unlockSelection();CKEDITOR.env.webkit&&b()});c.on("contentDomUnload",function(){c.unlockSelection()});if(CKEDITOR.env.ie9Compat)c.on("beforeDestroy",b,null,null,9);c.on("dataReady",function(){delete c._.fakeSelection;delete c._.hiddenSelectionContainer;c.selectionChange(1)});c.on("loadSnapshot",function(){var a=CKEDITOR.dom.walker.nodeType(CKEDITOR.NODE_ELEMENT),b=c.editable().getLast(a);b&&b.hasAttribute("data-cke-hidden-sel")&&(b.remove(),
CKEDITOR.env.gecko&&(a=c.editable().getFirst(a))&&a.is("br")&&a.getAttribute("_moz_editor_bogus_node")&&a.remove())},null,null,100);c.on("key",function(a){if("wysiwyg"==c.mode){var b=c.getSelection();if(b.isFake){var d=C[a.data.keyCode];if(d)return d({editor:c,selected:b.getSelectedElement(),selection:b,keyEvent:a})}}})});if(CKEDITOR.env.webkit)CKEDITOR.on("instanceReady",function(a){var b=a.editor;b.on("selectionChange",function(){var a=b.editable(),c=a.getCustomData("cke-fillingChar");c&&(c.getCustomData("ready")?
(y(a),a.editor.fire("selectionCheck")):c.setCustomData("ready",1))},null,null,-1);b.on("beforeSetMode",function(){y(b.editable())},null,null,-1);b.on("getSnapshot",function(a){a.data&&(a.data=v(a.data))},b,null,20);b.on("toDataFormat",function(a){a.data.dataValue=v(a.data.dataValue)},null,null,0)});CKEDITOR.editor.prototype.selectionChange=function(a){(a?h:k).call(this)};CKEDITOR.editor.prototype.getSelection=function(a){return!this._.savedSelection&&!this._.fakeSelection||a?(a=this.editable())&&
"wysiwyg"==this.mode?new CKEDITOR.dom.selection(a):null:this._.savedSelection||this._.fakeSelection};CKEDITOR.editor.prototype.lockSelection=function(a){a=a||this.getSelection(1);return a.getType()!=CKEDITOR.SELECTION_NONE?(!a.isLocked&&a.lock(),this._.savedSelection=a,!0):!1};CKEDITOR.editor.prototype.unlockSelection=function(a){var b=this._.savedSelection;return b?(b.unlock(a),delete this._.savedSelection,!0):!1};CKEDITOR.editor.prototype.forceNextSelectionCheck=function(){delete this._.selectionPreviousPath};
CKEDITOR.dom.document.prototype.getSelection=function(){return new CKEDITOR.dom.selection(this)};CKEDITOR.dom.range.prototype.select=function(){var a=this.root instanceof CKEDITOR.editable?this.root.editor.getSelection():new CKEDITOR.dom.selection(this.root);a.selectRanges([this]);return a};CKEDITOR.SELECTION_NONE=1;CKEDITOR.SELECTION_TEXT=2;CKEDITOR.SELECTION_ELEMENT=3;CKEDITOR.dom.selection=function(a){if(a instanceof CKEDITOR.dom.selection){var b=a;a=a.root}var c=a instanceof CKEDITOR.dom.element;
this.rev=b?b.rev:J++;this.document=a instanceof CKEDITOR.dom.document?a:a.getDocument();this.root=c?a:this.document.getBody();this.isLocked=0;this._={cache:{}};if(b)return CKEDITOR.tools.extend(this._.cache,b._.cache),this.isFake=b.isFake,this.isLocked=b.isLocked,this;a=this.getNative();var d,e;if(a)if(a.getRangeAt)d=(e=a.rangeCount&&a.getRangeAt(0))&&new CKEDITOR.dom.node(e.commonAncestorContainer);else{try{e=a.createRange()}catch(f){}d=e&&CKEDITOR.dom.element.get(e.item&&e.item(0)||e.parentElement())}if(!d||
d.type!=CKEDITOR.NODE_ELEMENT&&d.type!=CKEDITOR.NODE_TEXT||!this.root.equals(d)&&!this.root.contains(d))this._.cache.type=CKEDITOR.SELECTION_NONE,this._.cache.startElement=null,this._.cache.selectedElement=null,this._.cache.selectedText="",this._.cache.ranges=new CKEDITOR.dom.rangeList;return this};var M={img:1,hr:1,li:1,table:1,tr:1,td:1,th:1,embed:1,object:1,ol:1,ul:1,a:1,input:1,form:1,select:1,textarea:1,button:1,fieldset:1,thead:1,tfoot:1};CKEDITOR.tools.extend(CKEDITOR.dom.selection,{_removeFillingCharSequenceString:v,
_createFillingCharSequenceNode:e,FILLING_CHAR_SEQUENCE:u});CKEDITOR.dom.selection.prototype={getNative:function(){return void 0!==this._.cache.nativeSel?this._.cache.nativeSel:this._.cache.nativeSel=m?this.document.$.selection:this.document.getWindow().$.getSelection()},getType:m?function(){var a=this._.cache;if(a.type)return a.type;var b=CKEDITOR.SELECTION_NONE;try{var c=this.getNative(),d=c.type;"Text"==d&&(b=CKEDITOR.SELECTION_TEXT);"Control"==d&&(b=CKEDITOR.SELECTION_ELEMENT);c.createRange().parentElement()&&
(b=CKEDITOR.SELECTION_TEXT)}catch(e){}return a.type=b}:function(){var a=this._.cache;if(a.type)return a.type;var b=CKEDITOR.SELECTION_TEXT,c=this.getNative();if(!c||!c.rangeCount)b=CKEDITOR.SELECTION_NONE;else if(1==c.rangeCount){var c=c.getRangeAt(0),d=c.startContainer;d==c.endContainer&&1==d.nodeType&&1==c.endOffset-c.startOffset&&M[d.childNodes[c.startOffset].nodeName.toLowerCase()]&&(b=CKEDITOR.SELECTION_ELEMENT)}return a.type=b},getRanges:function(){var a=m?function(){function a(b){return(new CKEDITOR.dom.node(b)).getIndex()}
var b=function(b,c){b=b.duplicate();b.collapse(c);var d=b.parentElement();if(!d.hasChildNodes())return{container:d,offset:0};for(var e=d.children,f,g,h=b.duplicate(),k=0,l=e.length-1,q=-1,m,n;k<=l;)if(q=Math.floor((k+l)/2),f=e[q],h.moveToElementText(f),m=h.compareEndPoints("StartToStart",b),0<m)l=q-1;else if(0>m)k=q+1;else return{container:d,offset:a(f)};if(-1==q||q==e.length-1&&0>m){h.moveToElementText(d);h.setEndPoint("StartToStart",b);h=h.text.replace(/(\r\n|\r)/g,"\n").length;e=d.childNodes;if(!h)return f=
e[e.length-1],f.nodeType!=CKEDITOR.NODE_TEXT?{container:d,offset:e.length}:{container:f,offset:f.nodeValue.length};for(d=e.length;0<h&&0<d;)g=e[--d],g.nodeType==CKEDITOR.NODE_TEXT&&(n=g,h-=g.nodeValue.length);return{container:n,offset:-h}}h.collapse(0<m?!0:!1);h.setEndPoint(0<m?"StartToStart":"EndToStart",b);h=h.text.replace(/(\r\n|\r)/g,"\n").length;if(!h)return{container:d,offset:a(f)+(0<m?0:1)};for(;0<h;)try{g=f[0<m?"previousSibling":"nextSibling"],g.nodeType==CKEDITOR.NODE_TEXT&&(h-=g.nodeValue.length,
n=g),f=g}catch(r){return{container:d,offset:a(f)}}return{container:n,offset:0<m?-h:n.nodeValue.length+h}};return function(){var a=this.getNative(),c=a&&a.createRange(),d=this.getType();if(!a)return[];if(d==CKEDITOR.SELECTION_TEXT)return a=new CKEDITOR.dom.range(this.root),d=b(c,!0),a.setStart(new CKEDITOR.dom.node(d.container),d.offset),d=b(c),a.setEnd(new CKEDITOR.dom.node(d.container),d.offset),a.endContainer.getPosition(a.startContainer)&CKEDITOR.POSITION_PRECEDING&&a.endOffset<=a.startContainer.getIndex()&&
a.collapse(),[a];if(d==CKEDITOR.SELECTION_ELEMENT){for(var d=[],e=0;e<c.length;e++){for(var f=c.item(e),g=f.parentNode,h=0,a=new CKEDITOR.dom.range(this.root);h<g.childNodes.length&&g.childNodes[h]!=f;h++);a.setStart(new CKEDITOR.dom.node(g),h);a.setEnd(new CKEDITOR.dom.node(g),h+1);d.push(a)}return d}return[]}}():function(){var a=[],b,c=this.getNative();if(!c)return a;for(var d=0;d<c.rangeCount;d++){var e=c.getRangeAt(d);b=new CKEDITOR.dom.range(this.root);b.setStart(new CKEDITOR.dom.node(e.startContainer),
e.startOffset);b.setEnd(new CKEDITOR.dom.node(e.endContainer),e.endOffset);a.push(b)}return a};return function(b){var c=this._.cache,d=c.ranges;d||(c.ranges=d=new CKEDITOR.dom.rangeList(a.call(this)));return b?x(new CKEDITOR.dom.rangeList(d.slice())):d}}(),getStartElement:function(){var a=this._.cache;if(void 0!==a.startElement)return a.startElement;var b;switch(this.getType()){case CKEDITOR.SELECTION_ELEMENT:return this.getSelectedElement();case CKEDITOR.SELECTION_TEXT:var c=this.getRanges()[0];
if(c){if(c.collapsed)b=c.startContainer,b.type!=CKEDITOR.NODE_ELEMENT&&(b=b.getParent());else{for(c.optimize();b=c.startContainer,c.startOffset==(b.getChildCount?b.getChildCount():b.getLength())&&!b.isBlockBoundary();)c.setStartAfter(b);b=c.startContainer;if(b.type!=CKEDITOR.NODE_ELEMENT)return b.getParent();if((b=b.getChild(c.startOffset))&&b.type==CKEDITOR.NODE_ELEMENT)for(c=b.getFirst();c&&c.type==CKEDITOR.NODE_ELEMENT;)b=c,c=c.getFirst();else b=c.startContainer}b=b.$}}return a.startElement=b?
new CKEDITOR.dom.element(b):null},getSelectedElement:function(){var a=this._.cache;if(void 0!==a.selectedElement)return a.selectedElement;var b=this,c=CKEDITOR.tools.tryThese(function(){return b.getNative().createRange().item(0)},function(){for(var a=b.getRanges()[0].clone(),c,d,e=2;e&&!((c=a.getEnclosedNode())&&c.type==CKEDITOR.NODE_ELEMENT&&M[c.getName()]&&(d=c));e--)a.shrink(CKEDITOR.SHRINK_ELEMENT);return d&&d.$});return a.selectedElement=c?new CKEDITOR.dom.element(c):null},getSelectedText:function(){var a=
this._.cache;if(void 0!==a.selectedText)return a.selectedText;var b=this.getNative(),b=m?"Control"==b.type?"":b.createRange().text:b.toString();return a.selectedText=b},lock:function(){this.getRanges();this.getStartElement();this.getSelectedElement();this.getSelectedText();this._.cache.nativeSel=null;this.isLocked=1},unlock:function(a){if(this.isLocked){if(a)var b=this.getSelectedElement(),c=this.getRanges(),e=this.isFake;this.isLocked=0;this.reset();a&&(a=b||c[0]&&c[0].getCommonAncestor())&&a.getAscendant("body",
1)&&(d(c)?f.call(this,c):e?this.fake(b):b?this.selectElement(b):this.selectRanges(c))}},reset:function(){this._.cache={};this.isFake=0;var a=this.root.editor;if(a&&a._.fakeSelection)if(this.rev==a._.fakeSelection.rev){delete a._.fakeSelection;var b=a._.hiddenSelectionContainer;if(b){var c=a.checkDirty();a.fire("lockSnapshot");b.remove();a.fire("unlockSnapshot");!c&&a.resetDirty()}delete a._.hiddenSelectionContainer}else CKEDITOR.warn("selection-fake-reset");this.rev=J++},selectElement:function(a){var b=
new CKEDITOR.dom.range(this.root);b.setStartBefore(a);b.setEndAfter(a);this.selectRanges([b])},selectRanges:function(a){var b=this.root.editor,c=b&&b._.hiddenSelectionContainer;this.reset();if(c)for(var c=this.root,g,h=0;h<a.length;++h)g=a[h],g.endContainer.equals(c)&&(g.endOffset=Math.min(g.endOffset,c.getChildCount()));if(a.length)if(this.isLocked){var k=CKEDITOR.document.getActive();this.unlock();this.selectRanges(a);this.lock();k&&!k.equals(this.root)&&k.focus()}else{var p;a:{var n,w;if(1==a.length&&
!(w=a[0]).collapsed&&(p=w.getEnclosedNode())&&p.type==CKEDITOR.NODE_ELEMENT&&(w=w.clone(),w.shrink(CKEDITOR.SHRINK_ELEMENT,!0),(n=w.getEnclosedNode())&&n.type==CKEDITOR.NODE_ELEMENT&&(p=n),"false"==p.getAttribute("contenteditable")))break a;p=void 0}if(p)this.fake(p);else if(b&&b.plugins.tableselection&&CKEDITOR.plugins.tableselection.isSupportedEnvironment&&d(a)&&!l)f.call(this,a);else{if(m){n=CKEDITOR.dom.walker.whitespaces(!0);p=/\ufeff|\u00a0/;w={table:1,tbody:1,tr:1};1<a.length&&(b=a[a.length-
1],a[0].setEnd(b.endContainer,b.endOffset));b=a[0];a=b.collapsed;var A,G,I;if((c=b.getEnclosedNode())&&c.type==CKEDITOR.NODE_ELEMENT&&c.getName()in M&&(!c.is("a")||!c.getText()))try{I=c.$.createControlRange();I.addElement(c.$);I.select();return}catch(v){}if(b.startContainer.type==CKEDITOR.NODE_ELEMENT&&b.startContainer.getName()in w||b.endContainer.type==CKEDITOR.NODE_ELEMENT&&b.endContainer.getName()in w)b.shrink(CKEDITOR.NODE_ELEMENT,!0),a=b.collapsed;I=b.createBookmark();w=I.startNode;a||(k=I.endNode);
I=b.document.$.body.createTextRange();I.moveToElementText(w.$);I.moveStart("character",1);k?(p=b.document.$.body.createTextRange(),p.moveToElementText(k.$),I.setEndPoint("EndToEnd",p),I.moveEnd("character",-1)):(A=w.getNext(n),G=w.hasAscendant("pre"),A=!(A&&A.getText&&A.getText().match(p))&&(G||!w.hasPrevious()||w.getPrevious().is&&w.getPrevious().is("br")),G=b.document.createElement("span"),G.setHtml("\x26#65279;"),G.insertBefore(w),A&&b.document.createText("﻿").insertBefore(w));b.setStartBefore(w);
w.remove();a?(A?(I.moveStart("character",-1),I.select(),b.document.$.selection.clear()):I.select(),b.moveToPosition(G,CKEDITOR.POSITION_BEFORE_START),G.remove()):(b.setEndBefore(k),k.remove(),I.select())}else{k=this.getNative();if(!k)return;this.removeAllRanges();for(I=0;I<a.length;I++){if(I<a.length-1&&(A=a[I],G=a[I+1],p=A.clone(),p.setStart(A.endContainer,A.endOffset),p.setEnd(G.startContainer,G.startOffset),!p.collapsed&&(p.shrink(CKEDITOR.NODE_ELEMENT,!0),b=p.getCommonAncestor(),p=p.getEnclosedNode(),
b.isReadOnly()||p&&p.isReadOnly()))){G.setStart(A.startContainer,A.startOffset);a.splice(I--,1);continue}b=a[I];G=this.document.$.createRange();b.collapsed&&CKEDITOR.env.webkit&&r(b)&&(p=e(this.root),b.insertNode(p),(A=p.getNext())&&!p.getPrevious()&&A.type==CKEDITOR.NODE_ELEMENT&&"br"==A.getName()?(y(this.root),b.moveToPosition(A,CKEDITOR.POSITION_BEFORE_START)):b.moveToPosition(p,CKEDITOR.POSITION_AFTER_END));G.setStart(b.startContainer.$,b.startOffset);try{G.setEnd(b.endContainer.$,b.endOffset)}catch(t){if(0<=
t.toString().indexOf("NS_ERROR_ILLEGAL_VALUE"))b.collapse(1),G.setEnd(b.endContainer.$,b.endOffset);else throw t;}k.addRange(G)}}this.reset();this.root.fire("selectionchange")}}},fake:function(a,b){var c=this.root.editor;void 0===b&&a.hasAttribute("aria-label")&&(b=a.getAttribute("aria-label"));this.reset();B(c,b);var d=this._.cache,e=new CKEDITOR.dom.range(this.root);e.setStartBefore(a);e.setEndAfter(a);d.ranges=new CKEDITOR.dom.rangeList(e);d.selectedElement=d.startElement=a;d.type=CKEDITOR.SELECTION_ELEMENT;
d.selectedText=d.nativeSel=null;this.isFake=1;this.rev=J++;c._.fakeSelection=this;this.root.fire("selectionchange")},isHidden:function(){var a=this.getCommonAncestor();a&&a.type==CKEDITOR.NODE_TEXT&&(a=a.getParent());return!(!a||!a.data("cke-hidden-sel"))},isInTable:function(a){return d(this.getRanges(),a)},isCollapsed:function(){var a=this.getRanges();return 1===a.length&&a[0].collapsed},createBookmarks:function(a){a=this.getRanges().createBookmarks(a);this.isFake&&(a.isFake=1);return a},createBookmarks2:function(a){a=
this.getRanges().createBookmarks2(a);this.isFake&&(a.isFake=1);return a},selectBookmarks:function(a){for(var b=[],c,e=0;e<a.length;e++){var f=new CKEDITOR.dom.range(this.root);f.moveToBookmark(a[e]);b.push(f)}a.isFake&&(c=d(b)?b[0]._getTableElement():b[0].getEnclosedNode(),c&&c.type==CKEDITOR.NODE_ELEMENT||(CKEDITOR.warn("selection-not-fake"),a.isFake=0));a.isFake&&!d(b)?this.fake(c):this.selectRanges(b);return this},getCommonAncestor:function(){var a=this.getRanges();return a.length?a[0].startContainer.getCommonAncestor(a[a.length-
1].endContainer):null},scrollIntoView:function(){this.type!=CKEDITOR.SELECTION_NONE&&this.getRanges()[0].scrollIntoView()},removeAllRanges:function(){if(this.getType()!=CKEDITOR.SELECTION_NONE){var a=this.getNative();try{a&&a[m?"empty":"removeAllRanges"]()}catch(b){}this.reset()}}}})();"use strict";CKEDITOR.STYLE_BLOCK=1;CKEDITOR.STYLE_INLINE=2;CKEDITOR.STYLE_OBJECT=3;
(function(){function a(a,b){for(var c,d;(a=a.getParent())&&!a.equals(b);)if(a.getAttribute("data-nostyle"))c=a;else if(!d){var e=a.getAttribute("contentEditable");"false"==e?c=a:"true"==e&&(d=1)}return c}function d(a,b,c,d){return(a.getPosition(b)|d)==d&&(!c.childRule||c.childRule(a))}function b(c){var e=c.document;if(c.collapsed)e=J(this,e),c.insertNode(e),c.moveToPosition(e,CKEDITOR.POSITION_BEFORE_END);else{var g=this.element,h=this._.definition,k,l=h.ignoreReadonly,m=l||h.includeReadonly;null==
m&&(m=c.root.getCustomData("cke_includeReadonly"));var n=CKEDITOR.dtd[g];n||(k=!0,n=CKEDITOR.dtd.span);c.enlarge(CKEDITOR.ENLARGE_INLINE,1);c.trim();var r=c.createBookmark(),v=r.startNode,t=r.endNode,q=v,u;if(!l){var x=c.getCommonAncestor(),l=a(v,x),x=a(t,x);l&&(q=l.getNextSourceNode(!0));x&&(t=x)}for(q.getPosition(t)==CKEDITOR.POSITION_FOLLOWING&&(q=0);q;){l=!1;if(q.equals(t))q=null,l=!0;else{var y=q.type==CKEDITOR.NODE_ELEMENT?q.getName():null,x=y&&"false"==q.getAttribute("contentEditable"),B=y&&
q.getAttribute("data-nostyle");if(y&&q.data("cke-bookmark")){q=q.getNextSourceNode(!0);continue}if(x&&m&&CKEDITOR.dtd.$block[y])for(var C=q,E=f(C),F=void 0,H=E.length,K=0,C=H&&new CKEDITOR.dom.range(C.getDocument());K<H;++K){var F=E[K],L=CKEDITOR.filter.instances[F.data("cke-filter")];if(L?L.check(this):1)C.selectNodeContents(F),b.call(this,C)}E=y?!n[y]||B?0:x&&!m?0:d(q,t,h,P):1;if(E)if(F=q.getParent(),E=h,H=g,K=k,!F||!(F.getDtd()||CKEDITOR.dtd.span)[H]&&!K||E.parentRule&&!E.parentRule(F))l=!0;else{if(u||
y&&CKEDITOR.dtd.$removeEmpty[y]&&(q.getPosition(t)|P)!=P||(u=c.clone(),u.setStartBefore(q)),y=q.type,y==CKEDITOR.NODE_TEXT||x||y==CKEDITOR.NODE_ELEMENT&&!q.getChildCount()){for(var y=q,M;(l=!y.getNext(z))&&(M=y.getParent(),n[M.getName()])&&d(M,v,h,O);)y=M;u.setEndAfter(y)}}else l=!0;q=q.getNextSourceNode(B||x)}if(l&&u&&!u.collapsed){for(var l=J(this,e),x=l.hasAttributes(),B=u.getCommonAncestor(),y={},E={},F={},H={},U,R,aa;l&&B;){if(B.getName()==g){for(U in h.attributes)!H[U]&&(aa=B.getAttribute(R))&&
(l.getAttribute(U)==aa?E[U]=1:H[U]=1);for(R in h.styles)!F[R]&&(aa=B.getStyle(R))&&(l.getStyle(R)==aa?y[R]=1:F[R]=1)}B=B.getParent()}for(U in E)l.removeAttribute(U);for(R in y)l.removeStyle(R);x&&!l.hasAttributes()&&(l=null);l?(u.extractContents().appendTo(l),u.insertNode(l),D.call(this,l),l.mergeSiblings(),CKEDITOR.env.ie||l.$.normalize()):(l=new CKEDITOR.dom.element("span"),u.extractContents().appendTo(l),u.insertNode(l),D.call(this,l),l.remove(!0));u=null}}c.moveToBookmark(r);c.shrink(CKEDITOR.SHRINK_TEXT);
c.shrink(CKEDITOR.NODE_ELEMENT,!0)}}function c(a){function b(){for(var a=new CKEDITOR.dom.elementPath(d.getParent()),c=new CKEDITOR.dom.elementPath(n.getParent()),e=null,f=null,g=0;g<a.elements.length;g++){var h=a.elements[g];if(h==a.block||h==a.blockLimit)break;r.checkElementRemovable(h,!0)&&(e=h)}for(g=0;g<c.elements.length;g++){h=c.elements[g];if(h==c.block||h==c.blockLimit)break;r.checkElementRemovable(h,!0)&&(f=h)}f&&n.breakParent(f);e&&d.breakParent(e)}a.enlarge(CKEDITOR.ENLARGE_INLINE,1);var c=
a.createBookmark(),d=c.startNode,e=this._.definition.alwaysRemoveElement;if(a.collapsed){for(var f=new CKEDITOR.dom.elementPath(d.getParent(),a.root),g,h=0,k;h<f.elements.length&&(k=f.elements[h])&&k!=f.block&&k!=f.blockLimit;h++)if(this.checkElementRemovable(k)){var m;!e&&a.collapsed&&(a.checkBoundaryOfElement(k,CKEDITOR.END)||(m=a.checkBoundaryOfElement(k,CKEDITOR.START)))?(g=k,g.match=m?"start":"end"):(k.mergeSiblings(),k.is(this.element)?B.call(this,k):x(k,l(this)[k.getName()]))}if(g){e=d;for(h=
0;;h++){k=f.elements[h];if(k.equals(g))break;else if(k.match)continue;else k=k.clone();k.append(e);e=k}e["start"==g.match?"insertBefore":"insertAfter"](g)}}else{var n=c.endNode,r=this;b();for(f=d;!f.equals(n);)g=f.getNextSourceNode(),f.type==CKEDITOR.NODE_ELEMENT&&this.checkElementRemovable(f)&&(f.getName()==this.element?B.call(this,f):x(f,l(this)[f.getName()]),g.type==CKEDITOR.NODE_ELEMENT&&g.contains(d)&&(b(),g=d.getNext())),f=g}a.moveToBookmark(c);a.shrink(CKEDITOR.NODE_ELEMENT,!0)}function f(a){var b=
[];a.forEach(function(a){if("true"==a.getAttribute("contenteditable"))return b.push(a),!1},CKEDITOR.NODE_ELEMENT,!0);return b}function h(a){var b=a.getEnclosedNode()||a.getCommonAncestor(!1,!0);(a=(new CKEDITOR.dom.elementPath(b,a.root)).contains(this.element,1))&&!a.isReadOnly()&&u(a,this)}function k(a){var b=a.getCommonAncestor(!0,!0);if(a=(new CKEDITOR.dom.elementPath(b,a.root)).contains(this.element,1)){var b=this._.definition,c=b.attributes;if(c)for(var d in c)a.removeAttribute(d,c[d]);if(b.styles)for(var e in b.styles)b.styles.hasOwnProperty(e)&&
a.removeStyle(e)}}function g(a){var b=a.createBookmark(!0),c=a.createIterator();c.enforceRealBlocks=!0;this._.enterMode&&(c.enlargeBr=this._.enterMode!=CKEDITOR.ENTER_BR);for(var d,e=a.document,f;d=c.getNextParagraph();)!d.isReadOnly()&&(c.activeFilter?c.activeFilter.check(this):1)&&(f=J(this,e,d),r(d,f));a.moveToBookmark(b)}function n(a){var b=a.createBookmark(1),c=a.createIterator();c.enforceRealBlocks=!0;c.enlargeBr=this._.enterMode!=CKEDITOR.ENTER_BR;for(var d,e;d=c.getNextParagraph();)this.checkElementRemovable(d)&&
(d.is("pre")?((e=this._.enterMode==CKEDITOR.ENTER_BR?null:a.document.createElement(this._.enterMode==CKEDITOR.ENTER_P?"p":"div"))&&d.copyAttributes(e),r(d,e)):B.call(this,d));a.moveToBookmark(b)}function r(a,b){var c=!b;c&&(b=a.getDocument().createElement("div"),a.copyAttributes(b));var d=b&&b.is("pre"),f=a.is("pre"),g=!d&&f;if(d&&!f){f=b;(g=a.getBogus())&&g.remove();g=a.getHtml();g=y(g,/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g,"");g=g.replace(/[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi,"$1");g=g.replace(/([ \t\n\r]+|&nbsp;)/g,
" ");g=g.replace(/<br\b[^>]*>/gi,"\n");if(CKEDITOR.env.ie){var h=a.getDocument().createElement("div");h.append(f);f.$.outerHTML="\x3cpre\x3e"+g+"\x3c/pre\x3e";f.copyAttributes(h.getFirst());f=h.getFirst().remove()}else f.setHtml(g);b=f}else g?b=v(c?[a.getHtml()]:e(a),b):a.moveChildren(b);b.replace(a);if(d){var c=b,k;(k=c.getPrevious(H))&&k.type==CKEDITOR.NODE_ELEMENT&&k.is("pre")&&(d=y(k.getHtml(),/\n$/,"")+"\n\n"+y(c.getHtml(),/^\n/,""),CKEDITOR.env.ie?c.$.outerHTML="\x3cpre\x3e"+d+"\x3c/pre\x3e":
c.setHtml(d),k.remove())}else c&&m(b)}function e(a){var b=[];y(a.getOuterHtml(),/(\S\s*)\n(?:\s|(<span[^>]+data-cke-bookmark.*?\/span>))*\n(?!$)/gi,function(a,b,c){return b+"\x3c/pre\x3e"+c+"\x3cpre\x3e"}).replace(/<pre\b.*?>([\s\S]*?)<\/pre>/gi,function(a,c){b.push(c)});return b}function y(a,b,c){var d="",e="";a=a.replace(/(^<span[^>]+data-cke-bookmark.*?\/span>)|(<span[^>]+data-cke-bookmark.*?\/span>$)/gi,function(a,b,c){b&&(d=b);c&&(e=c);return""});return d+a.replace(b,c)+e}function v(a,b){var c;
1<a.length&&(c=new CKEDITOR.dom.documentFragment(b.getDocument()));for(var d=0;d<a.length;d++){var e=a[d],e=e.replace(/(\r\n|\r)/g,"\n"),e=y(e,/^[ \t]*\n/,""),e=y(e,/\n$/,""),e=y(e,/^[ \t]+|[ \t]+$/g,function(a,b){return 1==a.length?"\x26nbsp;":b?" "+CKEDITOR.tools.repeat("\x26nbsp;",a.length-1):CKEDITOR.tools.repeat("\x26nbsp;",a.length-1)+" "}),e=e.replace(/\n/g,"\x3cbr\x3e"),e=e.replace(/[ \t]{2,}/g,function(a){return CKEDITOR.tools.repeat("\x26nbsp;",a.length-1)+" "});if(c){var f=b.clone();f.setHtml(e);
c.append(f)}else b.setHtml(e)}return c||b}function B(a,b){var c=this._.definition,d=c.attributes,c=c.styles,e=l(this)[a.getName()],f=CKEDITOR.tools.isEmpty(d)&&CKEDITOR.tools.isEmpty(c),g;for(g in d)if("class"!=g&&!this._.definition.fullMatch||a.getAttribute(g)==t(g,d[g]))b&&"data-"==g.slice(0,5)||(f=a.hasAttribute(g),a.removeAttribute(g));for(var h in c)this._.definition.fullMatch&&a.getStyle(h)!=t(h,c[h],!0)||(f=f||!!a.getStyle(h),a.removeStyle(h));x(a,e,C[a.getName()]);f&&(this._.definition.alwaysRemoveElement?
m(a,1):!CKEDITOR.dtd.$block[a.getName()]||this._.enterMode==CKEDITOR.ENTER_BR&&!a.hasAttributes()?m(a):a.renameNode(this._.enterMode==CKEDITOR.ENTER_P?"p":"div"))}function D(a){for(var b=l(this),c=a.getElementsByTag(this.element),d,e=c.count();0<=--e;)d=c.getItem(e),d.isReadOnly()||B.call(this,d,!0);for(var f in b)if(f!=this.element)for(c=a.getElementsByTag(f),e=c.count()-1;0<=e;e--)d=c.getItem(e),d.isReadOnly()||x(d,b[f])}function x(a,b,c){if(b=b&&b.attributes)for(var d=0;d<b.length;d++){var e=b[d][0],
f;if(f=a.getAttribute(e)){var g=b[d][1];(null===g||g.test&&g.test(f)||"string"==typeof g&&f==g)&&a.removeAttribute(e)}}c||m(a)}function m(a,b){if(!a.hasAttributes()||b)if(CKEDITOR.dtd.$block[a.getName()]){var c=a.getPrevious(H),d=a.getNext(H);!c||c.type!=CKEDITOR.NODE_TEXT&&c.isBlockBoundary({br:1})||a.append("br",1);!d||d.type!=CKEDITOR.NODE_TEXT&&d.isBlockBoundary({br:1})||a.append("br");a.remove(!0)}else c=a.getFirst(),d=a.getLast(),a.remove(!0),c&&(c.type==CKEDITOR.NODE_ELEMENT&&c.mergeSiblings(),
d&&!c.equals(d)&&d.type==CKEDITOR.NODE_ELEMENT&&d.mergeSiblings())}function J(a,b,c){var d;d=a.element;"*"==d&&(d="span");d=new CKEDITOR.dom.element(d,b);c&&c.copyAttributes(d);d=u(d,a);b.getCustomData("doc_processing_style")&&d.hasAttribute("id")?d.removeAttribute("id"):b.setCustomData("doc_processing_style",1);return d}function u(a,b){var c=b._.definition,d=c.attributes,c=CKEDITOR.style.getStyleText(c);if(d)for(var e in d)a.setAttribute(e,d[e]);c&&a.setAttribute("style",c);a.getDocument().removeCustomData("doc_processing_style");
return a}function K(a,b){for(var c in a)a[c]=a[c].replace(E,function(a,c){return b[c]})}function l(a){if(a._.overrides)return a._.overrides;var b=a._.overrides={},c=a._.definition.overrides;if(c){CKEDITOR.tools.isArray(c)||(c=[c]);for(var d=0;d<c.length;d++){var e=c[d],f,g;"string"==typeof e?f=e.toLowerCase():(f=e.element?e.element.toLowerCase():a.element,g=e.attributes);e=b[f]||(b[f]={});if(g){var e=e.attributes=e.attributes||[],h;for(h in g)e.push([h.toLowerCase(),g[h]])}}}return b}function t(a,
b,c){var d=new CKEDITOR.dom.element("span");d[c?"setStyle":"setAttribute"](a,b);return d[c?"getStyle":"getAttribute"](a)}function F(a,b){function c(a,b){return"font-family"==b.toLowerCase()?a.replace(/["']/g,""):a}"string"==typeof a&&(a=CKEDITOR.tools.parseCssText(a));"string"==typeof b&&(b=CKEDITOR.tools.parseCssText(b,!0));for(var d in a)if(!(d in b)||c(b[d],d)!=c(a[d],d)&&"inherit"!=a[d]&&"inherit"!=b[d])return!1;return!0}function L(a,b,c){var d=a.getRanges();b=b?this.removeFromRange:this.applyToRange;
var e,f;if(a.isFake&&a.isInTable())for(e=[],f=0;f<d.length;f++)e.push(d[f].clone());for(var g=d.createIterator();f=g.getNextRange();)b.call(this,f,c);a.selectRanges(e||d)}var C={address:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,section:1,header:1,footer:1,nav:1,article:1,aside:1,figure:1,dialog:1,hgroup:1,time:1,meter:1,menu:1,command:1,keygen:1,output:1,progress:1,details:1,datagrid:1,datalist:1},M={a:1,blockquote:1,embed:1,hr:1,img:1,li:1,object:1,ol:1,table:1,td:1,tr:1,th:1,ul:1,dl:1,dt:1,
dd:1,form:1,audio:1,video:1},q=/\s*(?:;\s*|$)/,E=/#\((.+?)\)/g,z=CKEDITOR.dom.walker.bookmark(0,1),H=CKEDITOR.dom.walker.whitespaces(1);CKEDITOR.style=function(a,b){if("string"==typeof a.type)return new CKEDITOR.style.customHandlers[a.type](a);var c=a.attributes;c&&c.style&&(a.styles=CKEDITOR.tools.extend({},a.styles,CKEDITOR.tools.parseCssText(c.style)),delete c.style);b&&(a=CKEDITOR.tools.clone(a),K(a.attributes,b),K(a.styles,b));c=this.element=a.element?"string"==typeof a.element?a.element.toLowerCase():
a.element:"*";this.type=a.type||(C[c]?CKEDITOR.STYLE_BLOCK:M[c]?CKEDITOR.STYLE_OBJECT:CKEDITOR.STYLE_INLINE);"object"==typeof this.element&&(this.type=CKEDITOR.STYLE_OBJECT);this._={definition:a}};CKEDITOR.style.prototype={apply:function(a){if(a instanceof CKEDITOR.dom.document)return L.call(this,a.getSelection());if(this.checkApplicable(a.elementPath(),a)){var b=this._.enterMode;b||(this._.enterMode=a.activeEnterMode);L.call(this,a.getSelection(),0,a);this._.enterMode=b}},remove:function(a){if(a instanceof
CKEDITOR.dom.document)return L.call(this,a.getSelection(),1);if(this.checkApplicable(a.elementPath(),a)){var b=this._.enterMode;b||(this._.enterMode=a.activeEnterMode);L.call(this,a.getSelection(),1,a);this._.enterMode=b}},applyToRange:function(a){this.applyToRange=this.type==CKEDITOR.STYLE_INLINE?b:this.type==CKEDITOR.STYLE_BLOCK?g:this.type==CKEDITOR.STYLE_OBJECT?h:null;return this.applyToRange(a)},removeFromRange:function(a){this.removeFromRange=this.type==CKEDITOR.STYLE_INLINE?c:this.type==CKEDITOR.STYLE_BLOCK?
n:this.type==CKEDITOR.STYLE_OBJECT?k:null;return this.removeFromRange(a)},applyToObject:function(a){u(a,this)},checkActive:function(a,b){switch(this.type){case CKEDITOR.STYLE_BLOCK:return this.checkElementRemovable(a.block||a.blockLimit,!0,b);case CKEDITOR.STYLE_OBJECT:case CKEDITOR.STYLE_INLINE:for(var c=a.elements,d=0,e;d<c.length;d++)if(e=c[d],this.type!=CKEDITOR.STYLE_INLINE||e!=a.block&&e!=a.blockLimit){if(this.type==CKEDITOR.STYLE_OBJECT){var f=e.getName();if(!("string"==typeof this.element?
f==this.element:f in this.element))continue}if(this.checkElementRemovable(e,!0,b))return!0}}return!1},checkApplicable:function(a,b,c){b&&b instanceof CKEDITOR.filter&&(c=b);if(c&&!c.check(this))return!1;switch(this.type){case CKEDITOR.STYLE_OBJECT:return!!a.contains(this.element);case CKEDITOR.STYLE_BLOCK:return!!a.blockLimit.getDtd()[this.element]}return!0},checkElementMatch:function(a,b){var c=this._.definition;if(!a||!c.ignoreReadonly&&a.isReadOnly())return!1;var d=a.getName();if("string"==typeof this.element?
d==this.element:d in this.element){if(!b&&!a.hasAttributes())return!0;if(d=c._AC)c=d;else{var d={},e=0,f=c.attributes;if(f)for(var g in f)e++,d[g]=f[g];if(g=CKEDITOR.style.getStyleText(c))d.style||e++,d.style=g;d._length=e;c=c._AC=d}if(c._length){for(var h in c)if("_length"!=h)if(d=a.getAttribute(h)||"","style"==h?F(c[h],d):c[h]==d){if(!b)return!0}else if(b)return!1;if(b)return!0}else return!0}return!1},checkElementRemovable:function(a,b,c){if(this.checkElementMatch(a,b,c))return!0;if(b=l(this)[a.getName()]){var d;
if(!(b=b.attributes))return!0;for(c=0;c<b.length;c++)if(d=b[c][0],d=a.getAttribute(d)){var e=b[c][1];if(null===e)return!0;if("string"==typeof e){if(d==e)return!0}else if(e.test(d))return!0}}return!1},buildPreview:function(a){var b=this._.definition,c=[],d=b.element;"bdo"==d&&(d="span");var c=["\x3c",d],e=b.attributes;if(e)for(var f in e)c.push(" ",f,'\x3d"',e[f],'"');(e=CKEDITOR.style.getStyleText(b))&&c.push(' style\x3d"',e,'"');c.push("\x3e",a||b.name,"\x3c/",d,"\x3e");return c.join("")},getDefinition:function(){return this._.definition}};
CKEDITOR.style.getStyleText=function(a){var b=a._ST;if(b)return b;var b=a.styles,c=a.attributes&&a.attributes.style||"",d="";c.length&&(c=c.replace(q,";"));for(var e in b){var f=b[e],g=(e+":"+f).replace(q,";");"inherit"==f?d+=g:c+=g}c.length&&(c=CKEDITOR.tools.normalizeCssText(c,!0));return a._ST=c+d};CKEDITOR.style.customHandlers={};CKEDITOR.style.addCustomHandler=function(a){var b=function(a){this._={definition:a};this.setup&&this.setup(a)};b.prototype=CKEDITOR.tools.extend(CKEDITOR.tools.prototypedCopy(CKEDITOR.style.prototype),
{assignedTo:CKEDITOR.STYLE_OBJECT},a,!0);return this.customHandlers[a.type]=b};var P=CKEDITOR.POSITION_PRECEDING|CKEDITOR.POSITION_IDENTICAL|CKEDITOR.POSITION_IS_CONTAINED,O=CKEDITOR.POSITION_FOLLOWING|CKEDITOR.POSITION_IDENTICAL|CKEDITOR.POSITION_IS_CONTAINED})();CKEDITOR.styleCommand=function(a,d){this.requiredContent=this.allowedContent=this.style=a;CKEDITOR.tools.extend(this,d,!0)};
CKEDITOR.styleCommand.prototype.exec=function(a){a.focus();this.state==CKEDITOR.TRISTATE_OFF?a.applyStyle(this.style):this.state==CKEDITOR.TRISTATE_ON&&a.removeStyle(this.style)};CKEDITOR.stylesSet=new CKEDITOR.resourceManager("","stylesSet");CKEDITOR.addStylesSet=CKEDITOR.tools.bind(CKEDITOR.stylesSet.add,CKEDITOR.stylesSet);CKEDITOR.loadStylesSet=function(a,d,b){CKEDITOR.stylesSet.addExternal(a,d,"");CKEDITOR.stylesSet.load(a,b)};
CKEDITOR.tools.extend(CKEDITOR.editor.prototype,{attachStyleStateChange:function(a,d){var b=this._.styleStateChangeCallbacks;b||(b=this._.styleStateChangeCallbacks=[],this.on("selectionChange",function(a){for(var d=0;d<b.length;d++){var h=b[d],k=h.style.checkActive(a.data.path,this)?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF;h.fn.call(this,k)}}));b.push({style:a,fn:d})},applyStyle:function(a){a.apply(this)},removeStyle:function(a){a.remove(this)},getStylesSet:function(a){if(this._.stylesDefinitions)a(this._.stylesDefinitions);
else{var d=this,b=d.config.stylesCombo_stylesSet||d.config.stylesSet;if(!1===b)a(null);else if(b instanceof Array)d._.stylesDefinitions=b,a(b);else{b||(b="default");var b=b.split(":"),c=b[0];CKEDITOR.stylesSet.addExternal(c,b[1]?b.slice(1).join(":"):CKEDITOR.getUrl("styles.js"),"");CKEDITOR.stylesSet.load(c,function(b){d._.stylesDefinitions=b[c];a(d._.stylesDefinitions)})}}}});
CKEDITOR.dom.comment=function(a,d){"string"==typeof a&&(a=(d?d.$:document).createComment(a));CKEDITOR.dom.domObject.call(this,a)};CKEDITOR.dom.comment.prototype=new CKEDITOR.dom.node;CKEDITOR.tools.extend(CKEDITOR.dom.comment.prototype,{type:CKEDITOR.NODE_COMMENT,getOuterHtml:function(){return"\x3c!--"+this.$.nodeValue+"--\x3e"}});"use strict";
(function(){var a={},d={},b;for(b in CKEDITOR.dtd.$blockLimit)b in CKEDITOR.dtd.$list||(a[b]=1);for(b in CKEDITOR.dtd.$block)b in CKEDITOR.dtd.$blockLimit||b in CKEDITOR.dtd.$empty||(d[b]=1);CKEDITOR.dom.elementPath=function(b,f){var h=null,k=null,g=[],n=b,r;f=f||b.getDocument().getBody();n||(n=f);do if(n.type==CKEDITOR.NODE_ELEMENT){g.push(n);if(!this.lastElement&&(this.lastElement=n,n.is(CKEDITOR.dtd.$object)||"false"==n.getAttribute("contenteditable")))continue;if(n.equals(f))break;if(!k&&(r=n.getName(),
"true"==n.getAttribute("contenteditable")?k=n:!h&&d[r]&&(h=n),a[r])){if(r=!h&&"div"==r){a:{r=n.getChildren();for(var e=0,y=r.count();e<y;e++){var v=r.getItem(e);if(v.type==CKEDITOR.NODE_ELEMENT&&CKEDITOR.dtd.$block[v.getName()]){r=!0;break a}}r=!1}r=!r}r?h=n:k=n}}while(n=n.getParent());k||(k=f);this.block=h;this.blockLimit=k;this.root=f;this.elements=g}})();
CKEDITOR.dom.elementPath.prototype={compare:function(a){var d=this.elements;a=a&&a.elements;if(!a||d.length!=a.length)return!1;for(var b=0;b<d.length;b++)if(!d[b].equals(a[b]))return!1;return!0},contains:function(a,d,b){var c=0,f;"string"==typeof a&&(f=function(b){return b.getName()==a});a instanceof CKEDITOR.dom.element?f=function(b){return b.equals(a)}:CKEDITOR.tools.isArray(a)?f=function(b){return-1<CKEDITOR.tools.indexOf(a,b.getName())}:"function"==typeof a?f=a:"object"==typeof a&&(f=function(b){return b.getName()in
a});var h=this.elements,k=h.length;d&&(b?c+=1:--k);b&&(h=Array.prototype.slice.call(h,0),h.reverse());for(;c<k;c++)if(f(h[c]))return h[c];return null},isContextFor:function(a){var d;return a in CKEDITOR.dtd.$block?(d=this.contains(CKEDITOR.dtd.$intermediate)||this.root.equals(this.block)&&this.block||this.blockLimit,!!d.getDtd()[a]):!0},direction:function(){return(this.block||this.blockLimit||this.root).getDirection(1)}};
CKEDITOR.dom.text=function(a,d){"string"==typeof a&&(a=(d?d.$:document).createTextNode(a));this.$=a};CKEDITOR.dom.text.prototype=new CKEDITOR.dom.node;
CKEDITOR.tools.extend(CKEDITOR.dom.text.prototype,{type:CKEDITOR.NODE_TEXT,getLength:function(){return this.$.nodeValue.length},getText:function(){return this.$.nodeValue},setText:function(a){this.$.nodeValue=a},split:function(a){var d=this.$.parentNode,b=d.childNodes.length,c=this.getLength(),f=this.getDocument(),h=new CKEDITOR.dom.text(this.$.splitText(a),f);d.childNodes.length==b&&(a>=c?(h=f.createText(""),h.insertAfter(this)):(a=f.createText(""),a.insertAfter(h),a.remove()));return h},substring:function(a,
d){return"number"!=typeof d?this.$.nodeValue.substr(a):this.$.nodeValue.substring(a,d)}});
(function(){function a(a,c,d){var h=a.serializable,k=c[d?"endContainer":"startContainer"],g=d?"endOffset":"startOffset",n=h?c.document.getById(a.startNode):a.startNode;a=h?c.document.getById(a.endNode):a.endNode;k.equals(n.getPrevious())?(c.startOffset=c.startOffset-k.getLength()-a.getPrevious().getLength(),k=a.getNext()):k.equals(a.getPrevious())&&(c.startOffset-=k.getLength(),k=a.getNext());k.equals(n.getParent())&&c[g]++;k.equals(a.getParent())&&c[g]++;c[d?"endContainer":"startContainer"]=k;return c}
CKEDITOR.dom.rangeList=function(a){if(a instanceof CKEDITOR.dom.rangeList)return a;a?a instanceof CKEDITOR.dom.range&&(a=[a]):a=[];return CKEDITOR.tools.extend(a,d)};var d={createIterator:function(){var a=this,c=CKEDITOR.dom.walker.bookmark(),d=[],h;return{getNextRange:function(k){h=void 0===h?0:h+1;var g=a[h];if(g&&1<a.length){if(!h)for(var n=a.length-1;0<=n;n--)d.unshift(a[n].createBookmark(!0));if(k)for(var r=0;a[h+r+1];){var e=g.document;k=0;n=e.getById(d[r].endNode);for(e=e.getById(d[r+1].startNode);;){n=
n.getNextSourceNode(!1);if(e.equals(n))k=1;else if(c(n)||n.type==CKEDITOR.NODE_ELEMENT&&n.isBlockBoundary())continue;break}if(!k)break;r++}for(g.moveToBookmark(d.shift());r--;)n=a[++h],n.moveToBookmark(d.shift()),g.setEnd(n.endContainer,n.endOffset)}return g}}},createBookmarks:function(b){for(var c=[],d,h=0;h<this.length;h++){c.push(d=this[h].createBookmark(b,!0));for(var k=h+1;k<this.length;k++)this[k]=a(d,this[k]),this[k]=a(d,this[k],!0)}return c},createBookmarks2:function(a){for(var c=[],d=0;d<
this.length;d++)c.push(this[d].createBookmark2(a));return c},moveToBookmarks:function(a){for(var c=0;c<this.length;c++)this[c].moveToBookmark(a[c])}}})();
(function(){function a(){return CKEDITOR.getUrl(CKEDITOR.skinName.split(",")[1]||"skins/"+CKEDITOR.skinName.split(",")[0]+"/")}function d(b){var c=CKEDITOR.skin["ua_"+b],d=CKEDITOR.env;if(c)for(var c=c.split(",").sort(function(a,b){return a>b?-1:1}),f=0,g;f<c.length;f++)if(g=c[f],d.ie&&(g.replace(/^ie/,"")==d.version||d.quirks&&"iequirks"==g)&&(g="ie"),d[g]){b+="_"+c[f];break}return CKEDITOR.getUrl(a()+b+".css")}function b(a,b){h[a]||(CKEDITOR.document.appendStyleSheet(d(a)),h[a]=1);b&&b()}function c(a){var b=
a.getById(k);b||(b=a.getHead().append("style"),b.setAttribute("id",k),b.setAttribute("type","text/css"));return b}function f(a,b,c){var d,f,g;if(CKEDITOR.env.webkit)for(b=b.split("}").slice(0,-1),f=0;f<b.length;f++)b[f]=b[f].split("{");for(var h=0;h<a.length;h++)if(CKEDITOR.env.webkit)for(f=0;f<b.length;f++){g=b[f][1];for(d=0;d<c.length;d++)g=g.replace(c[d][0],c[d][1]);a[h].$.sheet.addRule(b[f][0],g)}else{g=b;for(d=0;d<c.length;d++)g=g.replace(c[d][0],c[d][1]);CKEDITOR.env.ie&&11>CKEDITOR.env.version?
a[h].$.styleSheet.cssText+=g:a[h].$.innerHTML+=g}}var h={};CKEDITOR.skin={path:a,loadPart:function(c,d){CKEDITOR.skin.name!=CKEDITOR.skinName.split(",")[0]?CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(a()+"skin.js"),function(){b(c,d)}):b(c,d)},getPath:function(a){return CKEDITOR.getUrl(d(a))},icons:{},addIcon:function(a,b,c,d){a=a.toLowerCase();this.icons[a]||(this.icons[a]={path:b,offset:c||0,bgsize:d||"16px"})},getIconStyle:function(a,b,c,d,f){var g;a&&(a=a.toLowerCase(),b&&(g=this.icons[a+"-rtl"]),
g||(g=this.icons[a]));a=c||g&&g.path||"";d=d||g&&g.offset;f=f||g&&g.bgsize||"16px";a&&(a=a.replace(/'/g,"\\'"));return a&&"background-image:url('"+CKEDITOR.getUrl(a)+"');background-position:0 "+d+"px;background-size:"+f+";"}};CKEDITOR.tools.extend(CKEDITOR.editor.prototype,{getUiColor:function(){return this.uiColor},setUiColor:function(a){var b=c(CKEDITOR.document);return(this.setUiColor=function(a){this.uiColor=a;var c=CKEDITOR.skin.chameleon,d="",h="";"function"==typeof c&&(d=c(this,"editor"),h=
c(this,"panel"));a=[[n,a]];f([b],d,a);f(g,h,a)}).call(this,a)}});var k="cke_ui_color",g=[],n=/\$color/g;CKEDITOR.on("instanceLoaded",function(a){if(!CKEDITOR.env.ie||!CKEDITOR.env.quirks){var b=a.editor;a=function(a){a=(a.data[0]||a.data).element.getElementsByTag("iframe").getItem(0).getFrameDocument();if(!a.getById("cke_ui_color")){a=c(a);g.push(a);var d=b.getUiColor();d&&f([a],CKEDITOR.skin.chameleon(b,"panel"),[[n,d]])}};b.on("panelShow",a);b.on("menuShow",a);b.config.uiColor&&b.setUiColor(b.config.uiColor)}})})();
(function(){if(CKEDITOR.env.webkit)CKEDITOR.env.hc=!1;else{var a=CKEDITOR.dom.element.createFromHtml('\x3cdiv style\x3d"width:0;height:0;position:absolute;left:-10000px;border:1px solid;border-color:red blue"\x3e\x3c/div\x3e',CKEDITOR.document);a.appendTo(CKEDITOR.document.getHead());try{var d=a.getComputedStyle("border-top-color"),b=a.getComputedStyle("border-right-color");CKEDITOR.env.hc=!(!d||d!=b)}catch(c){CKEDITOR.env.hc=!1}a.remove()}CKEDITOR.env.hc&&(CKEDITOR.env.cssClass+=" cke_hc");CKEDITOR.document.appendStyleText(".cke{visibility:hidden;}");
CKEDITOR.status="loaded";CKEDITOR.fireOnce("loaded");if(a=CKEDITOR._.pending)for(delete CKEDITOR._.pending,d=0;d<a.length;d++)CKEDITOR.editor.prototype.constructor.apply(a[d][0],a[d][1]),CKEDITOR.add(a[d][0])})();/*
 Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
 For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.skin.name="moono-lisa";CKEDITOR.skin.ua_editor="ie,iequirks,ie8,gecko";CKEDITOR.skin.ua_dialog="ie,iequirks,ie8";
CKEDITOR.skin.chameleon=function(){var b=function(){return function(b,d){for(var a=b.match(/[^#]./g),e=0;3>e;e++){var f=e,c;c=parseInt(a[e],16);c=("0"+(0>d?0|c*(1+d):0|c+(255-c)*d).toString(16)).slice(-2);a[f]=c}return"#"+a.join("")}}(),f={editor:new CKEDITOR.template("{id}.cke_chrome [border-color:{defaultBorder};] {id} .cke_top [ background-color:{defaultBackground};border-bottom-color:{defaultBorder};] {id} .cke_bottom [background-color:{defaultBackground};border-top-color:{defaultBorder};] {id} .cke_resizer [border-right-color:{ckeResizer}] {id} .cke_dialog_title [background-color:{defaultBackground};border-bottom-color:{defaultBorder};] {id} .cke_dialog_footer [background-color:{defaultBackground};outline-color:{defaultBorder};] {id} .cke_dialog_tab [background-color:{dialogTab};border-color:{defaultBorder};] {id} .cke_dialog_tab:hover [background-color:{lightBackground};] {id} .cke_dialog_contents [border-top-color:{defaultBorder};] {id} .cke_dialog_tab_selected, {id} .cke_dialog_tab_selected:hover [background:{dialogTabSelected};border-bottom-color:{dialogTabSelectedBorder};] {id} .cke_dialog_body [background:{dialogBody};border-color:{defaultBorder};] {id} a.cke_button_off:hover,{id} a.cke_button_off:focus,{id} a.cke_button_off:active [background-color:{darkBackground};border-color:{toolbarElementsBorder};] {id} .cke_button_on [background-color:{ckeButtonOn};border-color:{toolbarElementsBorder};] {id} .cke_toolbar_separator,{id} .cke_toolgroup a.cke_button:last-child:after,{id} .cke_toolgroup a.cke_button.cke_button_disabled:hover:last-child:after [background-color: {toolbarElementsBorder};border-color: {toolbarElementsBorder};] {id} a.cke_combo_button:hover,{id} a.cke_combo_button:focus,{id} .cke_combo_on a.cke_combo_button [border-color:{toolbarElementsBorder};background-color:{darkBackground};] {id} .cke_combo:after [border-color:{toolbarElementsBorder};] {id} .cke_path_item [color:{elementsPathColor};] {id} a.cke_path_item:hover,{id} a.cke_path_item:focus,{id} a.cke_path_item:active [background-color:{darkBackground};] {id}.cke_panel [border-color:{defaultBorder};] "),panel:new CKEDITOR.template(".cke_panel_grouptitle [background-color:{lightBackground};border-color:{defaultBorder};] .cke_menubutton_icon [background-color:{menubuttonIcon};] .cke_menubutton:hover,.cke_menubutton:focus,.cke_menubutton:active [background-color:{menubuttonHover};] .cke_menubutton:hover .cke_menubutton_icon, .cke_menubutton:focus .cke_menubutton_icon, .cke_menubutton:active .cke_menubutton_icon [background-color:{menubuttonIconHover};] .cke_menubutton_disabled:hover .cke_menubutton_icon,.cke_menubutton_disabled:focus .cke_menubutton_icon,.cke_menubutton_disabled:active .cke_menubutton_icon [background-color:{menubuttonIcon};] .cke_menuseparator [background-color:{menubuttonIcon};] a:hover.cke_colorbox, a:active.cke_colorbox [border-color:{defaultBorder};] a:hover.cke_colorauto, a:hover.cke_colormore, a:active.cke_colorauto, a:active.cke_colormore [background-color:{ckeColorauto};border-color:{defaultBorder};] ")};
return function(g,d){var a=b(g.uiColor,.4),a={id:"."+g.id,defaultBorder:b(a,-.2),toolbarElementsBorder:b(a,-.25),defaultBackground:a,lightBackground:b(a,.8),darkBackground:b(a,-.15),ckeButtonOn:b(a,.4),ckeResizer:b(a,-.4),ckeColorauto:b(a,.8),dialogBody:b(a,.7),dialogTab:b(a,.65),dialogTabSelected:"#FFF",dialogTabSelectedBorder:"#FFF",elementsPathColor:b(a,-.6),menubuttonHover:b(a,.1),menubuttonIcon:b(a,.5),menubuttonIconHover:b(a,.3)};return f[d].output(a).replace(/\[/g,"{").replace(/\]/g,"}")}}();CKEDITOR.plugins.add("dialogui",{onLoad:function(){var h=function(b){this._||(this._={});this._["default"]=this._.initValue=b["default"]||"";this._.required=b.required||!1;for(var a=[this._],d=1;d<arguments.length;d++)a.push(arguments[d]);a.push(!0);CKEDITOR.tools.extend.apply(CKEDITOR.tools,a);return this._},v={build:function(b,a,d){return new CKEDITOR.ui.dialog.textInput(b,a,d)}},n={build:function(b,a,d){return new CKEDITOR.ui.dialog[a.type](b,a,d)}},q={isChanged:function(){return this.getValue()!=
this.getInitValue()},reset:function(b){this.setValue(this.getInitValue(),b)},setInitValue:function(){this._.initValue=this.getValue()},resetInitValue:function(){this._.initValue=this._["default"]},getInitValue:function(){return this._.initValue}},r=CKEDITOR.tools.extend({},CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors,{onChange:function(b,a){this._.domOnChangeRegistered||(b.on("load",function(){this.getInputElement().on("change",function(){b.parts.dialog.isVisible()&&this.fire("change",{value:this.getValue()})},
this)},this),this._.domOnChangeRegistered=!0);this.on("change",a)}},!0),x=/^on([A-Z]\w+)/,t=function(b){for(var a in b)(x.test(a)||"title"==a||"type"==a)&&delete b[a];return b},w=function(b){b=b.data.getKeystroke();b==CKEDITOR.SHIFT+CKEDITOR.ALT+36?this.setDirectionMarker("ltr"):b==CKEDITOR.SHIFT+CKEDITOR.ALT+35&&this.setDirectionMarker("rtl")};CKEDITOR.tools.extend(CKEDITOR.ui.dialog,{labeledElement:function(b,a,d,f){if(!(4>arguments.length)){var c=h.call(this,a);c.labelId=CKEDITOR.tools.getNextId()+
"_label";this._.children=[];var e={role:a.role||"presentation"};a.includeLabel&&(e["aria-labelledby"]=c.labelId);CKEDITOR.ui.dialog.uiElement.call(this,b,a,d,"div",null,e,function(){var e=[],g=a.required?" cke_required":"";"horizontal"!=a.labelLayout?e.push('\x3clabel class\x3d"cke_dialog_ui_labeled_label'+g+'" ',' id\x3d"'+c.labelId+'"',c.inputId?' for\x3d"'+c.inputId+'"':"",(a.labelStyle?' style\x3d"'+a.labelStyle+'"':"")+"\x3e",a.label,"\x3c/label\x3e",'\x3cdiv class\x3d"cke_dialog_ui_labeled_content"',
a.controlStyle?' style\x3d"'+a.controlStyle+'"':"",' role\x3d"presentation"\x3e',f.call(this,b,a),"\x3c/div\x3e"):(g={type:"hbox",widths:a.widths,padding:0,children:[{type:"html",html:'\x3clabel class\x3d"cke_dialog_ui_labeled_label'+g+'" id\x3d"'+c.labelId+'" for\x3d"'+c.inputId+'"'+(a.labelStyle?' style\x3d"'+a.labelStyle+'"':"")+"\x3e"+CKEDITOR.tools.htmlEncode(a.label)+"\x3c/label\x3e"},{type:"html",html:'\x3cspan class\x3d"cke_dialog_ui_labeled_content"'+(a.controlStyle?' style\x3d"'+a.controlStyle+
'"':"")+"\x3e"+f.call(this,b,a)+"\x3c/span\x3e"}]},CKEDITOR.dialog._.uiElementBuilders.hbox.build(b,g,e));return e.join("")})}},textInput:function(b,a,d){if(!(3>arguments.length)){h.call(this,a);var f=this._.inputId=CKEDITOR.tools.getNextId()+"_textInput",c={"class":"cke_dialog_ui_input_"+a.type,id:f,type:a.type};a.validate&&(this.validate=a.validate);a.maxLength&&(c.maxlength=a.maxLength);a.size&&(c.size=a.size);a.inputStyle&&(c.style=a.inputStyle);var e=this,m=!1;b.on("load",function(){e.getInputElement().on("keydown",
function(a){13==a.data.getKeystroke()&&(m=!0)});e.getInputElement().on("keyup",function(a){13==a.data.getKeystroke()&&m&&(b.getButton("ok")&&setTimeout(function(){b.getButton("ok").click()},0),m=!1);e.bidi&&w.call(e,a)},null,null,1E3)});CKEDITOR.ui.dialog.labeledElement.call(this,b,a,d,function(){var b=['\x3cdiv class\x3d"cke_dialog_ui_input_',a.type,'" role\x3d"presentation"'];a.width&&b.push('style\x3d"width:'+a.width+'" ');b.push("\x3e\x3cinput ");c["aria-labelledby"]=this._.labelId;this._.required&&
(c["aria-required"]=this._.required);for(var e in c)b.push(e+'\x3d"'+c[e]+'" ');b.push(" /\x3e\x3c/div\x3e");return b.join("")})}},textarea:function(b,a,d){if(!(3>arguments.length)){h.call(this,a);var f=this,c=this._.inputId=CKEDITOR.tools.getNextId()+"_textarea",e={};a.validate&&(this.validate=a.validate);e.rows=a.rows||5;e.cols=a.cols||20;e["class"]="cke_dialog_ui_input_textarea "+(a["class"]||"");"undefined"!=typeof a.inputStyle&&(e.style=a.inputStyle);a.dir&&(e.dir=a.dir);if(f.bidi)b.on("load",
function(){f.getInputElement().on("keyup",w)},f);CKEDITOR.ui.dialog.labeledElement.call(this,b,a,d,function(){e["aria-labelledby"]=this._.labelId;this._.required&&(e["aria-required"]=this._.required);var a=['\x3cdiv class\x3d"cke_dialog_ui_input_textarea" role\x3d"presentation"\x3e\x3ctextarea id\x3d"',c,'" '],b;for(b in e)a.push(b+'\x3d"'+CKEDITOR.tools.htmlEncode(e[b])+'" ');a.push("\x3e",CKEDITOR.tools.htmlEncode(f._["default"]),"\x3c/textarea\x3e\x3c/div\x3e");return a.join("")})}},checkbox:function(b,
a,d){if(!(3>arguments.length)){var f=h.call(this,a,{"default":!!a["default"]});a.validate&&(this.validate=a.validate);CKEDITOR.ui.dialog.uiElement.call(this,b,a,d,"span",null,null,function(){var c=CKEDITOR.tools.extend({},a,{id:a.id?a.id+"_checkbox":CKEDITOR.tools.getNextId()+"_checkbox"},!0),e=[],d=CKEDITOR.tools.getNextId()+"_label",g={"class":"cke_dialog_ui_checkbox_input",type:"checkbox","aria-labelledby":d};t(c);a["default"]&&(g.checked="checked");"undefined"!=typeof c.inputStyle&&(c.style=c.inputStyle);
f.checkbox=new CKEDITOR.ui.dialog.uiElement(b,c,e,"input",null,g);e.push(' \x3clabel id\x3d"',d,'" for\x3d"',g.id,'"'+(a.labelStyle?' style\x3d"'+a.labelStyle+'"':"")+"\x3e",CKEDITOR.tools.htmlEncode(a.label),"\x3c/label\x3e");return e.join("")})}},radio:function(b,a,d){if(!(3>arguments.length)){h.call(this,a);this._["default"]||(this._["default"]=this._.initValue=a.items[0][1]);a.validate&&(this.validate=a.validate);var f=[],c=this;a.role="radiogroup";a.includeLabel=!0;CKEDITOR.ui.dialog.labeledElement.call(this,
b,a,d,function(){for(var e=[],d=[],g=(a.id?a.id:CKEDITOR.tools.getNextId())+"_radio",k=0;k<a.items.length;k++){var l=a.items[k],h=void 0!==l[2]?l[2]:l[0],n=void 0!==l[1]?l[1]:l[0],p=CKEDITOR.tools.getNextId()+"_radio_input",q=p+"_label",p=CKEDITOR.tools.extend({},a,{id:p,title:null,type:null},!0),h=CKEDITOR.tools.extend({},p,{title:h},!0),r={type:"radio","class":"cke_dialog_ui_radio_input",name:g,value:n,"aria-labelledby":q},u=[];c._["default"]==n&&(r.checked="checked");t(p);t(h);"undefined"!=typeof p.inputStyle&&
(p.style=p.inputStyle);p.keyboardFocusable=!0;f.push(new CKEDITOR.ui.dialog.uiElement(b,p,u,"input",null,r));u.push(" ");new CKEDITOR.ui.dialog.uiElement(b,h,u,"label",null,{id:q,"for":r.id},l[0]);e.push(u.join(""))}new CKEDITOR.ui.dialog.hbox(b,f,e,d);return d.join("")});this._.children=f}},button:function(b,a,d){if(arguments.length){"function"==typeof a&&(a=a(b.getParentEditor()));h.call(this,a,{disabled:a.disabled||!1});CKEDITOR.event.implementOn(this);var f=this;b.on("load",function(){var a=this.getElement();
(function(){a.on("click",function(a){f.click();a.data.preventDefault()});a.on("keydown",function(a){a.data.getKeystroke()in{32:1}&&(f.click(),a.data.preventDefault())})})();a.unselectable()},this);var c=CKEDITOR.tools.extend({},a);delete c.style;var e=CKEDITOR.tools.getNextId()+"_label";CKEDITOR.ui.dialog.uiElement.call(this,b,c,d,"a",null,{style:a.style,href:"javascript:void(0)",title:a.label,hidefocus:"true","class":a["class"],role:"button","aria-labelledby":e},'\x3cspan id\x3d"'+e+'" class\x3d"cke_dialog_ui_button"\x3e'+
CKEDITOR.tools.htmlEncode(a.label)+"\x3c/span\x3e")}},select:function(b,a,d){if(!(3>arguments.length)){var f=h.call(this,a);a.validate&&(this.validate=a.validate);f.inputId=CKEDITOR.tools.getNextId()+"_select";CKEDITOR.ui.dialog.labeledElement.call(this,b,a,d,function(){var c=CKEDITOR.tools.extend({},a,{id:a.id?a.id+"_select":CKEDITOR.tools.getNextId()+"_select"},!0),e=[],d=[],g={id:f.inputId,"class":"cke_dialog_ui_input_select","aria-labelledby":this._.labelId};e.push('\x3cdiv class\x3d"cke_dialog_ui_input_',
a.type,'" role\x3d"presentation"');a.width&&e.push('style\x3d"width:'+a.width+'" ');e.push("\x3e");void 0!==a.size&&(g.size=a.size);void 0!==a.multiple&&(g.multiple=a.multiple);t(c);for(var k=0,l;k<a.items.length&&(l=a.items[k]);k++)d.push('\x3coption value\x3d"',CKEDITOR.tools.htmlEncode(void 0!==l[1]?l[1]:l[0]).replace(/"/g,"\x26quot;"),'" /\x3e ',CKEDITOR.tools.htmlEncode(l[0]));"undefined"!=typeof c.inputStyle&&(c.style=c.inputStyle);f.select=new CKEDITOR.ui.dialog.uiElement(b,c,e,"select",null,
g,d.join(""));e.push("\x3c/div\x3e");return e.join("")})}},file:function(b,a,d){if(!(3>arguments.length)){void 0===a["default"]&&(a["default"]="");var f=CKEDITOR.tools.extend(h.call(this,a),{definition:a,buttons:[]});a.validate&&(this.validate=a.validate);b.on("load",function(){CKEDITOR.document.getById(f.frameId).getParent().addClass("cke_dialog_ui_input_file")});CKEDITOR.ui.dialog.labeledElement.call(this,b,a,d,function(){f.frameId=CKEDITOR.tools.getNextId()+"_fileInput";var b=['\x3ciframe frameborder\x3d"0" allowtransparency\x3d"0" class\x3d"cke_dialog_ui_input_file" role\x3d"presentation" id\x3d"',
f.frameId,'" title\x3d"',a.label,'" src\x3d"javascript:void('];b.push(CKEDITOR.env.ie?"(function(){"+encodeURIComponent("document.open();("+CKEDITOR.tools.fixDomain+")();document.close();")+"})()":"0");b.push(')"\x3e\x3c/iframe\x3e');return b.join("")})}},fileButton:function(b,a,d){var f=this;if(!(3>arguments.length)){h.call(this,a);a.validate&&(this.validate=a.validate);var c=CKEDITOR.tools.extend({},a),e=c.onClick;c.className=(c.className?c.className+" ":"")+"cke_dialog_ui_button";c.onClick=function(c){var d=
a["for"];c=e?e.call(this,c):!1;!1!==c&&("xhr"!==c&&b.getContentElement(d[0],d[1]).submit(),this.disable())};b.on("load",function(){b.getContentElement(a["for"][0],a["for"][1])._.buttons.push(f)});CKEDITOR.ui.dialog.button.call(this,b,c,d)}},html:function(){var b=/^\s*<[\w:]+\s+([^>]*)?>/,a=/^(\s*<[\w:]+(?:\s+[^>]*)?)((?:.|\r|\n)+)$/,d=/\/$/;return function(f,c,e){if(!(3>arguments.length)){var m=[],g=c.html;"\x3c"!=g.charAt(0)&&(g="\x3cspan\x3e"+g+"\x3c/span\x3e");var k=c.focus;if(k){var l=this.focus;
this.focus=function(){("function"==typeof k?k:l).call(this);this.fire("focus")};c.isFocusable&&(this.isFocusable=this.isFocusable);this.keyboardFocusable=!0}CKEDITOR.ui.dialog.uiElement.call(this,f,c,m,"span",null,null,"");m=m.join("").match(b);g=g.match(a)||["","",""];d.test(g[1])&&(g[1]=g[1].slice(0,-1),g[2]="/"+g[2]);e.push([g[1]," ",m[1]||"",g[2]].join(""))}}}(),fieldset:function(b,a,d,f,c){var e=c.label;this._={children:a};CKEDITOR.ui.dialog.uiElement.call(this,b,c,f,"fieldset",null,null,function(){var a=
[];e&&a.push("\x3clegend"+(c.labelStyle?' style\x3d"'+c.labelStyle+'"':"")+"\x3e"+e+"\x3c/legend\x3e");for(var b=0;b<d.length;b++)a.push(d[b]);return a.join("")})}},!0);CKEDITOR.ui.dialog.html.prototype=new CKEDITOR.ui.dialog.uiElement;CKEDITOR.ui.dialog.labeledElement.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.uiElement,{setLabel:function(b){var a=CKEDITOR.document.getById(this._.labelId);1>a.getChildCount()?(new CKEDITOR.dom.text(b,CKEDITOR.document)).appendTo(a):a.getChild(0).$.nodeValue=
b;return this},getLabel:function(){var b=CKEDITOR.document.getById(this._.labelId);return!b||1>b.getChildCount()?"":b.getChild(0).getText()},eventProcessors:r},!0);CKEDITOR.ui.dialog.button.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.uiElement,{click:function(){return this._.disabled?!1:this.fire("click",{dialog:this._.dialog})},enable:function(){this._.disabled=!1;var b=this.getElement();b&&b.removeClass("cke_disabled")},disable:function(){this._.disabled=!0;this.getElement().addClass("cke_disabled")},
isVisible:function(){return this.getElement().getFirst().isVisible()},isEnabled:function(){return!this._.disabled},eventProcessors:CKEDITOR.tools.extend({},CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors,{onClick:function(b,a){this.on("click",function(){a.apply(this,arguments)})}},!0),accessKeyUp:function(){this.click()},accessKeyDown:function(){this.focus()},keyboardFocusable:!0},!0);CKEDITOR.ui.dialog.textInput.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.labeledElement,{getInputElement:function(){return CKEDITOR.document.getById(this._.inputId)},
focus:function(){var b=this.selectParentTab();setTimeout(function(){var a=b.getInputElement();a&&a.$.focus()},0)},select:function(){var b=this.selectParentTab();setTimeout(function(){var a=b.getInputElement();a&&(a.$.focus(),a.$.select())},0)},accessKeyUp:function(){this.select()},setValue:function(b){if(this.bidi){var a=b&&b.charAt(0);(a="‪"==a?"ltr":"‫"==a?"rtl":null)&&(b=b.slice(1));this.setDirectionMarker(a)}b||(b="");return CKEDITOR.ui.dialog.uiElement.prototype.setValue.apply(this,arguments)},
getValue:function(){var b=CKEDITOR.ui.dialog.uiElement.prototype.getValue.call(this);if(this.bidi&&b){var a=this.getDirectionMarker();a&&(b=("ltr"==a?"‪":"‫")+b)}return b},setDirectionMarker:function(b){var a=this.getInputElement();b?a.setAttributes({dir:b,"data-cke-dir-marker":b}):this.getDirectionMarker()&&a.removeAttributes(["dir","data-cke-dir-marker"])},getDirectionMarker:function(){return this.getInputElement().data("cke-dir-marker")},keyboardFocusable:!0},q,!0);CKEDITOR.ui.dialog.textarea.prototype=
new CKEDITOR.ui.dialog.textInput;CKEDITOR.ui.dialog.select.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.labeledElement,{getInputElement:function(){return this._.select.getElement()},add:function(b,a,d){var f=new CKEDITOR.dom.element("option",this.getDialog().getParentEditor().document),c=this.getInputElement().$;f.$.text=b;f.$.value=void 0===a||null===a?b:a;void 0===d||null===d?CKEDITOR.env.ie?c.add(f.$):c.add(f.$,null):c.add(f.$,d);return this},remove:function(b){this.getInputElement().$.remove(b);
return this},clear:function(){for(var b=this.getInputElement().$;0<b.length;)b.remove(0);return this},keyboardFocusable:!0},q,!0);CKEDITOR.ui.dialog.checkbox.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.uiElement,{getInputElement:function(){return this._.checkbox.getElement()},setValue:function(b,a){this.getInputElement().$.checked=b;!a&&this.fire("change",{value:b})},getValue:function(){return this.getInputElement().$.checked},accessKeyUp:function(){this.setValue(!this.getValue())},eventProcessors:{onChange:function(b,
a){if(!CKEDITOR.env.ie||8<CKEDITOR.env.version)return r.onChange.apply(this,arguments);b.on("load",function(){var a=this._.checkbox.getElement();a.on("propertychange",function(b){b=b.data.$;"checked"==b.propertyName&&this.fire("change",{value:a.$.checked})},this)},this);this.on("change",a);return null}},keyboardFocusable:!0},q,!0);CKEDITOR.ui.dialog.radio.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.uiElement,{setValue:function(b,a){for(var d=this._.children,f,c=0;c<d.length&&(f=d[c]);c++)f.getElement().$.checked=
f.getValue()==b;!a&&this.fire("change",{value:b})},getValue:function(){for(var b=this._.children,a=0;a<b.length;a++)if(b[a].getElement().$.checked)return b[a].getValue();return null},accessKeyUp:function(){var b=this._.children,a;for(a=0;a<b.length;a++)if(b[a].getElement().$.checked){b[a].getElement().focus();return}b[0].getElement().focus()},eventProcessors:{onChange:function(b,a){if(!CKEDITOR.env.ie||8<CKEDITOR.env.version)return r.onChange.apply(this,arguments);b.on("load",function(){for(var a=
this._.children,b=this,c=0;c<a.length;c++)a[c].getElement().on("propertychange",function(a){a=a.data.$;"checked"==a.propertyName&&this.$.checked&&b.fire("change",{value:this.getAttribute("value")})})},this);this.on("change",a);return null}}},q,!0);CKEDITOR.ui.dialog.file.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.labeledElement,q,{getInputElement:function(){var b=CKEDITOR.document.getById(this._.frameId).getFrameDocument();return 0<b.$.forms.length?new CKEDITOR.dom.element(b.$.forms[0].elements[0]):
this.getElement()},submit:function(){this.getInputElement().getParent().$.submit();return this},getAction:function(){return this.getInputElement().getParent().$.action},registerEvents:function(b){var a=/^on([A-Z]\w+)/,d,f=function(a,b,c,d){a.on("formLoaded",function(){a.getInputElement().on(c,d,a)})},c;for(c in b)if(d=c.match(a))this.eventProcessors[c]?this.eventProcessors[c].call(this,this._.dialog,b[c]):f(this,this._.dialog,d[1].toLowerCase(),b[c]);return this},reset:function(){function b(){d.$.open();
var b="";f.size&&(b=f.size-(CKEDITOR.env.ie?7:0));var h=a.frameId+"_input";d.$.write(['\x3chtml dir\x3d"'+g+'" lang\x3d"'+k+'"\x3e\x3chead\x3e\x3ctitle\x3e\x3c/title\x3e\x3c/head\x3e\x3cbody style\x3d"margin: 0; overflow: hidden; background: transparent;"\x3e','\x3cform enctype\x3d"multipart/form-data" method\x3d"POST" dir\x3d"'+g+'" lang\x3d"'+k+'" action\x3d"',CKEDITOR.tools.htmlEncode(f.action),'"\x3e\x3clabel id\x3d"',a.labelId,'" for\x3d"',h,'" style\x3d"display:none"\x3e',CKEDITOR.tools.htmlEncode(f.label),
'\x3c/label\x3e\x3cinput style\x3d"width:100%" id\x3d"',h,'" aria-labelledby\x3d"',a.labelId,'" type\x3d"file" name\x3d"',CKEDITOR.tools.htmlEncode(f.id||"cke_upload"),'" size\x3d"',CKEDITOR.tools.htmlEncode(0<b?b:""),'" /\x3e\x3c/form\x3e\x3c/body\x3e\x3c/html\x3e\x3cscript\x3e',CKEDITOR.env.ie?"("+CKEDITOR.tools.fixDomain+")();":"","window.parent.CKEDITOR.tools.callFunction("+e+");","window.onbeforeunload \x3d function() {window.parent.CKEDITOR.tools.callFunction("+m+")}","\x3c/script\x3e"].join(""));
d.$.close();for(b=0;b<c.length;b++)c[b].enable()}var a=this._,d=CKEDITOR.document.getById(a.frameId).getFrameDocument(),f=a.definition,c=a.buttons,e=this.formLoadedNumber,m=this.formUnloadNumber,g=a.dialog._.editor.lang.dir,k=a.dialog._.editor.langCode;e||(e=this.formLoadedNumber=CKEDITOR.tools.addFunction(function(){this.fire("formLoaded")},this),m=this.formUnloadNumber=CKEDITOR.tools.addFunction(function(){this.getInputElement().clearCustomData()},this),this.getDialog()._.editor.on("destroy",function(){CKEDITOR.tools.removeFunction(e);
CKEDITOR.tools.removeFunction(m)}));CKEDITOR.env.gecko?setTimeout(b,500):b()},getValue:function(){return this.getInputElement().$.value||""},setInitValue:function(){this._.initValue=""},eventProcessors:{onChange:function(b,a){this._.domOnChangeRegistered||(this.on("formLoaded",function(){this.getInputElement().on("change",function(){this.fire("change",{value:this.getValue()})},this)},this),this._.domOnChangeRegistered=!0);this.on("change",a)}},keyboardFocusable:!0},!0);CKEDITOR.ui.dialog.fileButton.prototype=
new CKEDITOR.ui.dialog.button;CKEDITOR.ui.dialog.fieldset.prototype=CKEDITOR.tools.clone(CKEDITOR.ui.dialog.hbox.prototype);CKEDITOR.dialog.addUIElement("text",v);CKEDITOR.dialog.addUIElement("password",v);CKEDITOR.dialog.addUIElement("textarea",n);CKEDITOR.dialog.addUIElement("checkbox",n);CKEDITOR.dialog.addUIElement("radio",n);CKEDITOR.dialog.addUIElement("button",n);CKEDITOR.dialog.addUIElement("select",n);CKEDITOR.dialog.addUIElement("file",n);CKEDITOR.dialog.addUIElement("fileButton",n);CKEDITOR.dialog.addUIElement("html",
n);CKEDITOR.dialog.addUIElement("fieldset",{build:function(b,a,d){for(var f=a.children,c,e=[],h=[],g=0;g<f.length&&(c=f[g]);g++){var k=[];e.push(k);h.push(CKEDITOR.dialog._.uiElementBuilders[c.type].build(b,c,k))}return new CKEDITOR.ui.dialog[a.type](b,h,e,d,a)}})}});CKEDITOR.DIALOG_RESIZE_NONE=0;CKEDITOR.DIALOG_RESIZE_WIDTH=1;CKEDITOR.DIALOG_RESIZE_HEIGHT=2;CKEDITOR.DIALOG_RESIZE_BOTH=3;CKEDITOR.DIALOG_STATE_IDLE=1;CKEDITOR.DIALOG_STATE_BUSY=2;
(function(){function x(){for(var a=this._.tabIdList.length,b=CKEDITOR.tools.indexOf(this._.tabIdList,this._.currentTabId)+a,c=b-1;c>b-a;c--)if(this._.tabs[this._.tabIdList[c%a]][0].$.offsetHeight)return this._.tabIdList[c%a];return null}function A(){for(var a=this._.tabIdList.length,b=CKEDITOR.tools.indexOf(this._.tabIdList,this._.currentTabId),c=b+1;c<b+a;c++)if(this._.tabs[this._.tabIdList[c%a]][0].$.offsetHeight)return this._.tabIdList[c%a];return null}function K(a,b){for(var c=a.$.getElementsByTagName("input"),
e=0,d=c.length;e<d;e++){var f=new CKEDITOR.dom.element(c[e]);"text"==f.getAttribute("type").toLowerCase()&&(b?(f.setAttribute("value",f.getCustomData("fake_value")||""),f.removeCustomData("fake_value")):(f.setCustomData("fake_value",f.getAttribute("value")),f.setAttribute("value","")))}}function T(a,b){var c=this.getInputElement();c&&(a?c.removeAttribute("aria-invalid"):c.setAttribute("aria-invalid",!0));a||(this.select?this.select():this.focus());b&&alert(b);this.fire("validated",{valid:a,msg:b})}
function U(){var a=this.getInputElement();a&&a.removeAttribute("aria-invalid")}function V(a){var b=CKEDITOR.dom.element.createFromHtml(CKEDITOR.addTemplate("dialog",W).output({id:CKEDITOR.tools.getNextNumber(),editorId:a.id,langDir:a.lang.dir,langCode:a.langCode,editorDialogClass:"cke_editor_"+a.name.replace(/\./g,"\\.")+"_dialog",closeTitle:a.lang.common.close,hidpi:CKEDITOR.env.hidpi?"cke_hidpi":""})),c=b.getChild([0,0,0,0,0]),e=c.getChild(0),d=c.getChild(1);a.plugins.clipboard&&CKEDITOR.plugins.clipboard.preventDefaultDropOnElement(c);
!CKEDITOR.env.ie||CKEDITOR.env.quirks||CKEDITOR.env.edge||(a="javascript:void(function(){"+encodeURIComponent("document.open();("+CKEDITOR.tools.fixDomain+")();document.close();")+"}())",CKEDITOR.dom.element.createFromHtml('\x3ciframe frameBorder\x3d"0" class\x3d"cke_iframe_shim" src\x3d"'+a+'" tabIndex\x3d"-1"\x3e\x3c/iframe\x3e').appendTo(c.getParent()));e.unselectable();d.unselectable();return{element:b,parts:{dialog:b.getChild(0),title:e,close:d,tabs:c.getChild(2),contents:c.getChild([3,0,0,0]),
footer:c.getChild([3,0,1,0])}}}function L(a,b,c){this.element=b;this.focusIndex=c;this.tabIndex=0;this.isFocusable=function(){return!b.getAttribute("disabled")&&b.isVisible()};this.focus=function(){a._.currentFocusIndex=this.focusIndex;this.element.focus()};b.on("keydown",function(a){a.data.getKeystroke()in{32:1,13:1}&&this.fire("click")});b.on("focus",function(){this.fire("mouseover")});b.on("blur",function(){this.fire("mouseout")})}function X(a){function b(){a.layout()}var c=CKEDITOR.document.getWindow();
c.on("resize",b);a.on("hide",function(){c.removeListener("resize",b)})}function M(a,b){this._={dialog:a};CKEDITOR.tools.extend(this,b)}function Y(a){function b(b){var c=a.getSize(),k=CKEDITOR.document.getWindow().getViewPaneSize(),q=b.data.$.screenX,n=b.data.$.screenY,r=q-e.x,l=n-e.y;e={x:q,y:n};d.x+=r;d.y+=l;a.move(d.x+h[3]<g?-h[3]:d.x-h[1]>k.width-c.width-g?k.width-c.width+("rtl"==f.lang.dir?0:h[1]):d.x,d.y+h[0]<g?-h[0]:d.y-h[2]>k.height-c.height-g?k.height-c.height+h[2]:d.y,1);b.data.preventDefault()}
function c(){CKEDITOR.document.removeListener("mousemove",b);CKEDITOR.document.removeListener("mouseup",c);if(CKEDITOR.env.ie6Compat){var a=u.getChild(0).getFrameDocument();a.removeListener("mousemove",b);a.removeListener("mouseup",c)}}var e=null,d=null,f=a.getParentEditor(),g=f.config.dialog_magnetDistance,h=CKEDITOR.skin.margins||[0,0,0,0];"undefined"==typeof g&&(g=20);a.parts.title.on("mousedown",function(g){e={x:g.data.$.screenX,y:g.data.$.screenY};CKEDITOR.document.on("mousemove",b);CKEDITOR.document.on("mouseup",
c);d=a.getPosition();if(CKEDITOR.env.ie6Compat){var f=u.getChild(0).getFrameDocument();f.on("mousemove",b);f.on("mouseup",c)}g.data.preventDefault()},a)}function Z(a){function b(b){var c="rtl"==f.lang.dir,n=k.width,q=k.height,G=n+(b.data.$.screenX-m.x)*(c?-1:1)*(a._.moved?1:2),H=q+(b.data.$.screenY-m.y)*(a._.moved?1:2),B=a._.element.getFirst(),B=c&&B.getComputedStyle("right"),C=a.getPosition();C.y+H>p.height&&(H=p.height-C.y);(c?B:C.x)+G>p.width&&(G=p.width-(c?B:C.x));if(d==CKEDITOR.DIALOG_RESIZE_WIDTH||
d==CKEDITOR.DIALOG_RESIZE_BOTH)n=Math.max(e.minWidth||0,G-g);if(d==CKEDITOR.DIALOG_RESIZE_HEIGHT||d==CKEDITOR.DIALOG_RESIZE_BOTH)q=Math.max(e.minHeight||0,H-h);a.resize(n,q);a._.moved||a.layout();b.data.preventDefault()}function c(){CKEDITOR.document.removeListener("mouseup",c);CKEDITOR.document.removeListener("mousemove",b);q&&(q.remove(),q=null);if(CKEDITOR.env.ie6Compat){var a=u.getChild(0).getFrameDocument();a.removeListener("mouseup",c);a.removeListener("mousemove",b)}}var e=a.definition,d=e.resizable;
if(d!=CKEDITOR.DIALOG_RESIZE_NONE){var f=a.getParentEditor(),g,h,p,m,k,q,n=CKEDITOR.tools.addFunction(function(d){k=a.getSize();var e=a.parts.contents;e.$.getElementsByTagName("iframe").length&&(q=CKEDITOR.dom.element.createFromHtml('\x3cdiv class\x3d"cke_dialog_resize_cover" style\x3d"height: 100%; position: absolute; width: 100%;"\x3e\x3c/div\x3e'),e.append(q));h=k.height-a.parts.contents.getSize("height",!(CKEDITOR.env.gecko||CKEDITOR.env.ie&&CKEDITOR.env.quirks));g=k.width-a.parts.contents.getSize("width",
1);m={x:d.screenX,y:d.screenY};p=CKEDITOR.document.getWindow().getViewPaneSize();CKEDITOR.document.on("mousemove",b);CKEDITOR.document.on("mouseup",c);CKEDITOR.env.ie6Compat&&(e=u.getChild(0).getFrameDocument(),e.on("mousemove",b),e.on("mouseup",c));d.preventDefault&&d.preventDefault()});a.on("load",function(){var b="";d==CKEDITOR.DIALOG_RESIZE_WIDTH?b=" cke_resizer_horizontal":d==CKEDITOR.DIALOG_RESIZE_HEIGHT&&(b=" cke_resizer_vertical");b=CKEDITOR.dom.element.createFromHtml('\x3cdiv class\x3d"cke_resizer'+
b+" cke_resizer_"+f.lang.dir+'" title\x3d"'+CKEDITOR.tools.htmlEncode(f.lang.common.resize)+'" onmousedown\x3d"CKEDITOR.tools.callFunction('+n+', event )"\x3e'+("ltr"==f.lang.dir?"◢":"◣")+"\x3c/div\x3e");a.parts.footer.append(b,1)});f.on("destroy",function(){CKEDITOR.tools.removeFunction(n)})}}function I(a){a.data.preventDefault(1)}function N(a){var b=CKEDITOR.document.getWindow(),c=a.config,e=CKEDITOR.skinName||a.config.skin,d=c.dialog_backgroundCoverColor||("moono-lisa"==e?"black":"white"),e=c.dialog_backgroundCoverOpacity,
f=c.baseFloatZIndex,c=CKEDITOR.tools.genKey(d,e,f),g=z[c];g?g.show():(f=['\x3cdiv tabIndex\x3d"-1" style\x3d"position: ',CKEDITOR.env.ie6Compat?"absolute":"fixed","; z-index: ",f,"; top: 0px; left: 0px; ",CKEDITOR.env.ie6Compat?"":"background-color: "+d,'" class\x3d"cke_dialog_background_cover"\x3e'],CKEDITOR.env.ie6Compat&&(d="\x3chtml\x3e\x3cbody style\x3d\\'background-color:"+d+";\\'\x3e\x3c/body\x3e\x3c/html\x3e",f.push('\x3ciframe hidefocus\x3d"true" frameborder\x3d"0" id\x3d"cke_dialog_background_iframe" src\x3d"javascript:'),
f.push("void((function(){"+encodeURIComponent("document.open();("+CKEDITOR.tools.fixDomain+")();document.write( '"+d+"' );document.close();")+"})())"),f.push('" style\x3d"position:absolute;left:0;top:0;width:100%;height: 100%;filter: progid:DXImageTransform.Microsoft.Alpha(opacity\x3d0)"\x3e\x3c/iframe\x3e')),f.push("\x3c/div\x3e"),g=CKEDITOR.dom.element.createFromHtml(f.join("")),g.setOpacity(void 0!==e?e:.5),g.on("keydown",I),g.on("keypress",I),g.on("keyup",I),g.appendTo(CKEDITOR.document.getBody()),
z[c]=g);a.focusManager.add(g);u=g;a=function(){var a=b.getViewPaneSize();g.setStyles({width:a.width+"px",height:a.height+"px"})};var h=function(){var a=b.getScrollPosition(),c=CKEDITOR.dialog._.currentTop;g.setStyles({left:a.x+"px",top:a.y+"px"});if(c){do a=c.getPosition(),c.move(a.x,a.y);while(c=c._.parentDialog)}};J=a;b.on("resize",a);a();CKEDITOR.env.mac&&CKEDITOR.env.webkit||g.focus();if(CKEDITOR.env.ie6Compat){var p=function(){h();arguments.callee.prevScrollHandler.apply(this,arguments)};b.$.setTimeout(function(){p.prevScrollHandler=
window.onscroll||function(){};window.onscroll=p},0);h()}}function O(a){u&&(a.focusManager.remove(u),a=CKEDITOR.document.getWindow(),u.hide(),a.removeListener("resize",J),CKEDITOR.env.ie6Compat&&a.$.setTimeout(function(){window.onscroll=window.onscroll&&window.onscroll.prevScrollHandler||null},0),J=null)}var v=CKEDITOR.tools.cssLength,W='\x3cdiv class\x3d"cke_reset_all {editorId} {editorDialogClass} {hidpi}" dir\x3d"{langDir}" lang\x3d"{langCode}" role\x3d"dialog" aria-labelledby\x3d"cke_dialog_title_{id}"\x3e\x3ctable class\x3d"cke_dialog '+
CKEDITOR.env.cssClass+' cke_{langDir}" style\x3d"position:absolute" role\x3d"presentation"\x3e\x3ctr\x3e\x3ctd role\x3d"presentation"\x3e\x3cdiv class\x3d"cke_dialog_body" role\x3d"presentation"\x3e\x3cdiv id\x3d"cke_dialog_title_{id}" class\x3d"cke_dialog_title" role\x3d"presentation"\x3e\x3c/div\x3e\x3ca id\x3d"cke_dialog_close_button_{id}" class\x3d"cke_dialog_close_button" href\x3d"javascript:void(0)" title\x3d"{closeTitle}" role\x3d"button"\x3e\x3cspan class\x3d"cke_label"\x3eX\x3c/span\x3e\x3c/a\x3e\x3cdiv id\x3d"cke_dialog_tabs_{id}" class\x3d"cke_dialog_tabs" role\x3d"tablist"\x3e\x3c/div\x3e\x3ctable class\x3d"cke_dialog_contents" role\x3d"presentation"\x3e\x3ctr\x3e\x3ctd id\x3d"cke_dialog_contents_{id}" class\x3d"cke_dialog_contents_body" role\x3d"presentation"\x3e\x3c/td\x3e\x3c/tr\x3e\x3ctr\x3e\x3ctd id\x3d"cke_dialog_footer_{id}" class\x3d"cke_dialog_footer" role\x3d"presentation"\x3e\x3c/td\x3e\x3c/tr\x3e\x3c/table\x3e\x3c/div\x3e\x3c/td\x3e\x3c/tr\x3e\x3c/table\x3e\x3c/div\x3e';
CKEDITOR.dialog=function(a,b){function c(){var a=l._.focusList;a.sort(function(a,b){return a.tabIndex!=b.tabIndex?b.tabIndex-a.tabIndex:a.focusIndex-b.focusIndex});for(var b=a.length,c=0;c<b;c++)a[c].focusIndex=c}function e(a){var b=l._.focusList;a=a||0;if(!(1>b.length)){var c=l._.currentFocusIndex;l._.tabBarMode&&0>a&&(c=0);try{b[c].getInputElement().$.blur()}catch(d){}var e=c,g=1<l._.pageCount;do{e+=a;if(g&&!l._.tabBarMode&&(e==b.length||-1==e)){l._.tabBarMode=!0;l._.tabs[l._.currentTabId][0].focus();
l._.currentFocusIndex=-1;return}e=(e+b.length)%b.length;if(e==c)break}while(a&&!b[e].isFocusable());b[e].focus();"text"==b[e].type&&b[e].select()}}function d(b){if(l==CKEDITOR.dialog._.currentTop){var c=b.data.getKeystroke(),d="rtl"==a.lang.dir,g=[37,38,39,40];q=n=0;if(9==c||c==CKEDITOR.SHIFT+9)e(c==CKEDITOR.SHIFT+9?-1:1),q=1;else if(c==CKEDITOR.ALT+121&&!l._.tabBarMode&&1<l.getPageCount())l._.tabBarMode=!0,l._.tabs[l._.currentTabId][0].focus(),l._.currentFocusIndex=-1,q=1;else if(-1!=CKEDITOR.tools.indexOf(g,
c)&&l._.tabBarMode)c=-1!=CKEDITOR.tools.indexOf([d?39:37,38],c)?x.call(l):A.call(l),l.selectPage(c),l._.tabs[c][0].focus(),q=1;else if(13!=c&&32!=c||!l._.tabBarMode)if(13==c)c=b.data.getTarget(),c.is("a","button","select","textarea")||c.is("input")&&"button"==c.$.type||((c=this.getButton("ok"))&&CKEDITOR.tools.setTimeout(c.click,0,c),q=1),n=1;else if(27==c)(c=this.getButton("cancel"))?CKEDITOR.tools.setTimeout(c.click,0,c):!1!==this.fire("cancel",{hide:!0}).hide&&this.hide(),n=1;else return;else this.selectPage(this._.currentTabId),
this._.tabBarMode=!1,this._.currentFocusIndex=-1,e(1),q=1;f(b)}}function f(a){q?a.data.preventDefault(1):n&&a.data.stopPropagation()}var g=CKEDITOR.dialog._.dialogDefinitions[b],h=CKEDITOR.tools.clone(aa),p=a.config.dialog_buttonsOrder||"OS",m=a.lang.dir,k={},q,n;("OS"==p&&CKEDITOR.env.mac||"rtl"==p&&"ltr"==m||"ltr"==p&&"rtl"==m)&&h.buttons.reverse();g=CKEDITOR.tools.extend(g(a),h);g=CKEDITOR.tools.clone(g);g=new P(this,g);h=V(a);this._={editor:a,element:h.element,name:b,contentSize:{width:0,height:0},
size:{width:0,height:0},contents:{},buttons:{},accessKeyMap:{},tabs:{},tabIdList:[],currentTabId:null,currentTabIndex:null,pageCount:0,lastTab:null,tabBarMode:!1,focusList:[],currentFocusIndex:0,hasFocus:!1};this.parts=h.parts;CKEDITOR.tools.setTimeout(function(){a.fire("ariaWidget",this.parts.contents)},0,this);h={position:CKEDITOR.env.ie6Compat?"absolute":"fixed",top:0,visibility:"hidden"};h["rtl"==m?"right":"left"]=0;this.parts.dialog.setStyles(h);CKEDITOR.event.call(this);this.definition=g=CKEDITOR.fire("dialogDefinition",
{name:b,definition:g},a).definition;if(!("removeDialogTabs"in a._)&&a.config.removeDialogTabs){h=a.config.removeDialogTabs.split(";");for(m=0;m<h.length;m++)if(p=h[m].split(":"),2==p.length){var r=p[0];k[r]||(k[r]=[]);k[r].push(p[1])}a._.removeDialogTabs=k}if(a._.removeDialogTabs&&(k=a._.removeDialogTabs[b]))for(m=0;m<k.length;m++)g.removeContents(k[m]);if(g.onLoad)this.on("load",g.onLoad);if(g.onShow)this.on("show",g.onShow);if(g.onHide)this.on("hide",g.onHide);if(g.onOk)this.on("ok",function(b){a.fire("saveSnapshot");
setTimeout(function(){a.fire("saveSnapshot")},0);!1===g.onOk.call(this,b)&&(b.data.hide=!1)});this.state=CKEDITOR.DIALOG_STATE_IDLE;if(g.onCancel)this.on("cancel",function(a){!1===g.onCancel.call(this,a)&&(a.data.hide=!1)});var l=this,t=function(a){var b=l._.contents,c=!1,d;for(d in b)for(var e in b[d])if(c=a.call(this,b[d][e]))return};this.on("ok",function(a){t(function(b){if(b.validate){var c=b.validate(this),d="string"==typeof c||!1===c;d&&(a.data.hide=!1,a.stop());T.call(b,!d,"string"==typeof c?
c:void 0);return d}})},this,null,0);this.on("cancel",function(b){t(function(c){if(c.isChanged())return a.config.dialog_noConfirmCancel||confirm(a.lang.common.confirmCancel)||(b.data.hide=!1),!0})},this,null,0);this.parts.close.on("click",function(a){!1!==this.fire("cancel",{hide:!0}).hide&&this.hide();a.data.preventDefault()},this);this.changeFocus=e;var y=this._.element;a.focusManager.add(y,1);this.on("show",function(){y.on("keydown",d,this);if(CKEDITOR.env.gecko)y.on("keypress",f,this)});this.on("hide",
function(){y.removeListener("keydown",d);CKEDITOR.env.gecko&&y.removeListener("keypress",f);t(function(a){U.apply(a)})});this.on("iframeAdded",function(a){(new CKEDITOR.dom.document(a.data.iframe.$.contentWindow.document)).on("keydown",d,this,null,0)});this.on("show",function(){c();var b=1<l._.pageCount;a.config.dialog_startupFocusTab&&b?(l._.tabBarMode=!0,l._.tabs[l._.currentTabId][0].focus(),l._.currentFocusIndex=-1):this._.hasFocus||(this._.currentFocusIndex=b?-1:this._.focusList.length-1,g.onFocus?
(b=g.onFocus.call(this))&&b.focus():e(1))},this,null,4294967295);if(CKEDITOR.env.ie6Compat)this.on("load",function(){var a=this.getElement(),b=a.getFirst();b.remove();b.appendTo(a)},this);Y(this);Z(this);(new CKEDITOR.dom.text(g.title,CKEDITOR.document)).appendTo(this.parts.title);for(m=0;m<g.contents.length;m++)(k=g.contents[m])&&this.addPage(k);this.parts.tabs.on("click",function(a){var b=a.data.getTarget();b.hasClass("cke_dialog_tab")&&(b=b.$.id,this.selectPage(b.substring(4,b.lastIndexOf("_"))),
this._.tabBarMode&&(this._.tabBarMode=!1,this._.currentFocusIndex=-1,e(1)),a.data.preventDefault())},this);m=[];k=CKEDITOR.dialog._.uiElementBuilders.hbox.build(this,{type:"hbox",className:"cke_dialog_footer_buttons",widths:[],children:g.buttons},m).getChild();this.parts.footer.setHtml(m.join(""));for(m=0;m<k.length;m++)this._.buttons[k[m].id]=k[m]};CKEDITOR.dialog.prototype={destroy:function(){this.hide();this._.element.remove()},resize:function(){return function(a,b){this._.contentSize&&this._.contentSize.width==
a&&this._.contentSize.height==b||(CKEDITOR.dialog.fire("resize",{dialog:this,width:a,height:b},this._.editor),this.fire("resize",{width:a,height:b},this._.editor),this.parts.contents.setStyles({width:a+"px",height:b+"px"}),"rtl"==this._.editor.lang.dir&&this._.position&&(this._.position.x=CKEDITOR.document.getWindow().getViewPaneSize().width-this._.contentSize.width-parseInt(this._.element.getFirst().getStyle("right"),10)),this._.contentSize={width:a,height:b})}}(),getSize:function(){var a=this._.element.getFirst();
return{width:a.$.offsetWidth||0,height:a.$.offsetHeight||0}},move:function(a,b,c){var e=this._.element.getFirst(),d="rtl"==this._.editor.lang.dir,f="fixed"==e.getComputedStyle("position");CKEDITOR.env.ie&&e.setStyle("zoom","100%");f&&this._.position&&this._.position.x==a&&this._.position.y==b||(this._.position={x:a,y:b},f||(f=CKEDITOR.document.getWindow().getScrollPosition(),a+=f.x,b+=f.y),d&&(f=this.getSize(),a=CKEDITOR.document.getWindow().getViewPaneSize().width-f.width-a),b={top:(0<b?b:0)+"px"},
b[d?"right":"left"]=(0<a?a:0)+"px",e.setStyles(b),c&&(this._.moved=1))},getPosition:function(){return CKEDITOR.tools.extend({},this._.position)},show:function(){var a=this._.element,b=this.definition;a.getParent()&&a.getParent().equals(CKEDITOR.document.getBody())?a.setStyle("display","block"):a.appendTo(CKEDITOR.document.getBody());this.resize(this._.contentSize&&this._.contentSize.width||b.width||b.minWidth,this._.contentSize&&this._.contentSize.height||b.height||b.minHeight);this.reset();null===
this._.currentTabId&&this.selectPage(this.definition.contents[0].id);null===CKEDITOR.dialog._.currentZIndex&&(CKEDITOR.dialog._.currentZIndex=this._.editor.config.baseFloatZIndex);this._.element.getFirst().setStyle("z-index",CKEDITOR.dialog._.currentZIndex+=10);null===CKEDITOR.dialog._.currentTop?(CKEDITOR.dialog._.currentTop=this,this._.parentDialog=null,N(this._.editor)):(this._.parentDialog=CKEDITOR.dialog._.currentTop,this._.parentDialog.getElement().getFirst().$.style.zIndex-=Math.floor(this._.editor.config.baseFloatZIndex/
2),CKEDITOR.dialog._.currentTop=this);a.on("keydown",Q);a.on("keyup",R);this._.hasFocus=!1;for(var c in b.contents)if(b.contents[c]){var a=b.contents[c],e=this._.tabs[a.id],d=a.requiredContent,f=0;if(e){for(var g in this._.contents[a.id]){var h=this._.contents[a.id][g];"hbox"!=h.type&&"vbox"!=h.type&&h.getInputElement()&&(h.requiredContent&&!this._.editor.activeFilter.check(h.requiredContent)?h.disable():(h.enable(),f++))}!f||d&&!this._.editor.activeFilter.check(d)?e[0].addClass("cke_dialog_tab_disabled"):
e[0].removeClass("cke_dialog_tab_disabled")}}CKEDITOR.tools.setTimeout(function(){this.layout();X(this);this.parts.dialog.setStyle("visibility","");this.fireOnce("load",{});CKEDITOR.ui.fire("ready",this);this.fire("show",{});this._.editor.fire("dialogShow",this);this._.parentDialog||this._.editor.focusManager.lock();this.foreach(function(a){a.setInitValue&&a.setInitValue()})},100,this)},layout:function(){var a=this.parts.dialog,b=this.getSize(),c=CKEDITOR.document.getWindow().getViewPaneSize(),e=
(c.width-b.width)/2,d=(c.height-b.height)/2;CKEDITOR.env.ie6Compat||(b.height+(0<d?d:0)>c.height||b.width+(0<e?e:0)>c.width?a.setStyle("position","absolute"):a.setStyle("position","fixed"));this.move(this._.moved?this._.position.x:e,this._.moved?this._.position.y:d)},foreach:function(a){for(var b in this._.contents)for(var c in this._.contents[b])a.call(this,this._.contents[b][c]);return this},reset:function(){var a=function(a){a.reset&&a.reset(1)};return function(){this.foreach(a);return this}}(),
setupContent:function(){var a=arguments;this.foreach(function(b){b.setup&&b.setup.apply(b,a)})},commitContent:function(){var a=arguments;this.foreach(function(b){CKEDITOR.env.ie&&this._.currentFocusIndex==b.focusIndex&&b.getInputElement().$.blur();b.commit&&b.commit.apply(b,a)})},hide:function(){if(this.parts.dialog.isVisible()){this.fire("hide",{});this._.editor.fire("dialogHide",this);this.selectPage(this._.tabIdList[0]);var a=this._.element;a.setStyle("display","none");this.parts.dialog.setStyle("visibility",
"hidden");for(ba(this);CKEDITOR.dialog._.currentTop!=this;)CKEDITOR.dialog._.currentTop.hide();if(this._.parentDialog){var b=this._.parentDialog.getElement().getFirst();b.setStyle("z-index",parseInt(b.$.style.zIndex,10)+Math.floor(this._.editor.config.baseFloatZIndex/2))}else O(this._.editor);if(CKEDITOR.dialog._.currentTop=this._.parentDialog)CKEDITOR.dialog._.currentZIndex-=10;else{CKEDITOR.dialog._.currentZIndex=null;a.removeListener("keydown",Q);a.removeListener("keyup",R);var c=this._.editor;
c.focus();setTimeout(function(){c.focusManager.unlock();CKEDITOR.env.iOS&&c.window.focus()},0)}delete this._.parentDialog;this.foreach(function(a){a.resetInitValue&&a.resetInitValue()});this.setState(CKEDITOR.DIALOG_STATE_IDLE)}},addPage:function(a){if(!a.requiredContent||this._.editor.filter.check(a.requiredContent)){for(var b=[],c=a.label?' title\x3d"'+CKEDITOR.tools.htmlEncode(a.label)+'"':"",e=CKEDITOR.dialog._.uiElementBuilders.vbox.build(this,{type:"vbox",className:"cke_dialog_page_contents",
children:a.elements,expand:!!a.expand,padding:a.padding,style:a.style||"width: 100%;"},b),d=this._.contents[a.id]={},f=e.getChild(),g=0;e=f.shift();)e.notAllowed||"hbox"==e.type||"vbox"==e.type||g++,d[e.id]=e,"function"==typeof e.getChild&&f.push.apply(f,e.getChild());g||(a.hidden=!0);b=CKEDITOR.dom.element.createFromHtml(b.join(""));b.setAttribute("role","tabpanel");e=CKEDITOR.env;d="cke_"+a.id+"_"+CKEDITOR.tools.getNextNumber();c=CKEDITOR.dom.element.createFromHtml(['\x3ca class\x3d"cke_dialog_tab"',
0<this._.pageCount?" cke_last":"cke_first",c,a.hidden?' style\x3d"display:none"':"",' id\x3d"',d,'"',e.gecko&&!e.hc?"":' href\x3d"javascript:void(0)"',' tabIndex\x3d"-1" hidefocus\x3d"true" role\x3d"tab"\x3e',a.label,"\x3c/a\x3e"].join(""));b.setAttribute("aria-labelledby",d);this._.tabs[a.id]=[c,b];this._.tabIdList.push(a.id);!a.hidden&&this._.pageCount++;this._.lastTab=c;this.updateStyle();b.setAttribute("name",a.id);b.appendTo(this.parts.contents);c.unselectable();this.parts.tabs.append(c);a.accessKey&&
(S(this,this,"CTRL+"+a.accessKey,ca,da),this._.accessKeyMap["CTRL+"+a.accessKey]=a.id)}},selectPage:function(a){if(this._.currentTabId!=a&&!this._.tabs[a][0].hasClass("cke_dialog_tab_disabled")&&!1!==this.fire("selectPage",{page:a,currentPage:this._.currentTabId})){for(var b in this._.tabs){var c=this._.tabs[b][0],e=this._.tabs[b][1];b!=a&&(c.removeClass("cke_dialog_tab_selected"),e.hide());e.setAttribute("aria-hidden",b!=a)}var d=this._.tabs[a];d[0].addClass("cke_dialog_tab_selected");CKEDITOR.env.ie6Compat||
CKEDITOR.env.ie7Compat?(K(d[1]),d[1].show(),setTimeout(function(){K(d[1],1)},0)):d[1].show();this._.currentTabId=a;this._.currentTabIndex=CKEDITOR.tools.indexOf(this._.tabIdList,a)}},updateStyle:function(){this.parts.dialog[(1===this._.pageCount?"add":"remove")+"Class"]("cke_single_page")},hidePage:function(a){var b=this._.tabs[a]&&this._.tabs[a][0];b&&1!=this._.pageCount&&b.isVisible()&&(a==this._.currentTabId&&this.selectPage(x.call(this)),b.hide(),this._.pageCount--,this.updateStyle())},showPage:function(a){if(a=
this._.tabs[a]&&this._.tabs[a][0])a.show(),this._.pageCount++,this.updateStyle()},getElement:function(){return this._.element},getName:function(){return this._.name},getContentElement:function(a,b){var c=this._.contents[a];return c&&c[b]},getValueOf:function(a,b){return this.getContentElement(a,b).getValue()},setValueOf:function(a,b,c){return this.getContentElement(a,b).setValue(c)},getButton:function(a){return this._.buttons[a]},click:function(a){return this._.buttons[a].click()},disableButton:function(a){return this._.buttons[a].disable()},
enableButton:function(a){return this._.buttons[a].enable()},getPageCount:function(){return this._.pageCount},getParentEditor:function(){return this._.editor},getSelectedElement:function(){return this.getParentEditor().getSelection().getSelectedElement()},addFocusable:function(a,b){if("undefined"==typeof b)b=this._.focusList.length,this._.focusList.push(new L(this,a,b));else{this._.focusList.splice(b,0,new L(this,a,b));for(var c=b+1;c<this._.focusList.length;c++)this._.focusList[c].focusIndex++}},
setState:function(a){if(this.state!=a){this.state=a;if(a==CKEDITOR.DIALOG_STATE_BUSY){if(!this.parts.spinner){var b=this.getParentEditor().lang.dir,c={attributes:{"class":"cke_dialog_spinner"},styles:{"float":"rtl"==b?"right":"left"}};c.styles["margin-"+("rtl"==b?"left":"right")]="8px";this.parts.spinner=CKEDITOR.document.createElement("div",c);this.parts.spinner.setHtml("\x26#8987;");this.parts.spinner.appendTo(this.parts.title,1)}this.parts.spinner.show();this.getButton("ok").disable()}else a==
CKEDITOR.DIALOG_STATE_IDLE&&(this.parts.spinner&&this.parts.spinner.hide(),this.getButton("ok").enable());this.fire("state",a)}}};CKEDITOR.tools.extend(CKEDITOR.dialog,{add:function(a,b){this._.dialogDefinitions[a]&&"function"!=typeof b||(this._.dialogDefinitions[a]=b)},exists:function(a){return!!this._.dialogDefinitions[a]},getCurrent:function(){return CKEDITOR.dialog._.currentTop},isTabEnabled:function(a,b,c){a=a.config.removeDialogTabs;return!(a&&a.match(new RegExp("(?:^|;)"+b+":"+c+"(?:$|;)",
"i")))},okButton:function(){var a=function(a,c){c=c||{};return CKEDITOR.tools.extend({id:"ok",type:"button",label:a.lang.common.ok,"class":"cke_dialog_ui_button_ok",onClick:function(a){a=a.data.dialog;!1!==a.fire("ok",{hide:!0}).hide&&a.hide()}},c,!0)};a.type="button";a.override=function(b){return CKEDITOR.tools.extend(function(c){return a(c,b)},{type:"button"},!0)};return a}(),cancelButton:function(){var a=function(a,c){c=c||{};return CKEDITOR.tools.extend({id:"cancel",type:"button",label:a.lang.common.cancel,
"class":"cke_dialog_ui_button_cancel",onClick:function(a){a=a.data.dialog;!1!==a.fire("cancel",{hide:!0}).hide&&a.hide()}},c,!0)};a.type="button";a.override=function(b){return CKEDITOR.tools.extend(function(c){return a(c,b)},{type:"button"},!0)};return a}(),addUIElement:function(a,b){this._.uiElementBuilders[a]=b}});CKEDITOR.dialog._={uiElementBuilders:{},dialogDefinitions:{},currentTop:null,currentZIndex:null};CKEDITOR.event.implementOn(CKEDITOR.dialog);CKEDITOR.event.implementOn(CKEDITOR.dialog.prototype);
var aa={resizable:CKEDITOR.DIALOG_RESIZE_BOTH,minWidth:600,minHeight:400,buttons:[CKEDITOR.dialog.okButton,CKEDITOR.dialog.cancelButton]},D=function(a,b,c){for(var e=0,d;d=a[e];e++)if(d.id==b||c&&d[c]&&(d=D(d[c],b,c)))return d;return null},E=function(a,b,c,e,d){if(c){for(var f=0,g;g=a[f];f++){if(g.id==c)return a.splice(f,0,b),b;if(e&&g[e]&&(g=E(g[e],b,c,e,!0)))return g}if(d)return null}a.push(b);return b},F=function(a,b,c){for(var e=0,d;d=a[e];e++){if(d.id==b)return a.splice(e,1);if(c&&d[c]&&(d=F(d[c],
b,c)))return d}return null},P=function(a,b){this.dialog=a;for(var c=b.contents,e=0,d;d=c[e];e++)c[e]=d&&new M(a,d);CKEDITOR.tools.extend(this,b)};P.prototype={getContents:function(a){return D(this.contents,a)},getButton:function(a){return D(this.buttons,a)},addContents:function(a,b){return E(this.contents,a,b)},addButton:function(a,b){return E(this.buttons,a,b)},removeContents:function(a){F(this.contents,a)},removeButton:function(a){F(this.buttons,a)}};M.prototype={get:function(a){return D(this.elements,
a,"children")},add:function(a,b){return E(this.elements,a,b,"children")},remove:function(a){F(this.elements,a,"children")}};var J,z={},u,w={},Q=function(a){var b=a.data.$.ctrlKey||a.data.$.metaKey,c=a.data.$.altKey,e=a.data.$.shiftKey,d=String.fromCharCode(a.data.$.keyCode);(b=w[(b?"CTRL+":"")+(c?"ALT+":"")+(e?"SHIFT+":"")+d])&&b.length&&(b=b[b.length-1],b.keydown&&b.keydown.call(b.uiElement,b.dialog,b.key),a.data.preventDefault())},R=function(a){var b=a.data.$.ctrlKey||a.data.$.metaKey,c=a.data.$.altKey,
e=a.data.$.shiftKey,d=String.fromCharCode(a.data.$.keyCode);(b=w[(b?"CTRL+":"")+(c?"ALT+":"")+(e?"SHIFT+":"")+d])&&b.length&&(b=b[b.length-1],b.keyup&&(b.keyup.call(b.uiElement,b.dialog,b.key),a.data.preventDefault()))},S=function(a,b,c,e,d){(w[c]||(w[c]=[])).push({uiElement:a,dialog:b,key:c,keyup:d||a.accessKeyUp,keydown:e||a.accessKeyDown})},ba=function(a){for(var b in w){for(var c=w[b],e=c.length-1;0<=e;e--)c[e].dialog!=a&&c[e].uiElement!=a||c.splice(e,1);0===c.length&&delete w[b]}},da=function(a,
b){a._.accessKeyMap[b]&&a.selectPage(a._.accessKeyMap[b])},ca=function(){};(function(){CKEDITOR.ui.dialog={uiElement:function(a,b,c,e,d,f,g){if(!(4>arguments.length)){var h=(e.call?e(b):e)||"div",p=["\x3c",h," "],m=(d&&d.call?d(b):d)||{},k=(f&&f.call?f(b):f)||{},q=(g&&g.call?g.call(this,a,b):g)||"",n=this.domId=k.id||CKEDITOR.tools.getNextId()+"_uiElement";b.requiredContent&&!a.getParentEditor().filter.check(b.requiredContent)&&(m.display="none",this.notAllowed=!0);k.id=n;var r={};b.type&&(r["cke_dialog_ui_"+
b.type]=1);b.className&&(r[b.className]=1);b.disabled&&(r.cke_disabled=1);for(var l=k["class"]&&k["class"].split?k["class"].split(" "):[],n=0;n<l.length;n++)l[n]&&(r[l[n]]=1);l=[];for(n in r)l.push(n);k["class"]=l.join(" ");b.title&&(k.title=b.title);r=(b.style||"").split(";");b.align&&(l=b.align,m["margin-left"]="left"==l?0:"auto",m["margin-right"]="right"==l?0:"auto");for(n in m)r.push(n+":"+m[n]);b.hidden&&r.push("display:none");for(n=r.length-1;0<=n;n--)""===r[n]&&r.splice(n,1);0<r.length&&(k.style=
(k.style?k.style+"; ":"")+r.join("; "));for(n in k)p.push(n+'\x3d"'+CKEDITOR.tools.htmlEncode(k[n])+'" ');p.push("\x3e",q,"\x3c/",h,"\x3e");c.push(p.join(""));(this._||(this._={})).dialog=a;"boolean"==typeof b.isChanged&&(this.isChanged=function(){return b.isChanged});"function"==typeof b.isChanged&&(this.isChanged=b.isChanged);"function"==typeof b.setValue&&(this.setValue=CKEDITOR.tools.override(this.setValue,function(a){return function(c){a.call(this,b.setValue.call(this,c))}}));"function"==typeof b.getValue&&
(this.getValue=CKEDITOR.tools.override(this.getValue,function(a){return function(){return b.getValue.call(this,a.call(this))}}));CKEDITOR.event.implementOn(this);this.registerEvents(b);this.accessKeyUp&&this.accessKeyDown&&b.accessKey&&S(this,a,"CTRL+"+b.accessKey);var t=this;a.on("load",function(){var b=t.getInputElement();if(b){var c=t.type in{checkbox:1,ratio:1}&&CKEDITOR.env.ie&&8>CKEDITOR.env.version?"cke_dialog_ui_focused":"";b.on("focus",function(){a._.tabBarMode=!1;a._.hasFocus=!0;t.fire("focus");
c&&this.addClass(c)});b.on("blur",function(){t.fire("blur");c&&this.removeClass(c)})}});CKEDITOR.tools.extend(this,b);this.keyboardFocusable&&(this.tabIndex=b.tabIndex||0,this.focusIndex=a._.focusList.push(this)-1,this.on("focus",function(){a._.currentFocusIndex=t.focusIndex}))}},hbox:function(a,b,c,e,d){if(!(4>arguments.length)){this._||(this._={});var f=this._.children=b,g=d&&d.widths||null,h=d&&d.height||null,p,m={role:"presentation"};d&&d.align&&(m.align=d.align);CKEDITOR.ui.dialog.uiElement.call(this,
a,d||{type:"hbox"},e,"table",{},m,function(){var a=['\x3ctbody\x3e\x3ctr class\x3d"cke_dialog_ui_hbox"\x3e'];for(p=0;p<c.length;p++){var b="cke_dialog_ui_hbox_child",e=[];0===p&&(b="cke_dialog_ui_hbox_first");p==c.length-1&&(b="cke_dialog_ui_hbox_last");a.push('\x3ctd class\x3d"',b,'" role\x3d"presentation" ');g?g[p]&&e.push("width:"+v(g[p])):e.push("width:"+Math.floor(100/c.length)+"%");h&&e.push("height:"+v(h));d&&void 0!==d.padding&&e.push("padding:"+v(d.padding));CKEDITOR.env.ie&&CKEDITOR.env.quirks&&
f[p].align&&e.push("text-align:"+f[p].align);0<e.length&&a.push('style\x3d"'+e.join("; ")+'" ');a.push("\x3e",c[p],"\x3c/td\x3e")}a.push("\x3c/tr\x3e\x3c/tbody\x3e");return a.join("")})}},vbox:function(a,b,c,e,d){if(!(3>arguments.length)){this._||(this._={});var f=this._.children=b,g=d&&d.width||null,h=d&&d.heights||null;CKEDITOR.ui.dialog.uiElement.call(this,a,d||{type:"vbox"},e,"div",null,{role:"presentation"},function(){var b=['\x3ctable role\x3d"presentation" cellspacing\x3d"0" border\x3d"0" '];
b.push('style\x3d"');d&&d.expand&&b.push("height:100%;");b.push("width:"+v(g||"100%"),";");CKEDITOR.env.webkit&&b.push("float:none;");b.push('"');b.push('align\x3d"',CKEDITOR.tools.htmlEncode(d&&d.align||("ltr"==a.getParentEditor().lang.dir?"left":"right")),'" ');b.push("\x3e\x3ctbody\x3e");for(var e=0;e<c.length;e++){var k=[];b.push('\x3ctr\x3e\x3ctd role\x3d"presentation" ');g&&k.push("width:"+v(g||"100%"));h?k.push("height:"+v(h[e])):d&&d.expand&&k.push("height:"+Math.floor(100/c.length)+"%");
d&&void 0!==d.padding&&k.push("padding:"+v(d.padding));CKEDITOR.env.ie&&CKEDITOR.env.quirks&&f[e].align&&k.push("text-align:"+f[e].align);0<k.length&&b.push('style\x3d"',k.join("; "),'" ');b.push(' class\x3d"cke_dialog_ui_vbox_child"\x3e',c[e],"\x3c/td\x3e\x3c/tr\x3e")}b.push("\x3c/tbody\x3e\x3c/table\x3e");return b.join("")})}}}})();CKEDITOR.ui.dialog.uiElement.prototype={getElement:function(){return CKEDITOR.document.getById(this.domId)},getInputElement:function(){return this.getElement()},getDialog:function(){return this._.dialog},
setValue:function(a,b){this.getInputElement().setValue(a);!b&&this.fire("change",{value:a});return this},getValue:function(){return this.getInputElement().getValue()},isChanged:function(){return!1},selectParentTab:function(){for(var a=this.getInputElement();(a=a.getParent())&&-1==a.$.className.search("cke_dialog_page_contents"););if(!a)return this;a=a.getAttribute("name");this._.dialog._.currentTabId!=a&&this._.dialog.selectPage(a);return this},focus:function(){this.selectParentTab().getInputElement().focus();
return this},registerEvents:function(a){var b=/^on([A-Z]\w+)/,c,e=function(a,b,c,d){b.on("load",function(){a.getInputElement().on(c,d,a)})},d;for(d in a)if(c=d.match(b))this.eventProcessors[d]?this.eventProcessors[d].call(this,this._.dialog,a[d]):e(this,this._.dialog,c[1].toLowerCase(),a[d]);return this},eventProcessors:{onLoad:function(a,b){a.on("load",b,this)},onShow:function(a,b){a.on("show",b,this)},onHide:function(a,b){a.on("hide",b,this)}},accessKeyDown:function(){this.focus()},accessKeyUp:function(){},
disable:function(){var a=this.getElement();this.getInputElement().setAttribute("disabled","true");a.addClass("cke_disabled")},enable:function(){var a=this.getElement();this.getInputElement().removeAttribute("disabled");a.removeClass("cke_disabled")},isEnabled:function(){return!this.getElement().hasClass("cke_disabled")},isVisible:function(){return this.getInputElement().isVisible()},isFocusable:function(){return this.isEnabled()&&this.isVisible()?!0:!1}};CKEDITOR.ui.dialog.hbox.prototype=CKEDITOR.tools.extend(new CKEDITOR.ui.dialog.uiElement,
{getChild:function(a){if(1>arguments.length)return this._.children.concat();a.splice||(a=[a]);return 2>a.length?this._.children[a[0]]:this._.children[a[0]]&&this._.children[a[0]].getChild?this._.children[a[0]].getChild(a.slice(1,a.length)):null}},!0);CKEDITOR.ui.dialog.vbox.prototype=new CKEDITOR.ui.dialog.hbox;(function(){var a={build:function(a,c,e){for(var d=c.children,f,g=[],h=[],p=0;p<d.length&&(f=d[p]);p++){var m=[];g.push(m);h.push(CKEDITOR.dialog._.uiElementBuilders[f.type].build(a,f,m))}return new CKEDITOR.ui.dialog[c.type](a,
h,g,e,c)}};CKEDITOR.dialog.addUIElement("hbox",a);CKEDITOR.dialog.addUIElement("vbox",a)})();CKEDITOR.dialogCommand=function(a,b){this.dialogName=a;CKEDITOR.tools.extend(this,b,!0)};CKEDITOR.dialogCommand.prototype={exec:function(a){var b=this.tabId;a.openDialog(this.dialogName,function(a){b&&a.selectPage(b)})},canUndo:!1,editorFocus:1};(function(){var a=/^([a]|[^a])+$/,b=/^\d*$/,c=/^\d*(?:\.\d+)?$/,e=/^(((\d*(\.\d+))|(\d*))(px|\%)?)?$/,d=/^(((\d*(\.\d+))|(\d*))(px|em|ex|in|cm|mm|pt|pc|\%)?)?$/i,
f=/^(\s*[\w-]+\s*:\s*[^:;]+(?:;|$))*$/;CKEDITOR.VALIDATE_OR=1;CKEDITOR.VALIDATE_AND=2;CKEDITOR.dialog.validate={functions:function(){var a=arguments;return function(){var b=this&&this.getValue?this.getValue():a[0],c,d=CKEDITOR.VALIDATE_AND,e=[],f;for(f=0;f<a.length;f++)if("function"==typeof a[f])e.push(a[f]);else break;f<a.length&&"string"==typeof a[f]&&(c=a[f],f++);f<a.length&&"number"==typeof a[f]&&(d=a[f]);var n=d==CKEDITOR.VALIDATE_AND?!0:!1;for(f=0;f<e.length;f++)n=d==CKEDITOR.VALIDATE_AND?n&&
e[f](b):n||e[f](b);return n?!0:c}},regex:function(a,b){return function(c){c=this&&this.getValue?this.getValue():c;return a.test(c)?!0:b}},notEmpty:function(b){return this.regex(a,b)},integer:function(a){return this.regex(b,a)},number:function(a){return this.regex(c,a)},cssLength:function(a){return this.functions(function(a){return d.test(CKEDITOR.tools.trim(a))},a)},htmlLength:function(a){return this.functions(function(a){return e.test(CKEDITOR.tools.trim(a))},a)},inlineStyle:function(a){return this.functions(function(a){return f.test(CKEDITOR.tools.trim(a))},
a)},equals:function(a,b){return this.functions(function(b){return b==a},b)},notEqual:function(a,b){return this.functions(function(b){return b!=a},b)}};CKEDITOR.on("instanceDestroyed",function(a){if(CKEDITOR.tools.isEmpty(CKEDITOR.instances)){for(var b;b=CKEDITOR.dialog._.currentTop;)b.hide();for(var c in z)z[c].remove();z={}}a=a.editor._.storedDialogs;for(var d in a)a[d].destroy()})})();CKEDITOR.tools.extend(CKEDITOR.editor.prototype,{openDialog:function(a,b){var c=null,e=CKEDITOR.dialog._.dialogDefinitions[a];
null===CKEDITOR.dialog._.currentTop&&N(this);if("function"==typeof e)c=this._.storedDialogs||(this._.storedDialogs={}),c=c[a]||(c[a]=new CKEDITOR.dialog(this,a)),b&&b.call(c,c),c.show();else{if("failed"==e)throw O(this),Error('[CKEDITOR.dialog.openDialog] Dialog "'+a+'" failed when loading definition.');"string"==typeof e&&CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(e),function(){"function"!=typeof CKEDITOR.dialog._.dialogDefinitions[a]&&(CKEDITOR.dialog._.dialogDefinitions[a]="failed");this.openDialog(a,
b)},this,0,1)}CKEDITOR.skin.loadPart("dialog");return c}})})();CKEDITOR.plugins.add("dialog",{requires:"dialogui",init:function(x){x.on("doubleclick",function(A){A.data.dialog&&x.openDialog(A.data.dialog)},null,null,999)}});CKEDITOR.plugins.add("about",{requires:"dialog",init:function(a){var b=a.addCommand("about",new CKEDITOR.dialogCommand("about"));b.modes={wysiwyg:1,source:1};b.canUndo=!1;b.readOnly=1;a.ui.addButton&&a.ui.addButton("About",{label:a.lang.about.dlgTitle,command:"about",toolbar:"about"});CKEDITOR.dialog.add("about",this.path+"dialogs/about.js")}});(function(){CKEDITOR.plugins.add("a11yhelp",{requires:"dialog",availableLangs:{af:1,ar:1,az:1,bg:1,ca:1,cs:1,cy:1,da:1,de:1,"de-ch":1,el:1,en:1,"en-au":1,"en-gb":1,eo:1,es:1,"es-mx":1,et:1,eu:1,fa:1,fi:1,fo:1,fr:1,"fr-ca":1,gl:1,gu:1,he:1,hi:1,hr:1,hu:1,id:1,it:1,ja:1,km:1,ko:1,ku:1,lt:1,lv:1,mk:1,mn:1,nb:1,nl:1,no:1,oc:1,pl:1,pt:1,"pt-br":1,ro:1,ru:1,si:1,sk:1,sl:1,sq:1,sr:1,"sr-latn":1,sv:1,th:1,tr:1,tt:1,ug:1,uk:1,vi:1,zh:1,"zh-cn":1},init:function(b){var c=this;b.addCommand("a11yHelp",{exec:function(){var a=
b.langCode,a=c.availableLangs[a]?a:c.availableLangs[a.replace(/-.*/,"")]?a.replace(/-.*/,""):"en";CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(c.path+"dialogs/lang/"+a+".js"),function(){b.lang.a11yhelp=c.langEntries[a];b.openDialog("a11yHelp")})},modes:{wysiwyg:1,source:1},readOnly:1,canUndo:!1});b.setKeystroke(CKEDITOR.ALT+48,"a11yHelp");CKEDITOR.dialog.add("a11yHelp",this.path+"dialogs/a11yhelp.js");b.on("ariaEditorHelpLabel",function(a){a.data.label=b.lang.common.editorHelp})}})})();(function(){function f(c){var a=this.att;c=c&&c.hasAttribute(a)&&c.getAttribute(a)||"";void 0!==c&&this.setValue(c)}function g(){for(var c,a=0;a<arguments.length;a++)if(arguments[a]instanceof CKEDITOR.dom.element){c=arguments[a];break}if(c){var a=this.att,b=this.getValue();b?c.setAttribute(a,b):c.removeAttribute(a,b)}}var k={id:1,dir:1,classes:1,styles:1};CKEDITOR.plugins.add("dialogadvtab",{requires:"dialog",allowedContent:function(c){c||(c=k);var a=[];c.id&&a.push("id");c.dir&&a.push("dir");var b=
"";a.length&&(b+="["+a.join(",")+"]");c.classes&&(b+="(*)");c.styles&&(b+="{*}");return b},createAdvancedTab:function(c,a,b){a||(a=k);var d=c.lang.common,h={id:"advanced",label:d.advancedTab,title:d.advancedTab,elements:[{type:"vbox",padding:1,children:[]}]},e=[];if(a.id||a.dir)a.id&&e.push({id:"advId",att:"id",type:"text",requiredContent:b?b+"[id]":null,label:d.id,setup:f,commit:g}),a.dir&&e.push({id:"advLangDir",att:"dir",type:"select",requiredContent:b?b+"[dir]":null,label:d.langDir,"default":"",
style:"width:100%",items:[[d.notSet,""],[d.langDirLTR,"ltr"],[d.langDirRTL,"rtl"]],setup:f,commit:g}),h.elements[0].children.push({type:"hbox",widths:["50%","50%"],children:[].concat(e)});if(a.styles||a.classes)e=[],a.styles&&e.push({id:"advStyles",att:"style",type:"text",requiredContent:b?b+"{cke-xyz}":null,label:d.styles,"default":"",validate:CKEDITOR.dialog.validate.inlineStyle(d.invalidInlineStyle),onChange:function(){},getStyle:function(a,c){var b=this.getValue().match(new RegExp("(?:^|;)\\s*"+
a+"\\s*:\\s*([^;]*)","i"));return b?b[1]:c},updateStyle:function(a,b){var d=this.getValue(),e=c.document.createElement("span");e.setAttribute("style",d);e.setStyle(a,b);d=CKEDITOR.tools.normalizeCssText(e.getAttribute("style"));this.setValue(d,1)},setup:f,commit:g}),a.classes&&e.push({type:"hbox",widths:["45%","55%"],children:[{id:"advCSSClasses",att:"class",type:"text",requiredContent:b?b+"(cke-xyz)":null,label:d.cssClasses,"default":"",setup:f,commit:g}]}),h.elements[0].children.push({type:"hbox",
widths:["50%","50%"],children:[].concat(e)});return h}})})();CKEDITOR.plugins.add("basicstyles",{init:function(c){var e=0,d=function(g,d,b,a){if(a){a=new CKEDITOR.style(a);var f=h[b];f.unshift(a);c.attachStyleStateChange(a,function(a){!c.readOnly&&c.getCommand(b).setState(a)});c.addCommand(b,new CKEDITOR.styleCommand(a,{contentForms:f}));c.ui.addButton&&c.ui.addButton(g,{label:d,command:b,toolbar:"basicstyles,"+(e+=10)})}},h={bold:["strong","b",["span",function(a){a=a.styles["font-weight"];return"bold"==a||700<=+a}]],italic:["em","i",["span",function(a){return"italic"==
a.styles["font-style"]}]],underline:["u",["span",function(a){return"underline"==a.styles["text-decoration"]}]],strike:["s","strike",["span",function(a){return"line-through"==a.styles["text-decoration"]}]],subscript:["sub"],superscript:["sup"]},b=c.config,a=c.lang.basicstyles;d("Bold",a.bold,"bold",b.coreStyles_bold);d("Italic",a.italic,"italic",b.coreStyles_italic);d("Underline",a.underline,"underline",b.coreStyles_underline);d("Strike",a.strike,"strike",b.coreStyles_strike);d("Subscript",a.subscript,
"subscript",b.coreStyles_subscript);d("Superscript",a.superscript,"superscript",b.coreStyles_superscript);c.setKeystroke([[CKEDITOR.CTRL+66,"bold"],[CKEDITOR.CTRL+73,"italic"],[CKEDITOR.CTRL+85,"underline"]])}});CKEDITOR.config.coreStyles_bold={element:"strong",overrides:"b"};CKEDITOR.config.coreStyles_italic={element:"em",overrides:"i"};CKEDITOR.config.coreStyles_underline={element:"u"};CKEDITOR.config.coreStyles_strike={element:"s",overrides:"strike"};CKEDITOR.config.coreStyles_subscript={element:"sub"};
CKEDITOR.config.coreStyles_superscript={element:"sup"};(function(){function q(a,f,d,b){if(!a.isReadOnly()&&!a.equals(d.editable())){CKEDITOR.dom.element.setMarker(b,a,"bidi_processed",1);b=a;for(var c=d.editable();(b=b.getParent())&&!b.equals(c);)if(b.getCustomData("bidi_processed")){a.removeStyle("direction");a.removeAttribute("dir");return}b="useComputedState"in d.config?d.config.useComputedState:1;(b?a.getComputedStyle("direction"):a.getStyle("direction")||a.hasAttribute("dir"))!=f&&(a.removeStyle("direction"),b?(a.removeAttribute("dir"),f!=a.getComputedStyle("direction")&&
a.setAttribute("dir",f)):a.setAttribute("dir",f),d.forceNextSelectionCheck())}}function v(a,f,d){var b=a.getCommonAncestor(!1,!0);a=a.clone();a.enlarge(d==CKEDITOR.ENTER_BR?CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS:CKEDITOR.ENLARGE_BLOCK_CONTENTS);if(a.checkBoundaryOfElement(b,CKEDITOR.START)&&a.checkBoundaryOfElement(b,CKEDITOR.END)){for(var c;b&&b.type==CKEDITOR.NODE_ELEMENT&&(c=b.getParent())&&1==c.getChildCount()&&!(b.getName()in f);)b=c;return b.type==CKEDITOR.NODE_ELEMENT&&b.getName()in f&&b}}function p(a){return{context:"p",
allowedContent:{"h1 h2 h3 h4 h5 h6 table ul ol blockquote div tr p div li td":{propertiesOnly:!0,attributes:"dir"}},requiredContent:"p[dir]",refresh:function(a,d){var b=a.config.useComputedState,c,b=void 0===b||b;if(!b){c=d.lastElement;for(var h=a.editable();c&&!(c.getName()in u||c.equals(h));){var e=c.getParent();if(!e)break;c=e}}c=c||d.block||d.blockLimit;c.equals(a.editable())&&(h=a.getSelection().getRanges()[0].getEnclosedNode())&&h.type==CKEDITOR.NODE_ELEMENT&&(c=h);c&&(b=b?c.getComputedStyle("direction"):
c.getStyle("direction")||c.getAttribute("dir"),a.getCommand("bidirtl").setState("rtl"==b?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF),a.getCommand("bidiltr").setState("ltr"==b?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF));b=(d.block||d.blockLimit||a.editable()).getDirection(1);b!=(a._.selDir||a.lang.dir)&&(a._.selDir=b,a.fire("contentDirChanged",b))},exec:function(f){var d=f.getSelection(),b=f.config.enterMode,c=d.getRanges();if(c&&c.length){for(var h={},e=d.createBookmarks(),c=c.createIterator(),g,
l=0;g=c.getNextRange(1);){var k=g.getEnclosedNode();k&&(!k||k.type==CKEDITOR.NODE_ELEMENT&&k.getName()in r)||(k=v(g,t,b));k&&q(k,a,f,h);var m=new CKEDITOR.dom.walker(g),n=e[l].startNode,p=e[l++].endNode;m.evaluator=function(a){var c=b==CKEDITOR.ENTER_P?"p":"div",d;if(d=(a?a.type==CKEDITOR.NODE_ELEMENT:!1)&&a.getName()in t){if(c=a.is(c))c=(c=a.getParent())?c.type==CKEDITOR.NODE_ELEMENT:!1;d=!(c&&a.getParent().is("blockquote"))}return!!(d&&a.getPosition(n)&CKEDITOR.POSITION_FOLLOWING&&(a.getPosition(p)&
CKEDITOR.POSITION_PRECEDING+CKEDITOR.POSITION_CONTAINS)==CKEDITOR.POSITION_PRECEDING)};for(;k=m.next();)q(k,a,f,h);g=g.createIterator();for(g.enlargeBr=b!=CKEDITOR.ENTER_BR;k=g.getNextParagraph(b==CKEDITOR.ENTER_P?"p":"div");)q(k,a,f,h)}CKEDITOR.dom.element.clearAllMarkers(h);f.forceNextSelectionCheck();d.selectBookmarks(e);f.focus()}}}}function w(a){var f=a==l.setAttribute,d=a==l.removeAttribute,b=/\bdirection\s*:\s*(.*?)\s*(:?$|;)/;return function(c,h){if(!this.isReadOnly()){var e;if(e=c==(f||d?
"dir":"direction")||"style"==c&&(d||b.test(h))){a:{e=this;for(var g=e.getDocument().getBody().getParent();e;){if(e.equals(g)){e=!1;break a}e=e.getParent()}e=!0}e=!e}if(e&&(e=this.getDirection(1),g=a.apply(this,arguments),e!=this.getDirection(1)))return this.getDocument().fire("dirChanged",this),g}return a.apply(this,arguments)}}var t={table:1,ul:1,ol:1,blockquote:1,div:1},r={},u={};CKEDITOR.tools.extend(r,t,{tr:1,p:1,div:1,li:1});CKEDITOR.tools.extend(u,r,{td:1});CKEDITOR.plugins.add("bidi",{init:function(a){function f(b,
c,d,e,f){a.addCommand(d,new CKEDITOR.command(a,e));a.ui.addButton&&a.ui.addButton(b,{label:c,command:d,toolbar:"bidi,"+f})}if(!a.blockless){var d=a.lang.bidi;f("BidiLtr",d.ltr,"bidiltr",p("ltr"),10);f("BidiRtl",d.rtl,"bidirtl",p("rtl"),20);a.on("contentDom",function(){a.document.on("dirChanged",function(b){a.fire("dirChanged",{node:b.data,dir:b.data.getDirection(1)})})});a.on("contentDirChanged",function(b){b=(a.lang.dir!=b.data?"add":"remove")+"Class";var c=a.ui.space(a.config.toolbarLocation);if(c)c[b]("cke_mixed_dir_content")})}}});
for(var l=CKEDITOR.dom.element.prototype,n=["setStyle","removeStyle","setAttribute","removeAttribute"],m=0;m<n.length;m++)l[n[m]]=CKEDITOR.tools.override(l[n[m]],w)})();(function(){var m={exec:function(g){var a=g.getCommand("blockquote").state,k=g.getSelection(),c=k&&k.getRanges()[0];if(c){var h=k.createBookmarks();if(CKEDITOR.env.ie){var e=h[0].startNode,b=h[0].endNode,d;if(e&&"blockquote"==e.getParent().getName())for(d=e;d=d.getNext();)if(d.type==CKEDITOR.NODE_ELEMENT&&d.isBlockBoundary()){e.move(d,!0);break}if(b&&"blockquote"==b.getParent().getName())for(d=b;d=d.getPrevious();)if(d.type==CKEDITOR.NODE_ELEMENT&&d.isBlockBoundary()){b.move(d);break}}var f=c.createIterator();
f.enlargeBr=g.config.enterMode!=CKEDITOR.ENTER_BR;if(a==CKEDITOR.TRISTATE_OFF){for(e=[];a=f.getNextParagraph();)e.push(a);1>e.length&&(a=g.document.createElement(g.config.enterMode==CKEDITOR.ENTER_P?"p":"div"),b=h.shift(),c.insertNode(a),a.append(new CKEDITOR.dom.text("﻿",g.document)),c.moveToBookmark(b),c.selectNodeContents(a),c.collapse(!0),b=c.createBookmark(),e.push(a),h.unshift(b));d=e[0].getParent();c=[];for(b=0;b<e.length;b++)a=e[b],d=d.getCommonAncestor(a.getParent());for(a={table:1,tbody:1,
tr:1,ol:1,ul:1};a[d.getName()];)d=d.getParent();for(b=null;0<e.length;){for(a=e.shift();!a.getParent().equals(d);)a=a.getParent();a.equals(b)||c.push(a);b=a}for(;0<c.length;)if(a=c.shift(),"blockquote"==a.getName()){for(b=new CKEDITOR.dom.documentFragment(g.document);a.getFirst();)b.append(a.getFirst().remove()),e.push(b.getLast());b.replace(a)}else e.push(a);c=g.document.createElement("blockquote");for(c.insertBefore(e[0]);0<e.length;)a=e.shift(),c.append(a)}else if(a==CKEDITOR.TRISTATE_ON){b=[];
for(d={};a=f.getNextParagraph();){for(e=c=null;a.getParent();){if("blockquote"==a.getParent().getName()){c=a.getParent();e=a;break}a=a.getParent()}c&&e&&!e.getCustomData("blockquote_moveout")&&(b.push(e),CKEDITOR.dom.element.setMarker(d,e,"blockquote_moveout",!0))}CKEDITOR.dom.element.clearAllMarkers(d);a=[];e=[];for(d={};0<b.length;)f=b.shift(),c=f.getParent(),f.getPrevious()?f.getNext()?(f.breakParent(f.getParent()),e.push(f.getNext())):f.remove().insertAfter(c):f.remove().insertBefore(c),c.getCustomData("blockquote_processed")||
(e.push(c),CKEDITOR.dom.element.setMarker(d,c,"blockquote_processed",!0)),a.push(f);CKEDITOR.dom.element.clearAllMarkers(d);for(b=e.length-1;0<=b;b--){c=e[b];a:{d=c;for(var f=0,m=d.getChildCount(),l=void 0;f<m&&(l=d.getChild(f));f++)if(l.type==CKEDITOR.NODE_ELEMENT&&l.isBlockBoundary()){d=!1;break a}d=!0}d&&c.remove()}if(g.config.enterMode==CKEDITOR.ENTER_BR)for(c=!0;a.length;)if(f=a.shift(),"div"==f.getName()){b=new CKEDITOR.dom.documentFragment(g.document);!c||!f.getPrevious()||f.getPrevious().type==
CKEDITOR.NODE_ELEMENT&&f.getPrevious().isBlockBoundary()||b.append(g.document.createElement("br"));for(c=f.getNext()&&!(f.getNext().type==CKEDITOR.NODE_ELEMENT&&f.getNext().isBlockBoundary());f.getFirst();)f.getFirst().remove().appendTo(b);c&&b.append(g.document.createElement("br"));b.replace(f);c=!1}}k.selectBookmarks(h);g.focus()}},refresh:function(g,a){this.setState(g.elementPath(a.block||a.blockLimit).contains("blockquote",1)?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF)},context:"blockquote",allowedContent:"blockquote",
requiredContent:"blockquote"};CKEDITOR.plugins.add("blockquote",{init:function(g){g.blockless||(g.addCommand("blockquote",m),g.ui.addButton&&g.ui.addButton("Blockquote",{label:g.lang.blockquote.toolbar,command:"blockquote",toolbar:"blocks,10"}))}})})();(function(){function q(b,a){CKEDITOR.tools.extend(this,a,{editor:b,id:"cke-"+CKEDITOR.tools.getUniqueId(),area:b._.notificationArea});a.type||(this.type="info");this.element=this._createElement();b.plugins.clipboard&&CKEDITOR.plugins.clipboard.preventDefaultDropOnElement(this.element)}function r(b){var a=this;this.editor=b;this.notifications=[];this.element=this._createElement();this._uiBuffer=CKEDITOR.tools.eventsBuffer(10,this._layout,this);this._changeBuffer=CKEDITOR.tools.eventsBuffer(500,this._layout,
this);b.on("destroy",function(){a._removeListeners();a.element.remove()})}CKEDITOR.plugins.add("notification",{init:function(b){function a(b){var a=new CKEDITOR.dom.element("div");a.setStyles({position:"fixed","margin-left":"-9999px"});a.setAttributes({"aria-live":"assertive","aria-atomic":"true"});a.setText(b);CKEDITOR.document.getBody().append(a);setTimeout(function(){a.remove()},100)}b._.notificationArea=new r(b);b.showNotification=function(a,d,e){var f,l;"progress"==d?f=e:l=e;a=new CKEDITOR.plugins.notification(b,
{message:a,type:d,progress:f,duration:l});a.show();return a};b.on("key",function(c){if(27==c.data.keyCode){var d=b._.notificationArea.notifications;d.length&&(a(b.lang.notification.closed),d[d.length-1].hide(),c.cancel())}})}});q.prototype={show:function(){!1!==this.editor.fire("notificationShow",{notification:this})&&(this.area.add(this),this._hideAfterTimeout())},update:function(b){var a=!0;!1===this.editor.fire("notificationUpdate",{notification:this,options:b})&&(a=!1);var c=this.element,d=c.findOne(".cke_notification_message"),
e=c.findOne(".cke_notification_progress"),f=b.type;c.removeAttribute("role");b.progress&&"progress"!=this.type&&(f="progress");f&&(c.removeClass(this._getClass()),c.removeAttribute("aria-label"),this.type=f,c.addClass(this._getClass()),c.setAttribute("aria-label",this.type),"progress"!=this.type||e?"progress"!=this.type&&e&&e.remove():(e=this._createProgressElement(),e.insertBefore(d)));void 0!==b.message&&(this.message=b.message,d.setHtml(this.message));void 0!==b.progress&&(this.progress=b.progress,
e&&e.setStyle("width",this._getPercentageProgress()));a&&b.important&&(c.setAttribute("role","alert"),this.isVisible()||this.area.add(this));this.duration=b.duration;this._hideAfterTimeout()},hide:function(){!1!==this.editor.fire("notificationHide",{notification:this})&&this.area.remove(this)},isVisible:function(){return 0<=CKEDITOR.tools.indexOf(this.area.notifications,this)},_createElement:function(){var b=this,a,c,d=this.editor.lang.common.close;a=new CKEDITOR.dom.element("div");a.addClass("cke_notification");
a.addClass(this._getClass());a.setAttributes({id:this.id,role:"alert","aria-label":this.type});"progress"==this.type&&a.append(this._createProgressElement());c=new CKEDITOR.dom.element("p");c.addClass("cke_notification_message");c.setHtml(this.message);a.append(c);c=CKEDITOR.dom.element.createFromHtml('\x3ca class\x3d"cke_notification_close" href\x3d"javascript:void(0)" title\x3d"'+d+'" role\x3d"button" tabindex\x3d"-1"\x3e\x3cspan class\x3d"cke_label"\x3eX\x3c/span\x3e\x3c/a\x3e');a.append(c);c.on("click",
function(){b.editor.focus();b.hide()});return a},_getClass:function(){return"progress"==this.type?"cke_notification_info":"cke_notification_"+this.type},_createProgressElement:function(){var b=new CKEDITOR.dom.element("span");b.addClass("cke_notification_progress");b.setStyle("width",this._getPercentageProgress());return b},_getPercentageProgress:function(){return Math.round(100*(this.progress||0))+"%"},_hideAfterTimeout:function(){var b=this,a;this._hideTimeoutId&&clearTimeout(this._hideTimeoutId);
if("number"==typeof this.duration)a=this.duration;else if("info"==this.type||"success"==this.type)a="number"==typeof this.editor.config.notification_duration?this.editor.config.notification_duration:5E3;a&&(b._hideTimeoutId=setTimeout(function(){b.hide()},a))}};r.prototype={add:function(b){this.notifications.push(b);this.element.append(b.element);1==this.element.getChildCount()&&(CKEDITOR.document.getBody().append(this.element),this._attachListeners());this._layout()},remove:function(b){var a=CKEDITOR.tools.indexOf(this.notifications,
b);0>a||(this.notifications.splice(a,1),b.element.remove(),this.element.getChildCount()||(this._removeListeners(),this.element.remove()))},_createElement:function(){var b=this.editor,a=b.config,c=new CKEDITOR.dom.element("div");c.addClass("cke_notifications_area");c.setAttribute("id","cke_notifications_area_"+b.name);c.setStyle("z-index",a.baseFloatZIndex-2);return c},_attachListeners:function(){var b=CKEDITOR.document.getWindow(),a=this.editor;b.on("scroll",this._uiBuffer.input);b.on("resize",this._uiBuffer.input);
a.on("change",this._changeBuffer.input);a.on("floatingSpaceLayout",this._layout,this,null,20);a.on("blur",this._layout,this,null,20)},_removeListeners:function(){var b=CKEDITOR.document.getWindow(),a=this.editor;b.removeListener("scroll",this._uiBuffer.input);b.removeListener("resize",this._uiBuffer.input);a.removeListener("change",this._changeBuffer.input);a.removeListener("floatingSpaceLayout",this._layout);a.removeListener("blur",this._layout)},_layout:function(){function b(){a.setStyle("left",
k(n+d.width-g-h))}var a=this.element,c=this.editor,d=c.ui.contentsElement.getClientRect(),e=c.ui.contentsElement.getDocumentPosition(),f,l,u=a.getClientRect(),m,g=this._notificationWidth,h=this._notificationMargin;m=CKEDITOR.document.getWindow();var p=m.getScrollPosition(),t=m.getViewPaneSize(),q=CKEDITOR.document.getBody(),r=q.getDocumentPosition(),k=CKEDITOR.tools.cssLength;g&&h||(m=this.element.getChild(0),g=this._notificationWidth=m.getClientRect().width,h=this._notificationMargin=parseInt(m.getComputedStyle("margin-left"),
10)+parseInt(m.getComputedStyle("margin-right"),10));c.toolbar&&(f=c.ui.space("top"),l=f.getClientRect());f&&f.isVisible()&&l.bottom>d.top&&l.bottom<d.bottom-u.height?a.setStyles({position:"fixed",top:k(l.bottom)}):0<d.top?a.setStyles({position:"absolute",top:k(e.y)}):e.y+d.height-u.height>p.y?a.setStyles({position:"fixed",top:0}):a.setStyles({position:"absolute",top:k(e.y+d.height-u.height)});var n="fixed"==a.getStyle("position")?d.left:"static"!=q.getComputedStyle("position")?e.x-r.x:e.x;d.width<
g+h?e.x+g+h>p.x+t.width?b():a.setStyle("left",k(n)):e.x+g+h>p.x+t.width?a.setStyle("left",k(n)):e.x+d.width/2+g/2+h>p.x+t.width?a.setStyle("left",k(n-e.x+p.x+t.width-g-h)):0>d.left+d.width-g-h?b():0>d.left+d.width/2-g/2?a.setStyle("left",k(n-e.x+p.x)):a.setStyle("left",k(n+d.width/2-g/2-h/2))}};CKEDITOR.plugins.notification=q})();(function(){var c='\x3ca id\x3d"{id}" class\x3d"cke_button cke_button__{name} cke_button_{state} {cls}"'+(CKEDITOR.env.gecko&&!CKEDITOR.env.hc?"":" href\x3d\"javascript:void('{titleJs}')\"")+' title\x3d"{title}" tabindex\x3d"-1" hidefocus\x3d"true" role\x3d"button" aria-labelledby\x3d"{id}_label" aria-describedby\x3d"{id}_description" aria-haspopup\x3d"{hasArrow}" aria-disabled\x3d"{ariaDisabled}"';CKEDITOR.env.gecko&&CKEDITOR.env.mac&&(c+=' onkeypress\x3d"return false;"');CKEDITOR.env.gecko&&(c+=
' onblur\x3d"this.style.cssText \x3d this.style.cssText;"');var c=c+(' onkeydown\x3d"return CKEDITOR.tools.callFunction({keydownFn},event);" onfocus\x3d"return CKEDITOR.tools.callFunction({focusFn},event);" '+(CKEDITOR.env.ie?'onclick\x3d"return false;" onmouseup':"onclick")+'\x3d"CKEDITOR.tools.callFunction({clickFn},this);return false;"\x3e\x3cspan class\x3d"cke_button_icon cke_button__{iconName}_icon" style\x3d"{style}"'),c=c+'\x3e\x26nbsp;\x3c/span\x3e\x3cspan id\x3d"{id}_label" class\x3d"cke_button_label cke_button__{name}_label" aria-hidden\x3d"false"\x3e{label}\x3c/span\x3e\x3cspan id\x3d"{id}_description" class\x3d"cke_button_label" aria-hidden\x3d"false"\x3e{ariaShortcut}\x3c/span\x3e{arrowHtml}\x3c/a\x3e',
v=CKEDITOR.addTemplate("buttonArrow",'\x3cspan class\x3d"cke_button_arrow"\x3e'+(CKEDITOR.env.hc?"\x26#9660;":"")+"\x3c/span\x3e"),w=CKEDITOR.addTemplate("button",c);CKEDITOR.plugins.add("button",{beforeInit:function(a){a.ui.addHandler(CKEDITOR.UI_BUTTON,CKEDITOR.ui.button.handler)}});CKEDITOR.UI_BUTTON="button";CKEDITOR.ui.button=function(a){CKEDITOR.tools.extend(this,a,{title:a.label,click:a.click||function(b){b.execCommand(a.command)}});this._={}};CKEDITOR.ui.button.handler={create:function(a){return new CKEDITOR.ui.button(a)}};
CKEDITOR.ui.button.prototype={render:function(a,b){function c(){var f=a.mode;f&&(f=this.modes[f]?void 0!==n[f]?n[f]:CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,f=a.readOnly&&!this.readOnly?CKEDITOR.TRISTATE_DISABLED:f,this.setState(f),this.refresh&&this.refresh())}var n=null,p=CKEDITOR.env,q=this._.id=CKEDITOR.tools.getNextId(),g="",d=this.command,t,k,l;this._.editor=a;var e={id:q,button:this,editor:a,focus:function(){CKEDITOR.document.getById(q).focus()},execute:function(){this.button.click(a)},
attach:function(a){this.button.attach(a)}},x=CKEDITOR.tools.addFunction(function(a){if(e.onkey)return a=new CKEDITOR.dom.event(a),!1!==e.onkey(e,a.getKeystroke())}),y=CKEDITOR.tools.addFunction(function(a){var b;e.onfocus&&(b=!1!==e.onfocus(e,new CKEDITOR.dom.event(a)));return b}),u=0;e.clickFn=t=CKEDITOR.tools.addFunction(function(){u&&(a.unlockSelection(1),u=0);e.execute();p.iOS&&a.focus()});this.modes?(n={},a.on("beforeModeUnload",function(){a.mode&&this._.state!=CKEDITOR.TRISTATE_DISABLED&&(n[a.mode]=
this._.state)},this),a.on("activeFilterChange",c,this),a.on("mode",c,this),!this.readOnly&&a.on("readOnly",c,this)):d&&(d=a.getCommand(d))&&(d.on("state",function(){this.setState(d.state)},this),g+=d.state==CKEDITOR.TRISTATE_ON?"on":d.state==CKEDITOR.TRISTATE_DISABLED?"disabled":"off");var m;if(this.directional)a.on("contentDirChanged",function(b){var c=CKEDITOR.document.getById(this._.id),d=c.getFirst();b=b.data;b!=a.lang.dir?c.addClass("cke_"+b):c.removeClass("cke_ltr").removeClass("cke_rtl");d.setAttribute("style",
CKEDITOR.skin.getIconStyle(m,"rtl"==b,this.icon,this.iconOffset))},this);d?(k=a.getCommandKeystroke(d))&&(l=CKEDITOR.tools.keystrokeToString(a.lang.common.keyboard,k)):g+="off";k=this.name||this.command;var h=null,r=this.icon;m=k;this.icon&&!/\./.test(this.icon)?(m=this.icon,r=null):(this.icon&&(h=this.icon),CKEDITOR.env.hidpi&&this.iconHiDpi&&(h=this.iconHiDpi));h?(CKEDITOR.skin.addIcon(h,h),r=null):h=m;g={id:q,name:k,iconName:m,label:this.label,cls:this.className||"",state:g,ariaDisabled:"disabled"==
g?"true":"false",title:this.title+(l?" ("+l.display+")":""),ariaShortcut:l?a.lang.common.keyboardShortcut+" "+l.aria:"",titleJs:p.gecko&&!p.hc?"":(this.title||"").replace("'",""),hasArrow:this.hasArrow?"true":"false",keydownFn:x,focusFn:y,clickFn:t,style:CKEDITOR.skin.getIconStyle(h,"rtl"==a.lang.dir,r,this.iconOffset),arrowHtml:this.hasArrow?v.output():""};w.output(g,b);if(this.onRender)this.onRender();return e},setState:function(a){if(this._.state==a)return!1;this._.state=a;var b=CKEDITOR.document.getById(this._.id);
return b?(b.setState(a,"cke_button"),a==CKEDITOR.TRISTATE_DISABLED?b.setAttribute("aria-disabled",!0):b.removeAttribute("aria-disabled"),this.hasArrow?(a=a==CKEDITOR.TRISTATE_ON?this._.editor.lang.button.selectedLabel.replace(/%1/g,this.label):this.label,CKEDITOR.document.getById(this._.id+"_label").setText(a)):a==CKEDITOR.TRISTATE_ON?b.setAttribute("aria-pressed",!0):b.removeAttribute("aria-pressed"),!0):!1},getState:function(){return this._.state},toFeature:function(a){if(this._.feature)return this._.feature;
var b=this;this.allowedContent||this.requiredContent||!this.command||(b=a.getCommand(this.command)||b);return this._.feature=b}};CKEDITOR.ui.prototype.addButton=function(a,b){this.add(a,CKEDITOR.UI_BUTTON,b)}})();(function(){function D(a){function d(){for(var b=f(),e=CKEDITOR.tools.clone(a.config.toolbarGroups)||v(a),n=0;n<e.length;n++){var g=e[n];if("/"!=g){"string"==typeof g&&(g=e[n]={name:g});var l,d=g.groups;if(d)for(var h=0;h<d.length;h++)l=d[h],(l=b[l])&&c(g,l);(l=b[g.name])&&c(g,l)}}return e}function f(){var b={},c,e,g;for(c in a.ui.items)e=a.ui.items[c],g=e.toolbar||"others",g=g.split(","),e=g[0],g=parseInt(g[1]||-1,10),b[e]||(b[e]=[]),b[e].push({name:c,order:g});for(e in b)b[e]=b[e].sort(function(b,
a){return b.order==a.order?0:0>a.order?-1:0>b.order?1:b.order<a.order?-1:1});return b}function c(c,e){if(e.length){c.items?c.items.push(a.ui.create("-")):c.items=[];for(var d;d=e.shift();)d="string"==typeof d?d:d.name,b&&-1!=CKEDITOR.tools.indexOf(b,d)||(d=a.ui.create(d))&&a.addFeature(d)&&c.items.push(d)}}function h(b){var a=[],e,d,h;for(e=0;e<b.length;++e)d=b[e],h={},"/"==d?a.push(d):CKEDITOR.tools.isArray(d)?(c(h,CKEDITOR.tools.clone(d)),a.push(h)):d.items&&(c(h,CKEDITOR.tools.clone(d.items)),
h.name=d.name,a.push(h));return a}var b=a.config.removeButtons,b=b&&b.split(","),e=a.config.toolbar;"string"==typeof e&&(e=a.config["toolbar_"+e]);return a.toolbar=e?h(e):d()}function v(a){return a._.toolbarGroups||(a._.toolbarGroups=[{name:"document",groups:["mode","document","doctools"]},{name:"clipboard",groups:["clipboard","undo"]},{name:"editing",groups:["find","selection","spellchecker"]},{name:"forms"},"/",{name:"basicstyles",groups:["basicstyles","cleanup"]},{name:"paragraph",groups:["list",
"indent","blocks","align","bidi"]},{name:"links"},{name:"insert"},"/",{name:"styles"},{name:"colors"},{name:"tools"},{name:"others"},{name:"about"}])}var z=function(){this.toolbars=[];this.focusCommandExecuted=!1};z.prototype.focus=function(){for(var a=0,d;d=this.toolbars[a++];)for(var f=0,c;c=d.items[f++];)if(c.focus){c.focus();return}};var E={modes:{wysiwyg:1,source:1},readOnly:1,exec:function(a){a.toolbox&&(a.toolbox.focusCommandExecuted=!0,CKEDITOR.env.ie||CKEDITOR.env.air?setTimeout(function(){a.toolbox.focus()},
100):a.toolbox.focus())}};CKEDITOR.plugins.add("toolbar",{requires:"button",init:function(a){var d,f=function(c,h){var b,e="rtl"==a.lang.dir,k=a.config.toolbarGroupCycling,q=e?37:39,e=e?39:37,k=void 0===k||k;switch(h){case 9:case CKEDITOR.SHIFT+9:for(;!b||!b.items.length;)if(b=9==h?(b?b.next:c.toolbar.next)||a.toolbox.toolbars[0]:(b?b.previous:c.toolbar.previous)||a.toolbox.toolbars[a.toolbox.toolbars.length-1],b.items.length)for(c=b.items[d?b.items.length-1:0];c&&!c.focus;)(c=d?c.previous:c.next)||
(b=0);c&&c.focus();return!1;case q:b=c;do b=b.next,!b&&k&&(b=c.toolbar.items[0]);while(b&&!b.focus);b?b.focus():f(c,9);return!1;case 40:return c.button&&c.button.hasArrow?c.execute():f(c,40==h?q:e),!1;case e:case 38:b=c;do b=b.previous,!b&&k&&(b=c.toolbar.items[c.toolbar.items.length-1]);while(b&&!b.focus);b?b.focus():(d=1,f(c,CKEDITOR.SHIFT+9),d=0);return!1;case 27:return a.focus(),!1;case 13:case 32:return c.execute(),!1}return!0};a.on("uiSpace",function(c){if(c.data.space==a.config.toolbarLocation){c.removeListener();
a.toolbox=new z;var d=CKEDITOR.tools.getNextId(),b=['\x3cspan id\x3d"',d,'" class\x3d"cke_voice_label"\x3e',a.lang.toolbar.toolbars,"\x3c/span\x3e",'\x3cspan id\x3d"'+a.ui.spaceId("toolbox")+'" class\x3d"cke_toolbox" role\x3d"group" aria-labelledby\x3d"',d,'" onmousedown\x3d"return false;"\x3e'],d=!1!==a.config.toolbarStartupExpanded,e,k;a.config.toolbarCanCollapse&&a.elementMode!=CKEDITOR.ELEMENT_MODE_INLINE&&b.push('\x3cspan class\x3d"cke_toolbox_main"'+(d?"\x3e":' style\x3d"display:none"\x3e'));
for(var q=a.toolbox.toolbars,n=D(a),g=n.length,l=0;l<g;l++){var r,m=0,w,p=n[l],v="/"!==p&&("/"===n[l+1]||l==g-1),x;if(p)if(e&&(b.push("\x3c/span\x3e"),k=e=0),"/"===p)b.push('\x3cspan class\x3d"cke_toolbar_break"\x3e\x3c/span\x3e');else{x=p.items||p;for(var y=0;y<x.length;y++){var t=x[y],A;if(t){var B=function(c){c=c.render(a,b);u=m.items.push(c)-1;0<u&&(c.previous=m.items[u-1],c.previous.next=c);c.toolbar=m;c.onkey=f;c.onfocus=function(){a.toolbox.focusCommandExecuted||a.focus()}};if(t.type==CKEDITOR.UI_SEPARATOR)k=
e&&t;else{A=!1!==t.canGroup;if(!m){r=CKEDITOR.tools.getNextId();m={id:r,items:[]};w=p.name&&(a.lang.toolbar.toolbarGroups[p.name]||p.name);b.push('\x3cspan id\x3d"',r,'" class\x3d"cke_toolbar'+(v?' cke_toolbar_last"':'"'),w?' aria-labelledby\x3d"'+r+'_label"':"",' role\x3d"toolbar"\x3e');w&&b.push('\x3cspan id\x3d"',r,'_label" class\x3d"cke_voice_label"\x3e',w,"\x3c/span\x3e");b.push('\x3cspan class\x3d"cke_toolbar_start"\x3e\x3c/span\x3e');var u=q.push(m)-1;0<u&&(m.previous=q[u-1],m.previous.next=
m)}A?e||(b.push('\x3cspan class\x3d"cke_toolgroup" role\x3d"presentation"\x3e'),e=1):e&&(b.push("\x3c/span\x3e"),e=0);k&&(B(k),k=0);B(t)}}}e&&(b.push("\x3c/span\x3e"),k=e=0);m&&b.push('\x3cspan class\x3d"cke_toolbar_end"\x3e\x3c/span\x3e\x3c/span\x3e')}}a.config.toolbarCanCollapse&&b.push("\x3c/span\x3e");if(a.config.toolbarCanCollapse&&a.elementMode!=CKEDITOR.ELEMENT_MODE_INLINE){var C=CKEDITOR.tools.addFunction(function(){a.execCommand("toolbarCollapse")});a.on("destroy",function(){CKEDITOR.tools.removeFunction(C)});
a.addCommand("toolbarCollapse",{readOnly:1,exec:function(b){var a=b.ui.space("toolbar_collapser"),c=a.getPrevious(),d=b.ui.space("contents"),e=c.getParent(),h=parseInt(d.$.style.height,10),g=e.$.offsetHeight,f=a.hasClass("cke_toolbox_collapser_min");f?(c.show(),a.removeClass("cke_toolbox_collapser_min"),a.setAttribute("title",b.lang.toolbar.toolbarCollapse)):(c.hide(),a.addClass("cke_toolbox_collapser_min"),a.setAttribute("title",b.lang.toolbar.toolbarExpand));a.getFirst().setText(f?"▲":"◀");d.setStyle("height",
h-(e.$.offsetHeight-g)+"px");b.fire("resize",{outerHeight:b.container.$.offsetHeight,contentsHeight:d.$.offsetHeight,outerWidth:b.container.$.offsetWidth})},modes:{wysiwyg:1,source:1}});a.setKeystroke(CKEDITOR.ALT+(CKEDITOR.env.ie||CKEDITOR.env.webkit?189:109),"toolbarCollapse");b.push('\x3ca title\x3d"'+(d?a.lang.toolbar.toolbarCollapse:a.lang.toolbar.toolbarExpand)+'" id\x3d"'+a.ui.spaceId("toolbar_collapser")+'" tabIndex\x3d"-1" class\x3d"cke_toolbox_collapser');d||b.push(" cke_toolbox_collapser_min");
b.push('" onclick\x3d"CKEDITOR.tools.callFunction('+C+')"\x3e','\x3cspan class\x3d"cke_arrow"\x3e\x26#9650;\x3c/span\x3e',"\x3c/a\x3e")}b.push("\x3c/span\x3e");c.data.html+=b.join("")}});a.on("destroy",function(){if(this.toolbox){var a,d=0,b,e,f;for(a=this.toolbox.toolbars;d<a.length;d++)for(e=a[d].items,b=0;b<e.length;b++)f=e[b],f.clickFn&&CKEDITOR.tools.removeFunction(f.clickFn),f.keyDownFn&&CKEDITOR.tools.removeFunction(f.keyDownFn)}});a.on("uiReady",function(){var c=a.ui.space("toolbox");c&&a.focusManager.add(c,
1)});a.addCommand("toolbarFocus",E);a.setKeystroke(CKEDITOR.ALT+121,"toolbarFocus");a.ui.add("-",CKEDITOR.UI_SEPARATOR,{});a.ui.addHandler(CKEDITOR.UI_SEPARATOR,{create:function(){return{render:function(a,d){d.push('\x3cspan class\x3d"cke_toolbar_separator" role\x3d"separator"\x3e\x3c/span\x3e');return{}}}}})}});CKEDITOR.ui.prototype.addToolbarGroup=function(a,d,f){var c=v(this.editor),h=0===d,b={name:a};if(f){if(f=CKEDITOR.tools.search(c,function(a){return a.name==f})){!f.groups&&(f.groups=[]);if(d&&
(d=CKEDITOR.tools.indexOf(f.groups,d),0<=d)){f.groups.splice(d+1,0,a);return}h?f.groups.splice(0,0,a):f.groups.push(a);return}d=null}d&&(d=CKEDITOR.tools.indexOf(c,function(a){return a.name==d}));h?c.splice(0,0,a):"number"==typeof d?c.splice(d+1,0,b):c.push(a)}})();CKEDITOR.UI_SEPARATOR="separator";CKEDITOR.config.toolbarLocation="top";(function(){function r(a,b,c){b.type||(b.type="auto");if(c&&!1===a.fire("beforePaste",b)||!b.dataValue&&b.dataTransfer.isEmpty())return!1;b.dataValue||(b.dataValue="");if(CKEDITOR.env.gecko&&"drop"==b.method&&a.toolbox)a.once("afterPaste",function(){a.toolbox.focus()});return a.fire("paste",b)}function x(a){function b(){var b=a.editable();if(CKEDITOR.plugins.clipboard.isCustomCopyCutSupported){var c=function(b){a.getSelection().isCollapsed()||(a.readOnly&&"cut"==b.name||p.initPasteDataTransfer(b,
a),b.data.preventDefault())};b.on("copy",c);b.on("cut",c);b.on("cut",function(){a.readOnly||a.extractSelectedHtml()},null,null,999)}b.on(p.mainPasteEvent,function(a){"beforepaste"==p.mainPasteEvent&&m||k(a)});"beforepaste"==p.mainPasteEvent&&(b.on("paste",function(a){u||(g(),a.data.preventDefault(),k(a),e("paste"))}),b.on("contextmenu",h,null,null,0),b.on("beforepaste",function(a){!a.data||a.data.$.ctrlKey||a.data.$.shiftKey||h()},null,null,0));b.on("beforecut",function(){!m&&f(a)});var d;b.attachListener(CKEDITOR.env.ie?
b:a.document.getDocumentElement(),"mouseup",function(){d=setTimeout(function(){t()},0)});a.on("destroy",function(){clearTimeout(d)});b.on("keyup",t)}function c(b){return{type:b,canUndo:"cut"==b,startDisabled:!0,fakeKeystroke:"cut"==b?CKEDITOR.CTRL+88:CKEDITOR.CTRL+67,exec:function(){"cut"==this.type&&f();var b;var c=this.type;if(CKEDITOR.env.ie)b=e(c);else try{b=a.document.$.execCommand(c,!1,null)}catch(d){b=!1}b||a.showNotification(a.lang.clipboard[this.type+"Error"]);return b}}}function d(){return{canUndo:!1,
async:!0,fakeKeystroke:CKEDITOR.CTRL+86,exec:function(a,b){function c(b,h){h="undefined"!==typeof h?h:!0;b?(b.method="paste",b.dataTransfer||(b.dataTransfer=p.initPasteDataTransfer()),r(a,b,h)):e&&!a._.forcePasteDialog&&a.showNotification(n,"info",a.config.clipboard_notificationDuration);a._.forcePasteDialog=!1;a.fire("afterCommandExec",{name:"paste",command:d,returnValue:!!b})}b="undefined"!==typeof b&&null!==b?b:{};var d=this,e="undefined"!==typeof b.notification?b.notification:!0,h=b.type,f=CKEDITOR.tools.keystrokeToString(a.lang.common.keyboard,
a.getCommandKeystroke(this)),n="string"===typeof e?e:a.lang.clipboard.pasteNotification.replace(/%1/,'\x3ckbd aria-label\x3d"'+f.aria+'"\x3e'+f.display+"\x3c/kbd\x3e"),f="string"===typeof b?b:b.dataValue;h&&!0!==a.config.forcePasteAsPlainText&&"allow-word"!==a.config.forcePasteAsPlainText?a._.nextPasteType=h:delete a._.nextPasteType;"string"===typeof f?c({dataValue:f}):a.getClipboardData(c)}}}function g(){u=1;setTimeout(function(){u=0},100)}function h(){m=1;setTimeout(function(){m=0},10)}function e(b){var c=
a.document,d=c.getBody(),e=!1,h=function(){e=!0};d.on(b,h);7<CKEDITOR.env.version?c.$.execCommand(b):c.$.selection.createRange().execCommand(b);d.removeListener(b,h);return e}function f(){if(CKEDITOR.env.ie&&!CKEDITOR.env.quirks){var b=a.getSelection(),c,d,e;b.getType()==CKEDITOR.SELECTION_ELEMENT&&(c=b.getSelectedElement())&&(d=b.getRanges()[0],e=a.document.createText(""),e.insertBefore(c),d.setStartBefore(e),d.setEndAfter(c),b.selectRanges([d]),setTimeout(function(){c.getParent()&&(e.remove(),b.selectElement(c))},
0))}}function l(b,c){var d=a.document,e=a.editable(),h=function(a){a.cancel()},f;if(!d.getById("cke_pastebin")){var n=a.getSelection(),g=n.createBookmarks();CKEDITOR.env.ie&&n.root.fire("selectionchange");var k=new CKEDITOR.dom.element(!CKEDITOR.env.webkit&&!e.is("body")||CKEDITOR.env.ie?"div":"body",d);k.setAttributes({id:"cke_pastebin","data-cke-temp":"1"});var l=0,d=d.getWindow();CKEDITOR.env.webkit?(e.append(k),k.addClass("cke_editable"),e.is("body")||(l="static"!=e.getComputedStyle("position")?
e:CKEDITOR.dom.element.get(e.$.offsetParent),l=l.getDocumentPosition().y)):e.getAscendant(CKEDITOR.env.ie?"body":"html",1).append(k);k.setStyles({position:"absolute",top:d.getScrollPosition().y-l+10+"px",width:"1px",height:Math.max(1,d.getViewPaneSize().height-20)+"px",overflow:"hidden",margin:0,padding:0});CKEDITOR.env.safari&&k.setStyles(CKEDITOR.tools.cssVendorPrefix("user-select","text"));(l=k.getParent().isReadOnly())?(k.setOpacity(0),k.setAttribute("contenteditable",!0)):k.setStyle("ltr"==a.config.contentsLangDirection?
"left":"right","-10000px");a.on("selectionChange",h,null,null,0);if(CKEDITOR.env.webkit||CKEDITOR.env.gecko)f=e.once("blur",h,null,null,-100);l&&k.focus();l=new CKEDITOR.dom.range(k);l.selectNodeContents(k);var t=l.select();CKEDITOR.env.ie&&(f=e.once("blur",function(){a.lockSelection(t)}));var q=CKEDITOR.document.getWindow().getScrollPosition().y;setTimeout(function(){CKEDITOR.env.webkit&&(CKEDITOR.document.getBody().$.scrollTop=q);f&&f.removeListener();CKEDITOR.env.ie&&e.focus();n.selectBookmarks(g);
k.remove();var b;CKEDITOR.env.webkit&&(b=k.getFirst())&&b.is&&b.hasClass("Apple-style-span")&&(k=b);a.removeListener("selectionChange",h);c(k.getHtml())},0)}}function y(){if("paste"==p.mainPasteEvent)return a.fire("beforePaste",{type:"auto",method:"paste"}),!1;a.focus();g();var b=a.focusManager;b.lock();if(a.editable().fire(p.mainPasteEvent)&&!e("paste"))return b.unlock(),!1;b.unlock();return!0}function n(b){if("wysiwyg"==a.mode)switch(b.data.keyCode){case CKEDITOR.CTRL+86:case CKEDITOR.SHIFT+45:b=
a.editable();g();"paste"==p.mainPasteEvent&&b.fire("beforepaste");break;case CKEDITOR.CTRL+88:case CKEDITOR.SHIFT+46:a.fire("saveSnapshot"),setTimeout(function(){a.fire("saveSnapshot")},50)}}function k(b){var c={type:"auto",method:"paste",dataTransfer:p.initPasteDataTransfer(b)};c.dataTransfer.cacheData();var d=!1!==a.fire("beforePaste",c);d&&p.canClipboardApiBeTrusted(c.dataTransfer,a)?(b.data.preventDefault(),setTimeout(function(){r(a,c)},0)):l(b,function(b){c.dataValue=b.replace(/<span[^>]+data-cke-bookmark[^<]*?<\/span>/ig,
"");d&&r(a,c)})}function t(){if("wysiwyg"==a.mode){var b=q("paste");a.getCommand("cut").setState(q("cut"));a.getCommand("copy").setState(q("copy"));a.getCommand("paste").setState(b);a.fire("pasteState",b)}}function q(b){if(v&&b in{paste:1,cut:1})return CKEDITOR.TRISTATE_DISABLED;if("paste"==b)return CKEDITOR.TRISTATE_OFF;b=a.getSelection();var c=b.getRanges();return b.getType()==CKEDITOR.SELECTION_NONE||1==c.length&&c[0].collapsed?CKEDITOR.TRISTATE_DISABLED:CKEDITOR.TRISTATE_OFF}var p=CKEDITOR.plugins.clipboard,
m=0,u=0,v=0;(function(){a.on("key",n);a.on("contentDom",b);a.on("selectionChange",function(a){v=a.data.selection.getRanges()[0].checkReadOnly();t()});if(a.contextMenu){a.contextMenu.addListener(function(a,b){v=b.getRanges()[0].checkReadOnly();return{cut:q("cut"),copy:q("copy"),paste:q("paste")}});var c=null;a.on("menuShow",function(){c&&(c.removeListener(),c=null);var b=a.contextMenu.findItemByCommandName("paste");b&&b.element&&(c=b.element.on("touchend",function(){a._.forcePasteDialog=!0}))})}if(a.ui.addButton)a.once("instanceReady",
function(){a._.pasteButtons&&CKEDITOR.tools.array.forEach(a._.pasteButtons,function(b){if(b=a.ui.get(b))if(b=CKEDITOR.document.getById(b._.id))b.on("touchend",function(){a._.forcePasteDialog=!0})})})})();(function(){function b(c,d,e,h,f){var n=a.lang.clipboard[d];a.addCommand(d,e);a.ui.addButton&&a.ui.addButton(c,{label:n,command:d,toolbar:"clipboard,"+h});a.addMenuItems&&a.addMenuItem(d,{label:n,command:d,group:"clipboard",order:f})}b("Cut","cut",c("cut"),10,1);b("Copy","copy",c("copy"),20,4);b("Paste",
"paste",d(),30,8);a._.pasteButtons||(a._.pasteButtons=[]);a._.pasteButtons.push("Paste")})();a.getClipboardData=function(b,c){function d(a){a.removeListener();a.cancel();c(a.data)}function e(a){a.removeListener();a.cancel();c({type:f,dataValue:a.data.dataValue,dataTransfer:a.data.dataTransfer,method:"paste"})}var h=!1,f="auto";c||(c=b,b=null);a.on("beforePaste",function(a){a.removeListener();h=!0;f=a.data.type},null,null,1E3);a.on("paste",d,null,null,0);!1===y()&&(a.removeListener("paste",d),a._.forcePasteDialog&&
h&&a.fire("pasteDialog")?(a.on("pasteDialogCommit",e),a.on("dialogHide",function(a){a.removeListener();a.data.removeListener("pasteDialogCommit",e);a.data._.committed||c(null)})):c(null))}}function z(a){if(CKEDITOR.env.webkit){if(!a.match(/^[^<]*$/g)&&!a.match(/^(<div><br( ?\/)?><\/div>|<div>[^<]*<\/div>)*$/gi))return"html"}else if(CKEDITOR.env.ie){if(!a.match(/^([^<]|<br( ?\/)?>)*$/gi)&&!a.match(/^(<p>([^<]|<br( ?\/)?>)*<\/p>|(\r\n))*$/gi))return"html"}else if(CKEDITOR.env.gecko){if(!a.match(/^([^<]|<br( ?\/)?>)*$/gi))return"html"}else return"html";
return"htmlifiedtext"}function A(a,b){function c(a){return CKEDITOR.tools.repeat("\x3c/p\x3e\x3cp\x3e",~~(a/2))+(1==a%2?"\x3cbr\x3e":"")}b=b.replace(/(?!\u3000)\s+/g," ").replace(/> +</g,"\x3e\x3c").replace(/<br ?\/>/gi,"\x3cbr\x3e");b=b.replace(/<\/?[A-Z]+>/g,function(a){return a.toLowerCase()});if(b.match(/^[^<]$/))return b;CKEDITOR.env.webkit&&-1<b.indexOf("\x3cdiv\x3e")&&(b=b.replace(/^(<div>(<br>|)<\/div>)(?!$|(<div>(<br>|)<\/div>))/g,"\x3cbr\x3e").replace(/^(<div>(<br>|)<\/div>){2}(?!$)/g,"\x3cdiv\x3e\x3c/div\x3e"),
b.match(/<div>(<br>|)<\/div>/)&&(b="\x3cp\x3e"+b.replace(/(<div>(<br>|)<\/div>)+/g,function(a){return c(a.split("\x3c/div\x3e\x3cdiv\x3e").length+1)})+"\x3c/p\x3e"),b=b.replace(/<\/div><div>/g,"\x3cbr\x3e"),b=b.replace(/<\/?div>/g,""));CKEDITOR.env.gecko&&a.enterMode!=CKEDITOR.ENTER_BR&&(CKEDITOR.env.gecko&&(b=b.replace(/^<br><br>$/,"\x3cbr\x3e")),-1<b.indexOf("\x3cbr\x3e\x3cbr\x3e")&&(b="\x3cp\x3e"+b.replace(/(<br>){2,}/g,function(a){return c(a.length/4)})+"\x3c/p\x3e"));return B(a,b)}function C(){function a(){var a=
{},b;for(b in CKEDITOR.dtd)"$"!=b.charAt(0)&&"div"!=b&&"span"!=b&&(a[b]=1);return a}var b={};return{get:function(c){return"plain-text"==c?b.plainText||(b.plainText=new CKEDITOR.filter("br")):"semantic-content"==c?((c=b.semanticContent)||(c=new CKEDITOR.filter,c.allow({$1:{elements:a(),attributes:!0,styles:!1,classes:!1}}),c=b.semanticContent=c),c):c?new CKEDITOR.filter(c):null}}}function w(a,b,c){b=CKEDITOR.htmlParser.fragment.fromHtml(b);var d=new CKEDITOR.htmlParser.basicWriter;c.applyTo(b,!0,!1,
a.activeEnterMode);b.writeHtml(d);return d.getHtml()}function B(a,b){a.enterMode==CKEDITOR.ENTER_BR?b=b.replace(/(<\/p><p>)+/g,function(a){return CKEDITOR.tools.repeat("\x3cbr\x3e",a.length/7*2)}).replace(/<\/?p>/g,""):a.enterMode==CKEDITOR.ENTER_DIV&&(b=b.replace(/<(\/)?p>/g,"\x3c$1div\x3e"));return b}function D(a){a.data.preventDefault();a.data.$.dataTransfer.dropEffect="none"}function E(a){var b=CKEDITOR.plugins.clipboard;a.on("contentDom",function(){function c(b,c,e){c.select();r(a,{dataTransfer:e,
method:"drop"},1);e.sourceEditor.fire("saveSnapshot");e.sourceEditor.editable().extractHtmlFromRange(b);e.sourceEditor.getSelection().selectRanges([b]);e.sourceEditor.fire("saveSnapshot")}function d(c,e){c.select();r(a,{dataTransfer:e,method:"drop"},1);b.resetDragDataTransfer()}function g(b,c,e){var d={$:b.data.$,target:b.data.getTarget()};c&&(d.dragRange=c);e&&(d.dropRange=e);!1===a.fire(b.name,d)&&b.data.preventDefault()}function h(a){a.type!=CKEDITOR.NODE_ELEMENT&&(a=a.getParent());return a.getChildCount()}
var e=a.editable(),f=CKEDITOR.plugins.clipboard.getDropTarget(a),l=a.ui.space("top"),m=a.ui.space("bottom");b.preventDefaultDropOnElement(l);b.preventDefaultDropOnElement(m);e.attachListener(f,"dragstart",g);e.attachListener(a,"dragstart",b.resetDragDataTransfer,b,null,1);e.attachListener(a,"dragstart",function(c){b.initDragDataTransfer(c,a)},null,null,2);e.attachListener(a,"dragstart",function(){var c=b.dragRange=a.getSelection().getRanges()[0];CKEDITOR.env.ie&&10>CKEDITOR.env.version&&(b.dragStartContainerChildCount=
c?h(c.startContainer):null,b.dragEndContainerChildCount=c?h(c.endContainer):null)},null,null,100);e.attachListener(f,"dragend",g);e.attachListener(a,"dragend",b.initDragDataTransfer,b,null,1);e.attachListener(a,"dragend",b.resetDragDataTransfer,b,null,100);e.attachListener(f,"dragover",function(a){if(CKEDITOR.env.edge)a.data.preventDefault();else{var b=a.data.getTarget();b&&b.is&&b.is("html")?a.data.preventDefault():CKEDITOR.env.ie&&CKEDITOR.plugins.clipboard.isFileApiSupported&&a.data.$.dataTransfer.types.contains("Files")&&
a.data.preventDefault()}});e.attachListener(f,"drop",function(c){if(!c.data.$.defaultPrevented){c.data.preventDefault();var e=c.data.getTarget();if(!e.isReadOnly()||e.type==CKEDITOR.NODE_ELEMENT&&e.is("html")){var e=b.getRangeAtDropPosition(c,a),d=b.dragRange;e&&g(c,d,e)}}},null,null,9999);e.attachListener(a,"drop",b.initDragDataTransfer,b,null,1);e.attachListener(a,"drop",function(e){if(e=e.data){var h=e.dropRange,f=e.dragRange,g=e.dataTransfer;g.getTransferType(a)==CKEDITOR.DATA_TRANSFER_INTERNAL?
setTimeout(function(){b.internalDrop(f,h,g,a)},0):g.getTransferType(a)==CKEDITOR.DATA_TRANSFER_CROSS_EDITORS?c(f,h,g):d(h,g)}},null,null,9999)})}var m;CKEDITOR.plugins.add("clipboard",{requires:"dialog,notification,toolbar",init:function(a){var b,c=C();a.config.forcePasteAsPlainText?b="plain-text":a.config.pasteFilter?b=a.config.pasteFilter:!CKEDITOR.env.webkit||"pasteFilter"in a.config||(b="semantic-content");a.pasteFilter=c.get(b);x(a);E(a);CKEDITOR.dialog.add("paste",CKEDITOR.getUrl(this.path+
"dialogs/paste.js"));if(CKEDITOR.env.gecko){var d=["image/png","image/jpeg","image/gif"],g;a.on("paste",function(b){var c=b.data,f=c.dataTransfer;if(!c.dataValue&&"paste"==c.method&&f&&1==f.getFilesCount()&&g!=f.id&&(f=f.getFile(0),-1!=CKEDITOR.tools.indexOf(d,f.type))){var l=new FileReader;l.addEventListener("load",function(){b.data.dataValue='\x3cimg src\x3d"'+l.result+'" /\x3e';a.fire("paste",b.data)},!1);l.addEventListener("abort",function(){a.fire("paste",b.data)},!1);l.addEventListener("error",
function(){a.fire("paste",b.data)},!1);l.readAsDataURL(f);g=c.dataTransfer.id;b.stop()}},null,null,1)}a.on("paste",function(b){b.data.dataTransfer||(b.data.dataTransfer=new CKEDITOR.plugins.clipboard.dataTransfer);if(!b.data.dataValue){var c=b.data.dataTransfer,d=c.getData("text/html");if(d)b.data.dataValue=d,b.data.type="html";else if(d=c.getData("text/plain"))b.data.dataValue=a.editable().transformPlainTextToHtml(d),b.data.type="text"}},null,null,1);a.on("paste",function(a){var b=a.data.dataValue,
c=CKEDITOR.dtd.$block;-1<b.indexOf("Apple-")&&(b=b.replace(/<span class="Apple-converted-space">&nbsp;<\/span>/gi," "),"html"!=a.data.type&&(b=b.replace(/<span class="Apple-tab-span"[^>]*>([^<]*)<\/span>/gi,function(a,b){return b.replace(/\t/g,"\x26nbsp;\x26nbsp; \x26nbsp;")})),-1<b.indexOf('\x3cbr class\x3d"Apple-interchange-newline"\x3e')&&(a.data.startsWithEOL=1,a.data.preSniffing="html",b=b.replace(/<br class="Apple-interchange-newline">/,"")),b=b.replace(/(<[^>]+) class="Apple-[^"]*"/gi,"$1"));
if(b.match(/^<[^<]+cke_(editable|contents)/i)){var d,g,n=new CKEDITOR.dom.element("div");for(n.setHtml(b);1==n.getChildCount()&&(d=n.getFirst())&&d.type==CKEDITOR.NODE_ELEMENT&&(d.hasClass("cke_editable")||d.hasClass("cke_contents"));)n=g=d;g&&(b=g.getHtml().replace(/<br>$/i,""))}CKEDITOR.env.ie?b=b.replace(/^&nbsp;(?: |\r\n)?<(\w+)/g,function(b,d){return d.toLowerCase()in c?(a.data.preSniffing="html","\x3c"+d):b}):CKEDITOR.env.webkit?b=b.replace(/<\/(\w+)><div><br><\/div>$/,function(b,d){return d in
c?(a.data.endsWithEOL=1,"\x3c/"+d+"\x3e"):b}):CKEDITOR.env.gecko&&(b=b.replace(/(\s)<br>$/,"$1"));a.data.dataValue=b},null,null,3);a.on("paste",function(b){b=b.data;var d=a._.nextPasteType||b.type,f=b.dataValue,g,m=a.config.clipboard_defaultContentType||"html",n=b.dataTransfer.getTransferType(a)==CKEDITOR.DATA_TRANSFER_EXTERNAL,k=!0===a.config.forcePasteAsPlainText;g="html"==d||"html"==b.preSniffing?"html":z(f);delete a._.nextPasteType;"htmlifiedtext"==g&&(f=A(a.config,f));if("text"==d&&"html"==g)f=
w(a,f,c.get("plain-text"));else if(n&&a.pasteFilter&&!b.dontFilter||k)f=w(a,f,a.pasteFilter);b.startsWithEOL&&(f='\x3cbr data-cke-eol\x3d"1"\x3e'+f);b.endsWithEOL&&(f+='\x3cbr data-cke-eol\x3d"1"\x3e');"auto"==d&&(d="html"==g||"html"==m?"html":"text");b.type=d;b.dataValue=f;delete b.preSniffing;delete b.startsWithEOL;delete b.endsWithEOL},null,null,6);a.on("paste",function(b){b=b.data;b.dataValue&&(a.insertHtml(b.dataValue,b.type,b.range),setTimeout(function(){a.fire("afterPaste")},0))},null,null,
1E3);a.on("pasteDialog",function(b){setTimeout(function(){a.openDialog("paste",b.data)},0)})}});CKEDITOR.plugins.clipboard={isCustomCopyCutSupported:(!CKEDITOR.env.ie||16<=CKEDITOR.env.version)&&!CKEDITOR.env.iOS,isCustomDataTypesSupported:!CKEDITOR.env.ie||16<=CKEDITOR.env.version,isFileApiSupported:!CKEDITOR.env.ie||9<CKEDITOR.env.version,mainPasteEvent:CKEDITOR.env.ie&&!CKEDITOR.env.edge?"beforepaste":"paste",addPasteButton:function(a,b,c){a.ui.addButton&&(a.ui.addButton(b,c),a._.pasteButtons||
(a._.pasteButtons=[]),a._.pasteButtons.push(b))},canClipboardApiBeTrusted:function(a,b){return a.getTransferType(b)!=CKEDITOR.DATA_TRANSFER_EXTERNAL||CKEDITOR.env.chrome&&!a.isEmpty()||CKEDITOR.env.gecko&&(a.getData("text/html")||a.getFilesCount())||CKEDITOR.env.safari&&603<=CKEDITOR.env.version&&!CKEDITOR.env.iOS||CKEDITOR.env.edge&&16<=CKEDITOR.env.version?!0:!1},getDropTarget:function(a){var b=a.editable();return CKEDITOR.env.ie&&9>CKEDITOR.env.version||b.isInline()?b:a.document},fixSplitNodesAfterDrop:function(a,
b,c,d){function g(a,c,d){var g=a;g.type==CKEDITOR.NODE_TEXT&&(g=a.getParent());if(g.equals(c)&&d!=c.getChildCount())return a=b.startContainer.getChild(b.startOffset-1),c=b.startContainer.getChild(b.startOffset),a&&a.type==CKEDITOR.NODE_TEXT&&c&&c.type==CKEDITOR.NODE_TEXT&&(d=a.getLength(),a.setText(a.getText()+c.getText()),c.remove(),b.setStart(a,d),b.collapse(!0)),!0}var h=b.startContainer;"number"==typeof d&&"number"==typeof c&&h.type==CKEDITOR.NODE_ELEMENT&&(g(a.startContainer,h,c)||g(a.endContainer,
h,d))},isDropRangeAffectedByDragRange:function(a,b){var c=b.startContainer,d=b.endOffset;return a.endContainer.equals(c)&&a.endOffset<=d||a.startContainer.getParent().equals(c)&&a.startContainer.getIndex()<d||a.endContainer.getParent().equals(c)&&a.endContainer.getIndex()<d?!0:!1},internalDrop:function(a,b,c,d){var g=CKEDITOR.plugins.clipboard,h=d.editable(),e,f;d.fire("saveSnapshot");d.fire("lockSnapshot",{dontUpdate:1});CKEDITOR.env.ie&&10>CKEDITOR.env.version&&this.fixSplitNodesAfterDrop(a,b,g.dragStartContainerChildCount,
g.dragEndContainerChildCount);(f=this.isDropRangeAffectedByDragRange(a,b))||(e=a.createBookmark(!1));g=b.clone().createBookmark(!1);f&&(e=a.createBookmark(!1));a=e.startNode;b=e.endNode;f=g.startNode;b&&a.getPosition(f)&CKEDITOR.POSITION_PRECEDING&&b.getPosition(f)&CKEDITOR.POSITION_FOLLOWING&&f.insertBefore(a);a=d.createRange();a.moveToBookmark(e);h.extractHtmlFromRange(a,1);b=d.createRange();b.moveToBookmark(g);r(d,{dataTransfer:c,method:"drop",range:b},1);d.fire("unlockSnapshot")},getRangeAtDropPosition:function(a,
b){var c=a.data.$,d=c.clientX,g=c.clientY,h=b.getSelection(!0).getRanges()[0],e=b.createRange();if(a.data.testRange)return a.data.testRange;if(document.caretRangeFromPoint&&b.document.$.caretRangeFromPoint(d,g))c=b.document.$.caretRangeFromPoint(d,g),e.setStart(CKEDITOR.dom.node(c.startContainer),c.startOffset),e.collapse(!0);else if(c.rangeParent)e.setStart(CKEDITOR.dom.node(c.rangeParent),c.rangeOffset),e.collapse(!0);else{if(CKEDITOR.env.ie&&8<CKEDITOR.env.version&&h&&b.editable().hasFocus)return h;
if(document.body.createTextRange){b.focus();c=b.document.getBody().$.createTextRange();try{for(var f=!1,l=0;20>l&&!f;l++){if(!f)try{c.moveToPoint(d,g-l),f=!0}catch(m){}if(!f)try{c.moveToPoint(d,g+l),f=!0}catch(n){}}if(f){var k="cke-temp-"+(new Date).getTime();c.pasteHTML('\x3cspan id\x3d"'+k+'"\x3e​\x3c/span\x3e');var t=b.document.getById(k);e.moveToPosition(t,CKEDITOR.POSITION_BEFORE_START);t.remove()}else{var q=b.document.$.elementFromPoint(d,g),p=new CKEDITOR.dom.element(q),r;if(p.equals(b.editable())||
"html"==p.getName())return h&&h.startContainer&&!h.startContainer.equals(b.editable())?h:null;r=p.getClientRect();d<r.left?e.setStartAt(p,CKEDITOR.POSITION_AFTER_START):e.setStartAt(p,CKEDITOR.POSITION_BEFORE_END);e.collapse(!0)}}catch(u){return null}}else return null}return e},initDragDataTransfer:function(a,b){var c=a.data.$?a.data.$.dataTransfer:null,d=new this.dataTransfer(c,b);"dragstart"===a.name&&d.storeId();c?this.dragData&&d.id==this.dragData.id?d=this.dragData:this.dragData=d:this.dragData?
d=this.dragData:this.dragData=d;a.data.dataTransfer=d},resetDragDataTransfer:function(){this.dragData=null},initPasteDataTransfer:function(a,b){if(this.isCustomCopyCutSupported){if(a&&a.data&&a.data.$){var c=a.data.$.clipboardData,d=new this.dataTransfer(c,b);"copy"!==a.name&&"cut"!==a.name||d.storeId();this.copyCutData&&d.id==this.copyCutData.id?(d=this.copyCutData,d.$=c):this.copyCutData=d;return d}return new this.dataTransfer(null,b)}return new this.dataTransfer(CKEDITOR.env.edge&&a&&a.data.$&&
a.data.$.clipboardData||null,b)},preventDefaultDropOnElement:function(a){a&&a.on("dragover",D)}};m=CKEDITOR.plugins.clipboard.isCustomDataTypesSupported?"cke/id":"Text";CKEDITOR.plugins.clipboard.dataTransfer=function(a,b){a&&(this.$=a);this._={metaRegExp:/^<meta.*?>/i,bodyRegExp:/<body(?:[\s\S]*?)>([\s\S]*)<\/body>/i,fragmentRegExp:/\x3c!--(?:Start|End)Fragment--\x3e/g,data:{},files:[],nativeHtmlCache:"",normalizeType:function(a){a=a.toLowerCase();return"text"==a||"text/plain"==a?"Text":"url"==a?
"URL":a}};this._.fallbackDataTransfer=new CKEDITOR.plugins.clipboard.fallbackDataTransfer(this);this.id=this.getData(m);this.id||(this.id="Text"==m?"":"cke-"+CKEDITOR.tools.getUniqueId());b&&(this.sourceEditor=b,this.setData("text/html",b.getSelectedHtml(1)),"Text"==m||this.getData("text/plain")||this.setData("text/plain",b.getSelection().getSelectedText()))};CKEDITOR.DATA_TRANSFER_INTERNAL=1;CKEDITOR.DATA_TRANSFER_CROSS_EDITORS=2;CKEDITOR.DATA_TRANSFER_EXTERNAL=3;CKEDITOR.plugins.clipboard.dataTransfer.prototype=
{getData:function(a,b){a=this._.normalizeType(a);var c="text/html"==a&&b?this._.nativeHtmlCache:this._.data[a];if(void 0===c||null===c||""===c){if(this._.fallbackDataTransfer.isRequired())c=this._.fallbackDataTransfer.getData(a,b);else try{c=this.$.getData(a)||""}catch(d){c=""}"text/html"!=a||b||(c=this._stripHtml(c))}"Text"==a&&CKEDITOR.env.gecko&&this.getFilesCount()&&"file://"==c.substring(0,7)&&(c="");if("string"===typeof c)var g=c.indexOf("\x3c/html\x3e"),c=-1!==g?c.substring(0,g+7):c;return c},
setData:function(a,b){a=this._.normalizeType(a);"text/html"==a?(this._.data[a]=this._stripHtml(b),this._.nativeHtmlCache=b):this._.data[a]=b;if(CKEDITOR.plugins.clipboard.isCustomDataTypesSupported||"URL"==a||"Text"==a)if("Text"==m&&"Text"==a&&(this.id=b),this._.fallbackDataTransfer.isRequired())this._.fallbackDataTransfer.setData(a,b);else try{this.$.setData(a,b)}catch(c){}},storeId:function(){"Text"!==m&&this.setData(m,this.id)},getTransferType:function(a){return this.sourceEditor?this.sourceEditor==
a?CKEDITOR.DATA_TRANSFER_INTERNAL:CKEDITOR.DATA_TRANSFER_CROSS_EDITORS:CKEDITOR.DATA_TRANSFER_EXTERNAL},cacheData:function(){function a(a){a=b._.normalizeType(a);var c=b.getData(a);"text/html"==a&&(b._.nativeHtmlCache=b.getData(a,!0),c=b._stripHtml(c));c&&(b._.data[a]=c)}if(this.$){var b=this,c,d;if(CKEDITOR.plugins.clipboard.isCustomDataTypesSupported){if(this.$.types)for(c=0;c<this.$.types.length;c++)a(this.$.types[c])}else a("Text"),a("URL");d=this._getImageFromClipboard();if(this.$&&this.$.files||
d){this._.files=[];if(this.$.files&&this.$.files.length)for(c=0;c<this.$.files.length;c++)this._.files.push(this.$.files[c]);0===this._.files.length&&d&&this._.files.push(d)}}},getFilesCount:function(){return this._.files.length?this._.files.length:this.$&&this.$.files&&this.$.files.length?this.$.files.length:this._getImageFromClipboard()?1:0},getFile:function(a){return this._.files.length?this._.files[a]:this.$&&this.$.files&&this.$.files.length?this.$.files[a]:0===a?this._getImageFromClipboard():
void 0},isEmpty:function(){var a={},b;if(this.getFilesCount())return!1;CKEDITOR.tools.array.forEach(CKEDITOR.tools.objectKeys(this._.data),function(b){a[b]=1});if(this.$)if(CKEDITOR.plugins.clipboard.isCustomDataTypesSupported){if(this.$.types)for(var c=0;c<this.$.types.length;c++)a[this.$.types[c]]=1}else a.Text=1,a.URL=1;"Text"!=m&&(a[m]=0);for(b in a)if(a[b]&&""!==this.getData(b))return!1;return!0},_getImageFromClipboard:function(){var a;if(this.$&&this.$.items&&this.$.items[0])try{if((a=this.$.items[0].getAsFile())&&
a.type)return a}catch(b){}},_stripHtml:function(a){if(a&&a.length){a=a.replace(this._.metaRegExp,"");var b=this._.bodyRegExp.exec(a);b&&b.length&&(a=b[1],a=a.replace(this._.fragmentRegExp,""))}return a}};CKEDITOR.plugins.clipboard.fallbackDataTransfer=function(a){this._dataTransfer=a;this._customDataFallbackType="text/html"};CKEDITOR.plugins.clipboard.fallbackDataTransfer._isCustomMimeTypeSupported=null;CKEDITOR.plugins.clipboard.fallbackDataTransfer._customTypes=[];CKEDITOR.plugins.clipboard.fallbackDataTransfer.prototype=
{isRequired:function(){var a=CKEDITOR.plugins.clipboard.fallbackDataTransfer,b=this._dataTransfer.$;if(null===a._isCustomMimeTypeSupported)if(b){a._isCustomMimeTypeSupported=!1;if(CKEDITOR.env.edge&&17<=CKEDITOR.env.version)return!0;try{b.setData("cke/mimetypetest","cke test value"),a._isCustomMimeTypeSupported="cke test value"===b.getData("cke/mimetypetest"),b.clearData("cke/mimetypetest")}catch(c){}}else return!1;return!a._isCustomMimeTypeSupported},getData:function(a,b){var c=this._getData(this._customDataFallbackType,
!0);if(b)return c;var c=this._extractDataComment(c),d=null,d=a===this._customDataFallbackType?c.content:c.data&&c.data[a]?c.data[a]:this._getData(a,!0);return null!==d?d:""},setData:function(a,b){var c=a===this._customDataFallbackType;c&&(b=this._applyDataComment(b,this._getFallbackTypeData()));var d=b,g=this._dataTransfer.$;try{g.setData(a,d),c&&(this._dataTransfer._.nativeHtmlCache=d)}catch(h){if(this._isUnsupportedMimeTypeError(h)){c=CKEDITOR.plugins.clipboard.fallbackDataTransfer;-1===CKEDITOR.tools.indexOf(c._customTypes,
a)&&c._customTypes.push(a);var c=this._getFallbackTypeContent(),e=this._getFallbackTypeData();e[a]=d;try{d=this._applyDataComment(c,e),g.setData(this._customDataFallbackType,d),this._dataTransfer._.nativeHtmlCache=d}catch(f){d=""}}}return d},_getData:function(a,b){var c=this._dataTransfer._.data;if(!b&&c[a])return c[a];try{return this._dataTransfer.$.getData(a)}catch(d){return null}},_getFallbackTypeContent:function(){var a=this._dataTransfer._.data[this._customDataFallbackType];a||(a=this._extractDataComment(this._getData(this._customDataFallbackType,
!0)).content);return a},_getFallbackTypeData:function(){var a=CKEDITOR.plugins.clipboard.fallbackDataTransfer._customTypes,b=this._extractDataComment(this._getData(this._customDataFallbackType,!0)).data||{},c=this._dataTransfer._.data;CKEDITOR.tools.array.forEach(a,function(a){void 0!==c[a]?b[a]=c[a]:void 0!==b[a]&&(b[a]=b[a])},this);return b},_isUnsupportedMimeTypeError:function(a){return a.message&&-1!==a.message.search(/element not found/gi)},_extractDataComment:function(a){var b={data:null,content:a||
""};if(a&&16<a.length){var c;(c=/\x3c!--cke-data:(.*?)--\x3e/g.exec(a))&&c[1]&&(b.data=JSON.parse(decodeURIComponent(c[1])),b.content=a.replace(c[0],""))}return b},_applyDataComment:function(a,b){var c="";b&&CKEDITOR.tools.objectKeys(b).length&&(c="\x3c!--cke-data:"+encodeURIComponent(JSON.stringify(b))+"--\x3e");return c+(a&&a.length?a:"")}}})();CKEDITOR.config.clipboard_notificationDuration=1E4;CKEDITOR.plugins.add("panelbutton",{requires:"button",onLoad:function(){function e(c){var a=this._;a.state!=CKEDITOR.TRISTATE_DISABLED&&(this.createPanel(c),a.on?a.panel.hide():a.panel.showBlock(this._.id,this.document.getById(this._.id),4))}CKEDITOR.ui.panelButton=CKEDITOR.tools.createClass({base:CKEDITOR.ui.button,$:function(c){var a=c.panel||{};delete c.panel;this.base(c);this.document=a.parent&&a.parent.getDocument()||CKEDITOR.document;a.block={attributes:a.attributes};this.hasArrow=a.toolbarRelated=
!0;this.click=e;this._={panelDefinition:a}},statics:{handler:{create:function(c){return new CKEDITOR.ui.panelButton(c)}}},proto:{createPanel:function(c){var a=this._;if(!a.panel){var f=this._.panelDefinition,e=this._.panelDefinition.block,g=f.parent||CKEDITOR.document.getBody(),d=this._.panel=new CKEDITOR.ui.floatPanel(c,g,f),f=d.addBlock(a.id,e),b=this;d.onShow=function(){b.className&&this.element.addClass(b.className+"_panel");b.setState(CKEDITOR.TRISTATE_ON);a.on=1;b.editorFocus&&c.focus();if(b.onOpen)b.onOpen()};
d.onHide=function(d){b.className&&this.element.getFirst().removeClass(b.className+"_panel");b.setState(b.modes&&b.modes[c.mode]?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED);a.on=0;if(!d&&b.onClose)b.onClose()};d.onEscape=function(){d.hide(1);b.document.getById(a.id).focus()};if(this.onBlock)this.onBlock(d,f);f.onHide=function(){a.on=0;b.setState(CKEDITOR.TRISTATE_OFF)}}}}})},beforeInit:function(e){e.ui.addHandler(CKEDITOR.UI_PANELBUTTON,CKEDITOR.ui.panelButton.handler)}});
CKEDITOR.UI_PANELBUTTON="panelbutton";(function(){CKEDITOR.plugins.add("panel",{beforeInit:function(a){a.ui.addHandler(CKEDITOR.UI_PANEL,CKEDITOR.ui.panel.handler)}});CKEDITOR.UI_PANEL="panel";CKEDITOR.ui.panel=function(a,b){b&&CKEDITOR.tools.extend(this,b);CKEDITOR.tools.extend(this,{className:"",css:[]});this.id=CKEDITOR.tools.getNextId();this.document=a;this.isFramed=this.forceIFrame||this.css.length;this._={blocks:{}}};CKEDITOR.ui.panel.handler={create:function(a){return new CKEDITOR.ui.panel(a)}};var g=CKEDITOR.addTemplate("panel",
'\x3cdiv lang\x3d"{langCode}" id\x3d"{id}" dir\x3d{dir} class\x3d"cke cke_reset_all {editorId} cke_panel cke_panel {cls} cke_{dir}" style\x3d"z-index:{z-index}" role\x3d"presentation"\x3e{frame}\x3c/div\x3e'),h=CKEDITOR.addTemplate("panel-frame",'\x3ciframe id\x3d"{id}" class\x3d"cke_panel_frame" role\x3d"presentation" frameborder\x3d"0" src\x3d"{src}"\x3e\x3c/iframe\x3e'),k=CKEDITOR.addTemplate("panel-frame-inner",'\x3c!DOCTYPE html\x3e\x3chtml class\x3d"cke_panel_container {env}" dir\x3d"{dir}" lang\x3d"{langCode}"\x3e\x3chead\x3e{css}\x3c/head\x3e\x3cbody class\x3d"cke_{dir}" style\x3d"margin:0;padding:0" onload\x3d"{onload}"\x3e\x3c/body\x3e\x3c/html\x3e');
CKEDITOR.ui.panel.prototype={render:function(a,b){this.getHolderElement=function(){var a=this._.holder;if(!a){if(this.isFramed){var a=this.document.getById(this.id+"_frame"),b=a.getParent(),a=a.getFrameDocument();CKEDITOR.env.iOS&&b.setStyles({overflow:"scroll","-webkit-overflow-scrolling":"touch"});b=CKEDITOR.tools.addFunction(CKEDITOR.tools.bind(function(){this.isLoaded=!0;if(this.onLoad)this.onLoad()},this));a.write(k.output(CKEDITOR.tools.extend({css:CKEDITOR.tools.buildStyleHtml(this.css),onload:"window.parent.CKEDITOR.tools.callFunction("+
b+");"},e)));a.getWindow().$.CKEDITOR=CKEDITOR;a.on("keydown",function(a){var b=a.data.getKeystroke(),c=this.document.getById(this.id).getAttribute("dir");this._.onKeyDown&&!1===this._.onKeyDown(b)?a.data.preventDefault():(27==b||b==("rtl"==c?39:37))&&this.onEscape&&!1===this.onEscape(b)&&a.data.preventDefault()},this);a=a.getBody();a.unselectable();CKEDITOR.env.air&&CKEDITOR.tools.callFunction(b)}else a=this.document.getById(this.id);this._.holder=a}return a};var e={editorId:a.id,id:this.id,langCode:a.langCode,
dir:a.lang.dir,cls:this.className,frame:"",env:CKEDITOR.env.cssClass,"z-index":a.config.baseFloatZIndex+1};if(this.isFramed){var d=CKEDITOR.env.air?"javascript:void(0)":CKEDITOR.env.ie?"javascript:void(function(){"+encodeURIComponent("document.open();("+CKEDITOR.tools.fixDomain+")();document.close();")+"}())":"";e.frame=h.output({id:this.id+"_frame",src:d})}d=g.output(e);b&&b.push(d);return d},addBlock:function(a,b){b=this._.blocks[a]=b instanceof CKEDITOR.ui.panel.block?b:new CKEDITOR.ui.panel.block(this.getHolderElement(),
b);this._.currentBlock||this.showBlock(a);return b},getBlock:function(a){return this._.blocks[a]},showBlock:function(a){a=this._.blocks[a];var b=this._.currentBlock,e=!this.forceIFrame||CKEDITOR.env.ie?this._.holder:this.document.getById(this.id+"_frame");b&&b.hide();this._.currentBlock=a;CKEDITOR.fire("ariaWidget",e);a._.focusIndex=-1;this._.onKeyDown=a.onKeyDown&&CKEDITOR.tools.bind(a.onKeyDown,a);a.show();return a},destroy:function(){this.element&&this.element.remove()}};CKEDITOR.ui.panel.block=
CKEDITOR.tools.createClass({$:function(a,b){this.element=a.append(a.getDocument().createElement("div",{attributes:{tabindex:-1,"class":"cke_panel_block"},styles:{display:"none"}}));b&&CKEDITOR.tools.extend(this,b);this.element.setAttributes({role:this.attributes.role||"presentation","aria-label":this.attributes["aria-label"],title:this.attributes.title||this.attributes["aria-label"]});this.keys={};this._.focusIndex=-1;this.element.disableContextMenu()},_:{markItem:function(a){-1!=a&&(a=this.element.getElementsByTag("a").getItem(this._.focusIndex=
a),CKEDITOR.env.webkit&&a.getDocument().getWindow().focus(),a.focus(),this.onMark&&this.onMark(a))},markFirstDisplayed:function(a){for(var b=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&"none"==a.getStyle("display")},e=this._.getItems(),d,c,f=e.count()-1;0<=f;f--)if(d=e.getItem(f),d.getAscendant(b)||(c=d,this._.focusIndex=f),"true"==d.getAttribute("aria-selected")){c=d;this._.focusIndex=f;break}c&&(a&&a(),CKEDITOR.env.webkit&&c.getDocument().getWindow().focus(),c.focus(),this.onMark&&this.onMark(c))},
getItems:function(){return this.element.getElementsByTag("a")}},proto:{show:function(){this.element.setStyle("display","")},hide:function(){this.onHide&&!0===this.onHide.call(this)||this.element.setStyle("display","none")},onKeyDown:function(a,b){var e=this.keys[a];switch(e){case "next":for(var d=this._.focusIndex,e=this.element.getElementsByTag("a"),c;c=e.getItem(++d);)if(c.getAttribute("_cke_focus")&&c.$.offsetWidth){this._.focusIndex=d;c.focus();break}return c||b?!1:(this._.focusIndex=-1,this.onKeyDown(a,
1));case "prev":d=this._.focusIndex;for(e=this.element.getElementsByTag("a");0<d&&(c=e.getItem(--d));){if(c.getAttribute("_cke_focus")&&c.$.offsetWidth){this._.focusIndex=d;c.focus();break}c=null}return c||b?!1:(this._.focusIndex=e.count(),this.onKeyDown(a,1));case "click":case "mouseup":return d=this._.focusIndex,(c=0<=d&&this.element.getElementsByTag("a").getItem(d))&&(c.$[e]?c.$[e]():c.$["on"+e]()),!1}return!0}}})})();CKEDITOR.plugins.add("floatpanel",{requires:"panel"});
(function(){function v(a,b,c,m,h){h=CKEDITOR.tools.genKey(b.getUniqueId(),c.getUniqueId(),a.lang.dir,a.uiColor||"",m.css||"",h||"");var g=f[h];g||(g=f[h]=new CKEDITOR.ui.panel(b,m),g.element=c.append(CKEDITOR.dom.element.createFromHtml(g.render(a),b)),g.element.setStyles({display:"none",position:"absolute"}));return g}var f={};CKEDITOR.ui.floatPanel=CKEDITOR.tools.createClass({$:function(a,b,c,m){function h(){e.hide()}c.forceIFrame=1;c.toolbarRelated&&a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE&&
(b=CKEDITOR.document.getById("cke_"+a.name));var g=b.getDocument();m=v(a,g,b,c,m||0);var n=m.element,k=n.getFirst(),e=this;n.disableContextMenu();this.element=n;this._={editor:a,panel:m,parentElement:b,definition:c,document:g,iframe:k,children:[],dir:a.lang.dir,showBlockParams:null};a.on("mode",h);a.on("resize",h);g.getWindow().on("resize",function(){this.reposition()},this)},proto:{addBlock:function(a,b){return this._.panel.addBlock(a,b)},addListBlock:function(a,b){return this._.panel.addListBlock(a,
b)},getBlock:function(a){return this._.panel.getBlock(a)},showBlock:function(a,b,c,m,h,g){var n=this._.panel,k=n.showBlock(a);this._.showBlockParams=[].slice.call(arguments);this.allowBlur(!1);var e=this._.editor.editable();this._.returnFocus=e.hasFocus?e:new CKEDITOR.dom.element(CKEDITOR.document.$.activeElement);this._.hideTimeout=0;var l=this.element,e=this._.iframe,e=CKEDITOR.env.ie&&!CKEDITOR.env.edge?e:new CKEDITOR.dom.window(e.$.contentWindow),f=l.getDocument(),r=this._.parentElement.getPositionedAncestor(),
t=b.getDocumentPosition(f),f=r?r.getDocumentPosition(f):{x:0,y:0},q="rtl"==this._.dir,d=t.x+(m||0)-f.x,p=t.y+(h||0)-f.y;!q||1!=c&&4!=c?q||2!=c&&3!=c||(d+=b.$.offsetWidth-1):d+=b.$.offsetWidth;if(3==c||4==c)p+=b.$.offsetHeight-1;this._.panel._.offsetParentId=b.getId();l.setStyles({top:p+"px",left:0,display:""});l.setOpacity(0);l.getFirst().removeStyle("width");this._.editor.focusManager.add(e);this._.blurSet||(CKEDITOR.event.useCapture=!0,e.on("blur",function(a){function u(){delete this._.returnFocus;
this.hide()}this.allowBlur()&&a.data.getPhase()==CKEDITOR.EVENT_PHASE_AT_TARGET&&this.visible&&!this._.activeChild&&(CKEDITOR.env.iOS?this._.hideTimeout||(this._.hideTimeout=CKEDITOR.tools.setTimeout(u,0,this)):u.call(this))},this),e.on("focus",function(){this._.focused=!0;this.hideChild();this.allowBlur(!0)},this),CKEDITOR.env.iOS&&(e.on("touchstart",function(){clearTimeout(this._.hideTimeout)},this),e.on("touchend",function(){this._.hideTimeout=0;this.focus()},this)),CKEDITOR.event.useCapture=!1,
this._.blurSet=1);n.onEscape=CKEDITOR.tools.bind(function(a){if(this.onEscape&&!1===this.onEscape(a))return!1},this);CKEDITOR.tools.setTimeout(function(){var a=CKEDITOR.tools.bind(function(){var a=l;a.removeStyle("width");if(k.autoSize){var b=k.element.getDocument(),b=(CKEDITOR.env.webkit||CKEDITOR.env.edge?k.element:b.getBody()).$.scrollWidth;CKEDITOR.env.ie&&CKEDITOR.env.quirks&&0<b&&(b+=(a.$.offsetWidth||0)-(a.$.clientWidth||0)+3);a.setStyle("width",b+10+"px");b=k.element.$.scrollHeight;CKEDITOR.env.ie&&
CKEDITOR.env.quirks&&0<b&&(b+=(a.$.offsetHeight||0)-(a.$.clientHeight||0)+3);a.setStyle("height",b+"px");n._.currentBlock.element.setStyle("display","none").removeStyle("display")}else a.removeStyle("height");q&&(d-=l.$.offsetWidth);l.setStyle("left",d+"px");var b=n.element.getWindow(),a=l.$.getBoundingClientRect(),b=b.getViewPaneSize(),c=a.width||a.right-a.left,e=a.height||a.bottom-a.top,m=q?a.right:b.width-a.left,h=q?b.width-a.right:a.left;q?m<c&&(d=h>c?d+c:b.width>c?d-a.left:d-a.right+b.width):
m<c&&(d=h>c?d-c:b.width>c?d-a.right+b.width:d-a.left);c=a.top;b.height-a.top<e&&(p=c>e?p-e:b.height>e?p-a.bottom+b.height:p-a.top);CKEDITOR.env.ie&&(b=a=new CKEDITOR.dom.element(l.$.offsetParent),"html"==b.getName()&&(b=b.getDocument().getBody()),"rtl"==b.getComputedStyle("direction")&&(d=CKEDITOR.env.ie8Compat?d-2*l.getDocument().getDocumentElement().$.scrollLeft:d-(a.$.scrollWidth-a.$.clientWidth)));var a=l.getFirst(),f;(f=a.getCustomData("activePanel"))&&f.onHide&&f.onHide.call(this,1);a.setCustomData("activePanel",
this);l.setStyles({top:p+"px",left:d+"px"});l.setOpacity(1);g&&g()},this);n.isLoaded?a():n.onLoad=a;CKEDITOR.tools.setTimeout(function(){var a=CKEDITOR.env.webkit&&CKEDITOR.document.getWindow().getScrollPosition().y;this.focus();k.element.focus();CKEDITOR.env.webkit&&(CKEDITOR.document.getBody().$.scrollTop=a);this.allowBlur(!0);CKEDITOR.env.ie?CKEDITOR.tools.setTimeout(function(){k.markFirstDisplayed?k.markFirstDisplayed():k._.markFirstDisplayed()},0):k.markFirstDisplayed?k.markFirstDisplayed():
k._.markFirstDisplayed();this._.editor.fire("panelShow",this)},0,this)},CKEDITOR.env.air?200:0,this);this.visible=1;this.onShow&&this.onShow.call(this)},reposition:function(){var a=this._.showBlockParams;this.visible&&this._.showBlockParams&&(this.hide(),this.showBlock.apply(this,a))},focus:function(){if(CKEDITOR.env.webkit){var a=CKEDITOR.document.getActive();a&&!a.equals(this._.iframe)&&a.$.blur()}(this._.lastFocused||this._.iframe.getFrameDocument().getWindow()).focus()},blur:function(){var a=
this._.iframe.getFrameDocument().getActive();a&&a.is("a")&&(this._.lastFocused=a)},hide:function(a){if(this.visible&&(!this.onHide||!0!==this.onHide.call(this))){this.hideChild();CKEDITOR.env.gecko&&this._.iframe.getFrameDocument().$.activeElement.blur();this.element.setStyle("display","none");this.visible=0;this.element.getFirst().removeCustomData("activePanel");if(a=a&&this._.returnFocus)CKEDITOR.env.webkit&&a.type&&a.getWindow().$.focus(),a.focus();delete this._.lastFocused;this._.showBlockParams=
null;this._.editor.fire("panelHide",this)}},allowBlur:function(a){var b=this._.panel;void 0!==a&&(b.allowBlur=a);return b.allowBlur},showAsChild:function(a,b,c,f,h,g){if(this._.activeChild!=a||a._.panel._.offsetParentId!=c.getId())this.hideChild(),a.onHide=CKEDITOR.tools.bind(function(){CKEDITOR.tools.setTimeout(function(){this._.focused||this.hide()},0,this)},this),this._.activeChild=a,this._.focused=!1,a.showBlock(b,c,f,h,g),this.blur(),(CKEDITOR.env.ie7Compat||CKEDITOR.env.ie6Compat)&&setTimeout(function(){a.element.getChild(0).$.style.cssText+=
""},100)},hideChild:function(a){var b=this._.activeChild;b&&(delete b.onHide,delete this._.activeChild,b.hide(),a&&this.focus())}}});CKEDITOR.on("instanceDestroyed",function(){var a=CKEDITOR.tools.isEmpty(CKEDITOR.instances),b;for(b in f){var c=f[b];a?c.destroy():c.element.hide()}a&&(f={})})})();CKEDITOR.plugins.add("colorbutton",{requires:"panelbutton,floatpanel",init:function(e){function t(a,d,g,r,k){var p=new CKEDITOR.style(l["colorButton_"+d+"Style"]),m=CKEDITOR.tools.getNextId()+"_colorBox",q;k=k||{};e.ui.add(a,CKEDITOR.UI_PANELBUTTON,{label:g,title:g,modes:{wysiwyg:1},editorFocus:0,toolbar:"colors,"+r,allowedContent:p,requiredContent:p,contentTransformations:k.contentTransformations,panel:{css:CKEDITOR.skin.getPath("editor"),attributes:{role:"listbox","aria-label":h.panelTitle}},onBlock:function(a,
b){q=b;b.autoSize=!0;b.element.addClass("cke_colorblock");b.element.setHtml(y(a,d,m));b.element.getDocument().getBody().setStyle("overflow","hidden");CKEDITOR.ui.fire("ready",this);var c=b.keys,f="rtl"==e.lang.dir;c[f?37:39]="next";c[40]="next";c[9]="next";c[f?39:37]="prev";c[38]="prev";c[CKEDITOR.SHIFT+9]="prev";c[32]="click"},refresh:function(){e.activeFilter.check(p)||this.setState(CKEDITOR.TRISTATE_DISABLED)},onOpen:function(){var a=e.getSelection(),b=a&&a.getStartElement(),c=e.elementPath(b);
if(c){b=c.block||c.blockLimit||e.document.getBody();do c=b&&b.getComputedStyle("back"==d?"background-color":"color")||"transparent";while("back"==d&&"transparent"==c&&b&&(b=b.getParent()));c&&"transparent"!=c||(c="#ffffff");!1!==l.colorButton_enableAutomatic&&this._.panel._.iframe.getFrameDocument().getById(m).setStyle("background-color",c);if(b=a&&a.getRanges()[0]){for(var a=new CKEDITOR.dom.walker(b),f=b.collapsed?b.startContainer:a.next(),b="";f;){f.type!==CKEDITOR.NODE_ELEMENT&&(f=f.getParent());
f=u(f.getComputedStyle("back"==d?"background-color":"color"));b=b||f;if(b!==f){b="";break}f=a.next()}a=b;b=q._.getItems();for(f=0;f<b.count();f++){var g=b.getItem(f);g.removeAttribute("aria-selected");a&&a==u(g.getAttribute("data-value"))&&g.setAttribute("aria-selected",!0)}}return c}}})}function y(a,d,g){a=[];var r=l.colorButton_colors.split(","),k=l.colorButton_colorsPerRow||6,p=e.plugins.colordialog&&!1!==l.colorButton_enableMore,m=r.length+(p?2:1),q=CKEDITOR.tools.addFunction(function(a,b){function c(a){var d=
l["colorButton_"+b+"Style"];e.removeStyle(new CKEDITOR.style(d,{color:"inherit"}));d.childRule="back"==b?function(a){return v(a)}:function(a){return!(a.is("a")||a.getElementsByTag("a").count())||v(a)};e.focus();a&&e.applyStyle(new CKEDITOR.style(d,{color:a}));e.fire("saveSnapshot")}e.focus();e.fire("saveSnapshot");if("?"==a)e.getColorFromDialog(function(a){if(a)return c(a)});else return c(a)});!1!==l.colorButton_enableAutomatic&&a.push('\x3ca class\x3d"cke_colorauto" _cke_focus\x3d1 hidefocus\x3dtrue title\x3d"',
h.auto,'" onclick\x3d"CKEDITOR.tools.callFunction(',q,",null,'",d,"');return false;\" href\x3d\"javascript:void('",h.auto,'\')" role\x3d"option" aria-posinset\x3d"1" aria-setsize\x3d"',m,'"\x3e\x3ctable role\x3d"presentation" cellspacing\x3d0 cellpadding\x3d0 width\x3d"100%"\x3e\x3ctr\x3e\x3ctd colspan\x3d"'+k+'" align\x3d"center"\x3e\x3cspan class\x3d"cke_colorbox" id\x3d"',g,'"\x3e\x3c/span\x3e',h.auto,"\x3c/td\x3e\x3c/tr\x3e\x3c/table\x3e\x3c/a\x3e");a.push('\x3ctable role\x3d"presentation" cellspacing\x3d0 cellpadding\x3d0 width\x3d"100%"\x3e');
for(g=0;g<r.length;g++){0===g%k&&a.push("\x3c/tr\x3e\x3ctr\x3e");var n=r[g].split("/"),b=n[0],c=n[1]||b;n[1]?n=b:(b="#"+b.replace(/^(.)(.)(.)$/,"$1$1$2$2$3$3"),n=e.lang.colorbutton.colors[c]||c);a.push('\x3ctd\x3e\x3ca class\x3d"cke_colorbox" _cke_focus\x3d1 hidefocus\x3dtrue title\x3d"',n,'" onclick\x3d"CKEDITOR.tools.callFunction(',q,",'",b,"','",d,"'); return false;\" href\x3d\"javascript:void('",n,'\')" data-value\x3d"'+c+'" role\x3d"option" aria-posinset\x3d"',g+2,'" aria-setsize\x3d"',m,'"\x3e\x3cspan class\x3d"cke_colorbox" style\x3d"background-color:#',
c,'"\x3e\x3c/span\x3e\x3c/a\x3e\x3c/td\x3e')}p&&a.push('\x3c/tr\x3e\x3ctr\x3e\x3ctd colspan\x3d"'+k+'" align\x3d"center"\x3e\x3ca class\x3d"cke_colormore" _cke_focus\x3d1 hidefocus\x3dtrue title\x3d"',h.more,'" onclick\x3d"CKEDITOR.tools.callFunction(',q,",'?','",d,"');return false;\" href\x3d\"javascript:void('",h.more,"')\"",' role\x3d"option" aria-posinset\x3d"',m,'" aria-setsize\x3d"',m,'"\x3e',h.more,"\x3c/a\x3e\x3c/td\x3e");a.push("\x3c/tr\x3e\x3c/table\x3e");return a.join("")}function v(a){return"false"==
a.getAttribute("contentEditable")||a.getAttribute("data-nostyle")}function u(a){return CKEDITOR.tools.normalizeHex("#"+CKEDITOR.tools.convertRgbToHex(a||"")).replace(/#/g,"")}var l=e.config,h=e.lang.colorbutton;if(!CKEDITOR.env.hc){t("TextColor","fore",h.textColorTitle,10,{contentTransformations:[[{element:"font",check:"span{color}",left:function(a){return!!a.attributes.color},right:function(a){a.name="span";a.attributes.color&&(a.styles.color=a.attributes.color);delete a.attributes.color}}]]});var w=
{},x=e.config.colorButton_normalizeBackground;if(void 0===x||x)w.contentTransformations=[[{element:"span",left:function(a){var d=CKEDITOR.tools;if("span"!=a.name||!a.styles||!a.styles.background)return!1;a=d.style.parse.background(a.styles.background);return a.color&&1===d.objectKeys(a).length},right:function(a){var d=(new CKEDITOR.style(e.config.colorButton_backStyle,{color:a.styles.background})).getDefinition();a.name=d.element;a.styles=d.styles;a.attributes=d.attributes||{};return a}}]];t("BGColor",
"back",h.bgColorTitle,20,w)}}});CKEDITOR.config.colorButton_colors="1ABC9C,2ECC71,3498DB,9B59B6,4E5F70,F1C40F,16A085,27AE60,2980B9,8E44AD,2C3E50,F39C12,E67E22,E74C3C,ECF0F1,95A5A6,DDD,FFF,D35400,C0392B,BDC3C7,7F8C8D,999,000";CKEDITOR.config.colorButton_foreStyle={element:"span",styles:{color:"#(color)"},overrides:[{element:"font",attributes:{color:null}}]};CKEDITOR.config.colorButton_backStyle={element:"span",styles:{"background-color":"#(color)"}};CKEDITOR.plugins.colordialog={requires:"dialog",init:function(b){var d=new CKEDITOR.dialogCommand("colordialog");d.editorFocus=!1;b.addCommand("colordialog",d);CKEDITOR.dialog.add("colordialog",this.path+"dialogs/colordialog.js");b.getColorFromDialog=function(d,g){var c,f,e;c=function(a){f(this);a="ok"==a.name?this.getValueOf("picker","selectedColor"):null;/^[0-9a-f]{3}([0-9a-f]{3})?$/i.test(a)&&(a="#"+a);d.call(g,a)};f=function(a){a.removeListener("ok",c);a.removeListener("cancel",c)};e=function(a){a.on("ok",
c);a.on("cancel",c)};b.execCommand("colordialog");if(b._.storedDialogs&&b._.storedDialogs.colordialog)e(b._.storedDialogs.colordialog);else CKEDITOR.on("dialogDefinition",function(a){if("colordialog"==a.data.name){var b=a.data.definition;a.removeListener();b.onLoad=CKEDITOR.tools.override(b.onLoad,function(a){return function(){e(this);b.onLoad=a;"function"==typeof a&&a.call(this)}})}})}}};CKEDITOR.plugins.add("colordialog",CKEDITOR.plugins.colordialog);(function(){CKEDITOR.plugins.add("templates",{requires:"dialog",init:function(a){CKEDITOR.dialog.add("templates",CKEDITOR.getUrl(this.path+"dialogs/templates.js"));a.addCommand("templates",new CKEDITOR.dialogCommand("templates"));a.ui.addButton&&a.ui.addButton("Templates",{label:a.lang.templates.button,command:"templates",toolbar:"doctools,10"})}});var c={},f={};CKEDITOR.addTemplates=function(a,d){c[a]=d};CKEDITOR.getTemplates=function(a){return c[a]};CKEDITOR.loadTemplates=function(a,d){for(var e=
[],b=0,c=a.length;b<c;b++)f[a[b]]||(e.push(a[b]),f[a[b]]=1);e.length?CKEDITOR.scriptLoader.load(e,d):setTimeout(d,0)}})();CKEDITOR.config.templates_files=[CKEDITOR.getUrl("plugins/templates/templates/default.js")];CKEDITOR.config.templates_replaceContent=!0;CKEDITOR.plugins.add("menu",{requires:"floatpanel",beforeInit:function(l){for(var h=l.config.menu_groups.split(","),r=l._.menuGroups={},t=l._.menuItems={},n=0;n<h.length;n++)r[h[n]]=n+1;l.addMenuGroup=function(a,b){r[a]=b||100};l.addMenuItem=function(a,b){r[b.group]&&(t[a]=new CKEDITOR.menuItem(this,a,b))};l.addMenuItems=function(a){for(var b in a)this.addMenuItem(b,a[b])};l.getMenuItem=function(a){return t[a]};l.removeMenuItem=function(a){delete t[a]}}});
(function(){function l(a){a.sort(function(a,d){return a.group<d.group?-1:a.group>d.group?1:a.order<d.order?-1:a.order>d.order?1:0})}var h='\x3cspan class\x3d"cke_menuitem"\x3e\x3ca id\x3d"{id}" class\x3d"cke_menubutton cke_menubutton__{name} cke_menubutton_{state} {cls}" href\x3d"{href}" title\x3d"{title}" tabindex\x3d"-1" _cke_focus\x3d1 hidefocus\x3d"true" role\x3d"{role}" aria-label\x3d"{label}" aria-describedby\x3d"{id}_description" aria-haspopup\x3d"{hasPopup}" aria-disabled\x3d"{disabled}" {ariaChecked} draggable\x3d"false"';
CKEDITOR.env.gecko&&CKEDITOR.env.mac&&(h+=' onkeypress\x3d"return false;"');CKEDITOR.env.gecko&&(h+=' onblur\x3d"this.style.cssText \x3d this.style.cssText;" ondragstart\x3d"return false;"');var h=h+(' onmouseover\x3d"CKEDITOR.tools.callFunction({hoverFn},{index});" onmouseout\x3d"CKEDITOR.tools.callFunction({moveOutFn},{index});" '+(CKEDITOR.env.ie?'onclick\x3d"return false;" onmouseup':"onclick")+'\x3d"CKEDITOR.tools.callFunction({clickFn},{index}); return false;"\x3e'),r=CKEDITOR.addTemplate("menuItem",
h+'\x3cspan class\x3d"cke_menubutton_inner"\x3e\x3cspan class\x3d"cke_menubutton_icon"\x3e\x3cspan class\x3d"cke_button_icon cke_button__{iconName}_icon" style\x3d"{iconStyle}"\x3e\x3c/span\x3e\x3c/span\x3e\x3cspan class\x3d"cke_menubutton_label"\x3e{label}\x3c/span\x3e{shortcutHtml}{arrowHtml}\x3c/span\x3e\x3c/a\x3e\x3cspan id\x3d"{id}_description" class\x3d"cke_voice_label" aria-hidden\x3d"false"\x3e{ariaShortcut}\x3c/span\x3e\x3c/span\x3e'),t=CKEDITOR.addTemplate("menuArrow",'\x3cspan class\x3d"cke_menuarrow"\x3e\x3cspan\x3e{label}\x3c/span\x3e\x3c/span\x3e'),
n=CKEDITOR.addTemplate("menuShortcut",'\x3cspan class\x3d"cke_menubutton_label cke_menubutton_shortcut"\x3e{shortcut}\x3c/span\x3e');CKEDITOR.menu=CKEDITOR.tools.createClass({$:function(a,b){b=this._.definition=b||{};this.id=CKEDITOR.tools.getNextId();this.editor=a;this.items=[];this._.listeners=[];this._.level=b.level||1;var d=CKEDITOR.tools.extend({},b.panel,{css:[CKEDITOR.skin.getPath("editor")],level:this._.level-1,block:{}}),m=d.block.attributes=d.attributes||{};!m.role&&(m.role="menu");this._.panelDefinition=
d},_:{onShow:function(){var a=this.editor.getSelection(),b=a&&a.getStartElement(),d=this.editor.elementPath(),m=this._.listeners;this.removeAll();for(var g=0;g<m.length;g++){var k=m[g](b,a,d);if(k)for(var e in k){var f=this.editor.getMenuItem(e);!f||f.command&&!this.editor.getCommand(f.command).state||(f.state=k[e],this.add(f))}}},onClick:function(a){this.hide();if(a.onClick)a.onClick();else a.command&&this.editor.execCommand(a.command)},onEscape:function(a){var b=this.parent;b?b._.panel.hideChild(1):
27==a&&this.hide(1);return!1},onHide:function(){this.onHide&&this.onHide()},showSubMenu:function(a){var b=this._.subMenu,d=this.items[a];if(d=d.getItems&&d.getItems()){b?b.removeAll():(b=this._.subMenu=new CKEDITOR.menu(this.editor,CKEDITOR.tools.extend({},this._.definition,{level:this._.level+1},!0)),b.parent=this,b._.onClick=CKEDITOR.tools.bind(this._.onClick,this));for(var m in d){var g=this.editor.getMenuItem(m);g&&(g.state=d[m],b.add(g))}var k=this._.panel.getBlock(this.id).element.getDocument().getById(this.id+
String(a));setTimeout(function(){b.show(k,2)},0)}else this._.panel.hideChild(1)}},proto:{add:function(a){a.order||(a.order=this.items.length);this.items.push(a)},removeAll:function(){this.items=[]},show:function(a,b,d,m){if(!this.parent&&(this._.onShow(),!this.items.length))return;b=b||("rtl"==this.editor.lang.dir?2:1);var g=this.items,k=this.editor,e=this._.panel,f=this._.element;if(!e){e=this._.panel=new CKEDITOR.ui.floatPanel(this.editor,CKEDITOR.document.getBody(),this._.panelDefinition,this._.level);
e.onEscape=CKEDITOR.tools.bind(function(a){if(!1===this._.onEscape(a))return!1},this);e.onShow=function(){e._.panel.getHolderElement().getParent().addClass("cke").addClass("cke_reset_all")};e.onHide=CKEDITOR.tools.bind(function(){this._.onHide&&this._.onHide()},this);f=e.addBlock(this.id,this._.panelDefinition.block);f.autoSize=!0;var c=f.keys;c[40]="next";c[9]="next";c[38]="prev";c[CKEDITOR.SHIFT+9]="prev";c["rtl"==k.lang.dir?37:39]=CKEDITOR.env.ie?"mouseup":"click";c[32]=CKEDITOR.env.ie?"mouseup":
"click";CKEDITOR.env.ie&&(c[13]="mouseup");f=this._.element=f.element;c=f.getDocument();c.getBody().setStyle("overflow","hidden");c.getElementsByTag("html").getItem(0).setStyle("overflow","hidden");this._.itemOverFn=CKEDITOR.tools.addFunction(function(a){clearTimeout(this._.showSubTimeout);this._.showSubTimeout=CKEDITOR.tools.setTimeout(this._.showSubMenu,k.config.menu_subMenuDelay||400,this,[a])},this);this._.itemOutFn=CKEDITOR.tools.addFunction(function(){clearTimeout(this._.showSubTimeout)},this);
this._.itemClickFn=CKEDITOR.tools.addFunction(function(a){var b=this.items[a];if(b.state==CKEDITOR.TRISTATE_DISABLED)this.hide(1);else if(b.getItems)this._.showSubMenu(a);else this._.onClick(b)},this)}l(g);for(var c=k.elementPath(),c=['\x3cdiv class\x3d"cke_menu'+(c&&c.direction()!=k.lang.dir?" cke_mixed_dir_content":"")+'" role\x3d"presentation"\x3e'],h=g.length,n=h&&g[0].group,q=0;q<h;q++){var p=g[q];n!=p.group&&(c.push('\x3cdiv class\x3d"cke_menuseparator" role\x3d"separator"\x3e\x3c/div\x3e'),
n=p.group);p.render(this,q,c)}c.push("\x3c/div\x3e");f.setHtml(c.join(""));CKEDITOR.ui.fire("ready",this);this.parent?this.parent._.panel.showAsChild(e,this.id,a,b,d,m):e.showBlock(this.id,a,b,d,m);k.fire("menuShow",[e])},addListener:function(a){this._.listeners.push(a)},hide:function(a){this._.onHide&&this._.onHide();this._.panel&&this._.panel.hide(a)},findItemByCommandName:function(a){var b=CKEDITOR.tools.array.filter(this.items,function(b){return a===b.command});return b.length?(b=b[0],{item:b,
element:this._.element.findOne("."+b.className)}):null}}});CKEDITOR.menuItem=CKEDITOR.tools.createClass({$:function(a,b,d){CKEDITOR.tools.extend(this,d,{order:0,className:"cke_menubutton__"+b});this.group=a._.menuGroups[this.group];this.editor=a;this.name=b},proto:{render:function(a,b,d){var h=a.id+String(b),g="undefined"==typeof this.state?CKEDITOR.TRISTATE_OFF:this.state,k="",e=this.editor,f,c,l=g==CKEDITOR.TRISTATE_ON?"on":g==CKEDITOR.TRISTATE_DISABLED?"disabled":"off";this.role in{menuitemcheckbox:1,
menuitemradio:1}&&(k=' aria-checked\x3d"'+(g==CKEDITOR.TRISTATE_ON?"true":"false")+'"');var u=this.getItems,q="\x26#"+("rtl"==this.editor.lang.dir?"9668":"9658")+";",p=this.name;this.icon&&!/\./.test(this.icon)&&(p=this.icon);this.command&&(f=e.getCommand(this.command),(f=e.getCommandKeystroke(f))&&(c=CKEDITOR.tools.keystrokeToString(e.lang.common.keyboard,f)));a={id:h,name:this.name,iconName:p,label:this.label,cls:this.className||"",state:l,hasPopup:u?"true":"false",disabled:g==CKEDITOR.TRISTATE_DISABLED,
title:this.label+(c?" ("+c.display+")":""),ariaShortcut:c?e.lang.common.keyboardShortcut+" "+c.aria:"",href:"javascript:void('"+(this.label||"").replace("'")+"')",hoverFn:a._.itemOverFn,moveOutFn:a._.itemOutFn,clickFn:a._.itemClickFn,index:b,iconStyle:CKEDITOR.skin.getIconStyle(p,"rtl"==this.editor.lang.dir,p==this.icon?null:this.icon,this.iconOffset),shortcutHtml:c?n.output({shortcut:c.display}):"",arrowHtml:u?t.output({label:q}):"",role:this.role?this.role:"menuitem",ariaChecked:k};r.output(a,d)}}})})();
CKEDITOR.config.menu_groups="clipboard,form,tablecell,tablecellproperties,tablerow,tablecolumn,table,anchor,link,image,flash,checkbox,radio,textfield,hiddenfield,imagebutton,button,select,textarea,div";CKEDITOR.plugins.add("contextmenu",{requires:"menu",onLoad:function(){CKEDITOR.plugins.contextMenu=CKEDITOR.tools.createClass({base:CKEDITOR.menu,$:function(a){this.base.call(this,a,{panel:{className:"cke_menu_panel",attributes:{"aria-label":a.lang.contextmenu.options}}})},proto:{addTarget:function(a,e){a.on("contextmenu",function(a){a=a.data;var c=CKEDITOR.env.webkit?f:CKEDITOR.env.mac?a.$.metaKey:a.$.ctrlKey;if(!e||!c){a.preventDefault();if(CKEDITOR.env.mac&&CKEDITOR.env.webkit){var c=this.editor,
b=(new CKEDITOR.dom.elementPath(a.getTarget(),c.editable())).contains(function(a){return a.hasAttribute("contenteditable")},!0);b&&"false"==b.getAttribute("contenteditable")&&c.getSelection().fake(b)}var b=a.getTarget().getDocument(),d=a.getTarget().getDocument().getDocumentElement(),c=!b.equals(CKEDITOR.document),b=b.getWindow().getScrollPosition(),g=c?a.$.clientX:a.$.pageX||b.x+a.$.clientX,h=c?a.$.clientY:a.$.pageY||b.y+a.$.clientY;CKEDITOR.tools.setTimeout(function(){this.open(d,null,g,h)},CKEDITOR.env.ie?
200:0,this)}},this);if(CKEDITOR.env.webkit){var f,d=function(){f=0};a.on("keydown",function(a){f=CKEDITOR.env.mac?a.data.$.metaKey:a.data.$.ctrlKey});a.on("keyup",d);a.on("contextmenu",d)}},open:function(a,e,f,d){!1!==this.editor.config.enableContextMenu&&(this.editor.focus(),a=a||CKEDITOR.document.getDocumentElement(),this.editor.selectionChange(1),this.show(a,e,f,d))}}})},beforeInit:function(a){var e=a.contextMenu=new CKEDITOR.plugins.contextMenu(a);a.on("contentDom",function(){e.addTarget(a.editable(),
!1!==a.config.browserContextMenuOnCtrl)});a.addCommand("contextMenu",{exec:function(){a.contextMenu.open(a.document.getBody())}});a.setKeystroke(CKEDITOR.SHIFT+121,"contextMenu");a.setKeystroke(CKEDITOR.CTRL+CKEDITOR.SHIFT+121,"contextMenu")}});(function(){function k(a,b,d,e){var c=new CKEDITOR.dom.walker(a);if(a=a.startContainer.getAscendant(b,!0)||a.endContainer.getAscendant(b,!0))if(d(a),e)return;for(;a=c.next();)if(a=a.getAscendant(b,!0))if(d(a),e)break}function u(a,b){var d={ul:"ol",ol:"ul"};return-1!==l(b,function(b){return b.element===a||b.element===d[a]})}function q(a){this.styles=null;this.sticky=!1;this.editor=a;this.filter=new CKEDITOR.filter(a.config.copyFormatting_allowRules);!0===a.config.copyFormatting_allowRules&&(this.filter.disabled=
!0);a.config.copyFormatting_disallowRules&&this.filter.disallow(a.config.copyFormatting_disallowRules)}var l=CKEDITOR.tools.indexOf,r=CKEDITOR.tools.getMouseButton,t=!1;CKEDITOR.plugins.add("copyformatting",{lang:"az,de,en,it,ja,nb,nl,oc,pl,pt-br,ru,sv,tr,zh,zh-cn",icons:"copyformatting",hidpi:!0,init:function(a){var b=CKEDITOR.plugins.copyformatting;b._addScreenReaderContainer();t||(CKEDITOR.document.appendStyleSheet(this.path+"styles/copyformatting.css"),t=!0);a.addContentsCss&&a.addContentsCss(this.path+
"styles/copyformatting.css");a.copyFormatting=new b.state(a);a.addCommand("copyFormatting",b.commands.copyFormatting);a.addCommand("applyFormatting",b.commands.applyFormatting);a.ui.addButton("CopyFormatting",{label:a.lang.copyformatting.label,command:"copyFormatting",toolbar:"cleanup,0"});a.on("contentDom",function(){var d=a.editable(),b=d.isInline()?d:a.document,c=a.ui.get("CopyFormatting");d.attachListener(b,"mouseup",function(b){r(b)===CKEDITOR.MOUSE_BUTTON_LEFT&&a.execCommand("applyFormatting")});
d.attachListener(CKEDITOR.document,"mouseup",function(b){var e=a.getCommand("copyFormatting");r(b)!==CKEDITOR.MOUSE_BUTTON_LEFT||e.state!==CKEDITOR.TRISTATE_ON||d.contains(b.data.getTarget())||a.execCommand("copyFormatting")});c&&(b=CKEDITOR.document.getById(c._.id),d.attachListener(b,"dblclick",function(){a.execCommand("copyFormatting",{sticky:!0})}),d.attachListener(b,"mouseup",function(a){a.data.stopPropagation()}))});a.config.copyFormatting_keystrokeCopy&&a.setKeystroke(a.config.copyFormatting_keystrokeCopy,
"copyFormatting");a.on("key",function(b){var e=a.getCommand("copyFormatting");b=b.data.domEvent;b.getKeystroke&&27===b.getKeystroke()&&e.state===CKEDITOR.TRISTATE_ON&&a.execCommand("copyFormatting")});a.copyFormatting.on("extractFormatting",function(d){var e=d.data.element;if(e.contains(a.editable())||e.equals(a.editable()))return d.cancel();e=b._convertElementToStyleDef(e);if(!a.copyFormatting.filter.check(new CKEDITOR.style(e),!0,!0))return d.cancel();d.data.styleDef=e});a.copyFormatting.on("applyFormatting",
function(d){if(!d.data.preventFormatStripping){var e=d.data.range,c=b._extractStylesFromRange(a,e),f=b._determineContext(e),g,h;if(a.copyFormatting._isContextAllowed(f))for(h=0;h<c.length;h++)f=c[h],g=e.createBookmark(),-1===l(b.preservedElements,f.element)?CKEDITOR.env.webkit&&!CKEDITOR.env.chrome?c[h].removeFromRange(d.data.range,d.editor):c[h].remove(d.editor):u(f.element,d.data.styles)&&b._removeStylesFromElementInRange(e,f.element),e.moveToBookmark(g)}});a.copyFormatting.on("applyFormatting",
function(b){var e=CKEDITOR.plugins.copyformatting,c=e._determineContext(b.data.range);"list"===c&&a.copyFormatting._isContextAllowed("list")?e._applyStylesToListContext(b.editor,b.data.range,b.data.styles):"table"===c&&a.copyFormatting._isContextAllowed("table")?e._applyStylesToTableContext(b.editor,b.data.range,b.data.styles):a.copyFormatting._isContextAllowed("text")&&e._applyStylesToTextContext(b.editor,b.data.range,b.data.styles)},null,null,999)}});q.prototype._isContextAllowed=function(a){var b=
this.editor.config.copyFormatting_allowedContexts;return!0===b||-1!==l(b,a)};CKEDITOR.event.implementOn(q.prototype);CKEDITOR.plugins.copyformatting={state:q,inlineBoundary:"h1 h2 h3 h4 h5 h6 p div".split(" "),excludedAttributes:["id","style","href","data-cke-saved-href","dir"],elementsForInlineTransform:["li"],excludedElementsFromInlineTransform:["table","thead","tbody","ul","ol"],excludedAttributesFromInlineTransform:["value","type"],preservedElements:"ul ol li td th tr thead tbody table".split(" "),
breakOnElements:["ul","ol","table"],_initialKeystrokePasteCommand:null,commands:{copyFormatting:{exec:function(a,b){var d=CKEDITOR.plugins.copyformatting,e=a.copyFormatting,c=b?"keystrokeHandler"==b.from:!1,f=b?b.sticky||c:!1,g=d._getCursorContainer(a),h=CKEDITOR.document.getDocumentElement();if(this.state===CKEDITOR.TRISTATE_ON)return e.styles=null,e.sticky=!1,g.removeClass("cke_copyformatting_active"),h.removeClass("cke_copyformatting_disabled"),h.removeClass("cke_copyformatting_tableresize_cursor"),
d._putScreenReaderMessage(a,"canceled"),d._detachPasteKeystrokeHandler(a),this.setState(CKEDITOR.TRISTATE_OFF);e.styles=d._extractStylesFromElement(a,a.elementPath().lastElement);this.setState(CKEDITOR.TRISTATE_ON);c||(g.addClass("cke_copyformatting_active"),h.addClass("cke_copyformatting_tableresize_cursor"),a.config.copyFormatting_outerCursor&&h.addClass("cke_copyformatting_disabled"));e.sticky=f;d._putScreenReaderMessage(a,"copied");d._attachPasteKeystrokeHandler(a)}},applyFormatting:{editorFocus:CKEDITOR.env.ie&&
!CKEDITOR.env.edge?!1:!0,exec:function(a,b){var d=a.getCommand("copyFormatting"),e=b?"keystrokeHandler"==b.from:!1,c=CKEDITOR.plugins.copyformatting,f=a.copyFormatting,g=c._getCursorContainer(a),h=CKEDITOR.document.getDocumentElement();if(e||d.state===CKEDITOR.TRISTATE_ON){if(e&&!f.styles)return c._putScreenReaderMessage(a,"failed"),c._detachPasteKeystrokeHandler(a),!1;e=c._applyFormat(a,f.styles);f.sticky||(f.styles=null,g.removeClass("cke_copyformatting_active"),h.removeClass("cke_copyformatting_disabled"),
h.removeClass("cke_copyformatting_tableresize_cursor"),d.setState(CKEDITOR.TRISTATE_OFF),c._detachPasteKeystrokeHandler(a));c._putScreenReaderMessage(a,e?"applied":"canceled")}}}},_getCursorContainer:function(a){return a.elementMode===CKEDITOR.ELEMENT_MODE_INLINE?a.editable():a.editable().getParent()},_convertElementToStyleDef:function(a){var b=CKEDITOR.tools,d=a.getAttributes(CKEDITOR.plugins.copyformatting.excludedAttributes),b=b.parseCssText(a.getAttribute("style"),!0,!0);return{element:a.getName(),
type:CKEDITOR.STYLE_INLINE,attributes:d,styles:b}},_extractStylesFromElement:function(a,b){var d={},e=[];do if(b.type===CKEDITOR.NODE_ELEMENT&&!b.hasAttribute("data-cke-bookmark")&&(d.element=b,a.copyFormatting.fire("extractFormatting",d,a)&&d.styleDef&&e.push(new CKEDITOR.style(d.styleDef)),b.getName&&-1!==l(CKEDITOR.plugins.copyformatting.breakOnElements,b.getName())))break;while((b=b.getParent())&&b.type===CKEDITOR.NODE_ELEMENT);return e},_extractStylesFromRange:function(a,b){for(var d=[],e=new CKEDITOR.dom.walker(b),
c;c=e.next();)d=d.concat(CKEDITOR.plugins.copyformatting._extractStylesFromElement(a,c));return d},_removeStylesFromElementInRange:function(a,b){for(var d=-1!==l(["ol","ul","table"],b),e=new CKEDITOR.dom.walker(a),c;c=e.next();)if(c=c.getAscendant(b,!0))if(c.removeAttributes(c.getAttributes()),d)break},_getSelectedWordOffset:function(a){function b(a,b){return a[b?"getPrevious":"getNext"](function(a){return a.type!==CKEDITOR.NODE_COMMENT})}function d(a){return a.type==CKEDITOR.NODE_ELEMENT?(a=a.getHtml().replace(/<span.*?>&nbsp;<\/span>/g,
""),a.replace(/<.*?>/g,"")):a.getText()}function e(a,c){var f=a,g=/\s/g,h="p br ol ul li td th div caption body".split(" "),m=!1,k=!1,p,n;do{for(p=b(f,c);!p&&f.getParent();){f=f.getParent();if(-1!==l(h,f.getName())){k=m=!0;break}p=b(f,c)}if(p&&p.getName&&-1!==l(h,p.getName())){m=!0;break}f=p}while(f&&f.getStyle&&("none"==f.getStyle("display")||!f.getText()));for(f||(f=a);f.type!==CKEDITOR.NODE_TEXT;)f=!m||c||k?f.getChild(0):f.getChild(f.getChildCount()-1);for(h=d(f);null!=(k=g.exec(h))&&(n=k.index,
c););if("number"!==typeof n&&!m)return e(f,c);if(m)c?n=0:(g=/([\.\b]*$)/,n=(k=g.exec(h))?k.index:h.length);else if(c&&(n+=1,n>h.length))return e(f);return{node:f,offset:n}}var c=/\b\w+\b/ig,f,g,h,m,k;h=m=k=a.startContainer;for(f=d(h);null!=(g=c.exec(f));)if(g.index+g[0].length>=a.startOffset)return a=g.index,c=g.index+g[0].length,0===g.index&&(g=e(h,!0),m=g.node,a=g.offset),c>=f.length&&(f=e(h),k=f.node,c=f.offset),{startNode:m,startOffset:a,endNode:k,endOffset:c};return null},_filterStyles:function(a){var b=
CKEDITOR.tools.isEmpty,d=[],e,c;for(c=0;c<a.length;c++)e=a[c]._.definition,-1!==CKEDITOR.tools.indexOf(CKEDITOR.plugins.copyformatting.inlineBoundary,e.element)&&(e.element=a[c].element="span"),"span"===e.element&&b(e.attributes)&&b(e.styles)||d.push(a[c]);return d},_determineContext:function(a){function b(b){var e=new CKEDITOR.dom.walker(a),c;if(a.startContainer.getAscendant(b,!0)||a.endContainer.getAscendant(b,!0))return!0;for(;c=e.next();)if(c.getAscendant(b,!0))return!0}return b({ul:1,ol:1})?
"list":b("table")?"table":"text"},_applyStylesToTextContext:function(a,b,d){var e=CKEDITOR.plugins.copyformatting,c=e.excludedAttributesFromInlineTransform,f,g;CKEDITOR.env.webkit&&!CKEDITOR.env.chrome&&a.getSelection().selectRanges([b]);for(f=0;f<d.length;f++)if(b=d[f],-1===l(e.excludedElementsFromInlineTransform,b.element)){if(-1!==l(e.elementsForInlineTransform,b.element))for(b.element=b._.definition.element="span",g=0;g<c.length;g++)b._.definition.attributes[c[g]]&&delete b._.definition.attributes[c[g]];
b.apply(a)}},_applyStylesToListContext:function(a,b,d){var e,c,f;for(f=0;f<d.length;f++)e=d[f],c=b.createBookmark(),"ol"===e.element||"ul"===e.element?k(b,{ul:1,ol:1},function(a){var b=e;a.getName()!==b.element&&a.renameNode(b.element);b.applyToObject(a)},!0):"li"===e.element?k(b,"li",function(a){e.applyToObject(a)}):CKEDITOR.plugins.copyformatting._applyStylesToTextContext(a,b,[e]),b.moveToBookmark(c)},_applyStylesToTableContext:function(a,b,d){function e(a,b){a.getName()!==b.element&&(b=b.getDefinition(),
b.element=a.getName(),b=new CKEDITOR.style(b));b.applyToObject(a)}var c,f,g;for(g=0;g<d.length;g++)c=d[g],f=b.createBookmark(),-1!==l(["table","tr"],c.element)?k(b,c.element,function(a){c.applyToObject(a)}):-1!==l(["td","th"],c.element)?k(b,{td:1,th:1},function(a){e(a,c)}):-1!==l(["thead","tbody"],c.element)?k(b,{thead:1,tbody:1},function(a){e(a,c)}):CKEDITOR.plugins.copyformatting._applyStylesToTextContext(a,b,[c]),b.moveToBookmark(f)},_applyFormat:function(a,b){var d=a.getSelection().getRanges()[0],
e=CKEDITOR.plugins.copyformatting,c,f;if(!d)return!1;if(d.collapsed){f=a.getSelection().createBookmarks();if(!(c=e._getSelectedWordOffset(d)))return;d=a.createRange();d.setStart(c.startNode,c.startOffset);d.setEnd(c.endNode,c.endOffset);d.select()}b=e._filterStyles(b);if(!a.copyFormatting.fire("applyFormatting",{styles:b,range:d,preventFormatStripping:!1},a))return!1;f&&a.getSelection().selectBookmarks(f);return!0},_putScreenReaderMessage:function(a,b){var d=this._getScreenReaderContainer();d&&d.setText(a.lang.copyformatting.notification[b])},
_addScreenReaderContainer:function(){if(this._getScreenReaderContainer())return this._getScreenReaderContainer();if(!CKEDITOR.env.ie6Compat&&!CKEDITOR.env.ie7Compat)return CKEDITOR.document.getBody().append(CKEDITOR.dom.element.createFromHtml('\x3cdiv class\x3d"cke_screen_reader_only cke_copyformatting_notification"\x3e\x3cdiv aria-live\x3d"polite"\x3e\x3c/div\x3e\x3c/div\x3e')).getChild(0)},_getScreenReaderContainer:function(){if(!CKEDITOR.env.ie6Compat&&!CKEDITOR.env.ie7Compat)return CKEDITOR.document.getBody().findOne(".cke_copyformatting_notification div[aria-live]")},
_attachPasteKeystrokeHandler:function(a){var b=a.config.copyFormatting_keystrokePaste;b&&(this._initialKeystrokePasteCommand=a.keystrokeHandler.keystrokes[b],a.setKeystroke(b,"applyFormatting"))},_detachPasteKeystrokeHandler:function(a){var b=a.config.copyFormatting_keystrokePaste;b&&a.setKeystroke(b,this._initialKeystrokePasteCommand||!1)}};CKEDITOR.config.copyFormatting_outerCursor=!0;CKEDITOR.config.copyFormatting_allowRules="b s u i em strong span p div td th ol ul li(*)[*]{*}";CKEDITOR.config.copyFormatting_disallowRules=
"*[data-cke-widget*,data-widget*,data-cke-realelement](cke_widget*)";CKEDITOR.config.copyFormatting_allowedContexts=!0;CKEDITOR.config.copyFormatting_keystrokeCopy=CKEDITOR.CTRL+CKEDITOR.SHIFT+67;CKEDITOR.config.copyFormatting_keystrokePaste=CKEDITOR.CTRL+CKEDITOR.SHIFT+86})();(function(){CKEDITOR.plugins.add("div",{requires:"dialog",init:function(a){if(!a.blockless){var c=a.lang.div,b="div(*)";CKEDITOR.dialog.isTabEnabled(a,"editdiv","advanced")&&(b+=";div[dir,id,lang,title]{*}");a.addCommand("creatediv",new CKEDITOR.dialogCommand("creatediv",{allowedContent:b,requiredContent:"div",contextSensitive:!0,contentTransformations:[["div: alignmentToStyle"]],refresh:function(a,c){this.setState("div"in(a.config.div_wrapTable?c.root:c.blockLimit).getDtd()?CKEDITOR.TRISTATE_OFF:
CKEDITOR.TRISTATE_DISABLED)}}));a.addCommand("editdiv",new CKEDITOR.dialogCommand("editdiv",{requiredContent:"div"}));a.addCommand("removediv",{requiredContent:"div",exec:function(a){function c(b){(b=CKEDITOR.plugins.div.getSurroundDiv(a,b))&&!b.data("cke-div-added")&&(f.push(b),b.data("cke-div-added"))}for(var b=a.getSelection(),g=b&&b.getRanges(),e,h=b.createBookmarks(),f=[],d=0;d<g.length;d++)e=g[d],e.collapsed?c(b.getStartElement()):(e=new CKEDITOR.dom.walker(e),e.evaluator=c,e.lastForward());
for(d=0;d<f.length;d++)f[d].remove(!0);b.selectBookmarks(h)}});a.ui.addButton&&a.ui.addButton("CreateDiv",{label:c.toolbar,command:"creatediv",toolbar:"blocks,50"});a.addMenuItems&&(a.addMenuItems({editdiv:{label:c.edit,command:"editdiv",group:"div",order:1},removediv:{label:c.remove,command:"removediv",group:"div",order:5}}),a.contextMenu&&a.contextMenu.addListener(function(b){return!b||b.isReadOnly()?null:CKEDITOR.plugins.div.getSurroundDiv(a)?{editdiv:CKEDITOR.TRISTATE_OFF,removediv:CKEDITOR.TRISTATE_OFF}:
null}));CKEDITOR.dialog.add("creatediv",this.path+"dialogs/div.js");CKEDITOR.dialog.add("editdiv",this.path+"dialogs/div.js")}}});CKEDITOR.plugins.div={getSurroundDiv:function(a,c){var b=a.elementPath(c);return a.elementPath(b.blockLimit).contains(function(a){return a.is("div")&&!a.isReadOnly()},1)}}})();CKEDITOR.plugins.add("resize",{init:function(b){function f(d){var e=c.width,m=c.height,f=e+(d.data.$.screenX-n.x)*("rtl"==g?-1:1);d=m+(d.data.$.screenY-n.y);h&&(e=Math.max(a.resize_minWidth,Math.min(f,a.resize_maxWidth)));p&&(m=Math.max(a.resize_minHeight,Math.min(d,a.resize_maxHeight)));b.resize(h?e:null,m)}function k(){CKEDITOR.document.removeListener("mousemove",f);CKEDITOR.document.removeListener("mouseup",k);b.document&&(b.document.removeListener("mousemove",f),b.document.removeListener("mouseup",
k))}var a=b.config,r=b.ui.spaceId("resizer"),g=b.element?b.element.getDirection(1):"ltr";!a.resize_dir&&(a.resize_dir="vertical");void 0===a.resize_maxWidth&&(a.resize_maxWidth=3E3);void 0===a.resize_maxHeight&&(a.resize_maxHeight=3E3);void 0===a.resize_minWidth&&(a.resize_minWidth=750);void 0===a.resize_minHeight&&(a.resize_minHeight=250);if(!1!==a.resize_enabled){var l=null,n,c,h=("both"==a.resize_dir||"horizontal"==a.resize_dir)&&a.resize_minWidth!=a.resize_maxWidth,p=("both"==a.resize_dir||"vertical"==
a.resize_dir)&&a.resize_minHeight!=a.resize_maxHeight,q=CKEDITOR.tools.addFunction(function(d){l||(l=b.getResizable());c={width:l.$.offsetWidth||0,height:l.$.offsetHeight||0};n={x:d.screenX,y:d.screenY};a.resize_minWidth>c.width&&(a.resize_minWidth=c.width);a.resize_minHeight>c.height&&(a.resize_minHeight=c.height);CKEDITOR.document.on("mousemove",f);CKEDITOR.document.on("mouseup",k);b.document&&(b.document.on("mousemove",f),b.document.on("mouseup",k));d.preventDefault&&d.preventDefault()});b.on("destroy",
function(){CKEDITOR.tools.removeFunction(q)});b.on("uiSpace",function(a){if("bottom"==a.data.space){var e="";h&&!p&&(e=" cke_resizer_horizontal");!h&&p&&(e=" cke_resizer_vertical");var c='\x3cspan id\x3d"'+r+'" class\x3d"cke_resizer'+e+" cke_resizer_"+g+'" title\x3d"'+CKEDITOR.tools.htmlEncode(b.lang.common.resize)+'" onmousedown\x3d"CKEDITOR.tools.callFunction('+q+', event)"\x3e'+("ltr"==g?"◢":"◣")+"\x3c/span\x3e";"ltr"==g&&"ltr"==e?a.data.html+=c:a.data.html=c+a.data.html}},b,null,100);b.on("maximize",
function(a){b.ui.space("resizer")[a.data==CKEDITOR.TRISTATE_ON?"hide":"show"]()})}}});(function(){function q(a,c){function k(b){b=h.list[b];var e;b.equals(a.editable())||"true"==b.getAttribute("contenteditable")?(e=a.createRange(),e.selectNodeContents(b),e=e.select()):(e=a.getSelection(),e.selectElement(b));CKEDITOR.env.ie&&a.fire("selectionChange",{selection:e,path:new CKEDITOR.dom.elementPath(b)});a.focus()}function l(){m&&m.setHtml('\x3cspan class\x3d"cke_path_empty"\x3e\x26nbsp;\x3c/span\x3e');delete h.list}var n=a.ui.spaceId("path"),m,h=a._.elementsPath,q=h.idBase;c.html+='\x3cspan id\x3d"'+
n+'_label" class\x3d"cke_voice_label"\x3e'+a.lang.elementspath.eleLabel+'\x3c/span\x3e\x3cspan id\x3d"'+n+'" class\x3d"cke_path" role\x3d"group" aria-labelledby\x3d"'+n+'_label"\x3e\x3cspan class\x3d"cke_path_empty"\x3e\x26nbsp;\x3c/span\x3e\x3c/span\x3e';a.on("uiReady",function(){var b=a.ui.space("path");b&&a.focusManager.add(b,1)});h.onClick=k;var v=CKEDITOR.tools.addFunction(k),w=CKEDITOR.tools.addFunction(function(b,e){var g=h.idBase,d;e=new CKEDITOR.dom.event(e);d="rtl"==a.lang.dir;switch(e.getKeystroke()){case d?
39:37:case 9:return(d=CKEDITOR.document.getById(g+(b+1)))||(d=CKEDITOR.document.getById(g+"0")),d.focus(),!1;case d?37:39:case CKEDITOR.SHIFT+9:return(d=CKEDITOR.document.getById(g+(b-1)))||(d=CKEDITOR.document.getById(g+(h.list.length-1))),d.focus(),!1;case 27:return a.focus(),!1;case 13:case 32:return k(b),!1}return!0});a.on("selectionChange",function(b){for(var e=[],g=h.list=[],d=[],c=h.filters,p=!0,k=b.data.path.elements,u=k.length;u--;){var f=k[u],r=0;b=f.data("cke-display-name")?f.data("cke-display-name"):
f.data("cke-real-element-type")?f.data("cke-real-element-type"):f.getName();(p=f.hasAttribute("contenteditable")?"true"==f.getAttribute("contenteditable"):p)||f.hasAttribute("contenteditable")||(r=1);for(var t=0;t<c.length;t++){var l=c[t](f,b);if(!1===l){r=1;break}b=l||b}r||(g.unshift(f),d.unshift(b))}g=g.length;for(c=0;c<g;c++)b=d[c],p=a.lang.elementspath.eleTitle.replace(/%1/,b),b=x.output({id:q+c,label:p,text:b,jsTitle:"javascript:void('"+b+"')",index:c,keyDownFn:w,clickFn:v}),e.unshift(b);m||
(m=CKEDITOR.document.getById(n));d=m;d.setHtml(e.join("")+'\x3cspan class\x3d"cke_path_empty"\x3e\x26nbsp;\x3c/span\x3e');a.fire("elementsPathUpdate",{space:d})});a.on("readOnly",l);a.on("contentDomUnload",l);a.addCommand("elementsPathFocus",y.toolbarFocus);a.setKeystroke(CKEDITOR.ALT+122,"elementsPathFocus")}var y={toolbarFocus:{editorFocus:!1,readOnly:1,exec:function(a){(a=CKEDITOR.document.getById(a._.elementsPath.idBase+"0"))&&a.focus(CKEDITOR.env.ie||CKEDITOR.env.air)}}},c="";CKEDITOR.env.gecko&&
CKEDITOR.env.mac&&(c+=' onkeypress\x3d"return false;"');CKEDITOR.env.gecko&&(c+=' onblur\x3d"this.style.cssText \x3d this.style.cssText;"');var x=CKEDITOR.addTemplate("pathItem",'\x3ca id\x3d"{id}" href\x3d"{jsTitle}" tabindex\x3d"-1" class\x3d"cke_path_item" title\x3d"{label}"'+c+' hidefocus\x3d"true"  onkeydown\x3d"return CKEDITOR.tools.callFunction({keyDownFn},{index}, event );" onclick\x3d"CKEDITOR.tools.callFunction({clickFn},{index}); return false;" role\x3d"button" aria-label\x3d"{label}"\x3e{text}\x3c/a\x3e');
CKEDITOR.plugins.add("elementspath",{init:function(a){a._.elementsPath={idBase:"cke_elementspath_"+CKEDITOR.tools.getNextNumber()+"_",filters:[]};a.on("uiSpace",function(c){"bottom"==c.data.space&&q(a,c.data)})}})})();(function(){function x(a,e,b){b=a.config.forceEnterMode||b;if("wysiwyg"==a.mode){e||(e=a.activeEnterMode);var g=a.elementPath();g&&!g.isContextFor("p")&&(e=CKEDITOR.ENTER_BR,b=1);a.fire("saveSnapshot");e==CKEDITOR.ENTER_BR?u(a,e,null,b):r(a,e,null,b);a.fire("saveSnapshot")}}function y(a){a=a.getSelection().getRanges(!0);for(var e=a.length-1;0<e;e--)a[e].deleteContents();return a[0]}function z(a){var e=a.startContainer.getAscendant(function(a){return a.type==CKEDITOR.NODE_ELEMENT&&"true"==a.getAttribute("contenteditable")},
!0);if(a.root.equals(e))return a;e=new CKEDITOR.dom.range(e);e.moveToRange(a);return e}CKEDITOR.plugins.add("enterkey",{init:function(a){a.addCommand("enter",{modes:{wysiwyg:1},editorFocus:!1,exec:function(a){x(a)}});a.addCommand("shiftEnter",{modes:{wysiwyg:1},editorFocus:!1,exec:function(a){x(a,a.activeShiftEnterMode,1)}});a.setKeystroke([[13,"enter"],[CKEDITOR.SHIFT+13,"shiftEnter"]])}});var A=CKEDITOR.dom.walker.whitespaces(),B=CKEDITOR.dom.walker.bookmark(),v,u,r,w;CKEDITOR.plugins.enterkey=
{enterBlock:function(a,e,b,g){function m(a){var b;if(a===CKEDITOR.ENTER_BR||-1===CKEDITOR.tools.indexOf(["td","th"],p.lastElement.getName())||1!==p.lastElement.getChildCount())return!1;a=p.lastElement.getChild(0).clone(!0);(b=a.getBogus())&&b.remove();return a.getText().length?!1:!0}if(b=b||y(a)){b=z(b);var h=b.document,n=b.checkStartOfBlock(),f=b.checkEndOfBlock(),p=a.elementPath(b.startContainer),c=p.block,l=e==CKEDITOR.ENTER_DIV?"div":"p",d;if(n&&f){if(c&&(c.is("li")||c.getParent().is("li"))){c.is("li")||
(c=c.getParent());b=c.getParent();d=b.getParent();g=!c.hasPrevious();var f=!c.hasNext(),l=a.getSelection(),n=l.createBookmarks(),k=c.getDirection(1),t=c.getAttribute("class"),q=c.getAttribute("style"),r=d.getDirection(1)!=k;a=a.enterMode!=CKEDITOR.ENTER_BR||r||q||t;if(d.is("li"))g||f?(g&&f&&b.remove(),c[f?"insertAfter":"insertBefore"](d)):c.breakParent(d);else{if(a)if(p.block.is("li")?(d=h.createElement(e==CKEDITOR.ENTER_P?"p":"div"),r&&d.setAttribute("dir",k),q&&d.setAttribute("style",q),t&&d.setAttribute("class",
t),c.moveChildren(d)):d=p.block,g||f)d[g?"insertBefore":"insertAfter"](b);else c.breakParent(b),d.insertAfter(b);else if(c.appendBogus(!0),g||f)for(;h=c[g?"getFirst":"getLast"]();)h[g?"insertBefore":"insertAfter"](b);else for(c.breakParent(b);h=c.getLast();)h.insertAfter(b);c.remove()}l.selectBookmarks(n);return}if(c&&c.getParent().is("blockquote")){c.breakParent(c.getParent());c.getPrevious().getFirst(CKEDITOR.dom.walker.invisible(1))||c.getPrevious().remove();c.getNext().getFirst(CKEDITOR.dom.walker.invisible(1))||
c.getNext().remove();b.moveToElementEditStart(c);b.select();return}}else if(c&&c.is("pre")&&!f){u(a,e,b,g);return}if(q=b.splitBlock(l)){a=q.previousBlock;c=q.nextBlock;n=q.wasStartOfBlock;f=q.wasEndOfBlock;c?(k=c.getParent(),k.is("li")&&(c.breakParent(k),c.move(c.getNext(),1))):a&&(k=a.getParent())&&k.is("li")&&(a.breakParent(k),k=a.getNext(),b.moveToElementEditStart(k),a.move(a.getPrevious()));if(n||f)if(m(e))b.moveToElementEditStart(b.getTouchedStartNode());else{if(a){if(a.is("li")||!w.test(a.getName())&&
!a.is("pre"))d=a.clone()}else c&&(d=c.clone());d?g&&!d.is("li")&&d.renameNode(l):k&&k.is("li")?d=k:(d=h.createElement(l),a&&(t=a.getDirection())&&d.setAttribute("dir",t));if(h=q.elementPath)for(e=0,g=h.elements.length;e<g;e++){l=h.elements[e];if(l.equals(h.block)||l.equals(h.blockLimit))break;CKEDITOR.dtd.$removeEmpty[l.getName()]&&(l=l.clone(),d.moveChildren(l),d.append(l))}d.appendBogus();d.getParent()||b.insertNode(d);d.is("li")&&d.removeAttribute("value");!CKEDITOR.env.ie||!n||f&&a.getChildCount()||
(b.moveToElementEditStart(f?a:d),b.select());b.moveToElementEditStart(n&&!f?c:d)}else c.is("li")&&(d=b.clone(),d.selectNodeContents(c),d=new CKEDITOR.dom.walker(d),d.evaluator=function(a){return!(B(a)||A(a)||a.type==CKEDITOR.NODE_ELEMENT&&a.getName()in CKEDITOR.dtd.$inline&&!(a.getName()in CKEDITOR.dtd.$empty))},(k=d.next())&&k.type==CKEDITOR.NODE_ELEMENT&&k.is("ul","ol")&&(CKEDITOR.env.needsBrFiller?h.createElement("br"):h.createText(" ")).insertBefore(k)),c&&b.moveToElementEditStart(c);b.select();
b.scrollIntoView()}}},enterBr:function(a,e,b,g){if(b=b||y(a)){var m=b.document,h=b.checkEndOfBlock(),n=new CKEDITOR.dom.elementPath(a.getSelection().getStartElement()),f=n.block,p=f&&n.block.getName();g||"li"!=p?(!g&&h&&w.test(p)?(h=f.getDirection())?(m=m.createElement("div"),m.setAttribute("dir",h),m.insertAfter(f),b.setStart(m,0)):(m.createElement("br").insertAfter(f),CKEDITOR.env.gecko&&m.createText("").insertAfter(f),b.setStartAt(f.getNext(),CKEDITOR.env.ie?CKEDITOR.POSITION_BEFORE_START:CKEDITOR.POSITION_AFTER_START)):
(a="pre"==p&&CKEDITOR.env.ie&&8>CKEDITOR.env.version?m.createText("\r"):m.createElement("br"),b.deleteContents(),b.insertNode(a),CKEDITOR.env.needsBrFiller?(m.createText("﻿").insertAfter(a),h&&(f||n.blockLimit).appendBogus(),a.getNext().$.nodeValue="",b.setStartAt(a.getNext(),CKEDITOR.POSITION_AFTER_START)):b.setStartAt(a,CKEDITOR.POSITION_AFTER_END)),b.collapse(!0),b.select(),b.scrollIntoView()):r(a,e,b,g)}}};v=CKEDITOR.plugins.enterkey;u=v.enterBr;r=v.enterBlock;w=/^h[1-6]$/})();(function(){function k(b,f){var g={},c=[],e={nbsp:" ",shy:"­",gt:"\x3e",lt:"\x3c",amp:"\x26",apos:"'",quot:'"'};b=b.replace(/\b(nbsp|shy|gt|lt|amp|apos|quot)(?:,|$)/g,function(b,a){var d=f?"\x26"+a+";":e[a];g[d]=f?e[a]:"\x26"+a+";";c.push(d);return""});if(!f&&b){b=b.split(",");var a=document.createElement("div"),d;a.innerHTML="\x26"+b.join(";\x26")+";";d=a.innerHTML;a=null;for(a=0;a<d.length;a++){var h=d.charAt(a);g[h]="\x26"+b[a]+";";c.push(h)}}g.regex=c.join(f?"|":"");return g}CKEDITOR.plugins.add("entities",
{afterInit:function(b){function f(a){return h[a]}function g(b){return"force"!=c.entities_processNumerical&&a[b]?a[b]:"\x26#"+b.charCodeAt(0)+";"}var c=b.config;if(b=(b=b.dataProcessor)&&b.htmlFilter){var e=[];!1!==c.basicEntities&&e.push("nbsp,gt,lt,amp");c.entities&&(e.length&&e.push("quot,iexcl,cent,pound,curren,yen,brvbar,sect,uml,copy,ordf,laquo,not,shy,reg,macr,deg,plusmn,sup2,sup3,acute,micro,para,middot,cedil,sup1,ordm,raquo,frac14,frac12,frac34,iquest,times,divide,fnof,bull,hellip,prime,Prime,oline,frasl,weierp,image,real,trade,alefsym,larr,uarr,rarr,darr,harr,crarr,lArr,uArr,rArr,dArr,hArr,forall,part,exist,empty,nabla,isin,notin,ni,prod,sum,minus,lowast,radic,prop,infin,ang,and,or,cap,cup,int,there4,sim,cong,asymp,ne,equiv,le,ge,sub,sup,nsub,sube,supe,oplus,otimes,perp,sdot,lceil,rceil,lfloor,rfloor,lang,rang,loz,spades,clubs,hearts,diams,circ,tilde,ensp,emsp,thinsp,zwnj,zwj,lrm,rlm,ndash,mdash,lsquo,rsquo,sbquo,ldquo,rdquo,bdquo,dagger,Dagger,permil,lsaquo,rsaquo,euro"),
c.entities_latin&&e.push("Agrave,Aacute,Acirc,Atilde,Auml,Aring,AElig,Ccedil,Egrave,Eacute,Ecirc,Euml,Igrave,Iacute,Icirc,Iuml,ETH,Ntilde,Ograve,Oacute,Ocirc,Otilde,Ouml,Oslash,Ugrave,Uacute,Ucirc,Uuml,Yacute,THORN,szlig,agrave,aacute,acirc,atilde,auml,aring,aelig,ccedil,egrave,eacute,ecirc,euml,igrave,iacute,icirc,iuml,eth,ntilde,ograve,oacute,ocirc,otilde,ouml,oslash,ugrave,uacute,ucirc,uuml,yacute,thorn,yuml,OElig,oelig,Scaron,scaron,Yuml"),c.entities_greek&&e.push("Alpha,Beta,Gamma,Delta,Epsilon,Zeta,Eta,Theta,Iota,Kappa,Lambda,Mu,Nu,Xi,Omicron,Pi,Rho,Sigma,Tau,Upsilon,Phi,Chi,Psi,Omega,alpha,beta,gamma,delta,epsilon,zeta,eta,theta,iota,kappa,lambda,mu,nu,xi,omicron,pi,rho,sigmaf,sigma,tau,upsilon,phi,chi,psi,omega,thetasym,upsih,piv"),
c.entities_additional&&e.push(c.entities_additional));var a=k(e.join(",")),d=a.regex?"["+a.regex+"]":"a^";delete a.regex;c.entities&&c.entities_processNumerical&&(d="[^ -~]|"+d);var d=new RegExp(d,"g"),h=k("nbsp,gt,lt,amp,shy",!0),l=new RegExp(h.regex,"g");b.addRules({text:function(a){return a.replace(l,f).replace(d,g)}},{applyToAll:!0,excludeNestedEditable:!0})}}})})();CKEDITOR.config.basicEntities=!0;CKEDITOR.config.entities=!0;CKEDITOR.config.entities_latin=!0;CKEDITOR.config.entities_greek=!0;
CKEDITOR.config.entities_additional="#39";CKEDITOR.plugins.add("popup");
CKEDITOR.tools.extend(CKEDITOR.editor.prototype,{popup:function(e,a,b,d){a=a||"80%";b=b||"70%";"string"==typeof a&&1<a.length&&"%"==a.substr(a.length-1,1)&&(a=parseInt(window.screen.width*parseInt(a,10)/100,10));"string"==typeof b&&1<b.length&&"%"==b.substr(b.length-1,1)&&(b=parseInt(window.screen.height*parseInt(b,10)/100,10));640>a&&(a=640);420>b&&(b=420);var f=parseInt((window.screen.height-b)/2,10),g=parseInt((window.screen.width-a)/2,10);d=(d||"location\x3dno,menubar\x3dno,toolbar\x3dno,dependent\x3dyes,minimizable\x3dno,modal\x3dyes,alwaysRaised\x3dyes,resizable\x3dyes,scrollbars\x3dyes")+",width\x3d"+
a+",height\x3d"+b+",top\x3d"+f+",left\x3d"+g;var c=window.open("",null,d,!0);if(!c)return!1;try{-1==navigator.userAgent.toLowerCase().indexOf(" chrome/")&&(c.moveTo(g,f),c.resizeTo(a,b)),c.focus(),c.location.href=e}catch(h){window.open(e,null,d,!0)}return!0}});(function(){function k(a){this.editor=a;this.loaders=[]}function l(a,c,b){var d=a.config.fileTools_defaultFileName;this.editor=a;this.lang=a.lang;"string"===typeof c?(this.data=c,this.file=n(this.data),this.loaded=this.total=this.file.size):(this.data=null,this.file=c,this.total=this.file.size,this.loaded=0);b?this.fileName=b:this.file.name?this.fileName=this.file.name:(a=this.file.type.split("/"),d&&(a[0]=d),this.fileName=a.join("."));this.uploaded=0;this.responseData=this.uploadTotal=null;this.status=
"created";this.abort=function(){this.changeStatus("abort")}}function n(a){var c=a.match(m)[1];a=a.replace(m,"");a=atob(a);var b=[],d,f,g,e;for(d=0;d<a.length;d+=512){f=a.slice(d,d+512);g=Array(f.length);for(e=0;e<f.length;e++)g[e]=f.charCodeAt(e);f=new Uint8Array(g);b.push(f)}return new Blob(b,{type:c})}CKEDITOR.plugins.add("filetools",{beforeInit:function(a){a.uploadRepository=new k(a);a.on("fileUploadRequest",function(a){var b=a.data.fileLoader;b.xhr.open("POST",b.uploadUrl,!0);a.data.requestData.upload=
{file:b.file,name:b.fileName}},null,null,5);a.on("fileUploadRequest",function(c){var b=c.data.fileLoader,d=new FormData;c=c.data.requestData;var f=a.config.fileTools_requestHeaders,g,e;for(e in c){var h=c[e];"object"===typeof h&&h.file?d.append(e,h.file,h.name):d.append(e,h)}d.append("ckCsrfToken",CKEDITOR.tools.getCsrfToken());if(f)for(g in f)b.xhr.setRequestHeader(g,f[g]);b.xhr.send(d)},null,null,999);a.on("fileUploadResponse",function(a){var b=a.data.fileLoader,d=b.xhr,f=a.data;try{var g=JSON.parse(d.responseText);
g.error&&g.error.message&&(f.message=g.error.message);if(g.uploaded)for(var e in g)f[e]=g[e];else a.cancel()}catch(h){f.message=b.lang.filetools.responseError,CKEDITOR.warn("filetools-response-error",{responseText:d.responseText}),a.cancel()}},null,null,999)}});k.prototype={create:function(a,c,b){b=b||l;var d=this.loaders.length;a=new b(this.editor,a,c);a.id=d;this.loaders[d]=a;this.fire("instanceCreated",a);return a},isFinished:function(){for(var a=0;a<this.loaders.length;++a)if(!this.loaders[a].isFinished())return!1;
return!0}};l.prototype={loadAndUpload:function(a,c){var b=this;this.once("loaded",function(d){d.cancel();b.once("update",function(a){a.cancel()},null,null,0);b.upload(a,c)},null,null,0);this.load()},load:function(){var a=this,c=this.reader=new FileReader;a.changeStatus("loading");this.abort=function(){a.reader.abort()};c.onabort=function(){a.changeStatus("abort")};c.onerror=function(){a.message=a.lang.filetools.loadError;a.changeStatus("error")};c.onprogress=function(b){a.loaded=b.loaded;a.update()};
c.onload=function(){a.loaded=a.total;a.data=c.result;a.changeStatus("loaded")};c.readAsDataURL(this.file)},upload:function(a,c){var b=c||{};a?(this.uploadUrl=a,this.xhr=new XMLHttpRequest,this.attachRequestListeners(),this.editor.fire("fileUploadRequest",{fileLoader:this,requestData:b})&&this.changeStatus("uploading")):(this.message=this.lang.filetools.noUrlError,this.changeStatus("error"))},attachRequestListeners:function(){function a(){"error"!=b.status&&(b.message=b.lang.filetools.networkError,
b.changeStatus("error"))}function c(){"abort"!=b.status&&b.changeStatus("abort")}var b=this,d=this.xhr;b.abort=function(){d.abort();c()};d.onerror=a;d.onabort=c;d.upload?(d.upload.onprogress=function(a){a.lengthComputable&&(b.uploadTotal||(b.uploadTotal=a.total),b.uploaded=a.loaded,b.update())},d.upload.onerror=a,d.upload.onabort=c):(b.uploadTotal=b.total,b.update());d.onload=function(){b.update();if("abort"!=b.status)if(b.uploaded=b.uploadTotal,200>d.status||299<d.status)b.message=b.lang.filetools["httpError"+
d.status],b.message||(b.message=b.lang.filetools.httpError.replace("%1",d.status)),b.changeStatus("error");else{for(var a={fileLoader:b},c=["message","fileName","url"],e=b.editor.fire("fileUploadResponse",a),h=0;h<c.length;h++){var k=c[h];"string"===typeof a[k]&&(b[k]=a[k])}b.responseData=a;delete b.responseData.fileLoader;!1===e?b.changeStatus("error"):b.changeStatus("uploaded")}}},changeStatus:function(a){this.status=a;if("error"==a||"abort"==a||"loaded"==a||"uploaded"==a)this.abort=function(){};
this.fire(a);this.update()},update:function(){this.fire("update")},isFinished:function(){return!!this.status.match(/^(?:loaded|uploaded|error|abort)$/)}};CKEDITOR.event.implementOn(k.prototype);CKEDITOR.event.implementOn(l.prototype);var m=/^data:(\S*?);base64,/;CKEDITOR.fileTools||(CKEDITOR.fileTools={});CKEDITOR.tools.extend(CKEDITOR.fileTools,{uploadRepository:k,fileLoader:l,getUploadUrl:function(a,c){var b=CKEDITOR.tools.capitalize;return c&&a[c+"UploadUrl"]?a[c+"UploadUrl"]:a.uploadUrl?a.uploadUrl:
c&&a["filebrowser"+b(c,1)+"UploadUrl"]?a["filebrowser"+b(c,1)+"UploadUrl"]+"\x26responseType\x3djson":a.filebrowserUploadUrl?a.filebrowserUploadUrl+"\x26responseType\x3djson":null},isTypeSupported:function(a,c){return!!a.type.match(c)},isFileUploadSupported:"function"===typeof FileReader&&"function"===typeof(new FileReader).readAsDataURL&&"function"===typeof FormData&&"function"===typeof(new FormData).append&&"function"===typeof XMLHttpRequest&&"function"===typeof Blob})})();(function(){function g(a,b){var d=[];if(b)for(var c in b)d.push(c+"\x3d"+encodeURIComponent(b[c]));else return a;return a+(-1!=a.indexOf("?")?"\x26":"?")+d.join("\x26")}function p(a){return!a.match(/command=QuickUpload/)||a.match(/(\?|&)responseType=json/)?a:g(a,{responseType:"json"})}function k(a){a+="";return a.charAt(0).toUpperCase()+a.substr(1)}function q(){var a=this.getDialog(),b=a.getParentEditor();b._.filebrowserSe=this;var d=b.config["filebrowser"+k(a.getName())+"WindowWidth"]||b.config.filebrowserWindowWidth||
"80%",a=b.config["filebrowser"+k(a.getName())+"WindowHeight"]||b.config.filebrowserWindowHeight||"70%",c=this.filebrowser.params||{};c.CKEditor=b.name;c.CKEditorFuncNum=b._.filebrowserFn;c.langCode||(c.langCode=b.langCode);c=g(this.filebrowser.url,c);b.popup(c,d,a,b.config.filebrowserWindowFeatures||b.config.fileBrowserWindowFeatures)}function r(a){var b=new CKEDITOR.dom.element(a.$.form);b&&((a=b.$.elements.ckCsrfToken)?a=new CKEDITOR.dom.element(a):(a=new CKEDITOR.dom.element("input"),a.setAttributes({name:"ckCsrfToken",
type:"hidden"}),b.append(a)),a.setAttribute("value",CKEDITOR.tools.getCsrfToken()))}function t(){var a=this.getDialog();a.getParentEditor()._.filebrowserSe=this;return a.getContentElement(this["for"][0],this["for"][1]).getInputElement().$.value&&a.getContentElement(this["for"][0],this["for"][1]).getAction()?!0:!1}function u(a,b,d){var c=d.params||{};c.CKEditor=a.name;c.CKEditorFuncNum=a._.filebrowserFn;c.langCode||(c.langCode=a.langCode);b.action=g(d.url,c);b.filebrowser=d}function l(a,b,d,c){if(c&&
c.length)for(var e,g=c.length;g--;)if(e=c[g],"hbox"!=e.type&&"vbox"!=e.type&&"fieldset"!=e.type||l(a,b,d,e.children),e.filebrowser)if("string"==typeof e.filebrowser&&(e.filebrowser={action:"fileButton"==e.type?"QuickUpload":"Browse",target:e.filebrowser}),"Browse"==e.filebrowser.action){var f=e.filebrowser.url;void 0===f&&(f=a.config["filebrowser"+k(b)+"BrowseUrl"],void 0===f&&(f=a.config.filebrowserBrowseUrl));f&&(e.onClick=q,e.filebrowser.url=f,e.hidden=!1)}else if("QuickUpload"==e.filebrowser.action&&
e["for"]&&(f=e.filebrowser.url,void 0===f&&(f=a.config["filebrowser"+k(b)+"UploadUrl"],void 0===f&&(f=a.config.filebrowserUploadUrl)),f)){var h=e.onClick;e.onClick=function(b){var c=b.sender,d=c.getDialog().getContentElement(this["for"][0],this["for"][1]).getInputElement(),e=CKEDITOR.fileTools&&CKEDITOR.fileTools.isFileUploadSupported;if(h&&!1===h.call(c,b))return!1;if(t.call(c,b)){if("form"!==a.config.filebrowserUploadMethod&&e)return b=a.uploadRepository.create(d.$.files[0]),b.on("uploaded",function(a){var b=
a.sender.responseData;m.call(a.sender.editor,b.url,b.message)}),b.on("error",n.bind(this)),b.on("abort",n.bind(this)),b.loadAndUpload(p(f)),"xhr";r(d);return!0}return!1};e.filebrowser.url=f;e.hidden=!1;u(a,d.getContents(e["for"][0]).get(e["for"][1]),e.filebrowser)}}function n(a){var b={};try{b=JSON.parse(a.sender.xhr.response)||{}}catch(d){}this.enable();alert(b.error?b.error.message:a.sender.message)}function h(a,b,d){if(-1!==d.indexOf(";")){d=d.split(";");for(var c=0;c<d.length;c++)if(h(a,b,d[c]))return!0;
return!1}return(a=a.getContents(b).get(d).filebrowser)&&a.url}function m(a,b){var d=this._.filebrowserSe.getDialog(),c=this._.filebrowserSe["for"],e=this._.filebrowserSe.filebrowser.onSelect;c&&d.getContentElement(c[0],c[1]).reset();if("function"!=typeof b||!1!==b.call(this._.filebrowserSe))if(!e||!1!==e.call(this._.filebrowserSe,a,b))if("string"==typeof b&&b&&alert(b),a&&(c=this._.filebrowserSe,d=c.getDialog(),c=c.filebrowser.target||null))if(c=c.split(":"),e=d.getContentElement(c[0],c[1]))e.setValue(a),
d.selectPage(c[0])}CKEDITOR.plugins.add("filebrowser",{requires:"popup,filetools",init:function(a){a._.filebrowserFn=CKEDITOR.tools.addFunction(m,a);a.on("destroy",function(){CKEDITOR.tools.removeFunction(this._.filebrowserFn)})}});CKEDITOR.on("dialogDefinition",function(a){if(a.editor.plugins.filebrowser)for(var b=a.data.definition,d,c=0;c<b.contents.length;++c)if(d=b.contents[c])l(a.editor,a.data.name,b,d.elements),d.hidden&&d.filebrowser&&(d.hidden=!h(b,d.id,d.filebrowser))})})();CKEDITOR.plugins.add("find",{requires:"dialog",init:function(a){var b=a.addCommand("find",new CKEDITOR.dialogCommand("find")),c=a.addCommand("replace",new CKEDITOR.dialogCommand("find",{tabId:"replace"}));b.canUndo=!1;b.readOnly=1;c.canUndo=!1;a.ui.addButton&&(a.ui.addButton("Find",{label:a.lang.find.find,command:"find",toolbar:"find,10"}),a.ui.addButton("Replace",{label:a.lang.find.replace,command:"replace",toolbar:"find,20"}));CKEDITOR.dialog.add("find",this.path+"dialogs/find.js")}});
CKEDITOR.config.find_highlight={element:"span",styles:{"background-color":"#004",color:"#fff"}};(function(){function g(a,b){var c=l.exec(a),d=l.exec(b);if(c){if(!c[2]&&"px"==d[2])return d[1];if("px"==c[2]&&!d[2])return d[1]+"px"}return b}var k=CKEDITOR.htmlParser.cssStyle,h=CKEDITOR.tools.cssLength,l=/^((?:\d*(?:\.\d+))|(?:\d+))(.*)?$/i,m={elements:{$:function(a){var b=a.attributes;if((b=(b=(b=b&&b["data-cke-realelement"])&&new CKEDITOR.htmlParser.fragment.fromHtml(decodeURIComponent(b)))&&b.children[0])&&a.attributes["data-cke-resizable"]){var c=(new k(a)).rules;a=b.attributes;var d=c.width,
c=c.height;d&&(a.width=g(a.width,d));c&&(a.height=g(a.height,c))}return b}}};CKEDITOR.plugins.add("fakeobjects",{init:function(a){a.filter.allow("img[!data-cke-realelement,src,alt,title](*){*}","fakeobjects")},afterInit:function(a){(a=(a=a.dataProcessor)&&a.htmlFilter)&&a.addRules(m,{applyToAll:!0})}});CKEDITOR.editor.prototype.createFakeElement=function(a,b,c,d){var e=this.lang.fakeobjects,e=e[c]||e.unknown;b={"class":b,"data-cke-realelement":encodeURIComponent(a.getOuterHtml()),"data-cke-real-node-type":a.type,
alt:e,title:e,align:a.getAttribute("align")||""};CKEDITOR.env.hc||(b.src=CKEDITOR.tools.transparentImageData);c&&(b["data-cke-real-element-type"]=c);d&&(b["data-cke-resizable"]=d,c=new k,d=a.getAttribute("width"),a=a.getAttribute("height"),d&&(c.rules.width=h(d)),a&&(c.rules.height=h(a)),c.populate(b));return this.document.createElement("img",{attributes:b})};CKEDITOR.editor.prototype.createFakeParserElement=function(a,b,c,d){var e=this.lang.fakeobjects,e=e[c]||e.unknown,f;f=new CKEDITOR.htmlParser.basicWriter;
a.writeHtml(f);f=f.getHtml();b={"class":b,"data-cke-realelement":encodeURIComponent(f),"data-cke-real-node-type":a.type,alt:e,title:e,align:a.attributes.align||""};CKEDITOR.env.hc||(b.src=CKEDITOR.tools.transparentImageData);c&&(b["data-cke-real-element-type"]=c);d&&(b["data-cke-resizable"]=d,d=a.attributes,a=new k,c=d.width,d=d.height,void 0!==c&&(a.rules.width=h(c)),void 0!==d&&(a.rules.height=h(d)),a.populate(b));return new CKEDITOR.htmlParser.element("img",b)};CKEDITOR.editor.prototype.restoreRealElement=
function(a){if(a.data("cke-real-node-type")!=CKEDITOR.NODE_ELEMENT)return null;var b=CKEDITOR.dom.element.createFromHtml(decodeURIComponent(a.data("cke-realelement")),this.document);if(a.data("cke-resizable")){var c=a.getStyle("width");a=a.getStyle("height");c&&b.setAttribute("width",g(b.getAttribute("width"),c));a&&b.setAttribute("height",g(b.getAttribute("height"),a))}return b}})();(function(){function d(a){a=a.attributes;return"application/x-shockwave-flash"==a.type||f.test(a.src||"")}function e(a,b){return a.createFakeParserElement(b,"cke_flash","flash",!0)}var f=/\.swf(?:$|\?)/i;CKEDITOR.plugins.add("flash",{requires:"dialog,fakeobjects",onLoad:function(){CKEDITOR.addCss("img.cke_flash{background-image: url("+CKEDITOR.getUrl(this.path+"images/placeholder.png")+");background-position: center center;background-repeat: no-repeat;border: 1px solid #a9a9a9;width: 80px;height: 80px;}")},
init:function(a){var b="object[classid,codebase,height,hspace,vspace,width];param[name,value];embed[height,hspace,pluginspage,src,type,vspace,width]";CKEDITOR.dialog.isTabEnabled(a,"flash","properties")&&(b+=";object[align]; embed[allowscriptaccess,quality,scale,wmode]");CKEDITOR.dialog.isTabEnabled(a,"flash","advanced")&&(b+=";object[id]{*}; embed[bgcolor]{*}(*)");a.addCommand("flash",new CKEDITOR.dialogCommand("flash",{allowedContent:b,requiredContent:"embed"}));a.ui.addButton&&a.ui.addButton("Flash",
{label:a.lang.common.flash,command:"flash",toolbar:"insert,20"});CKEDITOR.dialog.add("flash",this.path+"dialogs/flash.js");a.addMenuItems&&a.addMenuItems({flash:{label:a.lang.flash.properties,command:"flash",group:"flash"}});a.on("doubleclick",function(a){var b=a.data.element;b.is("img")&&"flash"==b.data("cke-real-element-type")&&(a.data.dialog="flash")});a.contextMenu&&a.contextMenu.addListener(function(a){if(a&&a.is("img")&&!a.isReadOnly()&&"flash"==a.data("cke-real-element-type"))return{flash:CKEDITOR.TRISTATE_OFF}})},
afterInit:function(a){var b=a.dataProcessor;(b=b&&b.dataFilter)&&b.addRules({elements:{"cke:object":function(b){var c=b.attributes;if(!(c.classid&&String(c.classid).toLowerCase()||d(b))){for(c=0;c<b.children.length;c++)if("cke:embed"==b.children[c].name){if(!d(b.children[c]))break;return e(a,b)}return null}return e(a,b)},"cke:embed":function(b){return d(b)?e(a,b):null}}},5)}})})();CKEDITOR.tools.extend(CKEDITOR.config,{flashEmbedTagOnly:!1,flashAddEmbedTag:!0,flashConvertOnEdit:!1});(function(){function k(a){var l=a.config,p=a.fire("uiSpace",{space:"top",html:""}).html,t=function(){function f(a,c,e){b.setStyle(c,w(e));b.setStyle("position",a)}function e(a){var b=k.getDocumentPosition();switch(a){case "top":f("absolute","top",b.y-q-r);break;case "pin":f("fixed","top",x);break;case "bottom":f("absolute","top",b.y+(c.height||c.bottom-c.top)+r)}m=a}var m,k,n,c,h,q,v,p=l.floatSpaceDockedOffsetX||0,r=l.floatSpaceDockedOffsetY||0,u=l.floatSpacePinnedOffsetX||0,x=l.floatSpacePinnedOffsetY||
0;return function(d){if(k=a.editable()){var f=d&&"focus"==d.name;f&&b.show();a.fire("floatingSpaceLayout",{show:f});b.removeStyle("left");b.removeStyle("right");n=b.getClientRect();c=k.getClientRect();h=g.getViewPaneSize();q=n.height;v="pageXOffset"in g.$?g.$.pageXOffset:CKEDITOR.document.$.documentElement.scrollLeft;m?(q+r<=c.top?e("top"):q+r>h.height-c.bottom?e("pin"):e("bottom"),d=h.width/2,d=l.floatSpacePreferRight?"right":0<c.left&&c.right<h.width&&c.width>n.width?"rtl"==l.contentsLangDirection?
"right":"left":d-c.left>c.right-d?"left":"right",n.width>h.width?(d="left",f=0):(f="left"==d?0<c.left?c.left:0:c.right<h.width?h.width-c.right:0,f+n.width>h.width&&(d="left"==d?"right":"left",f=0)),b.setStyle(d,w(("pin"==m?u:p)+f+("pin"==m?0:"left"==d?v:-v)))):(m="pin",e("pin"),t(d))}}}();if(p){var k=new CKEDITOR.template('\x3cdiv id\x3d"cke_{name}" class\x3d"cke {id} cke_reset_all cke_chrome cke_editor_{name} cke_float cke_{langDir} '+CKEDITOR.env.cssClass+'" dir\x3d"{langDir}" title\x3d"'+(CKEDITOR.env.gecko?
" ":"")+'" lang\x3d"{langCode}" role\x3d"application" style\x3d"{style}"'+(a.title?' aria-labelledby\x3d"cke_{name}_arialbl"':" ")+"\x3e"+(a.title?'\x3cspan id\x3d"cke_{name}_arialbl" class\x3d"cke_voice_label"\x3e{voiceLabel}\x3c/span\x3e':" ")+'\x3cdiv class\x3d"cke_inner"\x3e\x3cdiv id\x3d"{topId}" class\x3d"cke_top" role\x3d"presentation"\x3e{content}\x3c/div\x3e\x3c/div\x3e\x3c/div\x3e'),b=CKEDITOR.document.getBody().append(CKEDITOR.dom.element.createFromHtml(k.output({content:p,id:a.id,langDir:a.lang.dir,
langCode:a.langCode,name:a.name,style:"display:none;z-index:"+(l.baseFloatZIndex-1),topId:a.ui.spaceId("top"),voiceLabel:a.title}))),u=CKEDITOR.tools.eventsBuffer(500,t),e=CKEDITOR.tools.eventsBuffer(100,t);b.unselectable();b.on("mousedown",function(a){a=a.data;a.getTarget().hasAscendant("a",1)||a.preventDefault()});a.on("focus",function(b){t(b);a.on("change",u.input);g.on("scroll",e.input);g.on("resize",e.input)});a.on("blur",function(){b.hide();a.removeListener("change",u.input);g.removeListener("scroll",
e.input);g.removeListener("resize",e.input)});a.on("destroy",function(){g.removeListener("scroll",e.input);g.removeListener("resize",e.input);b.clearCustomData();b.remove()});a.focusManager.hasFocus&&b.show();a.focusManager.add(b,1)}}var g=CKEDITOR.document.getWindow(),w=CKEDITOR.tools.cssLength;CKEDITOR.plugins.add("floatingspace",{init:function(a){a.on("loaded",function(){k(this)},null,null,20)}})})();CKEDITOR.plugins.add("listblock",{requires:"panel",onLoad:function(){var f=CKEDITOR.addTemplate("panel-list",'\x3cul role\x3d"presentation" class\x3d"cke_panel_list"\x3e{items}\x3c/ul\x3e'),g=CKEDITOR.addTemplate("panel-list-item",'\x3cli id\x3d"{id}" class\x3d"cke_panel_listItem" role\x3dpresentation\x3e\x3ca id\x3d"{id}_option" _cke_focus\x3d1 hidefocus\x3dtrue title\x3d"{title}" href\x3d"javascript:void(\'{val}\')"  {onclick}\x3d"CKEDITOR.tools.callFunction({clickFn},\'{val}\'); return false;" role\x3d"option"\x3e{text}\x3c/a\x3e\x3c/li\x3e'),
h=CKEDITOR.addTemplate("panel-list-group",'\x3ch1 id\x3d"{id}" class\x3d"cke_panel_grouptitle" role\x3d"presentation" \x3e{label}\x3c/h1\x3e'),k=/\'/g;CKEDITOR.ui.panel.prototype.addListBlock=function(a,b){return this.addBlock(a,new CKEDITOR.ui.listBlock(this.getHolderElement(),b))};CKEDITOR.ui.listBlock=CKEDITOR.tools.createClass({base:CKEDITOR.ui.panel.block,$:function(a,b){b=b||{};var c=b.attributes||(b.attributes={});(this.multiSelect=!!b.multiSelect)&&(c["aria-multiselectable"]=!0);!c.role&&
(c.role="listbox");this.base.apply(this,arguments);this.element.setAttribute("role",c.role);c=this.keys;c[40]="next";c[9]="next";c[38]="prev";c[CKEDITOR.SHIFT+9]="prev";c[32]=CKEDITOR.env.ie?"mouseup":"click";CKEDITOR.env.ie&&(c[13]="mouseup");this._.pendingHtml=[];this._.pendingList=[];this._.items={};this._.groups={}},_:{close:function(){if(this._.started){var a=f.output({items:this._.pendingList.join("")});this._.pendingList=[];this._.pendingHtml.push(a);delete this._.started}},getClick:function(){this._.click||
(this._.click=CKEDITOR.tools.addFunction(function(a){var b=this.toggle(a);if(this.onClick)this.onClick(a,b)},this));return this._.click}},proto:{add:function(a,b,c){var d=CKEDITOR.tools.getNextId();this._.started||(this._.started=1,this._.size=this._.size||0);this._.items[a]=d;var e;e=CKEDITOR.tools.htmlEncodeAttr(a).replace(k,"\\'");a={id:d,val:e,onclick:CKEDITOR.env.ie?'onclick\x3d"return false;" onmouseup':"onclick",clickFn:this._.getClick(),title:CKEDITOR.tools.htmlEncodeAttr(c||a),text:b||a};
this._.pendingList.push(g.output(a))},startGroup:function(a){this._.close();var b=CKEDITOR.tools.getNextId();this._.groups[a]=b;this._.pendingHtml.push(h.output({id:b,label:a}))},commit:function(){this._.close();this.element.appendHtml(this._.pendingHtml.join(""));delete this._.size;this._.pendingHtml=[]},toggle:function(a){var b=this.isMarked(a);b?this.unmark(a):this.mark(a);return!b},hideGroup:function(a){var b=(a=this.element.getDocument().getById(this._.groups[a]))&&a.getNext();a&&(a.setStyle("display",
"none"),b&&"ul"==b.getName()&&b.setStyle("display","none"))},hideItem:function(a){this.element.getDocument().getById(this._.items[a]).setStyle("display","none")},showAll:function(){var a=this._.items,b=this._.groups,c=this.element.getDocument(),d;for(d in a)c.getById(a[d]).setStyle("display","");for(var e in b)a=c.getById(b[e]),d=a.getNext(),a.setStyle("display",""),d&&"ul"==d.getName()&&d.setStyle("display","")},mark:function(a){this.multiSelect||this.unmarkAll();a=this._.items[a];var b=this.element.getDocument().getById(a);
b.addClass("cke_selected");this.element.getDocument().getById(a+"_option").setAttribute("aria-selected",!0);this.onMark&&this.onMark(b)},markFirstDisplayed:function(){var a=this;this._.markFirstDisplayed(function(){a.multiSelect||a.unmarkAll()})},unmark:function(a){var b=this.element.getDocument();a=this._.items[a];var c=b.getById(a);c.removeClass("cke_selected");b.getById(a+"_option").removeAttribute("aria-selected");this.onUnmark&&this.onUnmark(c)},unmarkAll:function(){var a=this._.items,b=this.element.getDocument(),
c;for(c in a){var d=a[c];b.getById(d).removeClass("cke_selected");b.getById(d+"_option").removeAttribute("aria-selected")}this.onUnmark&&this.onUnmark()},isMarked:function(a){return this.element.getDocument().getById(this._.items[a]).hasClass("cke_selected")},focus:function(a){this._.focusIndex=-1;var b=this.element.getElementsByTag("a"),c,d=-1;if(a)for(c=this.element.getDocument().getById(this._.items[a]).getFirst();a=b.getItem(++d);){if(a.equals(c)){this._.focusIndex=d;break}}else this.element.focus();
c&&setTimeout(function(){c.focus()},0)}}})}});CKEDITOR.plugins.add("richcombo",{requires:"floatpanel,listblock,button",beforeInit:function(c){c.ui.addHandler(CKEDITOR.UI_RICHCOMBO,CKEDITOR.ui.richCombo.handler)}});
(function(){var c='\x3cspan id\x3d"{id}" class\x3d"cke_combo cke_combo__{name} {cls}" role\x3d"presentation"\x3e\x3cspan id\x3d"{id}_label" class\x3d"cke_combo_label"\x3e{label}\x3c/span\x3e\x3ca class\x3d"cke_combo_button" title\x3d"{title}" tabindex\x3d"-1"'+(CKEDITOR.env.gecko&&!CKEDITOR.env.hc?"":" href\x3d\"javascript:void('{titleJs}')\"")+' hidefocus\x3d"true" role\x3d"button" aria-labelledby\x3d"{id}_label" aria-haspopup\x3d"true"';CKEDITOR.env.gecko&&CKEDITOR.env.mac&&(c+=' onkeypress\x3d"return false;"');
CKEDITOR.env.gecko&&(c+=' onblur\x3d"this.style.cssText \x3d this.style.cssText;"');var c=c+(' onkeydown\x3d"return CKEDITOR.tools.callFunction({keydownFn},event,this);" onfocus\x3d"return CKEDITOR.tools.callFunction({focusFn},event);" '+(CKEDITOR.env.ie?'onclick\x3d"return false;" onmouseup':"onclick")+'\x3d"CKEDITOR.tools.callFunction({clickFn},this);return false;"\x3e\x3cspan id\x3d"{id}_text" class\x3d"cke_combo_text cke_combo_inlinelabel"\x3e{label}\x3c/span\x3e\x3cspan class\x3d"cke_combo_open"\x3e\x3cspan class\x3d"cke_combo_arrow"\x3e'+
(CKEDITOR.env.hc?"\x26#9660;":CKEDITOR.env.air?"\x26nbsp;":"")+"\x3c/span\x3e\x3c/span\x3e\x3c/a\x3e\x3c/span\x3e"),k=CKEDITOR.addTemplate("combo",c);CKEDITOR.UI_RICHCOMBO="richcombo";CKEDITOR.ui.richCombo=CKEDITOR.tools.createClass({$:function(a){CKEDITOR.tools.extend(this,a,{canGroup:!1,title:a.label,modes:{wysiwyg:1},editorFocus:1});a=this.panel||{};delete this.panel;this.id=CKEDITOR.tools.getNextNumber();this.document=a.parent&&a.parent.getDocument()||CKEDITOR.document;a.className="cke_combopanel";
a.block={multiSelect:a.multiSelect,attributes:a.attributes};a.toolbarRelated=!0;this._={panelDefinition:a,items:{}}},proto:{renderHtml:function(a){var b=[];this.render(a,b);return b.join("")},render:function(a,b){function f(){if(this.getState()!=CKEDITOR.TRISTATE_ON){var b=this.modes[a.mode]?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED;a.readOnly&&!this.readOnly&&(b=CKEDITOR.TRISTATE_DISABLED);this.setState(b);this.setValue("");b!=CKEDITOR.TRISTATE_DISABLED&&this.refresh&&this.refresh()}}var c=
CKEDITOR.env,h="cke_"+this.id,e=CKEDITOR.tools.addFunction(function(b){l&&(a.unlockSelection(1),l=0);g.execute(b)},this),d=this,g={id:h,combo:this,focus:function(){CKEDITOR.document.getById(h).getChild(1).focus()},execute:function(b){var c=d._;if(c.state!=CKEDITOR.TRISTATE_DISABLED)if(d.createPanel(a),c.on)c.panel.hide();else{d.commit();var f=d.getValue();f?c.list.mark(f):c.list.unmarkAll();c.panel.showBlock(d.id,new CKEDITOR.dom.element(b),4)}},clickFn:e};a.on("activeFilterChange",f,this);a.on("mode",
f,this);a.on("selectionChange",f,this);!this.readOnly&&a.on("readOnly",f,this);var m=CKEDITOR.tools.addFunction(function(a,b){a=new CKEDITOR.dom.event(a);var d=a.getKeystroke();switch(d){case 13:case 32:case 40:CKEDITOR.tools.callFunction(e,b);break;default:g.onkey(g,d)}a.preventDefault()}),n=CKEDITOR.tools.addFunction(function(){g.onfocus&&g.onfocus()}),l=0;g.keyDownFn=m;c={id:h,name:this.name||this.command,label:this.label,title:this.title,cls:this.className||"",titleJs:c.gecko&&!c.hc?"":(this.title||
"").replace("'",""),keydownFn:m,focusFn:n,clickFn:e};k.output(c,b);if(this.onRender)this.onRender();return g},createPanel:function(a){if(!this._.panel){var b=this._.panelDefinition,c=this._.panelDefinition.block,k=b.parent||CKEDITOR.document.getBody(),h="cke_combopanel__"+this.name,e=new CKEDITOR.ui.floatPanel(a,k,b),b=e.addListBlock(this.id,c),d=this;e.onShow=function(){this.element.addClass(h);d.setState(CKEDITOR.TRISTATE_ON);d._.on=1;d.editorFocus&&!a.focusManager.hasFocus&&a.focus();if(d.onOpen)d.onOpen()};
e.onHide=function(b){this.element.removeClass(h);d.setState(d.modes&&d.modes[a.mode]?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED);d._.on=0;if(!b&&d.onClose)d.onClose()};e.onEscape=function(){e.hide(1)};b.onClick=function(a,b){d.onClick&&d.onClick.call(d,a,b);e.hide()};this._.panel=e;this._.list=b;e.getBlock(this.id).onHide=function(){d._.on=0;d.setState(CKEDITOR.TRISTATE_OFF)};this.init&&this.init()}},setValue:function(a,b){this._.value=a;var c=this.document.getById("cke_"+this.id+"_text");c&&
(a||b?c.removeClass("cke_combo_inlinelabel"):(b=this.label,c.addClass("cke_combo_inlinelabel")),c.setText("undefined"!=typeof b?b:a))},getValue:function(){return this._.value||""},unmarkAll:function(){this._.list.unmarkAll()},mark:function(a){this._.list.mark(a)},hideItem:function(a){this._.list.hideItem(a)},hideGroup:function(a){this._.list.hideGroup(a)},showAll:function(){this._.list.showAll()},add:function(a,b,c){this._.items[a]=c||a;this._.list.add(a,b,c)},startGroup:function(a){this._.list.startGroup(a)},
commit:function(){this._.committed||(this._.list.commit(),this._.committed=1,CKEDITOR.ui.fire("ready",this));this._.committed=1},setState:function(a){if(this._.state!=a){var b=this.document.getById("cke_"+this.id);b.setState(a,"cke_combo");a==CKEDITOR.TRISTATE_DISABLED?b.setAttribute("aria-disabled",!0):b.removeAttribute("aria-disabled");this._.state=a}},getState:function(){return this._.state},enable:function(){this._.state==CKEDITOR.TRISTATE_DISABLED&&this.setState(this._.lastState)},disable:function(){this._.state!=
CKEDITOR.TRISTATE_DISABLED&&(this._.lastState=this._.state,this.setState(CKEDITOR.TRISTATE_DISABLED))}},statics:{handler:{create:function(a){return new CKEDITOR.ui.richCombo(a)}}}});CKEDITOR.ui.prototype.addRichCombo=function(a,b){this.add(a,CKEDITOR.UI_RICHCOMBO,b)}})();(function(){function p(b,f,e,d,r,p,t,x){var y=b.config,u=new CKEDITOR.style(t),g=r.split(";");r=[];for(var k={},l=0;l<g.length;l++){var m=g[l];if(m){var m=m.split("/"),w={},q=g[l]=m[0];w[e]=r[l]=m[1]||q;k[q]=new CKEDITOR.style(t,w);k[q]._.definition.name=q}else g.splice(l--,1)}b.ui.addRichCombo(f,{label:d.label,title:d.panelTitle,toolbar:"styles,"+x,defaultValue:"cke-default",allowedContent:u,requiredContent:u,contentTransformations:"span"===t.element?[[{element:"font",check:"span",left:function(a){return!!a.attributes.size||
!!a.attributes.align||!!a.attributes.face},right:function(a){var b=" x-small small medium large x-large xx-large 48px".split(" ");a.name="span";a.attributes.size&&(a.styles["font-size"]=b[a.attributes.size],delete a.attributes.size);a.attributes.align&&(a.styles["text-align"]=a.attributes.align,delete a.attributes.align);a.attributes.face&&(a.styles["font-family"]=a.attributes.face,delete a.attributes.face)}}]]:null,panel:{css:[CKEDITOR.skin.getPath("editor")].concat(y.contentsCss),multiSelect:!1,
attributes:{"aria-label":d.panelTitle}},init:function(){var a;a="("+b.lang.common.optionDefault+")";this.startGroup(d.panelTitle);this.add(this.defaultValue,a,a);for(var c=0;c<g.length;c++)a=g[c],this.add(a,k[a].buildPreview(),a)},onClick:function(a){b.focus();b.fire("saveSnapshot");var c=this.getValue(),f=k[a],e,n,h,d,g;if(c&&a!=c)if(e=k[c],c=b.getSelection().getRanges()[0],c.collapsed){if(n=b.elementPath(),h=n.contains(function(a){return e.checkElementRemovable(a)})){d=c.checkBoundaryOfElement(h,
CKEDITOR.START);g=c.checkBoundaryOfElement(h,CKEDITOR.END);if(d&&g){for(d=c.createBookmark();n=h.getFirst();)n.insertBefore(h);h.remove();c.moveToBookmark(d)}else d||g?c.moveToPosition(h,d?CKEDITOR.POSITION_BEFORE_START:CKEDITOR.POSITION_AFTER_END):(c.splitElement(h),c.moveToPosition(h,CKEDITOR.POSITION_AFTER_END)),v(c,n.elements.slice(),h);b.getSelection().selectRanges([c])}}else b.removeStyle(e);a===this.defaultValue?e&&b.removeStyle(e):b.applyStyle(f);b.fire("saveSnapshot")},onRender:function(){b.on("selectionChange",
function(a){var c=this.getValue();a=a.data.path.elements;for(var d=0,f;d<a.length;d++){f=a[d];for(var e in k)if(k[e].checkElementMatch(f,!0,b)){e!=c&&this.setValue(e);return}}this.setValue("",p)},this)},refresh:function(){b.activeFilter.check(u)||this.setState(CKEDITOR.TRISTATE_DISABLED)}})}function v(b,f,e){var d=f.pop();if(d){if(e)return v(b,f,d.equals(e)?null:e);e=d.clone();b.insertNode(e);b.moveToPosition(e,CKEDITOR.POSITION_AFTER_START);v(b,f)}}CKEDITOR.plugins.add("font",{requires:"richcombo",
init:function(b){var f=b.config;p(b,"Font","family",b.lang.font,f.font_names,f.font_defaultLabel,f.font_style,30);p(b,"FontSize","size",b.lang.font.fontSize,f.fontSize_sizes,f.fontSize_defaultLabel,f.fontSize_style,40)}})})();CKEDITOR.config.font_names="Arial/Arial, Helvetica, sans-serif;Comic Sans MS/Comic Sans MS, cursive;Courier New/Courier New, Courier, monospace;Georgia/Georgia, serif;Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;Tahoma/Tahoma, Geneva, sans-serif;Times New Roman/Times New Roman, Times, serif;Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;Verdana/Verdana, Geneva, sans-serif";
CKEDITOR.config.font_defaultLabel="";CKEDITOR.config.font_style={element:"span",styles:{"font-family":"#(family)"},overrides:[{element:"font",attributes:{face:null}}]};CKEDITOR.config.fontSize_sizes="8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px";CKEDITOR.config.fontSize_defaultLabel="";CKEDITOR.config.fontSize_style={element:"span",styles:{"font-size":"#(size)"},overrides:[{element:"font",attributes:{size:null}}]};CKEDITOR.plugins.add("forms",{requires:"dialog,fakeobjects",onLoad:function(){CKEDITOR.addCss(".cke_editable form{border: 1px dotted #FF0000;padding: 2px;}\n");CKEDITOR.addCss("img.cke_hidden{background-image: url("+CKEDITOR.getUrl(this.path+"images/hiddenfield.gif")+");background-position: center center;background-repeat: no-repeat;border: 1px solid #a9a9a9;width: 16px !important;height: 16px !important;}")},init:function(a){var b=a.lang,g=0,h={email:1,password:1,search:1,tel:1,text:1,url:1},l={checkbox:"input[type,name,checked,required]",
radio:"input[type,name,checked,required]",textfield:"input[type,name,value,size,maxlength,required]",textarea:"textarea[cols,rows,name,required]",select:"select[name,size,multiple,required]; option[value,selected]",button:"input[type,name,value]",form:"form[action,name,id,enctype,target,method]",hiddenfield:"input[type,name,value]",imagebutton:"input[type,alt,src]{width,height,border,border-width,border-style,margin,float}"},m={checkbox:"input",radio:"input",textfield:"input",textarea:"textarea",
select:"select",button:"input",form:"form",hiddenfield:"input",imagebutton:"input"},e=function(d,c,e){var h={allowedContent:l[c],requiredContent:m[c]};"form"==c&&(h.context="form");a.addCommand(c,new CKEDITOR.dialogCommand(c,h));a.ui.addButton&&a.ui.addButton(d,{label:b.common[d.charAt(0).toLowerCase()+d.slice(1)],command:c,toolbar:"forms,"+(g+=10)});CKEDITOR.dialog.add(c,e)},f=this.path+"dialogs/";!a.blockless&&e("Form","form",f+"form.js");e("Checkbox","checkbox",f+"checkbox.js");e("Radio","radio",
f+"radio.js");e("TextField","textfield",f+"textfield.js");e("Textarea","textarea",f+"textarea.js");e("Select","select",f+"select.js");e("Button","button",f+"button.js");var k=a.plugins.image;k&&!a.plugins.image2&&e("ImageButton","imagebutton",CKEDITOR.plugins.getPath("image")+"dialogs/image.js");e("HiddenField","hiddenfield",f+"hiddenfield.js");a.addMenuItems&&(e={checkbox:{label:b.forms.checkboxAndRadio.checkboxTitle,command:"checkbox",group:"checkbox"},radio:{label:b.forms.checkboxAndRadio.radioTitle,
command:"radio",group:"radio"},textfield:{label:b.forms.textfield.title,command:"textfield",group:"textfield"},hiddenfield:{label:b.forms.hidden.title,command:"hiddenfield",group:"hiddenfield"},button:{label:b.forms.button.title,command:"button",group:"button"},select:{label:b.forms.select.title,command:"select",group:"select"},textarea:{label:b.forms.textarea.title,command:"textarea",group:"textarea"}},k&&(e.imagebutton={label:b.image.titleButton,command:"imagebutton",group:"imagebutton"}),!a.blockless&&
(e.form={label:b.forms.form.menu,command:"form",group:"form"}),a.addMenuItems(e));a.contextMenu&&(!a.blockless&&a.contextMenu.addListener(function(d,c,a){if((d=a.contains("form",1))&&!d.isReadOnly())return{form:CKEDITOR.TRISTATE_OFF}}),a.contextMenu.addListener(function(d){if(d&&!d.isReadOnly()){var c=d.getName();if("select"==c)return{select:CKEDITOR.TRISTATE_OFF};if("textarea"==c)return{textarea:CKEDITOR.TRISTATE_OFF};if("input"==c){var a=d.getAttribute("type")||"text";switch(a){case "button":case "submit":case "reset":return{button:CKEDITOR.TRISTATE_OFF};
case "checkbox":return{checkbox:CKEDITOR.TRISTATE_OFF};case "radio":return{radio:CKEDITOR.TRISTATE_OFF};case "image":return k?{imagebutton:CKEDITOR.TRISTATE_OFF}:null}if(h[a])return{textfield:CKEDITOR.TRISTATE_OFF}}if("img"==c&&"hiddenfield"==d.data("cke-real-element-type"))return{hiddenfield:CKEDITOR.TRISTATE_OFF}}}));a.on("doubleclick",function(d){var c=d.data.element;if(!a.blockless&&c.is("form"))d.data.dialog="form";else if(c.is("select"))d.data.dialog="select";else if(c.is("textarea"))d.data.dialog=
"textarea";else if(c.is("img")&&"hiddenfield"==c.data("cke-real-element-type"))d.data.dialog="hiddenfield";else if(c.is("input")){c=c.getAttribute("type")||"text";switch(c){case "button":case "submit":case "reset":d.data.dialog="button";break;case "checkbox":d.data.dialog="checkbox";break;case "radio":d.data.dialog="radio";break;case "image":d.data.dialog="imagebutton"}h[c]&&(d.data.dialog="textfield")}})},afterInit:function(a){var b=a.dataProcessor,g=b&&b.htmlFilter,b=b&&b.dataFilter;CKEDITOR.env.ie&&
g&&g.addRules({elements:{input:function(a){a=a.attributes;var b=a.type;b||(a.type="text");"checkbox"!=b&&"radio"!=b||"on"!=a.value||delete a.value}}},{applyToAll:!0});b&&b.addRules({elements:{input:function(b){if("hidden"==b.attributes.type)return a.createFakeParserElement(b,"cke_hidden","hiddenfield")}}},{applyToAll:!0})}});CKEDITOR.plugins.add("format",{requires:"richcombo",init:function(a){if(!a.blockless){for(var f=a.config,c=a.lang.format,l=f.format_tags.split(";"),d={},m=0,n=[],g=0;g<l.length;g++){var h=l[g],k=new CKEDITOR.style(f["format_"+h]);if(!a.filter.customConfig||a.filter.check(k))m++,d[h]=k,d[h]._.enterMode=a.config.enterMode,n.push(k)}0!==m&&a.ui.addRichCombo("Format",{label:c.label,title:c.panelTitle,toolbar:"styles,20",allowedContent:n,panel:{css:[CKEDITOR.skin.getPath("editor")].concat(f.contentsCss),
multiSelect:!1,attributes:{"aria-label":c.panelTitle}},init:function(){this.startGroup(c.panelTitle);for(var a in d){var e=c["tag_"+a];this.add(a,d[a].buildPreview(e),e)}},onClick:function(b){a.focus();a.fire("saveSnapshot");b=d[b];var e=a.elementPath();b.checkActive(e,a)||a.applyStyle(b);setTimeout(function(){a.fire("saveSnapshot")},0)},onRender:function(){a.on("selectionChange",function(b){var e=this.getValue();b=b.data.path;this.refresh();for(var c in d)if(d[c].checkActive(b,a)){c!=e&&this.setValue(c,
a.lang.format["tag_"+c]);return}this.setValue("")},this)},onOpen:function(){this.showAll();for(var b in d)a.activeFilter.check(d[b])||this.hideItem(b)},refresh:function(){var b=a.elementPath();if(b){if(b.isContextFor("p"))for(var c in d)if(a.activeFilter.check(d[c]))return;this.setState(CKEDITOR.TRISTATE_DISABLED)}}})}}});CKEDITOR.config.format_tags="p;h1;h2;h3;h4;h5;h6;pre;address;div";CKEDITOR.config.format_p={element:"p"};CKEDITOR.config.format_div={element:"div"};CKEDITOR.config.format_pre={element:"pre"};
CKEDITOR.config.format_address={element:"address"};CKEDITOR.config.format_h1={element:"h1"};CKEDITOR.config.format_h2={element:"h2"};CKEDITOR.config.format_h3={element:"h3"};CKEDITOR.config.format_h4={element:"h4"};CKEDITOR.config.format_h5={element:"h5"};CKEDITOR.config.format_h6={element:"h6"};(function(){var b={canUndo:!1,exec:function(a){var b=a.document.createElement("hr");a.insertElement(b)},allowedContent:"hr",requiredContent:"hr"};CKEDITOR.plugins.add("horizontalrule",{init:function(a){a.blockless||(a.addCommand("horizontalrule",b),a.ui.addButton&&a.ui.addButton("HorizontalRule",{label:a.lang.horizontalrule.toolbar,command:"horizontalrule",toolbar:"insert,40"}))}})})();CKEDITOR.plugins.add("htmlwriter",{init:function(b){var a=new CKEDITOR.htmlWriter;a.forceSimpleAmpersand=b.config.forceSimpleAmpersand;a.indentationChars=b.config.dataIndentationChars||"\t";b.dataProcessor.writer=a}});
CKEDITOR.htmlWriter=CKEDITOR.tools.createClass({base:CKEDITOR.htmlParser.basicWriter,$:function(){this.base();this.indentationChars="\t";this.selfClosingEnd=" /\x3e";this.lineBreakChars="\n";this.sortAttributes=1;this._.indent=0;this._.indentation="";this._.inPre=0;this._.rules={};var b=CKEDITOR.dtd,a;for(a in CKEDITOR.tools.extend({},b.$nonBodyContent,b.$block,b.$listItem,b.$tableContent))this.setRules(a,{indent:!b[a]["#"],breakBeforeOpen:1,breakBeforeClose:!b[a]["#"],breakAfterClose:1,needsSpace:a in
b.$block&&!(a in{li:1,dt:1,dd:1})});this.setRules("br",{breakAfterOpen:1});this.setRules("title",{indent:0,breakAfterOpen:0});this.setRules("style",{indent:0,breakBeforeClose:1});this.setRules("pre",{breakAfterOpen:1,indent:0})},proto:{openTag:function(b){var a=this._.rules[b];this._.afterCloser&&a&&a.needsSpace&&this._.needsSpace&&this._.output.push("\n");this._.indent?this.indentation():a&&a.breakBeforeOpen&&(this.lineBreak(),this.indentation());this._.output.push("\x3c",b);this._.afterCloser=0},
openTagClose:function(b,a){var c=this._.rules[b];a?(this._.output.push(this.selfClosingEnd),c&&c.breakAfterClose&&(this._.needsSpace=c.needsSpace)):(this._.output.push("\x3e"),c&&c.indent&&(this._.indentation+=this.indentationChars));c&&c.breakAfterOpen&&this.lineBreak();"pre"==b&&(this._.inPre=1)},attribute:function(b,a){"string"==typeof a&&(this.forceSimpleAmpersand&&(a=a.replace(/&amp;/g,"\x26")),a=CKEDITOR.tools.htmlEncodeAttr(a));this._.output.push(" ",b,'\x3d"',a,'"')},closeTag:function(b){var a=
this._.rules[b];a&&a.indent&&(this._.indentation=this._.indentation.substr(this.indentationChars.length));this._.indent?this.indentation():a&&a.breakBeforeClose&&(this.lineBreak(),this.indentation());this._.output.push("\x3c/",b,"\x3e");"pre"==b&&(this._.inPre=0);a&&a.breakAfterClose&&(this.lineBreak(),this._.needsSpace=a.needsSpace);this._.afterCloser=1},text:function(b){this._.indent&&(this.indentation(),!this._.inPre&&(b=CKEDITOR.tools.ltrim(b)));this._.output.push(b)},comment:function(b){this._.indent&&
this.indentation();this._.output.push("\x3c!--",b,"--\x3e")},lineBreak:function(){!this._.inPre&&0<this._.output.length&&this._.output.push(this.lineBreakChars);this._.indent=1},indentation:function(){!this._.inPre&&this._.indentation&&this._.output.push(this._.indentation);this._.indent=0},reset:function(){this._.output=[];this._.indent=0;this._.indentation="";this._.afterCloser=0;this._.inPre=0;this._.needsSpace=0},setRules:function(b,a){var c=this._.rules[b];c?CKEDITOR.tools.extend(c,a,!0):this._.rules[b]=
a}}});(function(){CKEDITOR.plugins.add("iframe",{requires:"dialog,fakeobjects",onLoad:function(){CKEDITOR.addCss("img.cke_iframe{background-image: url("+CKEDITOR.getUrl(this.path+"images/placeholder.png")+");background-position: center center;background-repeat: no-repeat;border: 1px solid #a9a9a9;width: 80px;height: 80px;}")},init:function(a){var b=a.lang.iframe,c="iframe[align,longdesc,frameborder,height,name,scrolling,src,title,width]";a.plugins.dialogadvtab&&(c+=";iframe"+a.plugins.dialogadvtab.allowedContent({id:1,
classes:1,styles:1}));CKEDITOR.dialog.add("iframe",this.path+"dialogs/iframe.js");a.addCommand("iframe",new CKEDITOR.dialogCommand("iframe",{allowedContent:c,requiredContent:"iframe"}));a.ui.addButton&&a.ui.addButton("Iframe",{label:b.toolbar,command:"iframe",toolbar:"insert,80"});a.on("doubleclick",function(a){var b=a.data.element;b.is("img")&&"iframe"==b.data("cke-real-element-type")&&(a.data.dialog="iframe")});a.addMenuItems&&a.addMenuItems({iframe:{label:b.title,command:"iframe",group:"image"}});
a.contextMenu&&a.contextMenu.addListener(function(a){if(a&&a.is("img")&&"iframe"==a.data("cke-real-element-type"))return{iframe:CKEDITOR.TRISTATE_OFF}})},afterInit:function(a){var b=a.dataProcessor;(b=b&&b.dataFilter)&&b.addRules({elements:{iframe:function(b){return a.createFakeParserElement(b,"cke_iframe","iframe",!0)}}})}})})();(function(){function m(a){function f(a){var b=!1;g.attachListener(g,"keydown",function(){var d=c.getBody().getElementsByTag(a);if(!b){for(var e=0;e<d.count();e++)d.getItem(e).setCustomData("retain",!0);b=!0}},null,null,1);g.attachListener(g,"keyup",function(){var d=c.getElementsByTag(a);b&&(1==d.count()&&!d.getItem(0).getCustomData("retain")&&CKEDITOR.tools.isEmpty(d.getItem(0).getAttributes())&&d.getItem(0).remove(1),b=!1)})}var b=this.editor,c=a.document,d=c.body,e=c.getElementById("cke_actscrpt");
e&&e.parentNode.removeChild(e);(e=c.getElementById("cke_shimscrpt"))&&e.parentNode.removeChild(e);(e=c.getElementById("cke_basetagscrpt"))&&e.parentNode.removeChild(e);d.contentEditable=!0;CKEDITOR.env.ie&&(d.hideFocus=!0,d.disabled=!0,d.removeAttribute("disabled"));delete this._.isLoadingData;this.$=d;c=new CKEDITOR.dom.document(c);this.setup();this.fixInitialSelection();var g=this;CKEDITOR.env.ie&&!CKEDITOR.env.edge&&c.getDocumentElement().addClass(c.$.compatMode);CKEDITOR.env.ie&&!CKEDITOR.env.edge&&
b.enterMode!=CKEDITOR.ENTER_P?f("p"):CKEDITOR.env.edge&&15>CKEDITOR.env.version&&b.enterMode!=CKEDITOR.ENTER_DIV&&f("div");if(CKEDITOR.env.webkit||CKEDITOR.env.ie&&10<CKEDITOR.env.version)c.getDocumentElement().on("mousedown",function(a){a.data.getTarget().is("html")&&setTimeout(function(){b.editable().focus()})});n(b);try{b.document.$.execCommand("2D-position",!1,!0)}catch(h){}(CKEDITOR.env.gecko||CKEDITOR.env.ie&&"CSS1Compat"==b.document.$.compatMode)&&this.attachListener(this,"keydown",function(a){var c=
a.data.getKeystroke();if(33==c||34==c)if(CKEDITOR.env.ie)setTimeout(function(){b.getSelection().scrollIntoView()},0);else if(b.window.$.innerHeight>this.$.offsetHeight){var d=b.createRange();d[33==c?"moveToElementEditStart":"moveToElementEditEnd"](this);d.select();a.data.preventDefault()}});CKEDITOR.env.ie&&this.attachListener(c,"blur",function(){try{c.$.selection.empty()}catch(a){}});CKEDITOR.env.iOS&&this.attachListener(c,"touchend",function(){a.focus()});d=b.document.getElementsByTag("title").getItem(0);
d.data("cke-title",d.getText());CKEDITOR.env.ie&&(b.document.$.title=this._.docTitle);CKEDITOR.tools.setTimeout(function(){"unloaded"==this.status&&(this.status="ready");b.fire("contentDom");this._.isPendingFocus&&(b.focus(),this._.isPendingFocus=!1);setTimeout(function(){b.fire("dataReady")},0)},0,this)}function n(a){function f(){var c;a.editable().attachListener(a,"selectionChange",function(){var d=a.getSelection().getSelectedElement();d&&(c&&(c.detachEvent("onresizestart",b),c=null),d.$.attachEvent("onresizestart",
b),c=d.$)})}function b(a){a.returnValue=!1}if(CKEDITOR.env.gecko)try{var c=a.document.$;c.execCommand("enableObjectResizing",!1,!a.config.disableObjectResizing);c.execCommand("enableInlineTableEditing",!1,!a.config.disableNativeTableHandles)}catch(d){}else CKEDITOR.env.ie&&11>CKEDITOR.env.version&&a.config.disableObjectResizing&&f(a)}function p(){var a=[];if(8<=CKEDITOR.document.$.documentMode){a.push("html.CSS1Compat [contenteditable\x3dfalse]{min-height:0 !important}");var f=[],b;for(b in CKEDITOR.dtd.$removeEmpty)f.push("html.CSS1Compat "+
b+"[contenteditable\x3dfalse]");a.push(f.join(",")+"{display:inline-block}")}else CKEDITOR.env.gecko&&(a.push("html{height:100% !important}"),a.push("img:-moz-broken{-moz-force-broken-image-icon:1;min-width:24px;min-height:24px}"));a.push("html{cursor:text;*cursor:auto}");a.push("img,input,textarea{cursor:default}");return a.join("\n")}var l;CKEDITOR.plugins.add("wysiwygarea",{init:function(a){a.config.fullPage&&a.addFeature({allowedContent:"html head title; style [media,type]; body (*)[id]; meta link [*]",
requiredContent:"body"});a.addMode("wysiwyg",function(f){function b(b){b&&b.removeListener();a.editable(new l(a,d.$.contentWindow.document.body));a.setData(a.getData(1),f)}var c="document.open();"+(CKEDITOR.env.ie?"("+CKEDITOR.tools.fixDomain+")();":"")+"document.close();",c=CKEDITOR.env.air?"javascript:void(0)":CKEDITOR.env.ie&&!CKEDITOR.env.edge?"javascript:void(function(){"+encodeURIComponent(c)+"}())":"",d=CKEDITOR.dom.element.createFromHtml('\x3ciframe src\x3d"'+c+'" frameBorder\x3d"0"\x3e\x3c/iframe\x3e');
d.setStyles({width:"100%",height:"100%"});d.addClass("cke_wysiwyg_frame").addClass("cke_reset");c=a.ui.space("contents");c.append(d);var e=CKEDITOR.env.ie&&!CKEDITOR.env.edge||CKEDITOR.env.gecko;if(e)d.on("load",b);var g=a.title,h=a.fire("ariaEditorHelpLabel",{}).label;g&&(CKEDITOR.env.ie&&h&&(g+=", "+h),d.setAttribute("title",g));if(h){var g=CKEDITOR.tools.getNextId(),k=CKEDITOR.dom.element.createFromHtml('\x3cspan id\x3d"'+g+'" class\x3d"cke_voice_label"\x3e'+h+"\x3c/span\x3e");c.append(k,1);d.setAttribute("aria-describedby",
g)}a.on("beforeModeUnload",function(a){a.removeListener();k&&k.remove()});d.setAttributes({tabIndex:a.tabIndex,allowTransparency:"true"});!e&&b();a.fire("ariaWidget",d)})}});CKEDITOR.editor.prototype.addContentsCss=function(a){var f=this.config,b=f.contentsCss;CKEDITOR.tools.isArray(b)||(f.contentsCss=b?[b]:[]);f.contentsCss.push(a)};l=CKEDITOR.tools.createClass({$:function(){this.base.apply(this,arguments);this._.frameLoadedHandler=CKEDITOR.tools.addFunction(function(a){CKEDITOR.tools.setTimeout(m,
0,this,a)},this);this._.docTitle=this.getWindow().getFrame().getAttribute("title")},base:CKEDITOR.editable,proto:{setData:function(a,f){var b=this.editor;if(f)this.setHtml(a),this.fixInitialSelection(),b.fire("dataReady");else{this._.isLoadingData=!0;b._.dataStore={id:1};var c=b.config,d=c.fullPage,e=c.docType,g=CKEDITOR.tools.buildStyleHtml(p()).replace(/<style>/,'\x3cstyle data-cke-temp\x3d"1"\x3e');d||(g+=CKEDITOR.tools.buildStyleHtml(b.config.contentsCss));var h=c.baseHref?'\x3cbase href\x3d"'+
c.baseHref+'" data-cke-temp\x3d"1" /\x3e':"";d&&(a=a.replace(/<!DOCTYPE[^>]*>/i,function(a){b.docType=e=a;return""}).replace(/<\?xml\s[^\?]*\?>/i,function(a){b.xmlDeclaration=a;return""}));a=b.dataProcessor.toHtml(a);d?(/<body[\s|>]/.test(a)||(a="\x3cbody\x3e"+a),/<html[\s|>]/.test(a)||(a="\x3chtml\x3e"+a+"\x3c/html\x3e"),/<head[\s|>]/.test(a)?/<title[\s|>]/.test(a)||(a=a.replace(/<head[^>]*>/,"$\x26\x3ctitle\x3e\x3c/title\x3e")):a=a.replace(/<html[^>]*>/,"$\x26\x3chead\x3e\x3ctitle\x3e\x3c/title\x3e\x3c/head\x3e"),
h&&(a=a.replace(/<head[^>]*?>/,"$\x26"+h)),a=a.replace(/<\/head\s*>/,g+"$\x26"),a=e+a):a=c.docType+'\x3chtml dir\x3d"'+c.contentsLangDirection+'" lang\x3d"'+(c.contentsLanguage||b.langCode)+'"\x3e\x3chead\x3e\x3ctitle\x3e'+this._.docTitle+"\x3c/title\x3e"+h+g+"\x3c/head\x3e\x3cbody"+(c.bodyId?' id\x3d"'+c.bodyId+'"':"")+(c.bodyClass?' class\x3d"'+c.bodyClass+'"':"")+"\x3e"+a+"\x3c/body\x3e\x3c/html\x3e";CKEDITOR.env.gecko&&(a=a.replace(/<body/,'\x3cbody contenteditable\x3d"true" '),2E4>CKEDITOR.env.version&&
(a=a.replace(/<body[^>]*>/,"$\x26\x3c!-- cke-content-start --\x3e")));c='\x3cscript id\x3d"cke_actscrpt" type\x3d"text/javascript"'+(CKEDITOR.env.ie?' defer\x3d"defer" ':"")+"\x3evar wasLoaded\x3d0;function onload(){if(!wasLoaded)window.parent.CKEDITOR.tools.callFunction("+this._.frameLoadedHandler+",window);wasLoaded\x3d1;}"+(CKEDITOR.env.ie?"onload();":'document.addEventListener("DOMContentLoaded", onload, false );')+"\x3c/script\x3e";CKEDITOR.env.ie&&9>CKEDITOR.env.version&&(c+='\x3cscript id\x3d"cke_shimscrpt"\x3ewindow.parent.CKEDITOR.tools.enableHtml5Elements(document)\x3c/script\x3e');
h&&CKEDITOR.env.ie&&10>CKEDITOR.env.version&&(c+='\x3cscript id\x3d"cke_basetagscrpt"\x3evar baseTag \x3d document.querySelector( "base" );baseTag.href \x3d baseTag.href;\x3c/script\x3e');a=a.replace(/(?=\s*<\/(:?head)>)/,c);this.clearCustomData();this.clearListeners();b.fire("contentDomUnload");var k=this.getDocument();try{k.write(a)}catch(l){setTimeout(function(){k.write(a)},0)}}},getData:function(a){if(a)return this.getHtml();a=this.editor;var f=a.config,b=f.fullPage,c=b&&a.docType,d=b&&a.xmlDeclaration,
e=this.getDocument(),b=b?e.getDocumentElement().getOuterHtml():e.getBody().getHtml();CKEDITOR.env.gecko&&f.enterMode!=CKEDITOR.ENTER_BR&&(b=b.replace(/<br>(?=\s*(:?$|<\/body>))/,""));b=a.dataProcessor.toDataFormat(b);d&&(b=d+"\n"+b);c&&(b=c+"\n"+b);return b},focus:function(){this._.isLoadingData?this._.isPendingFocus=!0:l.baseProto.focus.call(this)},detach:function(){var a=this.editor,f=a.document,b;try{b=a.window.getFrame()}catch(c){}l.baseProto.detach.call(this);this.clearCustomData();f.getDocumentElement().clearCustomData();
CKEDITOR.tools.removeFunction(this._.frameLoadedHandler);b&&b.getParent()?(b.clearCustomData(),(a=b.removeCustomData("onResize"))&&a.removeListener(),b.remove()):CKEDITOR.warn("editor-destroy-iframe")}}})})();CKEDITOR.config.disableObjectResizing=!1;CKEDITOR.config.disableNativeTableHandles=!0;CKEDITOR.config.disableNativeSpellChecker=!0;(function(){function e(b,a){a||(a=b.getSelection().getSelectedElement());if(a&&a.is("img")&&!a.data("cke-realelement")&&!a.isReadOnly())return a}function f(b){var a=b.getStyle("float");if("inherit"==a||"none"==a)a=0;a||(a=b.getAttribute("align"));return a}CKEDITOR.plugins.add("image",{requires:"dialog",init:function(b){if(!b.plugins.detectConflict("image",["easyimage","image2"])){CKEDITOR.dialog.add("image",this.path+"dialogs/image.js");var a="img[alt,!src]{border-style,border-width,float,height,margin,margin-bottom,margin-left,margin-right,margin-top,width}";
CKEDITOR.dialog.isTabEnabled(b,"image","advanced")&&(a="img[alt,dir,id,lang,longdesc,!src,title]{*}(*)");b.addCommand("image",new CKEDITOR.dialogCommand("image",{allowedContent:a,requiredContent:"img[alt,src]",contentTransformations:[["img{width}: sizeToStyle","img[width]: sizeToAttribute"],["img{float}: alignmentToStyle","img[align]: alignmentToAttribute"]]}));b.ui.addButton&&b.ui.addButton("Image",{label:b.lang.common.image,command:"image",toolbar:"insert,10"});b.on("doubleclick",function(b){var a=
b.data.element;!a.is("img")||a.data("cke-realelement")||a.isReadOnly()||(b.data.dialog="image")});b.addMenuItems&&b.addMenuItems({image:{label:b.lang.image.menu,command:"image",group:"image"}});b.contextMenu&&b.contextMenu.addListener(function(a){if(e(b,a))return{image:CKEDITOR.TRISTATE_OFF}})}},afterInit:function(b){function a(a){var d=b.getCommand("justify"+a);if(d){if("left"==a||"right"==a)d.on("exec",function(d){var c=e(b),g;c&&(g=f(c),g==a?(c.removeStyle("float"),a==f(c)&&c.removeAttribute("align")):
c.setStyle("float",a),d.cancel())});d.on("refresh",function(d){var c=e(b);c&&(c=f(c),this.setState(c==a?CKEDITOR.TRISTATE_ON:"right"==a||"left"==a?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED),d.cancel())})}}b.plugins.image2||(a("left"),a("right"),a("center"),a("block"))}})})();CKEDITOR.config.image_removeLinkByEmptyURL=!0;(function(){function m(a,b){var e,f;b.on("refresh",function(a){var b=[k],c;for(c in a.data.states)b.push(a.data.states[c]);this.setState(CKEDITOR.tools.search(b,p)?p:k)},b,null,100);b.on("exec",function(b){e=a.getSelection();f=e.createBookmarks(1);b.data||(b.data={});b.data.done=!1},b,null,0);b.on("exec",function(){a.forceNextSelectionCheck();e.selectBookmarks(f)},b,null,100)}var k=CKEDITOR.TRISTATE_DISABLED,p=CKEDITOR.TRISTATE_OFF;CKEDITOR.plugins.add("indent",{init:function(a){var b=CKEDITOR.plugins.indent.genericDefinition;
m(a,a.addCommand("indent",new b(!0)));m(a,a.addCommand("outdent",new b));a.ui.addButton&&(a.ui.addButton("Indent",{label:a.lang.indent.indent,command:"indent",directional:!0,toolbar:"indent,20"}),a.ui.addButton("Outdent",{label:a.lang.indent.outdent,command:"outdent",directional:!0,toolbar:"indent,10"}));a.on("dirChanged",function(b){var f=a.createRange(),l=b.data.node;f.setStartBefore(l);f.setEndAfter(l);for(var n=new CKEDITOR.dom.walker(f),c;c=n.next();)if(c.type==CKEDITOR.NODE_ELEMENT)if(!c.equals(l)&&
c.getDirection())f.setStartAfter(c),n=new CKEDITOR.dom.walker(f);else{var d=a.config.indentClasses;if(d)for(var g="ltr"==b.data.dir?["_rtl",""]:["","_rtl"],h=0;h<d.length;h++)c.hasClass(d[h]+g[0])&&(c.removeClass(d[h]+g[0]),c.addClass(d[h]+g[1]));d=c.getStyle("margin-right");g=c.getStyle("margin-left");d?c.setStyle("margin-left",d):c.removeStyle("margin-left");g?c.setStyle("margin-right",g):c.removeStyle("margin-right")}})}});CKEDITOR.plugins.indent={genericDefinition:function(a){this.isIndent=!!a;
this.startDisabled=!this.isIndent},specificDefinition:function(a,b,e){this.name=b;this.editor=a;this.jobs={};this.enterBr=a.config.enterMode==CKEDITOR.ENTER_BR;this.isIndent=!!e;this.relatedGlobal=e?"indent":"outdent";this.indentKey=e?9:CKEDITOR.SHIFT+9;this.database={}},registerCommands:function(a,b){a.on("pluginsLoaded",function(){for(var a in b)(function(a,b){var e=a.getCommand(b.relatedGlobal),c;for(c in b.jobs)e.on("exec",function(d){d.data.done||(a.fire("lockSnapshot"),b.execJob(a,c)&&(d.data.done=
!0),a.fire("unlockSnapshot"),CKEDITOR.dom.element.clearAllMarkers(b.database))},this,null,c),e.on("refresh",function(d){d.data.states||(d.data.states={});d.data.states[b.name+"@"+c]=b.refreshJob(a,c,d.data.path)},this,null,c);a.addFeature(b)})(this,b[a])})}};CKEDITOR.plugins.indent.genericDefinition.prototype={context:"p",exec:function(){}};CKEDITOR.plugins.indent.specificDefinition.prototype={execJob:function(a,b){var e=this.jobs[b];if(e.state!=k)return e.exec.call(this,a)},refreshJob:function(a,
b,e){b=this.jobs[b];a.activeFilter.checkFeature(this)?b.state=b.refresh.call(this,a,e):b.state=k;return b.state},getContext:function(a){return a.contains(this.context)}}})();(function(){function f(b,c,a){if(!b.getCustomData("indent_processed")){var d=this.editor,l=this.isIndent;if(c){d=b.$.className.match(this.classNameRegex);a=0;d&&(d=d[1],a=CKEDITOR.tools.indexOf(c,d)+1);if(0>(a+=l?1:-1))return;a=Math.min(a,c.length);a=Math.max(a,0);b.$.className=CKEDITOR.tools.ltrim(b.$.className.replace(this.classNameRegex,""));0<a&&b.addClass(c[a-1])}else{c=m(b,a);a=parseInt(b.getStyle(c),10);var g=d.config.indentOffset||40;isNaN(a)&&(a=0);a+=(l?1:-1)*g;if(0>a)return;a=Math.max(a,
0);a=Math.ceil(a/g)*g;b.setStyle(c,a?a+(d.config.indentUnit||"px"):"");""===b.getAttribute("style")&&b.removeAttribute("style")}CKEDITOR.dom.element.setMarker(this.database,b,"indent_processed",1)}}function m(b,c){return"ltr"==(c||b.getComputedStyle("direction"))?"margin-left":"margin-right"}var h=CKEDITOR.dtd.$listItem,p=CKEDITOR.dtd.$list,k=CKEDITOR.TRISTATE_DISABLED,n=CKEDITOR.TRISTATE_OFF;CKEDITOR.plugins.add("indentblock",{requires:"indent",init:function(b){function c(){a.specificDefinition.apply(this,
arguments);this.allowedContent={"div h1 h2 h3 h4 h5 h6 ol p pre ul":{propertiesOnly:!0,styles:d?null:"margin-left,margin-right",classes:d||null}};this.contentTransformations=[["div: splitMarginShorthand"],["h1: splitMarginShorthand"],["h2: splitMarginShorthand"],["h3: splitMarginShorthand"],["h4: splitMarginShorthand"],["h5: splitMarginShorthand"],["h6: splitMarginShorthand"],["ol: splitMarginShorthand"],["p: splitMarginShorthand"],["pre: splitMarginShorthand"],["ul: splitMarginShorthand"]];this.enterBr&&
(this.allowedContent.div=!0);this.requiredContent=(this.enterBr?"div":"p")+(d?"("+d.join(",")+")":"{margin-left}");this.jobs={20:{refresh:function(a,b){var e=b.block||b.blockLimit;if(!e.is(h))var c=e.getAscendant(h),e=c&&b.contains(c)||e;e.is(h)&&(e=e.getParent());if(this.enterBr||this.getContext(b)){if(d){var c=d,e=e.$.className.match(this.classNameRegex),f=this.isIndent,c=e?f?e[1]!=c.slice(-1):!0:f;return c?n:k}return this.isIndent?n:e?CKEDITOR[0>=(parseInt(e.getStyle(m(e)),10)||0)?"TRISTATE_DISABLED":
"TRISTATE_OFF"]:k}return k},exec:function(a){var b=a.getSelection(),b=b&&b.getRanges()[0],c;if(c=a.elementPath().contains(p))f.call(this,c,d);else for(b=b.createIterator(),a=a.config.enterMode,b.enforceRealBlocks=!0,b.enlargeBr=a!=CKEDITOR.ENTER_BR;c=b.getNextParagraph(a==CKEDITOR.ENTER_P?"p":"div");)c.isReadOnly()||f.call(this,c,d);return!0}}}}var a=CKEDITOR.plugins.indent,d=b.config.indentClasses;a.registerCommands(b,{indentblock:new c(b,"indentblock",!0),outdentblock:new c(b,"outdentblock")});
CKEDITOR.tools.extend(c.prototype,a.specificDefinition.prototype,{context:{div:1,dl:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,ul:1,ol:1,p:1,pre:1,table:1},classNameRegex:d?new RegExp("(?:^|\\s+)("+d.join("|")+")(?\x3d$|\\s)"):null})}})})();(function(){function w(f){function g(b){for(var e=c.startContainer,a=c.endContainer;e&&!e.getParent().equals(b);)e=e.getParent();for(;a&&!a.getParent().equals(b);)a=a.getParent();if(!e||!a)return!1;for(var d=[],h=!1;!h;)e.equals(a)&&(h=!0),d.push(e),e=e.getNext();if(1>d.length)return!1;e=b.getParents(!0);for(a=0;a<e.length;a++)if(e[a].getName&&p[e[a].getName()]){b=e[a];break}for(var e=k.isIndent?1:-1,a=d[0],d=d[d.length-1],h=CKEDITOR.plugins.list.listToArray(b,q),m=h[d.getCustomData("listarray_index")].indent,
a=a.getCustomData("listarray_index");a<=d.getCustomData("listarray_index");a++)if(h[a].indent+=e,0<e){for(var g=h[a].parent,n=a-1;0<=n;n--)if(h[n].indent===e){g=h[n].parent;break}h[a].parent=new CKEDITOR.dom.element(g.getName(),g.getDocument())}for(a=d.getCustomData("listarray_index")+1;a<h.length&&h[a].indent>m;a++)h[a].indent+=e;e=CKEDITOR.plugins.list.arrayToList(h,q,null,f.config.enterMode,b.getDirection());if(!k.isIndent){var t;if((t=b.getParent())&&t.is("li"))for(var d=e.listNode.getChildren(),
r=[],l,a=d.count()-1;0<=a;a--)(l=d.getItem(a))&&l.is&&l.is("li")&&r.push(l)}e&&e.listNode.replace(b);if(r&&r.length)for(a=0;a<r.length;a++){for(l=b=r[a];(l=l.getNext())&&l.is&&l.getName()in p;)CKEDITOR.env.needsNbspFiller&&!b.getFirst(x)&&b.append(c.document.createText(" ")),b.append(l);b.insertAfter(t)}e&&f.fire("contentDomInvalidated");return!0}for(var k=this,q=this.database,p=this.context,c,m=f.getSelection(),m=(m&&m.getRanges()).createIterator();c=m.getNextRange();){for(var b=c.getCommonAncestor();b&&
(b.type!=CKEDITOR.NODE_ELEMENT||!p[b.getName()]);){if(f.editable().equals(b)){b=!1;break}b=b.getParent()}b||(b=c.startPath().contains(p))&&c.setEndAt(b,CKEDITOR.POSITION_BEFORE_END);if(!b){var d=c.getEnclosedNode();d&&d.type==CKEDITOR.NODE_ELEMENT&&d.getName()in p&&(c.setStartAt(d,CKEDITOR.POSITION_AFTER_START),c.setEndAt(d,CKEDITOR.POSITION_BEFORE_END),b=d)}b&&c.startContainer.type==CKEDITOR.NODE_ELEMENT&&c.startContainer.getName()in p&&(d=new CKEDITOR.dom.walker(c),d.evaluator=n,c.startContainer=
d.next());b&&c.endContainer.type==CKEDITOR.NODE_ELEMENT&&c.endContainer.getName()in p&&(d=new CKEDITOR.dom.walker(c),d.evaluator=n,c.endContainer=d.previous());if(b)return g(b)}return 0}function n(f){return f.type==CKEDITOR.NODE_ELEMENT&&f.is("li")}function x(f){return y(f)&&z(f)}var y=CKEDITOR.dom.walker.whitespaces(!0),z=CKEDITOR.dom.walker.bookmark(!1,!0),u=CKEDITOR.TRISTATE_DISABLED,v=CKEDITOR.TRISTATE_OFF;CKEDITOR.plugins.add("indentlist",{requires:"indent",init:function(f){function g(f){k.specificDefinition.apply(this,
arguments);this.requiredContent=["ul","ol"];f.on("key",function(g){var c=f.elementPath();if("wysiwyg"==f.mode&&g.data.keyCode==this.indentKey&&c){var m=this.getContext(c);!m||this.isIndent&&CKEDITOR.plugins.indentList.firstItemInPath(this.context,c,m)||(f.execCommand(this.relatedGlobal),g.cancel())}},this);this.jobs[this.isIndent?10:30]={refresh:this.isIndent?function(f,c){var g=this.getContext(c),b=CKEDITOR.plugins.indentList.firstItemInPath(this.context,c,g);return g&&this.isIndent&&!b?v:u}:function(f,
c){return!this.getContext(c)||this.isIndent?u:v},exec:CKEDITOR.tools.bind(w,this)}}var k=CKEDITOR.plugins.indent;k.registerCommands(f,{indentlist:new g(f,"indentlist",!0),outdentlist:new g(f,"outdentlist")});CKEDITOR.tools.extend(g.prototype,k.specificDefinition.prototype,{context:{ol:1,ul:1}})}});CKEDITOR.plugins.indentList={};CKEDITOR.plugins.indentList.firstItemInPath=function(f,g,k){var q=g.contains(n);k||(k=g.contains(f));return k&&q&&q.equals(k.getFirst(n))}})();CKEDITOR.plugins.add("smiley",{requires:"dialog",init:function(a){a.config.smiley_path=a.config.smiley_path||this.path+"images/";a.addCommand("smiley",new CKEDITOR.dialogCommand("smiley",{allowedContent:"img[alt,height,!src,title,width]",requiredContent:"img"}));a.ui.addButton&&a.ui.addButton("Smiley",{label:a.lang.smiley.toolbar,command:"smiley",toolbar:"insert,50"});CKEDITOR.dialog.add("smiley",this.path+"dialogs/smiley.js")}});CKEDITOR.config.smiley_images="regular_smile.png sad_smile.png wink_smile.png teeth_smile.png confused_smile.png tongue_smile.png embarrassed_smile.png omg_smile.png whatchutalkingabout_smile.png angry_smile.png angel_smile.png shades_smile.png devil_smile.png cry_smile.png lightbulb.png thumbs_down.png thumbs_up.png heart.png broken_heart.png kiss.png envelope.png".split(" ");
CKEDITOR.config.smiley_descriptions="smiley;sad;wink;laugh;frown;cheeky;blush;surprise;indecision;angry;angel;cool;devil;crying;enlightened;no;yes;heart;broken heart;kiss;mail".split(";");(function(){function q(a,c){c=void 0===c||c;var b;if(c)b=a.getComputedStyle("text-align");else{for(;!a.hasAttribute||!a.hasAttribute("align")&&!a.getStyle("text-align");){b=a.getParent();if(!b)break;a=b}b=a.getStyle("text-align")||a.getAttribute("align")||""}b&&(b=b.replace(/(?:-(?:moz|webkit)-)?(?:start|auto)/i,""));!b&&c&&(b="rtl"==a.getComputedStyle("direction")?"right":"left");return b}function h(a,c,b){this.editor=a;this.name=c;this.value=b;this.context="p";c=a.config.justifyClasses;var f=a.config.enterMode==
CKEDITOR.ENTER_P?"p":"div";if(c){switch(b){case "left":this.cssClassName=c[0];break;case "center":this.cssClassName=c[1];break;case "right":this.cssClassName=c[2];break;case "justify":this.cssClassName=c[3]}this.cssClassRegex=new RegExp("(?:^|\\s+)(?:"+c.join("|")+")(?\x3d$|\\s)");this.requiredContent=f+"("+this.cssClassName+")"}else this.requiredContent=f+"{text-align}";this.allowedContent={"caption div h1 h2 h3 h4 h5 h6 p pre td th li":{propertiesOnly:!0,styles:this.cssClassName?null:"text-align",
classes:this.cssClassName||null}};a.config.enterMode==CKEDITOR.ENTER_BR&&(this.allowedContent.div=!0)}function m(a){var c=a.editor,b=c.createRange();b.setStartBefore(a.data.node);b.setEndAfter(a.data.node);for(var f=new CKEDITOR.dom.walker(b),d;d=f.next();)if(d.type==CKEDITOR.NODE_ELEMENT)if(!d.equals(a.data.node)&&d.getDirection())b.setStartAfter(d),f=new CKEDITOR.dom.walker(b);else{var e=c.config.justifyClasses;e&&(d.hasClass(e[0])?(d.removeClass(e[0]),d.addClass(e[2])):d.hasClass(e[2])&&(d.removeClass(e[2]),
d.addClass(e[0])));e=d.getStyle("text-align");"left"==e?d.setStyle("text-align","right"):"right"==e&&d.setStyle("text-align","left")}}h.prototype={exec:function(a){var c=a.getSelection(),b=a.config.enterMode;if(c){for(var f=c.createBookmarks(),d=c.getRanges(),e=this.cssClassName,h,g,k=a.config.useComputedState,k=void 0===k||k,n=d.length-1;0<=n;n--)for(h=d[n].createIterator(),h.enlargeBr=b!=CKEDITOR.ENTER_BR;g=h.getNextParagraph(b==CKEDITOR.ENTER_P?"p":"div");)if(!g.isReadOnly()){var l=g.getName(),
p;p=a.activeFilter.check(l+"{text-align}");if((l=a.activeFilter.check(l+"("+e+")"))||p){g.removeAttribute("align");g.removeStyle("text-align");var m=e&&(g.$.className=CKEDITOR.tools.ltrim(g.$.className.replace(this.cssClassRegex,""))),r=this.state==CKEDITOR.TRISTATE_OFF&&(!k||q(g,!0)!=this.value);e&&l?r?g.addClass(e):m||g.removeAttribute("class"):r&&p&&g.setStyle("text-align",this.value)}}a.focus();a.forceNextSelectionCheck();c.selectBookmarks(f)}},refresh:function(a,c){var b=c.block||c.blockLimit,
f=b.getName(),d=b.equals(a.editable()),f=this.cssClassName?a.activeFilter.check(f+"("+this.cssClassName+")"):a.activeFilter.check(f+"{text-align}");d&&1===c.elements.length?this.setState(CKEDITOR.TRISTATE_OFF):!d&&f?this.setState(q(b,this.editor.config.useComputedState)==this.value?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF):this.setState(CKEDITOR.TRISTATE_DISABLED)}};CKEDITOR.plugins.add("justify",{init:function(a){if(!a.blockless){var c=new h(a,"justifyleft","left"),b=new h(a,"justifycenter","center"),
f=new h(a,"justifyright","right"),d=new h(a,"justifyblock","justify");a.addCommand("justifyleft",c);a.addCommand("justifycenter",b);a.addCommand("justifyright",f);a.addCommand("justifyblock",d);a.ui.addButton&&(a.ui.addButton("JustifyLeft",{label:a.lang.common.alignLeft,command:"justifyleft",toolbar:"align,10"}),a.ui.addButton("JustifyCenter",{label:a.lang.common.center,command:"justifycenter",toolbar:"align,20"}),a.ui.addButton("JustifyRight",{label:a.lang.common.alignRight,command:"justifyright",
toolbar:"align,30"}),a.ui.addButton("JustifyBlock",{label:a.lang.common.justify,command:"justifyblock",toolbar:"align,40"}));a.on("dirChanged",m)}}})})();CKEDITOR.plugins.add("menubutton",{requires:"button,menu",onLoad:function(){var d=function(c){var a=this._,b=a.menu;a.state!==CKEDITOR.TRISTATE_DISABLED&&(a.on&&b?b.hide():(a.previousState=a.state,b||(b=a.menu=new CKEDITOR.menu(c,{panel:{className:"cke_menu_panel",attributes:{"aria-label":c.lang.common.options}}}),b.onHide=CKEDITOR.tools.bind(function(){var b=this.command?c.getCommand(this.command).modes:this.modes;this.setState(!b||b[c.mode]?a.previousState:CKEDITOR.TRISTATE_DISABLED);a.on=0},this),
this.onMenu&&b.addListener(this.onMenu)),this.setState(CKEDITOR.TRISTATE_ON),a.on=1,setTimeout(function(){b.show(CKEDITOR.document.getById(a.id),4)},0)))};CKEDITOR.ui.menuButton=CKEDITOR.tools.createClass({base:CKEDITOR.ui.button,$:function(c){delete c.panel;this.base(c);this.hasArrow=!0;this.click=d},statics:{handler:{create:function(c){return new CKEDITOR.ui.menuButton(c)}}}})},beforeInit:function(d){d.ui.addHandler(CKEDITOR.UI_MENUBUTTON,CKEDITOR.ui.menuButton.handler)}});
CKEDITOR.UI_MENUBUTTON="menubutton";(function(){CKEDITOR.plugins.add("language",{requires:"menubutton",init:function(a){var b=a.config.language_list||["ar:Arabic:rtl","fr:French","es:Spanish"],c=this,d=a.lang.language,e={},g,h,k,f;a.addCommand("language",{allowedContent:"span[!lang,!dir]",requiredContent:"span[lang,dir]",contextSensitive:!0,exec:function(a,b){var c=e["language_"+b];if(c)a[c.style.checkActive(a.elementPath(),a)?"removeStyle":"applyStyle"](c.style)},refresh:function(a){this.setState(c.getCurrentLangElement(a)?CKEDITOR.TRISTATE_ON:
CKEDITOR.TRISTATE_OFF)}});for(f=0;f<b.length;f++)g=b[f].split(":"),h=g[0],k="language_"+h,e[k]={label:g[1],langId:h,group:"language",order:f,ltr:"rtl"!=(""+g[2]).toLowerCase(),onClick:function(){a.execCommand("language",this.langId)},role:"menuitemcheckbox"},e[k].style=new CKEDITOR.style({element:"span",attributes:{lang:h,dir:e[k].ltr?"ltr":"rtl"}});e.language_remove={label:d.remove,group:"language_remove",state:CKEDITOR.TRISTATE_DISABLED,order:e.length,onClick:function(){var b=c.getCurrentLangElement(a);
b&&a.execCommand("language",b.getAttribute("lang"))}};a.addMenuGroup("language",1);a.addMenuGroup("language_remove");a.addMenuItems(e);a.ui.add("Language",CKEDITOR.UI_MENUBUTTON,{label:d.button,allowedContent:"span[!lang,!dir]",requiredContent:"span[lang,dir]",toolbar:"bidi,30",command:"language",onMenu:function(){var b={},d=c.getCurrentLangElement(a),f;for(f in e)b[f]=CKEDITOR.TRISTATE_OFF;b.language_remove=d?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED;d&&(b["language_"+d.getAttribute("lang")]=
CKEDITOR.TRISTATE_ON);return b}});a.addRemoveFormatFilter&&a.addRemoveFormatFilter(function(a){return!(a.is("span")&&a.getAttribute("dir")&&a.getAttribute("lang"))})},getCurrentLangElement:function(a){var b=a.elementPath();a=b&&b.elements;var c;if(b)for(var d=0;d<a.length;d++)b=a[d],!c&&"span"==b.getName()&&b.hasAttribute("dir")&&b.hasAttribute("lang")&&(c=b);return c}})})();(function(){function p(c){return c.replace(/'/g,"\\$\x26")}function q(c){for(var b,a=c.length,d=[],f=0;f<a;f++)b=c.charCodeAt(f),d.push(b);return"String.fromCharCode("+d.join(",")+")"}function r(c,b){var a=c.plugins.link,d=a.compiledProtectionFunction.params,f,e;e=[a.compiledProtectionFunction.name,"("];for(var g=0;g<d.length;g++)a=d[g].toLowerCase(),f=b[a],0<g&&e.push(","),e.push("'",f?p(encodeURIComponent(b[a])):"","'");e.push(")");return e.join("")}function n(c){c=c.config.emailProtection||"";
var b;c&&"encode"!=c&&(b={},c.replace(/^([^(]+)\(([^)]+)\)$/,function(a,c,f){b.name=c;b.params=[];f.replace(/[^,\s]+/g,function(a){b.params.push(a)})}));return b}CKEDITOR.plugins.add("link",{requires:"dialog,fakeobjects",onLoad:function(){function c(b){return a.replace(/%1/g,"rtl"==b?"right":"left").replace(/%2/g,"cke_contents_"+b)}var b="background:url("+CKEDITOR.getUrl(this.path+"images"+(CKEDITOR.env.hidpi?"/hidpi":"")+"/anchor.png")+") no-repeat %1 center;border:1px dotted #00f;background-size:16px;",
a=".%2 a.cke_anchor,.%2 a.cke_anchor_empty,.cke_editable.%2 a[name],.cke_editable.%2 a[data-cke-saved-name]{"+b+"padding-%1:18px;cursor:auto;}.%2 img.cke_anchor{"+b+"width:16px;min-height:15px;height:1.15em;vertical-align:text-bottom;}";CKEDITOR.addCss(c("ltr")+c("rtl"))},init:function(c){var b="a[!href]";CKEDITOR.dialog.isTabEnabled(c,"link","advanced")&&(b=b.replace("]",",accesskey,charset,dir,id,lang,name,rel,tabindex,title,type,download]{*}(*)"));CKEDITOR.dialog.isTabEnabled(c,"link","target")&&
(b=b.replace("]",",target,onclick]"));c.addCommand("link",new CKEDITOR.dialogCommand("link",{allowedContent:b,requiredContent:"a[href]"}));c.addCommand("anchor",new CKEDITOR.dialogCommand("anchor",{allowedContent:"a[!name,id]",requiredContent:"a[name]"}));c.addCommand("unlink",new CKEDITOR.unlinkCommand);c.addCommand("removeAnchor",new CKEDITOR.removeAnchorCommand);c.setKeystroke(CKEDITOR.CTRL+76,"link");c.ui.addButton&&(c.ui.addButton("Link",{label:c.lang.link.toolbar,command:"link",toolbar:"links,10"}),
c.ui.addButton("Unlink",{label:c.lang.link.unlink,command:"unlink",toolbar:"links,20"}),c.ui.addButton("Anchor",{label:c.lang.link.anchor.toolbar,command:"anchor",toolbar:"links,30"}));CKEDITOR.dialog.add("link",this.path+"dialogs/link.js");CKEDITOR.dialog.add("anchor",this.path+"dialogs/anchor.js");c.on("doubleclick",function(a){var b=a.data.element.getAscendant({a:1,img:1},!0);b&&!b.isReadOnly()&&(b.is("a")?(a.data.dialog=!b.getAttribute("name")||b.getAttribute("href")&&b.getChildCount()?"link":
"anchor",a.data.link=b):CKEDITOR.plugins.link.tryRestoreFakeAnchor(c,b)&&(a.data.dialog="anchor"))},null,null,0);c.on("doubleclick",function(a){a.data.dialog in{link:1,anchor:1}&&a.data.link&&c.getSelection().selectElement(a.data.link)},null,null,20);c.addMenuItems&&c.addMenuItems({anchor:{label:c.lang.link.anchor.menu,command:"anchor",group:"anchor",order:1},removeAnchor:{label:c.lang.link.anchor.remove,command:"removeAnchor",group:"anchor",order:5},link:{label:c.lang.link.menu,command:"link",group:"link",
order:1},unlink:{label:c.lang.link.unlink,command:"unlink",group:"link",order:5}});c.contextMenu&&c.contextMenu.addListener(function(a){if(!a||a.isReadOnly())return null;a=CKEDITOR.plugins.link.tryRestoreFakeAnchor(c,a);if(!a&&!(a=CKEDITOR.plugins.link.getSelectedLink(c)))return null;var b={};a.getAttribute("href")&&a.getChildCount()&&(b={link:CKEDITOR.TRISTATE_OFF,unlink:CKEDITOR.TRISTATE_OFF});a&&a.hasAttribute("name")&&(b.anchor=b.removeAnchor=CKEDITOR.TRISTATE_OFF);return b});this.compiledProtectionFunction=
n(c)},afterInit:function(c){c.dataProcessor.dataFilter.addRules({elements:{a:function(a){return a.attributes.name?a.children.length?null:c.createFakeParserElement(a,"cke_anchor","anchor"):null}}});var b=c._.elementsPath&&c._.elementsPath.filters;b&&b.push(function(a,b){if("a"==b&&(CKEDITOR.plugins.link.tryRestoreFakeAnchor(c,a)||a.getAttribute("name")&&(!a.getAttribute("href")||!a.getChildCount())))return"anchor"})}});var t=/^javascript:/,u=/^mailto:([^?]+)(?:\?(.+))?$/,v=/subject=([^;?:@&=$,\/]*)/i,
w=/body=([^;?:@&=$,\/]*)/i,x=/^#(.*)$/,y=/^((?:http|https|ftp|news):\/\/)?(.*)$/,z=/^(_(?:self|top|parent|blank))$/,A=/^javascript:void\(location\.href='mailto:'\+String\.fromCharCode\(([^)]+)\)(?:\+'(.*)')?\)$/,B=/^javascript:([^(]+)\(([^)]+)\)$/,C=/\s*window.open\(\s*this\.href\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*;\s*return\s*false;*\s*/,D=/(?:^|,)([^=]+)=(\d+|yes|no)/gi,m={id:"advId",dir:"advLangDir",accessKey:"advAccessKey",name:"advName",lang:"advLangCode",tabindex:"advTabIndex",
title:"advTitle",type:"advContentType","class":"advCSSClasses",charset:"advCharset",style:"advStyles",rel:"advRel"};CKEDITOR.plugins.link={getSelectedLink:function(c,b){var a=c.getSelection(),d=a.getSelectedElement(),f=a.getRanges(),e=[],g;if(!b&&d&&d.is("a"))return d;for(d=0;d<f.length;d++)if(g=a.getRanges()[d],g.shrink(CKEDITOR.SHRINK_ELEMENT,!0,{skipBogus:!0}),(g=c.elementPath(g.getCommonAncestor()).contains("a",1))&&b)e.push(g);else if(g)return g;return b?e:null},getEditorAnchors:function(c){for(var b=
c.editable(),a=b.isInline()&&!c.plugins.divarea?c.document:b,b=a.getElementsByTag("a"),a=a.getElementsByTag("img"),d=[],f=0,e;e=b.getItem(f++);)(e.data("cke-saved-name")||e.hasAttribute("name"))&&d.push({name:e.data("cke-saved-name")||e.getAttribute("name"),id:e.getAttribute("id")});for(f=0;e=a.getItem(f++);)(e=this.tryRestoreFakeAnchor(c,e))&&d.push({name:e.getAttribute("name"),id:e.getAttribute("id")});return d},fakeAnchor:!0,tryRestoreFakeAnchor:function(c,b){if(b&&b.data("cke-real-element-type")&&
"anchor"==b.data("cke-real-element-type")){var a=c.restoreRealElement(b);if(a.data("cke-saved-name"))return a}},parseLinkAttributes:function(c,b){var a=b&&(b.data("cke-saved-href")||b.getAttribute("href"))||"",d=c.plugins.link.compiledProtectionFunction,f=c.config.emailProtection,e,g={};a.match(t)&&("encode"==f?a=a.replace(A,function(a,b,c){c=c||"";return"mailto:"+String.fromCharCode.apply(String,b.split(","))+c.replace(/\\'/g,"'")}):f&&a.replace(B,function(a,b,c){if(b==d.name){g.type="email";a=g.email=
{};b=/(^')|('$)/g;c=c.match(/[^,\s]+/g);for(var e=c.length,f,h,k=0;k<e;k++)f=decodeURIComponent,h=c[k].replace(b,"").replace(/\\'/g,"'"),h=f(h),f=d.params[k].toLowerCase(),a[f]=h;a.address=[a.name,a.domain].join("@")}}));if(!g.type)if(f=a.match(x))g.type="anchor",g.anchor={},g.anchor.name=g.anchor.id=f[1];else if(f=a.match(u)){e=a.match(v);a=a.match(w);g.type="email";var k=g.email={};k.address=f[1];e&&(k.subject=decodeURIComponent(e[1]));a&&(k.body=decodeURIComponent(a[1]))}else a&&(e=a.match(y))&&
(g.type="url",g.url={},g.url.protocol=e[1],g.url.url=e[2]);if(b){if(a=b.getAttribute("target"))g.target={type:a.match(z)?a:"frame",name:a};else if(a=(a=b.data("cke-pa-onclick")||b.getAttribute("onclick"))&&a.match(C))for(g.target={type:"popup",name:a[1]};f=D.exec(a[2]);)"yes"!=f[2]&&"1"!=f[2]||f[1]in{height:1,width:1,top:1,left:1}?isFinite(f[2])&&(g.target[f[1]]=f[2]):g.target[f[1]]=!0;null!==b.getAttribute("download")&&(g.download=!0);var a={},h;for(h in m)(f=b.getAttribute(h))&&(a[m[h]]=f);if(h=
b.data("cke-saved-name")||a.advName)a.advName=h;CKEDITOR.tools.isEmpty(a)||(g.advanced=a)}return g},getLinkAttributes:function(c,b){var a=c.config.emailProtection||"",d={};switch(b.type){case "url":var a=b.url&&void 0!==b.url.protocol?b.url.protocol:"http://",f=b.url&&CKEDITOR.tools.trim(b.url.url)||"";d["data-cke-saved-href"]=0===f.indexOf("/")?f:a+f;break;case "anchor":a=b.anchor&&b.anchor.id;d["data-cke-saved-href"]="#"+(b.anchor&&b.anchor.name||a||"");break;case "email":var e=b.email,f=e.address;
switch(a){case "":case "encode":var g=encodeURIComponent(e.subject||""),k=encodeURIComponent(e.body||""),e=[];g&&e.push("subject\x3d"+g);k&&e.push("body\x3d"+k);e=e.length?"?"+e.join("\x26"):"";"encode"==a?(a=["javascript:void(location.href\x3d'mailto:'+",q(f)],e&&a.push("+'",p(e),"'"),a.push(")")):a=["mailto:",f,e];break;default:a=f.split("@",2),e.name=a[0],e.domain=a[1],a=["javascript:",r(c,e)]}d["data-cke-saved-href"]=a.join("")}if(b.target)if("popup"==b.target.type){for(var a=["window.open(this.href, '",
b.target.name||"","', '"],h="resizable status location toolbar menubar fullscreen scrollbars dependent".split(" "),f=h.length,g=function(a){b.target[a]&&h.push(a+"\x3d"+b.target[a])},e=0;e<f;e++)h[e]+=b.target[h[e]]?"\x3dyes":"\x3dno";g("width");g("left");g("height");g("top");a.push(h.join(","),"'); return false;");d["data-cke-pa-onclick"]=a.join("")}else"notSet"!=b.target.type&&b.target.name&&(d.target=b.target.name);b.download&&(d.download="");if(b.advanced){for(var l in m)(a=b.advanced[m[l]])&&
(d[l]=a);d.name&&(d["data-cke-saved-name"]=d.name)}d["data-cke-saved-href"]&&(d.href=d["data-cke-saved-href"]);l={target:1,onclick:1,"data-cke-pa-onclick":1,"data-cke-saved-name":1,download:1};b.advanced&&CKEDITOR.tools.extend(l,m);for(var n in d)delete l[n];return{set:d,removed:CKEDITOR.tools.objectKeys(l)}},showDisplayTextForElement:function(c,b){var a={img:1,table:1,tbody:1,thead:1,tfoot:1,input:1,select:1,textarea:1},d=b.getSelection();return b.widgets&&b.widgets.focused||d&&1<d.getRanges().length?
!1:!c||!c.getName||!c.is(a)}};CKEDITOR.unlinkCommand=function(){};CKEDITOR.unlinkCommand.prototype={exec:function(c){if(CKEDITOR.env.ie){var b=c.getSelection().getRanges()[0],a=b.getPreviousEditableNode()&&b.getPreviousEditableNode().getAscendant("a",!0)||b.getNextEditableNode()&&b.getNextEditableNode().getAscendant("a",!0),d;b.collapsed&&a&&(d=b.createBookmark(),b.selectNodeContents(a),b.select())}a=new CKEDITOR.style({element:"a",type:CKEDITOR.STYLE_INLINE,alwaysRemoveElement:1});c.removeStyle(a);
d&&(b.moveToBookmark(d),b.select())},refresh:function(c,b){var a=b.lastElement&&b.lastElement.getAscendant("a",!0);a&&"a"==a.getName()&&a.getAttribute("href")&&a.getChildCount()?this.setState(CKEDITOR.TRISTATE_OFF):this.setState(CKEDITOR.TRISTATE_DISABLED)},contextSensitive:1,startDisabled:1,requiredContent:"a[href]",editorFocus:1};CKEDITOR.removeAnchorCommand=function(){};CKEDITOR.removeAnchorCommand.prototype={exec:function(c){var b=c.getSelection(),a=b.createBookmarks(),d;if(b&&(d=b.getSelectedElement())&&
(d.getChildCount()?d.is("a"):CKEDITOR.plugins.link.tryRestoreFakeAnchor(c,d)))d.remove(1);else if(d=CKEDITOR.plugins.link.getSelectedLink(c))d.hasAttribute("href")?(d.removeAttributes({name:1,"data-cke-saved-name":1}),d.removeClass("cke_anchor")):d.remove(1);b.selectBookmarks(a)},requiredContent:"a[name]"};CKEDITOR.tools.extend(CKEDITOR.config,{linkShowAdvancedTab:!0,linkShowTargetTab:!0})})();(function(){function I(b,m,e){function c(c){if(!(!(a=d[c?"getFirst":"getLast"]())||a.is&&a.isBlockBoundary()||!(p=m.root[c?"getPrevious":"getNext"](CKEDITOR.dom.walker.invisible(!0)))||p.is&&p.isBlockBoundary({br:1})))b.document.createElement("br")[c?"insertBefore":"insertAfter"](a)}for(var f=CKEDITOR.plugins.list.listToArray(m.root,e),g=[],k=0;k<m.contents.length;k++){var h=m.contents[k];(h=h.getAscendant("li",!0))&&!h.getCustomData("list_item_processed")&&(g.push(h),CKEDITOR.dom.element.setMarker(e,
h,"list_item_processed",!0))}h=null;for(k=0;k<g.length;k++)h=g[k].getCustomData("listarray_index"),f[h].indent=-1;for(k=h+1;k<f.length;k++)if(f[k].indent>f[k-1].indent+1){g=f[k-1].indent+1-f[k].indent;for(h=f[k].indent;f[k]&&f[k].indent>=h;)f[k].indent+=g,k++;k--}var d=CKEDITOR.plugins.list.arrayToList(f,e,null,b.config.enterMode,m.root.getAttribute("dir")).listNode,a,p;c(!0);c();d.replace(m.root);b.fire("contentDomInvalidated")}function B(b,m){this.name=b;this.context=this.type=m;this.allowedContent=
m+" li";this.requiredContent=m}function E(b,m,e,c){for(var f,g;f=b[c?"getLast":"getFirst"](J);)(g=f.getDirection(1))!==m.getDirection(1)&&f.setAttribute("dir",g),f.remove(),e?f[c?"insertBefore":"insertAfter"](e):m.append(f,c)}function F(b){function m(e){var c=b[e?"getPrevious":"getNext"](u);c&&c.type==CKEDITOR.NODE_ELEMENT&&c.is(b.getName())&&(E(b,c,null,!e),b.remove(),b=c)}m();m(1)}function G(b){return b.type==CKEDITOR.NODE_ELEMENT&&(b.getName()in CKEDITOR.dtd.$block||b.getName()in CKEDITOR.dtd.$listItem)&&
CKEDITOR.dtd[b.getName()]["#"]}function C(b,m,e){b.fire("saveSnapshot");e.enlarge(CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS);var c=e.extractContents();m.trim(!1,!0);var f=m.createBookmark(),g=new CKEDITOR.dom.elementPath(m.startContainer),k=g.block,g=g.lastElement.getAscendant("li",1)||k,h=new CKEDITOR.dom.elementPath(e.startContainer),d=h.contains(CKEDITOR.dtd.$listItem),h=h.contains(CKEDITOR.dtd.$list);k?(k=k.getBogus())&&k.remove():h&&(k=h.getPrevious(u))&&z(k)&&k.remove();(k=c.getLast())&&k.type==CKEDITOR.NODE_ELEMENT&&
k.is("br")&&k.remove();(k=m.startContainer.getChild(m.startOffset))?c.insertBefore(k):m.startContainer.append(c);d&&(c=A(d))&&(g.contains(d)?(E(c,d.getParent(),d),c.remove()):g.append(c));for(;e.checkStartOfBlock()&&e.checkEndOfBlock();){h=e.startPath();c=h.block;if(!c)break;c.is("li")&&(g=c.getParent(),c.equals(g.getLast(u))&&c.equals(g.getFirst(u))&&(c=g));e.moveToPosition(c,CKEDITOR.POSITION_BEFORE_START);c.remove()}e=e.clone();c=b.editable();e.setEndAt(c,CKEDITOR.POSITION_BEFORE_END);e=new CKEDITOR.dom.walker(e);
e.evaluator=function(a){return u(a)&&!z(a)};(e=e.next())&&e.type==CKEDITOR.NODE_ELEMENT&&e.getName()in CKEDITOR.dtd.$list&&F(e);m.moveToBookmark(f);m.select();b.fire("saveSnapshot")}function A(b){return(b=b.getLast(u))&&b.type==CKEDITOR.NODE_ELEMENT&&b.getName()in v?b:null}var v={ol:1,ul:1},K=CKEDITOR.dom.walker.whitespaces(),H=CKEDITOR.dom.walker.bookmark(),u=function(b){return!(K(b)||H(b))},z=CKEDITOR.dom.walker.bogus();CKEDITOR.plugins.list={listToArray:function(b,m,e,c,f){if(!v[b.getName()])return[];
c||(c=0);e||(e=[]);for(var g=0,k=b.getChildCount();g<k;g++){var h=b.getChild(g);h.type==CKEDITOR.NODE_ELEMENT&&h.getName()in CKEDITOR.dtd.$list&&CKEDITOR.plugins.list.listToArray(h,m,e,c+1);if("li"==h.$.nodeName.toLowerCase()){var d={parent:b,indent:c,element:h,contents:[]};f?d.grandparent=f:(d.grandparent=b.getParent(),d.grandparent&&"li"==d.grandparent.$.nodeName.toLowerCase()&&(d.grandparent=d.grandparent.getParent()));m&&CKEDITOR.dom.element.setMarker(m,h,"listarray_index",e.length);e.push(d);
for(var a=0,p=h.getChildCount(),l;a<p;a++)l=h.getChild(a),l.type==CKEDITOR.NODE_ELEMENT&&v[l.getName()]?CKEDITOR.plugins.list.listToArray(l,m,e,c+1,d.grandparent):d.contents.push(l)}}return e},arrayToList:function(b,m,e,c,f){e||(e=0);if(!b||b.length<e+1)return null;for(var g,k=b[e].parent.getDocument(),h=new CKEDITOR.dom.documentFragment(k),d=null,a=e,p=Math.max(b[e].indent,0),l=null,q,n,t=c==CKEDITOR.ENTER_P?"p":"div";;){var r=b[a];g=r.grandparent;q=r.element.getDirection(1);if(r.indent==p){d&&b[a].parent.getName()==
d.getName()||(d=b[a].parent.clone(!1,1),f&&d.setAttribute("dir",f),h.append(d));l=d.append(r.element.clone(0,1));q!=d.getDirection(1)&&l.setAttribute("dir",q);for(g=0;g<r.contents.length;g++)l.append(r.contents[g].clone(1,1));a++}else if(r.indent==Math.max(p,0)+1)r=b[a-1].element.getDirection(1),a=CKEDITOR.plugins.list.arrayToList(b,null,a,c,r!=q?q:null),!l.getChildCount()&&CKEDITOR.env.needsNbspFiller&&7>=k.$.documentMode&&l.append(k.createText(" ")),l.append(a.listNode),a=a.nextIndex;else if(-1==
r.indent&&!e&&g){v[g.getName()]?(l=r.element.clone(!1,!0),q!=g.getDirection(1)&&l.setAttribute("dir",q)):l=new CKEDITOR.dom.documentFragment(k);var d=g.getDirection(1)!=q,y=r.element,D=y.getAttribute("class"),z=y.getAttribute("style"),A=l.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT&&(c!=CKEDITOR.ENTER_BR||d||z||D),w,B=r.contents.length,x;for(g=0;g<B;g++)if(w=r.contents[g],H(w)&&1<B)A?x=w.clone(1,1):l.append(w.clone(1,1));else if(w.type==CKEDITOR.NODE_ELEMENT&&w.isBlockBoundary()){d&&!w.getDirection()&&
w.setAttribute("dir",q);n=w;var C=y.getAttribute("style");C&&n.setAttribute("style",C.replace(/([^;])$/,"$1;")+(n.getAttribute("style")||""));D&&w.addClass(D);n=null;x&&(l.append(x),x=null);l.append(w.clone(1,1))}else A?(n||(n=k.createElement(t),l.append(n),d&&n.setAttribute("dir",q)),z&&n.setAttribute("style",z),D&&n.setAttribute("class",D),x&&(n.append(x),x=null),n.append(w.clone(1,1))):l.append(w.clone(1,1));x&&((n||l).append(x),x=null);l.type==CKEDITOR.NODE_DOCUMENT_FRAGMENT&&a!=b.length-1&&(CKEDITOR.env.needsBrFiller&&
(q=l.getLast())&&q.type==CKEDITOR.NODE_ELEMENT&&q.is("br")&&q.remove(),(q=l.getLast(u))&&q.type==CKEDITOR.NODE_ELEMENT&&q.is(CKEDITOR.dtd.$block)||l.append(k.createElement("br")));q=l.$.nodeName.toLowerCase();"div"!=q&&"p"!=q||l.appendBogus();h.append(l);d=null;a++}else return null;n=null;if(b.length<=a||Math.max(b[a].indent,0)<p)break}if(m)for(b=h.getFirst();b;){if(b.type==CKEDITOR.NODE_ELEMENT&&(CKEDITOR.dom.element.clearMarkers(m,b),b.getName()in CKEDITOR.dtd.$listItem&&(e=b,k=f=c=void 0,c=e.getDirection()))){for(f=
e.getParent();f&&!(k=f.getDirection());)f=f.getParent();c==k&&e.removeAttribute("dir")}b=b.getNextSourceNode()}return{listNode:h,nextIndex:a}}};var L=/^h[1-6]$/,J=CKEDITOR.dom.walker.nodeType(CKEDITOR.NODE_ELEMENT);B.prototype={exec:function(b){this.refresh(b,b.elementPath());var m=b.config,e=b.getSelection(),c=e&&e.getRanges();if(this.state==CKEDITOR.TRISTATE_OFF){var f=b.editable();if(f.getFirst(u)){var g=1==c.length&&c[0];(m=g&&g.getEnclosedNode())&&m.is&&this.type==m.getName()&&this.setState(CKEDITOR.TRISTATE_ON)}else m.enterMode==
CKEDITOR.ENTER_BR?f.appendBogus():c[0].fixBlock(1,m.enterMode==CKEDITOR.ENTER_P?"p":"div"),e.selectRanges(c)}for(var m=e.createBookmarks(!0),f=[],k={},c=c.createIterator(),h=0;(g=c.getNextRange())&&++h;){var d=g.getBoundaryNodes(),a=d.startNode,p=d.endNode;a.type==CKEDITOR.NODE_ELEMENT&&"td"==a.getName()&&g.setStartAt(d.startNode,CKEDITOR.POSITION_AFTER_START);p.type==CKEDITOR.NODE_ELEMENT&&"td"==p.getName()&&g.setEndAt(d.endNode,CKEDITOR.POSITION_BEFORE_END);g=g.createIterator();for(g.forceBrBreak=
this.state==CKEDITOR.TRISTATE_OFF;d=g.getNextParagraph();)if(!d.getCustomData("list_block")){CKEDITOR.dom.element.setMarker(k,d,"list_block",1);for(var l=b.elementPath(d),a=l.elements,p=0,l=l.blockLimit,q,n=a.length-1;0<=n&&(q=a[n]);n--)if(v[q.getName()]&&l.contains(q)){l.removeCustomData("list_group_object_"+h);(a=q.getCustomData("list_group_object"))?a.contents.push(d):(a={root:q,contents:[d]},f.push(a),CKEDITOR.dom.element.setMarker(k,q,"list_group_object",a));p=1;break}p||(p=l,p.getCustomData("list_group_object_"+
h)?p.getCustomData("list_group_object_"+h).contents.push(d):(a={root:p,contents:[d]},CKEDITOR.dom.element.setMarker(k,p,"list_group_object_"+h,a),f.push(a)))}}for(q=[];0<f.length;)if(a=f.shift(),this.state==CKEDITOR.TRISTATE_OFF)if(v[a.root.getName()]){c=b;h=a;a=k;g=q;p=CKEDITOR.plugins.list.listToArray(h.root,a);l=[];for(d=0;d<h.contents.length;d++)n=h.contents[d],(n=n.getAscendant("li",!0))&&!n.getCustomData("list_item_processed")&&(l.push(n),CKEDITOR.dom.element.setMarker(a,n,"list_item_processed",
!0));for(var n=h.root.getDocument(),t=void 0,r=void 0,d=0;d<l.length;d++){var y=l[d].getCustomData("listarray_index"),t=p[y].parent;t.is(this.type)||(r=n.createElement(this.type),t.copyAttributes(r,{start:1,type:1}),r.removeStyle("list-style-type"),p[y].parent=r)}a=CKEDITOR.plugins.list.arrayToList(p,a,null,c.config.enterMode);p=void 0;l=a.listNode.getChildCount();for(d=0;d<l&&(p=a.listNode.getChild(d));d++)p.getName()==this.type&&g.push(p);a.listNode.replace(h.root);c.fire("contentDomInvalidated")}else{p=
b;g=a;d=q;l=g.contents;c=g.root.getDocument();h=[];1==l.length&&l[0].equals(g.root)&&(a=c.createElement("div"),l[0].moveChildren&&l[0].moveChildren(a),l[0].append(a),l[0]=a);g=g.contents[0].getParent();for(n=0;n<l.length;n++)g=g.getCommonAncestor(l[n].getParent());t=p.config.useComputedState;p=a=void 0;t=void 0===t||t;for(n=0;n<l.length;n++)for(r=l[n];y=r.getParent();){if(y.equals(g)){h.push(r);!p&&r.getDirection()&&(p=1);r=r.getDirection(t);null!==a&&(a=a&&a!=r?null:r);break}r=y}if(!(1>h.length)){l=
h[h.length-1].getNext();n=c.createElement(this.type);d.push(n);for(t=d=void 0;h.length;)d=h.shift(),t=c.createElement("li"),r=d,r.is("pre")||L.test(r.getName())||"false"==r.getAttribute("contenteditable")?d.appendTo(t):(d.copyAttributes(t),a&&d.getDirection()&&(t.removeStyle("direction"),t.removeAttribute("dir")),d.moveChildren(t),d.remove()),t.appendTo(n);a&&p&&n.setAttribute("dir",a);l?n.insertBefore(l):n.appendTo(g)}}else this.state==CKEDITOR.TRISTATE_ON&&v[a.root.getName()]&&I.call(this,b,a,k);
for(n=0;n<q.length;n++)F(q[n]);CKEDITOR.dom.element.clearAllMarkers(k);e.selectBookmarks(m);b.focus()},refresh:function(b,m){var e=m.contains(v,1),c=m.blockLimit||m.root;e&&c.contains(e)?this.setState(e.is(this.type)?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF):this.setState(CKEDITOR.TRISTATE_OFF)}};CKEDITOR.plugins.add("list",{requires:"indentlist",init:function(b){b.blockless||(b.addCommand("numberedlist",new B("numberedlist","ol")),b.addCommand("bulletedlist",new B("bulletedlist","ul")),b.ui.addButton&&
(b.ui.addButton("NumberedList",{label:b.lang.list.numberedlist,command:"numberedlist",directional:!0,toolbar:"list,10"}),b.ui.addButton("BulletedList",{label:b.lang.list.bulletedlist,command:"bulletedlist",directional:!0,toolbar:"list,20"})),b.on("key",function(m){var e=m.data.domEvent.getKey(),c;if("wysiwyg"==b.mode&&e in{8:1,46:1}){var f=b.getSelection().getRanges()[0],g=f&&f.startPath();if(f&&f.collapsed){var k=8==e,h=b.editable(),d=new CKEDITOR.dom.walker(f.clone());d.evaluator=function(a){return u(a)&&
!z(a)};d.guard=function(a,b){return!(b&&a.type==CKEDITOR.NODE_ELEMENT&&a.is("table"))};e=f.clone();if(k){var a;(a=g.contains(v))&&f.checkBoundaryOfElement(a,CKEDITOR.START)&&(a=a.getParent())&&a.is("li")&&(a=A(a))?(c=a,a=a.getPrevious(u),e.moveToPosition(a&&z(a)?a:c,CKEDITOR.POSITION_BEFORE_START)):(d.range.setStartAt(h,CKEDITOR.POSITION_AFTER_START),d.range.setEnd(f.startContainer,f.startOffset),(a=d.previous())&&a.type==CKEDITOR.NODE_ELEMENT&&(a.getName()in v||a.is("li"))&&(a.is("li")||(d.range.selectNodeContents(a),
d.reset(),d.evaluator=G,a=d.previous()),c=a,e.moveToElementEditEnd(c),e.moveToPosition(e.endPath().block,CKEDITOR.POSITION_BEFORE_END)));if(c)C(b,e,f),m.cancel();else{var p=g.contains(v);p&&f.checkBoundaryOfElement(p,CKEDITOR.START)&&(c=p.getFirst(u),f.checkBoundaryOfElement(c,CKEDITOR.START)&&(a=p.getPrevious(u),A(c)?a&&(f.moveToElementEditEnd(a),f.select()):b.execCommand("outdent"),m.cancel()))}}else if(c=g.contains("li")){if(d.range.setEndAt(h,CKEDITOR.POSITION_BEFORE_END),k=(h=c.getLast(u))&&
G(h)?h:c,g=0,(a=d.next())&&a.type==CKEDITOR.NODE_ELEMENT&&a.getName()in v&&a.equals(h)?(g=1,a=d.next()):f.checkBoundaryOfElement(k,CKEDITOR.END)&&(g=2),g&&a){f=f.clone();f.moveToElementEditStart(a);if(1==g&&(e.optimize(),!e.startContainer.equals(c))){for(c=e.startContainer;c.is(CKEDITOR.dtd.$inline);)p=c,c=c.getParent();p&&e.moveToPosition(p,CKEDITOR.POSITION_AFTER_END)}2==g&&(e.moveToPosition(e.endPath().block,CKEDITOR.POSITION_BEFORE_END),f.endPath().block&&f.moveToPosition(f.endPath().block,CKEDITOR.POSITION_AFTER_START));
C(b,e,f);m.cancel()}}else d.range.setEndAt(h,CKEDITOR.POSITION_BEFORE_END),(a=d.next())&&a.type==CKEDITOR.NODE_ELEMENT&&a.is(v)&&(a=a.getFirst(u),g.block&&f.checkStartOfBlock()&&f.checkEndOfBlock()?(g.block.remove(),f.moveToElementEditStart(a),f.select()):A(a)?(f.moveToElementEditStart(a),f.select()):(f=f.clone(),f.moveToElementEditStart(a),C(b,e,f)),m.cancel());setTimeout(function(){b.selectionChange(1)})}}}))}})})();(function(){CKEDITOR.plugins.liststyle={requires:"dialog,contextmenu",init:function(a){if(!a.blockless){var b;b=new CKEDITOR.dialogCommand("numberedListStyle",{requiredContent:"ol",allowedContent:"ol{list-style-type}[start]; li{list-style-type}[value]",contentTransformations:[["ol: listTypeToStyle"]]});b=a.addCommand("numberedListStyle",b);a.addFeature(b);CKEDITOR.dialog.add("numberedListStyle",this.path+"dialogs/liststyle.js");b=new CKEDITOR.dialogCommand("bulletedListStyle",{requiredContent:"ul",
allowedContent:"ul{list-style-type}",contentTransformations:[["ul: listTypeToStyle"]]});b=a.addCommand("bulletedListStyle",b);a.addFeature(b);CKEDITOR.dialog.add("bulletedListStyle",this.path+"dialogs/liststyle.js");a.addMenuGroup("list",108);a.addMenuItems({numberedlist:{label:a.lang.liststyle.numberedTitle,group:"list",command:"numberedListStyle"},bulletedlist:{label:a.lang.liststyle.bulletedTitle,group:"list",command:"bulletedListStyle"}});a.contextMenu.addListener(function(a){if(!a||a.isReadOnly())return null;
for(;a;){var b=a.getName();if("ol"==b)return{numberedlist:CKEDITOR.TRISTATE_OFF};if("ul"==b)return{bulletedlist:CKEDITOR.TRISTATE_OFF};a=a.getParent()}return null})}}};CKEDITOR.plugins.add("liststyle",CKEDITOR.plugins.liststyle)})();(function(){function V(a,c,d){return n(c)&&n(d)&&d.equals(c.getNext(function(a){return!(E(a)||F(a)||u(a))}))}function z(a){this.upper=a[0];this.lower=a[1];this.set.apply(this,a.slice(2))}function O(a){var c=a.element;if(c&&n(c)&&(c=c.getAscendant(a.triggers,!0))&&a.editable.contains(c)){var d=P(c);if("true"==d.getAttribute("contenteditable"))return c;if(d.is(a.triggers))return d}return null}function ka(a,c,d){r(a,c);r(a,d);a=c.size.bottom;d=d.size.top;return a&&d?0|(a+d)/2:a||d}function w(a,c,d){return c=
c[d?"getPrevious":"getNext"](function(b){return b&&b.type==CKEDITOR.NODE_TEXT&&!E(b)||n(b)&&!u(b)&&!A(a,b)})}function q(a,c,d){return a>c&&a<d}function P(a,c){if(a.data("cke-editable"))return null;for(c||(a=a.getParent());a&&!a.data("cke-editable");){if(a.hasAttribute("contenteditable"))return a;a=a.getParent()}return null}function la(a){var c=a.doc,d=G('\x3cspan contenteditable\x3d"false" data-cke-magic-line\x3d"1" style\x3d"'+Q+"position:absolute;border-top:1px dashed "+a.boxColor+'"\x3e\x3c/span\x3e',
c),b=CKEDITOR.getUrl(this.path+"images/"+(t.hidpi?"hidpi/":"")+"icon"+(a.rtl?"-rtl":"")+".png");v(d,{attach:function(){this.wrap.getParent()||this.wrap.appendTo(a.editable,!0);return this},lineChildren:[v(G('\x3cspan title\x3d"'+a.editor.lang.magicline.title+'" contenteditable\x3d"false"\x3e\x26#8629;\x3c/span\x3e',c),{base:Q+"height:17px;width:17px;"+(a.rtl?"left":"right")+":17px;background:url("+b+") center no-repeat "+a.boxColor+";cursor:pointer;"+(t.hc?"font-size: 15px;line-height:14px;border:1px solid #fff;text-align:center;":
"")+(t.hidpi?"background-size: 9px 10px;":""),looks:["top:-8px; border-radius: 2px;","top:-17px; border-radius: 2px 2px 0px 0px;","top:-1px; border-radius: 0px 0px 2px 2px;"]}),v(G(W,c),{base:X+"left:0px;border-left-color:"+a.boxColor+";",looks:["border-width:8px 0 8px 8px;top:-8px","border-width:8px 0 0 8px;top:-8px","border-width:0 0 8px 8px;top:0px"]}),v(G(W,c),{base:X+"right:0px;border-right-color:"+a.boxColor+";",looks:["border-width:8px 8px 8px 0;top:-8px","border-width:8px 8px 0 0;top:-8px",
"border-width:0 8px 8px 0;top:0px"]})],detach:function(){this.wrap.getParent()&&this.wrap.remove();return this},mouseNear:function(){r(a,this);var b=a.holdDistance,c=this.size;return c&&q(a.mouse.y,c.top-b,c.bottom+b)&&q(a.mouse.x,c.left-b,c.right+b)?!0:!1},place:function(){var b=a.view,c=a.editable,d=a.trigger,h=d.upper,g=d.lower,l=h||g,p=l.getParent(),m={};this.trigger=d;h&&r(a,h,!0);g&&r(a,g,!0);r(a,p,!0);a.inInlineMode&&H(a,!0);p.equals(c)?(m.left=b.scroll.x,m.right=-b.scroll.x,m.width=""):(m.left=
l.size.left-l.size.margin.left+b.scroll.x-(a.inInlineMode?b.editable.left+b.editable.border.left:0),m.width=l.size.outerWidth+l.size.margin.left+l.size.margin.right+b.scroll.x,m.right="");h&&g?m.top=h.size.margin.bottom===g.size.margin.top?0|h.size.bottom+h.size.margin.bottom/2:h.size.margin.bottom<g.size.margin.top?h.size.bottom+h.size.margin.bottom:h.size.bottom+h.size.margin.bottom-g.size.margin.top:h?g||(m.top=h.size.bottom+h.size.margin.bottom):m.top=g.size.top-g.size.margin.top;d.is(C)||q(m.top,
b.scroll.y-15,b.scroll.y+5)?(m.top=a.inInlineMode?0:b.scroll.y,this.look(C)):d.is(D)||q(m.top,b.pane.bottom-5,b.pane.bottom+15)?(m.top=a.inInlineMode?b.editable.height+b.editable.padding.top+b.editable.padding.bottom:b.pane.bottom-1,this.look(D)):(a.inInlineMode&&(m.top-=b.editable.top+b.editable.border.top),this.look(x));a.inInlineMode&&(m.top--,m.top+=b.editable.scroll.top,m.left+=b.editable.scroll.left);for(var n in m)m[n]=CKEDITOR.tools.cssLength(m[n]);this.setStyles(m)},look:function(a){if(this.oldLook!=
a){for(var b=this.lineChildren.length,c;b--;)(c=this.lineChildren[b]).setAttribute("style",c.base+c.looks[0|a/2]);this.oldLook=a}},wrap:new R("span",a.doc)});for(c=d.lineChildren.length;c--;)d.lineChildren[c].appendTo(d);d.look(x);d.appendTo(d.wrap);d.unselectable();d.lineChildren[0].on("mouseup",function(b){d.detach();S(a,function(b){var c=a.line.trigger;b[c.is(I)?"insertBefore":"insertAfter"](c.is(I)?c.lower:c.upper)},!0);a.editor.focus();t.ie||a.enterMode==CKEDITOR.ENTER_BR||a.hotNode.scrollIntoView();
b.data.preventDefault(!0)});d.on("mousedown",function(a){a.data.preventDefault(!0)});a.line=d}function S(a,c,d){var b=new CKEDITOR.dom.range(a.doc),e=a.editor,f;t.ie&&a.enterMode==CKEDITOR.ENTER_BR?f=a.doc.createText(J):(f=(f=P(a.element,!0))&&f.data("cke-enter-mode")||a.enterMode,f=new R(K[f],a.doc),f.is("br")||a.doc.createText(J).appendTo(f));d&&e.fire("saveSnapshot");c(f);b.moveToPosition(f,CKEDITOR.POSITION_AFTER_START);e.getSelection().selectRanges([b]);a.hotNode=f;d&&e.fire("saveSnapshot")}
function Y(a,c){return{canUndo:!0,modes:{wysiwyg:1},exec:function(){function d(b){var d=t.ie&&9>t.version?" ":J,f=a.hotNode&&a.hotNode.getText()==d&&a.element.equals(a.hotNode)&&a.lastCmdDirection===!!c;S(a,function(d){f&&a.hotNode&&a.hotNode.remove();d[c?"insertAfter":"insertBefore"](b);d.setAttributes({"data-cke-magicline-hot":1,"data-cke-magicline-dir":!!c});a.lastCmdDirection=!!c});t.ie||a.enterMode==CKEDITOR.ENTER_BR||a.hotNode.scrollIntoView();a.line.detach()}return function(b){b=b.getSelection().getStartElement();
var e;b=b.getAscendant(Z,1);if(!aa(a,b)&&b&&!b.equals(a.editable)&&!b.contains(a.editable)){(e=P(b))&&"false"==e.getAttribute("contenteditable")&&(b=e);a.element=b;e=w(a,b,!c);var f;n(e)&&e.is(a.triggers)&&e.is(ma)&&(!w(a,e,!c)||(f=w(a,e,!c))&&n(f)&&f.is(a.triggers))?d(e):(f=O(a,b),n(f)&&(w(a,f,!c)?(b=w(a,f,!c))&&n(b)&&b.is(a.triggers)&&d(f):d(f)))}}}()}}function A(a,c){if(!c||c.type!=CKEDITOR.NODE_ELEMENT||!c.$)return!1;var d=a.line;return d.wrap.equals(c)||d.wrap.contains(c)}function n(a){return a&&
a.type==CKEDITOR.NODE_ELEMENT&&a.$}function u(a){if(!n(a))return!1;var c;(c=ba(a))||(n(a)?(c={left:1,right:1,center:1},c=!(!c[a.getComputedStyle("float")]&&!c[a.getAttribute("align")])):c=!1);return c}function ba(a){return!!{absolute:1,fixed:1}[a.getComputedStyle("position")]}function L(a,c){return n(c)?c.is(a.triggers):null}function aa(a,c){if(!c)return!1;for(var d=c.getParents(1),b=d.length;b--;)for(var e=a.tabuList.length;e--;)if(d[b].hasAttribute(a.tabuList[e]))return!0;return!1}function na(a,
c,d){c=c[d?"getLast":"getFirst"](function(b){return a.isRelevant(b)&&!b.is(oa)});if(!c)return!1;r(a,c);return d?c.size.top>a.mouse.y:c.size.bottom<a.mouse.y}function ca(a){var c=a.editable,d=a.mouse,b=a.view,e=a.triggerOffset;H(a);var f=d.y>(a.inInlineMode?b.editable.top+b.editable.height/2:Math.min(b.editable.height,b.pane.height)/2),c=c[f?"getLast":"getFirst"](function(a){return!(E(a)||F(a))});if(!c)return null;A(a,c)&&(c=a.line.wrap[f?"getPrevious":"getNext"](function(a){return!(E(a)||F(a))}));
if(!n(c)||u(c)||!L(a,c))return null;r(a,c);return!f&&0<=c.size.top&&q(d.y,0,c.size.top+e)?(a=a.inInlineMode||0===b.scroll.y?C:x,new z([null,c,I,M,a])):f&&c.size.bottom<=b.pane.height&&q(d.y,c.size.bottom-e,b.pane.height)?(a=a.inInlineMode||q(c.size.bottom,b.pane.height-e,b.pane.height)?D:x,new z([c,null,da,M,a])):null}function ea(a){var c=a.mouse,d=a.view,b=a.triggerOffset,e=O(a);if(!e)return null;r(a,e);var b=Math.min(b,0|e.size.outerHeight/2),f=[],k,h;if(q(c.y,e.size.top-1,e.size.top+b))h=!1;else if(q(c.y,
e.size.bottom-b,e.size.bottom+1))h=!0;else return null;if(u(e)||na(a,e,h)||e.getParent().is(fa))return null;var g=w(a,e,!h);if(g){if(g&&g.type==CKEDITOR.NODE_TEXT)return null;if(n(g)){if(u(g)||!L(a,g)||g.getParent().is(fa))return null;f=[g,e][h?"reverse":"concat"]().concat([T,M])}}else e.equals(a.editable[h?"getLast":"getFirst"](a.isRelevant))?(H(a),h&&q(c.y,e.size.bottom-b,d.pane.height)&&q(e.size.bottom,d.pane.height-b,d.pane.height)?k=D:q(c.y,0,e.size.top+b)&&(k=C)):k=x,f=[null,e][h?"reverse":
"concat"]().concat([h?da:I,M,k,e.equals(a.editable[h?"getLast":"getFirst"](a.isRelevant))?h?D:C:x]);return 0 in f?new z(f):null}function U(a,c,d,b){for(var e=c.getDocumentPosition(),f={},k={},h={},g={},l=y.length;l--;)f[y[l]]=parseInt(c.getComputedStyle.call(c,"border-"+y[l]+"-width"),10)||0,h[y[l]]=parseInt(c.getComputedStyle.call(c,"padding-"+y[l]),10)||0,k[y[l]]=parseInt(c.getComputedStyle.call(c,"margin-"+y[l]),10)||0;d&&!b||N(a,b);g.top=e.y-(d?0:a.view.scroll.y);g.left=e.x-(d?0:a.view.scroll.x);
g.outerWidth=c.$.offsetWidth;g.outerHeight=c.$.offsetHeight;g.height=g.outerHeight-(h.top+h.bottom+f.top+f.bottom);g.width=g.outerWidth-(h.left+h.right+f.left+f.right);g.bottom=g.top+g.outerHeight;g.right=g.left+g.outerWidth;a.inInlineMode&&(g.scroll={top:c.$.scrollTop,left:c.$.scrollLeft});return v({border:f,padding:h,margin:k,ignoreScroll:d},g,!0)}function r(a,c,d){if(!n(c))return c.size=null;if(!c.size)c.size={};else if(c.size.ignoreScroll==d&&c.size.date>new Date-ga)return null;return v(c.size,
U(a,c,d),{date:+new Date},!0)}function H(a,c){a.view.editable=U(a,a.editable,c,!0)}function N(a,c){a.view||(a.view={});var d=a.view;if(!(!c&&d&&d.date>new Date-ga)){var b=a.win,d=b.getScrollPosition(),b=b.getViewPaneSize();v(a.view,{scroll:{x:d.x,y:d.y,width:a.doc.$.documentElement.scrollWidth-b.width,height:a.doc.$.documentElement.scrollHeight-b.height},pane:{width:b.width,height:b.height,bottom:b.height+d.y},date:+new Date},!0)}}function pa(a,c,d,b){for(var e=b,f=b,k=0,h=!1,g=!1,l=a.view.pane.height,
p=a.mouse;p.y+k<l&&0<p.y-k;){h||(h=c(e,b));g||(g=c(f,b));!h&&0<p.y-k&&(e=d(a,{x:p.x,y:p.y-k}));!g&&p.y+k<l&&(f=d(a,{x:p.x,y:p.y+k}));if(h&&g)break;k+=2}return new z([e,f,null,null])}CKEDITOR.plugins.add("magicline",{init:function(a){var c=a.config,d=c.magicline_triggerOffset||30,b={editor:a,enterMode:c.enterMode,triggerOffset:d,holdDistance:0|d*(c.magicline_holdDistance||.5),boxColor:c.magicline_color||"#ff0000",rtl:"rtl"==c.contentsLangDirection,tabuList:["data-cke-hidden-sel"].concat(c.magicline_tabuList||
[]),triggers:c.magicline_everywhere?Z:{table:1,hr:1,div:1,ul:1,ol:1,dl:1,form:1,blockquote:1}},e,f,k;b.isRelevant=function(a){return n(a)&&!A(b,a)&&!u(a)};a.on("contentDom",function(){var d=a.editable(),g=a.document,l=a.window;v(b,{editable:d,inInlineMode:d.isInline(),doc:g,win:l,hotNode:null},!0);b.boundary=b.inInlineMode?b.editable:b.doc.getDocumentElement();d.is(B.$inline)||(b.inInlineMode&&!ba(d)&&d.setStyles({position:"relative",top:null,left:null}),la.call(this,b),N(b),d.attachListener(a,"beforeUndoImage",
function(){b.line.detach()}),d.attachListener(a,"beforeGetData",function(){b.line.wrap.getParent()&&(b.line.detach(),a.once("getData",function(){b.line.attach()},null,null,1E3))},null,null,0),d.attachListener(b.inInlineMode?g:g.getWindow().getFrame(),"mouseout",function(c){if("wysiwyg"==a.mode)if(b.inInlineMode){var d=c.data.$.clientX;c=c.data.$.clientY;N(b);H(b,!0);var e=b.view.editable,f=b.view.scroll;d>e.left-f.x&&d<e.right-f.x&&c>e.top-f.y&&c<e.bottom-f.y||(clearTimeout(k),k=null,b.line.detach())}else clearTimeout(k),
k=null,b.line.detach()}),d.attachListener(d,"keyup",function(){b.hiddenMode=0}),d.attachListener(d,"keydown",function(c){if("wysiwyg"==a.mode)switch(c.data.getKeystroke()){case 2228240:case 16:b.hiddenMode=1,b.line.detach()}}),d.attachListener(b.inInlineMode?d:g,"mousemove",function(c){f=!0;if("wysiwyg"==a.mode&&!a.readOnly&&!k){var d={x:c.data.$.clientX,y:c.data.$.clientY};k=setTimeout(function(){b.mouse=d;k=b.trigger=null;N(b);f&&!b.hiddenMode&&a.focusManager.hasFocus&&!b.line.mouseNear()&&(b.element=
ha(b,!0))&&((b.trigger=ca(b)||ea(b)||ia(b))&&!aa(b,b.trigger.upper||b.trigger.lower)?b.line.attach().place():(b.trigger=null,b.line.detach()),f=!1)},30)}}),d.attachListener(l,"scroll",function(){"wysiwyg"==a.mode&&(b.line.detach(),t.webkit&&(b.hiddenMode=1,clearTimeout(e),e=setTimeout(function(){b.mouseDown||(b.hiddenMode=0)},50)))}),d.attachListener(ja?g:l,"mousedown",function(){"wysiwyg"==a.mode&&(b.line.detach(),b.hiddenMode=1,b.mouseDown=1)}),d.attachListener(ja?g:l,"mouseup",function(){b.hiddenMode=
0;b.mouseDown=0}),a.addCommand("accessPreviousSpace",Y(b)),a.addCommand("accessNextSpace",Y(b,!0)),a.setKeystroke([[c.magicline_keystrokePrevious,"accessPreviousSpace"],[c.magicline_keystrokeNext,"accessNextSpace"]]),a.on("loadSnapshot",function(){var c,d,e,f;for(f in{p:1,br:1,div:1})for(c=a.document.getElementsByTag(f),e=c.count();e--;)if((d=c.getItem(e)).data("cke-magicline-hot")){b.hotNode=d;b.lastCmdDirection="true"===d.data("cke-magicline-dir")?!0:!1;return}}),this.backdoor={accessFocusSpace:S,
boxTrigger:z,isLine:A,getAscendantTrigger:O,getNonEmptyNeighbour:w,getSize:U,that:b,triggerEdge:ea,triggerEditable:ca,triggerExpand:ia})},this)}});var v=CKEDITOR.tools.extend,R=CKEDITOR.dom.element,G=R.createFromHtml,t=CKEDITOR.env,ja=CKEDITOR.env.ie&&9>CKEDITOR.env.version,B=CKEDITOR.dtd,K={},I=128,da=64,T=32,M=16,C=4,D=2,x=1,J=" ",fa=B.$listItem,oa=B.$tableContent,ma=v({},B.$nonEditable,B.$empty),Z=B.$block,ga=100,Q="width:0px;height:0px;padding:0px;margin:0px;display:block;z-index:9999;color:#fff;position:absolute;font-size: 0px;line-height:0px;",
X=Q+"border-color:transparent;display:block;border-style:solid;",W="\x3cspan\x3e"+J+"\x3c/span\x3e";K[CKEDITOR.ENTER_BR]="br";K[CKEDITOR.ENTER_P]="p";K[CKEDITOR.ENTER_DIV]="div";z.prototype={set:function(a,c,d){this.properties=a+c+(d||x);return this},is:function(a){return(this.properties&a)==a}};var ha=function(){function a(a,d){var b=a.$.elementFromPoint(d.x,d.y);return b&&b.nodeType?new CKEDITOR.dom.element(b):null}return function(c,d,b){if(!c.mouse)return null;var e=c.doc,f=c.line.wrap;b=b||c.mouse;
var k=a(e,b);d&&A(c,k)&&(f.hide(),k=a(e,b),f.show());return!k||k.type!=CKEDITOR.NODE_ELEMENT||!k.$||t.ie&&9>t.version&&!c.boundary.equals(k)&&!c.boundary.contains(k)?null:k}}(),E=CKEDITOR.dom.walker.whitespaces(),F=CKEDITOR.dom.walker.nodeType(CKEDITOR.NODE_COMMENT),ia=function(){function a(a){var b=a.element,e,f,k;if(!n(b)||b.contains(a.editable)||b.isReadOnly())return null;k=pa(a,function(a,b){return!b.equals(a)},function(a,b){return ha(a,!0,b)},b);e=k.upper;f=k.lower;if(V(a,e,f))return k.set(T,
8);if(e&&b.contains(e))for(;!e.getParent().equals(b);)e=e.getParent();else e=b.getFirst(function(b){return c(a,b)});if(f&&b.contains(f))for(;!f.getParent().equals(b);)f=f.getParent();else f=b.getLast(function(b){return c(a,b)});if(!e||!f)return null;r(a,e);r(a,f);if(!q(a.mouse.y,e.size.top,f.size.bottom))return null;for(var b=Number.MAX_VALUE,h,g,l,p;f&&!f.equals(e)&&(g=e.getNext(a.isRelevant));)h=Math.abs(ka(a,e,g)-a.mouse.y),h<b&&(b=h,l=e,p=g),e=g,r(a,e);if(!l||!p||!q(a.mouse.y,l.size.top,p.size.bottom))return null;
k.upper=l;k.lower=p;return k.set(T,8)}function c(a,b){return!(b&&b.type==CKEDITOR.NODE_TEXT||F(b)||u(b)||A(a,b)||b.type==CKEDITOR.NODE_ELEMENT&&b.$&&b.is("br"))}return function(c){var b=a(c),e;if(e=b){e=b.upper;var f=b.lower;e=!e||!f||u(f)||u(e)||f.equals(e)||e.equals(f)||f.contains(e)||e.contains(f)?!1:L(c,e)&&L(c,f)&&V(c,e,f)?!0:!1}return e?b:null}}(),y=["top","left","right","bottom"]})();CKEDITOR.config.magicline_keystrokePrevious=CKEDITOR.CTRL+CKEDITOR.SHIFT+51;
CKEDITOR.config.magicline_keystrokeNext=CKEDITOR.CTRL+CKEDITOR.SHIFT+52;(function(){function n(a){if(!a||a.type!=CKEDITOR.NODE_ELEMENT||"form"!=a.getName())return[];for(var e=[],f=["style","className"],b=0;b<f.length;b++){var c=a.$.elements.namedItem(f[b]);c&&(c=new CKEDITOR.dom.element(c),e.push([c,c.nextSibling]),c.remove())}return e}function t(a,e){if(a&&a.type==CKEDITOR.NODE_ELEMENT&&"form"==a.getName()&&0<e.length)for(var f=e.length-1;0<=f;f--){var b=e[f][0],c=e[f][1];c?b.insertBefore(c):b.appendTo(a)}}function r(a,e){var f=n(a),b={},c=a.$;e||(b["class"]=c.className||
"",c.className="");b.inline=c.style.cssText||"";e||(c.style.cssText="position: static; overflow: visible");t(f);return b}function u(a,e){var f=n(a),b=a.$;"class"in e&&(b.className=e["class"]);"inline"in e&&(b.style.cssText=e.inline);t(f)}function v(a){if(!a.editable().isInline()){var e=CKEDITOR.instances,f;for(f in e){var b=e[f];"wysiwyg"!=b.mode||b.readOnly||(b=b.document.getBody(),b.setAttribute("contentEditable",!1),b.setAttribute("contentEditable",!0))}a.editable().hasFocus&&(a.toolbox.focus(),
a.focus())}}CKEDITOR.plugins.add("maximize",{init:function(a){function e(){var b=c.getViewPaneSize();a.resize(b.width,b.height,null,!0)}if(a.elementMode!=CKEDITOR.ELEMENT_MODE_INLINE){var f=a.lang,b=CKEDITOR.document,c=b.getWindow(),l,m,p,n=CKEDITOR.TRISTATE_OFF;a.addCommand("maximize",{modes:{wysiwyg:!CKEDITOR.env.iOS,source:!CKEDITOR.env.iOS},readOnly:1,editorFocus:!1,exec:function(){var h=a.container.getFirst(function(a){return a.type==CKEDITOR.NODE_ELEMENT&&a.hasClass("cke_inner")}),g=a.ui.space("contents");
if("wysiwyg"==a.mode){var d=a.getSelection();l=d&&d.getRanges();m=c.getScrollPosition()}else{var k=a.editable().$;l=!CKEDITOR.env.ie&&[k.selectionStart,k.selectionEnd];m=[k.scrollLeft,k.scrollTop]}if(this.state==CKEDITOR.TRISTATE_OFF){c.on("resize",e);p=c.getScrollPosition();for(d=a.container;d=d.getParent();)d.setCustomData("maximize_saved_styles",r(d)),d.setStyle("z-index",a.config.baseFloatZIndex-5);g.setCustomData("maximize_saved_styles",r(g,!0));h.setCustomData("maximize_saved_styles",r(h,!0));
g={overflow:CKEDITOR.env.webkit?"":"hidden",width:0,height:0};b.getDocumentElement().setStyles(g);!CKEDITOR.env.gecko&&b.getDocumentElement().setStyle("position","fixed");CKEDITOR.env.gecko&&CKEDITOR.env.quirks||b.getBody().setStyles(g);CKEDITOR.env.ie?setTimeout(function(){c.$.scrollTo(0,0)},0):c.$.scrollTo(0,0);h.setStyle("position",CKEDITOR.env.gecko&&CKEDITOR.env.quirks?"fixed":"absolute");h.$.offsetLeft;h.setStyles({"z-index":a.config.baseFloatZIndex-5,left:"0px",top:"0px"});h.addClass("cke_maximized");
e();g=h.getDocumentPosition();h.setStyles({left:-1*g.x+"px",top:-1*g.y+"px"});CKEDITOR.env.gecko&&v(a)}else if(this.state==CKEDITOR.TRISTATE_ON){c.removeListener("resize",e);for(var d=[g,h],q=0;q<d.length;q++)u(d[q],d[q].getCustomData("maximize_saved_styles")),d[q].removeCustomData("maximize_saved_styles");for(d=a.container;d=d.getParent();)u(d,d.getCustomData("maximize_saved_styles")),d.removeCustomData("maximize_saved_styles");CKEDITOR.env.ie?setTimeout(function(){c.$.scrollTo(p.x,p.y)},0):c.$.scrollTo(p.x,
p.y);h.removeClass("cke_maximized");CKEDITOR.env.webkit&&(h.setStyle("display","inline"),setTimeout(function(){h.setStyle("display","block")},0));a.fire("resize",{outerHeight:a.container.$.offsetHeight,contentsHeight:g.$.offsetHeight,outerWidth:a.container.$.offsetWidth})}this.toggleState();if(d=this.uiItems[0])g=this.state==CKEDITOR.TRISTATE_OFF?f.maximize.maximize:f.maximize.minimize,d=CKEDITOR.document.getById(d._.id),d.getChild(1).setHtml(g),d.setAttribute("title",g),d.setAttribute("href",'javascript:void("'+
g+'");');"wysiwyg"==a.mode?l?(CKEDITOR.env.gecko&&v(a),a.getSelection().selectRanges(l),(k=a.getSelection().getStartElement())&&k.scrollIntoView(!0)):c.$.scrollTo(m.x,m.y):(l&&(k.selectionStart=l[0],k.selectionEnd=l[1]),k.scrollLeft=m[0],k.scrollTop=m[1]);l=m=null;n=this.state;a.fire("maximize",this.state)},canUndo:!1});a.ui.addButton&&a.ui.addButton("Maximize",{label:f.maximize.maximize,command:"maximize",toolbar:"tools,10"});a.on("mode",function(){var b=a.getCommand("maximize");b.setState(b.state==
CKEDITOR.TRISTATE_DISABLED?CKEDITOR.TRISTATE_DISABLED:n)},null,null,100)}}})})();CKEDITOR.plugins.add("newpage",{init:function(a){a.addCommand("newpage",{modes:{wysiwyg:1,source:1},exec:function(b){var a=this;b.setData(b.config.newpage_html||"",function(){b.focus();setTimeout(function(){b.fire("afterCommandExec",{name:"newpage",command:a});b.selectionChange()},200)})},async:!0});a.ui.addButton&&a.ui.addButton("NewPage",{label:a.lang.newpage.toolbar,command:"newpage",toolbar:"document,20"})}});(function(){function e(a){return{"aria-label":a,"class":"cke_pagebreak",contenteditable:"false","data-cke-display-name":"pagebreak","data-cke-pagebreak":1,style:"page-break-after: always",title:a}}CKEDITOR.plugins.add("pagebreak",{requires:"fakeobjects",onLoad:function(){var a=("background:url("+CKEDITOR.getUrl(this.path+"images/pagebreak.gif")+") no-repeat center center;clear:both;width:100%;border-top:#999 1px dotted;border-bottom:#999 1px dotted;padding:0;height:7px;cursor:default;").replace(/;/g,
" !important;");CKEDITOR.addCss("div.cke_pagebreak{"+a+"}")},init:function(a){a.blockless||(a.addCommand("pagebreak",CKEDITOR.plugins.pagebreakCmd),a.ui.addButton&&a.ui.addButton("PageBreak",{label:a.lang.pagebreak.toolbar,command:"pagebreak",toolbar:"insert,70"}),CKEDITOR.env.webkit&&a.on("contentDom",function(){a.document.on("click",function(b){b=b.data.getTarget();b.is("div")&&b.hasClass("cke_pagebreak")&&a.getSelection().selectElement(b)})}))},afterInit:function(a){function b(f){CKEDITOR.tools.extend(f.attributes,
e(a.lang.pagebreak.alt),!0);f.children.length=0}var c=a.dataProcessor,g=c&&c.dataFilter,c=c&&c.htmlFilter,h=/page-break-after\s*:\s*always/i,k=/display\s*:\s*none/i;c&&c.addRules({attributes:{"class":function(a,b){var c=a.replace("cke_pagebreak","");if(c!=a){var d=CKEDITOR.htmlParser.fragment.fromHtml('\x3cspan style\x3d"display: none;"\x3e\x26nbsp;\x3c/span\x3e').children[0];b.children.length=0;b.add(d);d=b.attributes;delete d["aria-label"];delete d.contenteditable;delete d.title}return c}}},{applyToAll:!0,
priority:5});g&&g.addRules({elements:{div:function(a){if(a.attributes["data-cke-pagebreak"])b(a);else if(h.test(a.attributes.style)){var c=a.children[0];c&&"span"==c.name&&k.test(c.attributes.style)&&b(a)}}}})}});CKEDITOR.plugins.pagebreakCmd={exec:function(a){var b=a.document.createElement("div",{attributes:e(a.lang.pagebreak.alt)});a.insertElement(b)},context:"div",allowedContent:{div:{styles:"!page-break-after"},span:{match:function(a){return(a=a.parent)&&"div"==a.name&&a.styles&&a.styles["page-break-after"]},
styles:"display"}},requiredContent:"div{page-break-after}"}})();(function(){var f={canUndo:!1,async:!0,exec:function(a,b){var c=a.lang,e=CKEDITOR.tools.keystrokeToString(c.common.keyboard,a.getCommandKeystroke(CKEDITOR.env.ie?a.commands.paste:this)),d=b&&"undefined"!==typeof b.notification?b.notification:!b||!b.from||"keystrokeHandler"===b.from&&CKEDITOR.env.ie,c=d&&"string"===typeof d?d:c.pastetext.pasteNotification.replace(/%1/,'\x3ckbd aria-label\x3d"'+e.aria+'"\x3e'+e.display+"\x3c/kbd\x3e");a.execCommand("paste",{type:"text",notification:d?c:!1})}};CKEDITOR.plugins.add("pastetext",
{requires:"clipboard",init:function(a){var b=CKEDITOR.env.safari?CKEDITOR.CTRL+CKEDITOR.ALT+CKEDITOR.SHIFT+86:CKEDITOR.CTRL+CKEDITOR.SHIFT+86;a.addCommand("pastetext",f);a.setKeystroke(b,"pastetext");CKEDITOR.plugins.clipboard.addPasteButton(a,"PasteText",{label:a.lang.pastetext.button,command:"pastetext",toolbar:"clipboard,40"});if(a.config.forcePasteAsPlainText)a.on("beforePaste",function(a){"html"!=a.data.type&&(a.data.type="text")});a.on("pasteState",function(b){a.getCommand("pastetext").setState(b.data)})}})})();(function(){function l(a,f,e){var h=CKEDITOR.cleanWord;h?e():(a=CKEDITOR.getUrl(a.config.pasteFromWordCleanupFile||f+"filter/default.js"),CKEDITOR.scriptLoader.load(a,e,null,!0));return!h}CKEDITOR.plugins.add("pastefromword",{requires:"clipboard",init:function(a){function f(a){var b=CKEDITOR.plugins.pastefromword&&CKEDITOR.plugins.pastefromword.images,c,d=[];if(b&&a.editor.filter.check("img[src]")&&(c=b.extractTagsFromHtml(a.data.dataValue),0!==c.length&&(b=b.extractFromRtf(a.data.dataTransfer["text/rtf"]),
0!==b.length&&(CKEDITOR.tools.array.forEach(b,function(a){d.push(a.type?"data:"+a.type+";base64,"+CKEDITOR.tools.convertBytesToBase64(CKEDITOR.tools.convertHexStringToBytes(a.hex)):null)},this),c.length===d.length))))for(b=0;b<c.length;b++)0===c[b].indexOf("file://")&&d[b]&&(a.data.dataValue=a.data.dataValue.replace(c[b],d[b]))}var e=0,h=this.path,m=void 0===a.config.pasteFromWord_inlineImages?!0:a.config.pasteFromWord_inlineImages;a.addCommand("pastefromword",{canUndo:!1,async:!0,exec:function(a,
b){e=1;a.execCommand("paste",{type:"html",notification:b&&"undefined"!==typeof b.notification?b.notification:!0})}});CKEDITOR.plugins.clipboard.addPasteButton(a,"PasteFromWord",{label:a.lang.pastefromword.toolbar,command:"pastefromword",toolbar:"clipboard,50"});a.on("paste",function(f){var b=f.data,c=CKEDITOR.plugins.clipboard.isCustomDataTypesSupported?b.dataTransfer.getData("text/html",!0):null,d=CKEDITOR.plugins.clipboard.isCustomDataTypesSupported?b.dataTransfer.getData("text/rtf"):null,c=c||
b.dataValue,g={dataValue:c,dataTransfer:{"text/rtf":d}},d=/(class=\"?Mso|style=(?:\"|\')[^\"]*?\bmso\-|w:WordDocument|<o:\w+>|<\/font>)/,d=/<meta\s*name=(?:\"|\')?generator(?:\"|\')?\s*content=(?:\"|\')?microsoft/gi.test(c)||d.test(c);if(c&&(e||d)&&(!1!==a.fire("pasteFromWord",g)||e)){b.dontFilter=!0;var k=l(a,h,function(){if(k)a.fire("paste",b);else if(!a.config.pasteFromWordPromptCleanup||e||confirm(a.lang.pastefromword.confirmCleanup))g.dataValue=CKEDITOR.cleanWord(g.dataValue,a),a.fire("afterPasteFromWord",
g),b.dataValue=g.dataValue,!0===a.config.forcePasteAsPlainText?b.type="text":CKEDITOR.plugins.clipboard.isCustomCopyCutSupported||"allow-word"!==a.config.forcePasteAsPlainText||(b.type="html");e=0});k&&f.cancel()}},null,null,3);if(CKEDITOR.plugins.clipboard.isCustomDataTypesSupported&&m)a.on("afterPasteFromWord",f)}})})();(function(){var h,k={modes:{wysiwyg:1,source:1},canUndo:!1,readOnly:1,exec:function(a){var g,b=a.config,f=b.baseHref?'\x3cbase href\x3d"'+b.baseHref+'"/\x3e':"";if(b.fullPage)g=a.getData().replace(/<head>/,"$\x26"+f).replace(/[^>]*(?=<\/title>)/,"$\x26 \x26mdash; "+a.lang.preview.preview);else{var b="\x3cbody ",d=a.document&&a.document.getBody();d&&(d.getAttribute("id")&&(b+='id\x3d"'+d.getAttribute("id")+'" '),d.getAttribute("class")&&(b+='class\x3d"'+d.getAttribute("class")+'" '));b+="\x3e";g=a.config.docType+
'\x3chtml dir\x3d"'+a.config.contentsLangDirection+'"\x3e\x3chead\x3e'+f+"\x3ctitle\x3e"+a.lang.preview.preview+"\x3c/title\x3e"+CKEDITOR.tools.buildStyleHtml(a.config.contentsCss)+"\x3c/head\x3e"+b+a.getData()+"\x3c/body\x3e\x3c/html\x3e"}f=640;b=420;d=80;try{var c=window.screen,f=Math.round(.8*c.width),b=Math.round(.7*c.height),d=Math.round(.1*c.width)}catch(k){}if(!1===a.fire("contentPreview",a={dataValue:g}))return!1;var c="",e;CKEDITOR.env.ie&&(window._cke_htmlToLoad=a.dataValue,e="javascript:void( (function(){document.open();"+
("("+CKEDITOR.tools.fixDomain+")();").replace(/\/\/.*?\n/g,"").replace(/parent\./g,"window.opener.")+"document.write( window.opener._cke_htmlToLoad );document.close();window.opener._cke_htmlToLoad \x3d null;})() )",c="");CKEDITOR.env.gecko&&(window._cke_htmlToLoad=a.dataValue,c=CKEDITOR.getUrl(h+"preview.html"));c=window.open(c,null,"toolbar\x3dyes,location\x3dno,status\x3dyes,menubar\x3dyes,scrollbars\x3dyes,resizable\x3dyes,width\x3d"+f+",height\x3d"+b+",left\x3d"+d);CKEDITOR.env.ie&&c&&(c.location=
e);CKEDITOR.env.ie||CKEDITOR.env.gecko||(e=c.document,e.open(),e.write(a.dataValue),e.close());return!0}};CKEDITOR.plugins.add("preview",{init:function(a){a.elementMode!=CKEDITOR.ELEMENT_MODE_INLINE&&(h=this.path,a.addCommand("preview",k),a.ui.addButton&&a.ui.addButton("Preview",{label:a.lang.preview.preview,command:"preview",toolbar:"document,40"}))}})})();CKEDITOR.plugins.add("print",{init:function(a){a.elementMode!=CKEDITOR.ELEMENT_MODE_INLINE&&(a.addCommand("print",CKEDITOR.plugins.print),a.ui.addButton&&a.ui.addButton("Print",{label:a.lang.print.toolbar,command:"print",toolbar:"document,50"}))}});CKEDITOR.plugins.print={exec:function(a){CKEDITOR.env.gecko?a.window.$.print():a.document.$.execCommand("Print")},canUndo:!1,readOnly:1,modes:{wysiwyg:1}};CKEDITOR.plugins.add("removeformat",{init:function(a){a.addCommand("removeFormat",CKEDITOR.plugins.removeformat.commands.removeformat);a.ui.addButton&&a.ui.addButton("RemoveFormat",{label:a.lang.removeformat.toolbar,command:"removeFormat",toolbar:"cleanup,10"})}});
CKEDITOR.plugins.removeformat={commands:{removeformat:{exec:function(a){for(var h=a._.removeFormatRegex||(a._.removeFormatRegex=new RegExp("^(?:"+a.config.removeFormatTags.replace(/,/g,"|")+")$","i")),e=a._.removeAttributes||(a._.removeAttributes=a.config.removeFormatAttributes.split(",")),f=CKEDITOR.plugins.removeformat.filter,m=a.getSelection().getRanges(),n=m.createIterator(),p=function(a){return a.type==CKEDITOR.NODE_ELEMENT},c;c=n.getNextRange();){c.collapsed||c.enlarge(CKEDITOR.ENLARGE_ELEMENT);
var l=c.createBookmark(),b=l.startNode,d=l.endNode,k=function(b){for(var c=a.elementPath(b),e=c.elements,d=1,g;(g=e[d])&&!g.equals(c.block)&&!g.equals(c.blockLimit);d++)h.test(g.getName())&&f(a,g)&&b.breakParent(g)};k(b);if(d)for(k(d),b=b.getNextSourceNode(!0,CKEDITOR.NODE_ELEMENT);b&&!b.equals(d);)if(b.isReadOnly()){if(b.getPosition(d)&CKEDITOR.POSITION_CONTAINS)break;b=b.getNext(p)}else k=b.getNextSourceNode(!1,CKEDITOR.NODE_ELEMENT),"img"==b.getName()&&b.data("cke-realelement")||!f(a,b)||(h.test(b.getName())?
b.remove(1):(b.removeAttributes(e),a.fire("removeFormatCleanup",b))),b=k;c.moveToBookmark(l)}a.forceNextSelectionCheck();a.getSelection().selectRanges(m)}}},filter:function(a,h){for(var e=a._.removeFormatFilters||[],f=0;f<e.length;f++)if(!1===e[f](h))return!1;return!0}};CKEDITOR.editor.prototype.addRemoveFormatFilter=function(a){this._.removeFormatFilters||(this._.removeFormatFilters=[]);this._.removeFormatFilters.push(a)};CKEDITOR.config.removeFormatTags="b,big,cite,code,del,dfn,em,font,i,ins,kbd,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var";
CKEDITOR.config.removeFormatAttributes="class,style,lang,width,height,align,hspace,valign";(function(){var b={readOnly:1,modes:{wysiwyg:1,source:1},exec:function(a){if(a.fire("save")&&(a=a.element.$.form))try{a.submit()}catch(b){a.submit.click&&a.submit.click()}}};CKEDITOR.plugins.add("save",{init:function(a){a.elementMode==CKEDITOR.ELEMENT_MODE_REPLACE&&(a.addCommand("save",b).startDisabled=!a.element.$.form,a.ui.addButton&&a.ui.addButton("Save",{label:a.lang.save.toolbar,command:"save",toolbar:"document,10"}))}})})();(function(){CKEDITOR.plugins.add("selectall",{init:function(b){b.addCommand("selectAll",{modes:{wysiwyg:1,source:1},exec:function(a){var b=a.editable();if(b.is("textarea"))a=b.$,CKEDITOR.env.ie&&a.createTextRange?a.createTextRange().execCommand("SelectAll"):(a.selectionStart=0,a.selectionEnd=a.value.length),a.focus();else{if(b.is("body"))a.document.$.execCommand("SelectAll",!1,null);else{var c=a.createRange();c.selectNodeContents(b);c.select()}a.forceNextSelectionCheck();a.selectionChange()}},canUndo:!1});
b.ui.addButton&&b.ui.addButton("SelectAll",{label:b.lang.selectall.toolbar,command:"selectAll",toolbar:"selection,10"})}})})();(function(){var k={readOnly:1,preserveState:!0,editorFocus:!1,exec:function(a){this.toggleState();this.refresh(a)},refresh:function(a){if(a.document){var c=this.state!=CKEDITOR.TRISTATE_ON||a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE&&!a.focusManager.hasFocus?"removeClass":"attachClass";a.editable()[c]("cke_show_blocks")}}};CKEDITOR.plugins.add("showblocks",{onLoad:function(){var a="p div pre address blockquote h1 h2 h3 h4 h5 h6".split(" "),c,b,e,f,k=CKEDITOR.getUrl(this.path),l=!(CKEDITOR.env.ie&&
9>CKEDITOR.env.version),g=l?":not([contenteditable\x3dfalse]):not(.cke_show_blocks_off)":"",d,h;for(c=b=e=f="";d=a.pop();)h=a.length?",":"",c+=".cke_show_blocks "+d+g+h,e+=".cke_show_blocks.cke_contents_ltr "+d+g+h,f+=".cke_show_blocks.cke_contents_rtl "+d+g+h,b+=".cke_show_blocks "+d+g+"{background-image:url("+CKEDITOR.getUrl(k+"images/block_"+d+".png")+")}";CKEDITOR.addCss((c+"{background-repeat:no-repeat;border:1px dotted gray;padding-top:8px}").concat(b,e+"{background-position:top left;padding-left:8px}",
f+"{background-position:top right;padding-right:8px}"));l||CKEDITOR.addCss(".cke_show_blocks [contenteditable\x3dfalse],.cke_show_blocks .cke_show_blocks_off{border:none;padding-top:0;background-image:none}.cke_show_blocks.cke_contents_rtl [contenteditable\x3dfalse],.cke_show_blocks.cke_contents_rtl .cke_show_blocks_off{padding-right:0}.cke_show_blocks.cke_contents_ltr [contenteditable\x3dfalse],.cke_show_blocks.cke_contents_ltr .cke_show_blocks_off{padding-left:0}")},init:function(a){function c(){b.refresh(a)}
if(!a.blockless){var b=a.addCommand("showblocks",k);b.canUndo=!1;a.config.startupOutlineBlocks&&b.setState(CKEDITOR.TRISTATE_ON);a.ui.addButton&&a.ui.addButton("ShowBlocks",{label:a.lang.showblocks.toolbar,command:"showblocks",toolbar:"tools,20"});a.on("mode",function(){b.state!=CKEDITOR.TRISTATE_DISABLED&&b.refresh(a)});a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE&&(a.on("focus",c),a.on("blur",c));a.on("contentDom",function(){b.state!=CKEDITOR.TRISTATE_DISABLED&&b.refresh(a)})}}})})();(function(){var f={preserveState:!0,editorFocus:!1,readOnly:1,exec:function(a){this.toggleState();this.refresh(a)},refresh:function(a){if(a.document){var b=this.state==CKEDITOR.TRISTATE_ON?"attachClass":"removeClass";a.editable()[b]("cke_show_borders")}}};CKEDITOR.plugins.add("showborders",{modes:{wysiwyg:1},onLoad:function(){var a;a=(CKEDITOR.env.ie6Compat?[".%1 table.%2,",".%1 table.%2 td, .%1 table.%2 th","{","border : #d3d3d3 1px dotted","}"]:".%1 table.%2,;.%1 table.%2 \x3e tr \x3e td, .%1 table.%2 \x3e tr \x3e th,;.%1 table.%2 \x3e tbody \x3e tr \x3e td, .%1 table.%2 \x3e tbody \x3e tr \x3e th,;.%1 table.%2 \x3e thead \x3e tr \x3e td, .%1 table.%2 \x3e thead \x3e tr \x3e th,;.%1 table.%2 \x3e tfoot \x3e tr \x3e td, .%1 table.%2 \x3e tfoot \x3e tr \x3e th;{;border : #d3d3d3 1px dotted;}".split(";")).join("").replace(/%2/g,
"cke_show_border").replace(/%1/g,"cke_show_borders ");CKEDITOR.addCss(a)},init:function(a){var b=a.addCommand("showborders",f);b.canUndo=!1;!1!==a.config.startupShowBorders&&b.setState(CKEDITOR.TRISTATE_ON);a.on("mode",function(){b.state!=CKEDITOR.TRISTATE_DISABLED&&b.refresh(a)},null,null,100);a.on("contentDom",function(){b.state!=CKEDITOR.TRISTATE_DISABLED&&b.refresh(a)});a.on("removeFormatCleanup",function(d){d=d.data;a.getCommand("showborders").state==CKEDITOR.TRISTATE_ON&&d.is("table")&&(!d.hasAttribute("border")||
0>=parseInt(d.getAttribute("border"),10))&&d.addClass("cke_show_border")})},afterInit:function(a){var b=a.dataProcessor;a=b&&b.dataFilter;b=b&&b.htmlFilter;a&&a.addRules({elements:{table:function(a){a=a.attributes;var b=a["class"],c=parseInt(a.border,10);c&&!(0>=c)||b&&-1!=b.indexOf("cke_show_border")||(a["class"]=(b||"")+" cke_show_border")}}});b&&b.addRules({elements:{table:function(a){a=a.attributes;var b=a["class"];b&&(a["class"]=b.replace("cke_show_border","").replace(/\s{2}/," ").replace(/^\s+|\s+$/,
""))}}})}});CKEDITOR.on("dialogDefinition",function(a){var b=a.data.name;if("table"==b||"tableProperties"==b)if(a=a.data.definition,b=a.getContents("info").get("txtBorder"),b.commit=CKEDITOR.tools.override(b.commit,function(a){return function(b,c){a.apply(this,arguments);var e=parseInt(this.getValue(),10);c[!e||0>=e?"addClass":"removeClass"]("cke_show_border")}}),a=(a=a.getContents("advanced"))&&a.get("advCSSClasses"))a.setup=CKEDITOR.tools.override(a.setup,function(a){return function(){a.apply(this,
arguments);this.setValue(this.getValue().replace(/cke_show_border/,""))}}),a.commit=CKEDITOR.tools.override(a.commit,function(a){return function(b,c){a.apply(this,arguments);parseInt(c.getAttribute("border"),10)||c.addClass("cke_show_border")}})})})();(function(){CKEDITOR.plugins.add("sourcearea",{init:function(a){function d(){var a=e&&this.equals(CKEDITOR.document.getActive());this.hide();this.setStyle("height",this.getParent().$.clientHeight+"px");this.setStyle("width",this.getParent().$.clientWidth+"px");this.show();a&&this.focus()}if(a.elementMode!=CKEDITOR.ELEMENT_MODE_INLINE){var f=CKEDITOR.plugins.sourcearea;a.addMode("source",function(e){var b=a.ui.space("contents").getDocument().createElement("textarea");b.setStyles(CKEDITOR.tools.extend({width:CKEDITOR.env.ie7Compat?
"99%":"100%",height:"100%",resize:"none",outline:"none","text-align":"left"},CKEDITOR.tools.cssVendorPrefix("tab-size",a.config.sourceAreaTabSize||4)));b.setAttribute("dir","ltr");b.addClass("cke_source").addClass("cke_reset").addClass("cke_enable_context_menu");a.ui.space("contents").append(b);b=a.editable(new c(a,b));b.setData(a.getData(1));CKEDITOR.env.ie&&(b.attachListener(a,"resize",d,b),b.attachListener(CKEDITOR.document.getWindow(),"resize",d,b),CKEDITOR.tools.setTimeout(d,0,b));a.fire("ariaWidget",
this);e()});a.addCommand("source",f.commands.source);a.ui.addButton&&a.ui.addButton("Source",{label:a.lang.sourcearea.toolbar,command:"source",toolbar:"mode,10"});a.on("mode",function(){a.getCommand("source").setState("source"==a.mode?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF)});var e=CKEDITOR.env.ie&&9==CKEDITOR.env.version}}});var c=CKEDITOR.tools.createClass({base:CKEDITOR.editable,proto:{setData:function(a){this.setValue(a);this.status="ready";this.editor.fire("dataReady")},getData:function(){return this.getValue()},
insertHtml:function(){},insertElement:function(){},insertText:function(){},setReadOnly:function(a){this[(a?"set":"remove")+"Attribute"]("readOnly","readonly")},detach:function(){c.baseProto.detach.call(this);this.clearCustomData();this.remove()}}})})();
CKEDITOR.plugins.sourcearea={commands:{source:{modes:{wysiwyg:1,source:1},editorFocus:!1,readOnly:1,exec:function(c){"wysiwyg"==c.mode&&c.fire("saveSnapshot");c.getCommand("source").setState(CKEDITOR.TRISTATE_DISABLED);c.setMode("source"==c.mode?"wysiwyg":"source")},canUndo:!1}}};CKEDITOR.plugins.add("specialchar",{availableLangs:{af:1,ar:1,az:1,bg:1,ca:1,cs:1,cy:1,da:1,de:1,"de-ch":1,el:1,en:1,"en-au":1,"en-ca":1,"en-gb":1,eo:1,es:1,"es-mx":1,et:1,eu:1,fa:1,fi:1,fr:1,"fr-ca":1,gl:1,he:1,hr:1,hu:1,id:1,it:1,ja:1,km:1,ko:1,ku:1,lt:1,lv:1,nb:1,nl:1,no:1,oc:1,pl:1,pt:1,"pt-br":1,ro:1,ru:1,si:1,sk:1,sl:1,sq:1,sv:1,th:1,tr:1,tt:1,ug:1,uk:1,vi:1,zh:1,"zh-cn":1},requires:"dialog",init:function(a){var c=this;CKEDITOR.dialog.add("specialchar",this.path+"dialogs/specialchar.js");a.addCommand("specialchar",
{exec:function(){var b=a.langCode,b=c.availableLangs[b]?b:c.availableLangs[b.replace(/-.*/,"")]?b.replace(/-.*/,""):"en";CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(c.path+"dialogs/lang/"+b+".js"),function(){CKEDITOR.tools.extend(a.lang.specialchar,c.langEntries[b]);a.openDialog("specialchar")})},modes:{wysiwyg:1},canUndo:!1});a.ui.addButton&&a.ui.addButton("SpecialChar",{label:a.lang.specialchar.toolbar,command:"specialchar",toolbar:"insert,50"})}});CKEDITOR.config.specialChars="! \x26quot; # $ % \x26amp; ' ( ) * + - . / 0 1 2 3 4 5 6 7 8 9 : ; \x26lt; \x3d \x26gt; ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ \x26euro; \x26lsquo; \x26rsquo; \x26ldquo; \x26rdquo; \x26ndash; \x26mdash; \x26iexcl; \x26cent; \x26pound; \x26curren; \x26yen; \x26brvbar; \x26sect; \x26uml; \x26copy; \x26ordf; \x26laquo; \x26not; \x26reg; \x26macr; \x26deg; \x26sup2; \x26sup3; \x26acute; \x26micro; \x26para; \x26middot; \x26cedil; \x26sup1; \x26ordm; \x26raquo; \x26frac14; \x26frac12; \x26frac34; \x26iquest; \x26Agrave; \x26Aacute; \x26Acirc; \x26Atilde; \x26Auml; \x26Aring; \x26AElig; \x26Ccedil; \x26Egrave; \x26Eacute; \x26Ecirc; \x26Euml; \x26Igrave; \x26Iacute; \x26Icirc; \x26Iuml; \x26ETH; \x26Ntilde; \x26Ograve; \x26Oacute; \x26Ocirc; \x26Otilde; \x26Ouml; \x26times; \x26Oslash; \x26Ugrave; \x26Uacute; \x26Ucirc; \x26Uuml; \x26Yacute; \x26THORN; \x26szlig; \x26agrave; \x26aacute; \x26acirc; \x26atilde; \x26auml; \x26aring; \x26aelig; \x26ccedil; \x26egrave; \x26eacute; \x26ecirc; \x26euml; \x26igrave; \x26iacute; \x26icirc; \x26iuml; \x26eth; \x26ntilde; \x26ograve; \x26oacute; \x26ocirc; \x26otilde; \x26ouml; \x26divide; \x26oslash; \x26ugrave; \x26uacute; \x26ucirc; \x26uuml; \x26yacute; \x26thorn; \x26yuml; \x26OElig; \x26oelig; \x26#372; \x26#374 \x26#373 \x26#375; \x26sbquo; \x26#8219; \x26bdquo; \x26hellip; \x26trade; \x26#9658; \x26bull; \x26rarr; \x26rArr; \x26hArr; \x26diams; \x26asymp;".split(" ");CKEDITOR.plugins.add("scayt",{requires:"menubutton,dialog",tabToOpen:null,dialogName:"scaytDialog",onLoad:function(a){CKEDITOR.plugins.scayt.onLoadTimestamp=(new Date).getTime();"moono-lisa"==(CKEDITOR.skinName||a.config.skin)&&CKEDITOR.document.appendStyleSheet(this.path+"skins/"+CKEDITOR.skin.name+"/scayt.css");CKEDITOR.document.appendStyleSheet(this.path+"dialogs/dialog.css")},init:function(a){var c=this,d=CKEDITOR.plugins.scayt;this.bindEvents(a);this.parseConfig(a);this.addRule(a);CKEDITOR.dialog.add(this.dialogName,
CKEDITOR.getUrl(this.path+"dialogs/options.js"));this.addMenuItems(a);var b=a.lang.scayt,e=CKEDITOR.env;a.ui.add("Scayt",CKEDITOR.UI_MENUBUTTON,{label:b.text_title,title:a.plugins.wsc?a.lang.wsc.title:b.text_title,modes:{wysiwyg:!(e.ie&&(8>e.version||e.quirks))},toolbar:"spellchecker,20",refresh:function(){var b=a.ui.instances.Scayt.getState();a.scayt&&(b=d.state.scayt[a.name]?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF);a.fire("scaytButtonState",b)},onRender:function(){var b=this;a.on("scaytButtonState",
function(a){void 0!==typeof a.data&&b.setState(a.data)})},onMenu:function(){var b=a.scayt;a.getMenuItem("scaytToggle").label=a.lang.scayt[b&&d.state.scayt[a.name]?"btn_disable":"btn_enable"];var c={scaytToggle:CKEDITOR.TRISTATE_OFF,scaytOptions:b?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,scaytLangs:b?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,scaytDict:b?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,scaytAbout:b?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,WSC:a.plugins.wsc?CKEDITOR.TRISTATE_OFF:
CKEDITOR.TRISTATE_DISABLED};a.config.scayt_uiTabs[0]||delete c.scaytOptions;a.config.scayt_uiTabs[1]||delete c.scaytLangs;a.config.scayt_uiTabs[2]||delete c.scaytDict;b&&!CKEDITOR.plugins.scayt.isNewUdSupported(b)&&(delete c.scaytDict,a.config.scayt_uiTabs[2]=0,CKEDITOR.plugins.scayt.alarmCompatibilityMessage());return c}});a.contextMenu&&a.addMenuItems&&(a.contextMenu.addListener(function(b,d){var e=a.scayt,l,m;e&&(m=e.getSelectionNode())&&(l=c.menuGenerator(a,m),e.showBanner("."+a.contextMenu._.definition.panel.className.split(" ").join(" .")));
return l}),a.contextMenu._.onHide=CKEDITOR.tools.override(a.contextMenu._.onHide,function(b){return function(){var d=a.scayt;d&&d.hideBanner();return b.apply(this)}}))},addMenuItems:function(a){var c=this,d=CKEDITOR.plugins.scayt;a.addMenuGroup("scaytButton");for(var b=a.config.scayt_contextMenuItemsOrder.split("|"),e=0;e<b.length;e++)b[e]="scayt_"+b[e];if((b=["grayt_description","grayt_suggest","grayt_control"].concat(b))&&b.length)for(e=0;e<b.length;e++)a.addMenuGroup(b[e],e-10);a.addCommand("scaytToggle",
{exec:function(a){var b=a.scayt;d.state.scayt[a.name]=!d.state.scayt[a.name];!0===d.state.scayt[a.name]?b||d.createScayt(a):b&&d.destroy(a)}});a.addCommand("scaytAbout",{exec:function(a){a.scayt.tabToOpen="about";d.openDialog(c.dialogName,a)}});a.addCommand("scaytOptions",{exec:function(a){a.scayt.tabToOpen="options";d.openDialog(c.dialogName,a)}});a.addCommand("scaytLangs",{exec:function(a){a.scayt.tabToOpen="langs";d.openDialog(c.dialogName,a)}});a.addCommand("scaytDict",{exec:function(a){a.scayt.tabToOpen=
"dictionaries";d.openDialog(c.dialogName,a)}});b={scaytToggle:{label:a.lang.scayt.btn_enable,group:"scaytButton",command:"scaytToggle"},scaytAbout:{label:a.lang.scayt.btn_about,group:"scaytButton",command:"scaytAbout"},scaytOptions:{label:a.lang.scayt.btn_options,group:"scaytButton",command:"scaytOptions"},scaytLangs:{label:a.lang.scayt.btn_langs,group:"scaytButton",command:"scaytLangs"},scaytDict:{label:a.lang.scayt.btn_dictionaries,group:"scaytButton",command:"scaytDict"}};a.plugins.wsc&&(b.WSC=
{label:a.lang.wsc.toolbar,group:"scaytButton",onClick:function(){var b=CKEDITOR.plugins.scayt,d=a.scayt,c=a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE?a.container.getText():a.document.getBody().getText();(c=c.replace(/\s/g,""))?(d&&b.state.scayt[a.name]&&d.setMarkupPaused&&d.setMarkupPaused(!0),a.lockSelection(),a.execCommand("checkspell")):alert("Nothing to check!")}});a.addMenuItems(b)},bindEvents:function(a){var c=CKEDITOR.plugins.scayt,d=a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE,b=function(){c.destroy(a)},
e=function(){!c.state.scayt[a.name]||a.readOnly||a.scayt||c.createScayt(a)},f=function(){var b=a.editable();b.attachListener(b,"focus",function(b){CKEDITOR.plugins.scayt&&!a.scayt&&setTimeout(e,0);b=CKEDITOR.plugins.scayt&&CKEDITOR.plugins.scayt.state.scayt[a.name]&&a.scayt;var c,k;if((d||b)&&a._.savedSelection){b=a._.savedSelection.getSelectedElement();b=!b&&a._.savedSelection.getRanges();for(var h=0;h<b.length;h++)k=b[h],"string"===typeof k.startContainer.$.nodeValue&&(c=k.startContainer.getText().length,
(c<k.startOffset||c<k.endOffset)&&a.unlockSelection(!1))}},this,null,-10)},g=function(){d?a.config.scayt_inlineModeImmediateMarkup?e():(a.on("blur",function(){setTimeout(b,0)}),a.on("focus",e),a.focusManager.hasFocus&&e()):e();f();var c=a.editable();c.attachListener(c,"mousedown",function(b){b=b.data.getTarget();var d=a.widgets&&a.widgets.getByElement(b);d&&(d.wrapper=b.getAscendant(function(a){return a.hasAttribute("data-cke-widget-wrapper")},!0))},this,null,-10)};a.on("contentDom",g);a.on("beforeCommandExec",
function(b){var d=a.scayt,e=!1,f=!1,h=!0;b.data.name in c.options.disablingCommandExec&&"wysiwyg"==a.mode?d&&(c.destroy(a),a.fire("scaytButtonState",CKEDITOR.TRISTATE_DISABLED)):"bold"!==b.data.name&&"italic"!==b.data.name&&"underline"!==b.data.name&&"strike"!==b.data.name&&"subscript"!==b.data.name&&"superscript"!==b.data.name&&"enter"!==b.data.name&&"cut"!==b.data.name&&"language"!==b.data.name||!d||("cut"===b.data.name&&(h=!1,f=!0),"language"===b.data.name&&(f=e=!0),a.fire("reloadMarkupScayt",
{removeOptions:{removeInside:h,forceBookmark:f,language:e},timeout:0}))});a.on("beforeSetMode",function(b){if("source"==b.data){if(b=a.scayt)c.destroy(a),a.fire("scaytButtonState",CKEDITOR.TRISTATE_DISABLED);a.document&&a.document.getBody().removeAttribute("_jquid")}});a.on("afterCommandExec",function(b){"wysiwyg"!=a.mode||"undo"!=b.data.name&&"redo"!=b.data.name||setTimeout(function(){c.reloadMarkup(a.scayt)},250)});a.on("readOnly",function(b){var d;b&&(d=a.scayt,!0===b.editor.readOnly?d&&d.fire("removeMarkupInDocument",
{}):d?c.reloadMarkup(d):"wysiwyg"==b.editor.mode&&!0===c.state.scayt[b.editor.name]&&(c.createScayt(a),b.editor.fire("scaytButtonState",CKEDITOR.TRISTATE_ON)))});a.on("beforeDestroy",b);a.on("setData",function(){b();(a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE||a.plugins.divarea)&&g()},this,null,50);a.on("reloadMarkupScayt",function(b){var d=b.data&&b.data.removeOptions,e=b.data&&b.data.timeout,f=b.data&&b.data.language,h=a.scayt;h&&setTimeout(function(){f&&(d.selectionNode=a.plugins.language.getCurrentLangElement(a),
d.selectionNode=d.selectionNode&&d.selectionNode.$||null);h.removeMarkupInSelectionNode(d);c.reloadMarkup(h)},e||0)});a.on("insertElement",function(){a.fire("reloadMarkupScayt",{removeOptions:{forceBookmark:!0}})},this,null,50);a.on("insertHtml",function(){a.scayt&&a.scayt.setFocused&&a.scayt.setFocused(!0);a.fire("reloadMarkupScayt")},this,null,50);a.on("insertText",function(){a.scayt&&a.scayt.setFocused&&a.scayt.setFocused(!0);a.fire("reloadMarkupScayt")},this,null,50);a.on("scaytDialogShown",function(b){b.data.selectPage(a.scayt.tabToOpen)})},
parseConfig:function(a){var c=CKEDITOR.plugins.scayt;c.replaceOldOptionsNames(a.config);"boolean"!==typeof a.config.scayt_autoStartup&&(a.config.scayt_autoStartup=!1);c.state.scayt[a.name]=a.config.scayt_autoStartup;"boolean"!==typeof a.config.grayt_autoStartup&&(a.config.grayt_autoStartup=!1);"boolean"!==typeof a.config.scayt_inlineModeImmediateMarkup&&(a.config.scayt_inlineModeImmediateMarkup=!1);c.state.grayt[a.name]=a.config.grayt_autoStartup;a.config.scayt_contextCommands||(a.config.scayt_contextCommands=
"ignoreall|add");a.config.scayt_contextMenuItemsOrder||(a.config.scayt_contextMenuItemsOrder="suggest|moresuggest|control");a.config.scayt_sLang||(a.config.scayt_sLang="en_US");if(void 0===a.config.scayt_maxSuggestions||"number"!=typeof a.config.scayt_maxSuggestions||0>a.config.scayt_maxSuggestions)a.config.scayt_maxSuggestions=3;if(void 0===a.config.scayt_minWordLength||"number"!=typeof a.config.scayt_minWordLength||1>a.config.scayt_minWordLength)a.config.scayt_minWordLength=3;if(void 0===a.config.scayt_customDictionaryIds||
"string"!==typeof a.config.scayt_customDictionaryIds)a.config.scayt_customDictionaryIds="";if(void 0===a.config.scayt_userDictionaryName||"string"!==typeof a.config.scayt_userDictionaryName)a.config.scayt_userDictionaryName=null;if("string"===typeof a.config.scayt_uiTabs&&3===a.config.scayt_uiTabs.split(",").length){var d=[],b=[];a.config.scayt_uiTabs=a.config.scayt_uiTabs.split(",");CKEDITOR.tools.search(a.config.scayt_uiTabs,function(a){1===Number(a)||0===Number(a)?(b.push(!0),d.push(Number(a))):
b.push(!1)});null===CKEDITOR.tools.search(b,!1)?a.config.scayt_uiTabs=d:a.config.scayt_uiTabs=[1,1,1]}else a.config.scayt_uiTabs=[1,1,1];"string"!=typeof a.config.scayt_serviceProtocol&&(a.config.scayt_serviceProtocol=null);"string"!=typeof a.config.scayt_serviceHost&&(a.config.scayt_serviceHost=null);"string"!=typeof a.config.scayt_servicePort&&(a.config.scayt_servicePort=null);"string"!=typeof a.config.scayt_servicePath&&(a.config.scayt_servicePath=null);a.config.scayt_moreSuggestions||(a.config.scayt_moreSuggestions=
"on");"string"!==typeof a.config.scayt_customerId&&(a.config.scayt_customerId="1:WvF0D4-UtPqN1-43nkD4-NKvUm2-daQqk3-LmNiI-z7Ysb4-mwry24-T8YrS3-Q2tpq2");"string"!==typeof a.config.scayt_customPunctuation&&(a.config.scayt_customPunctuation="-");"string"!==typeof a.config.scayt_srcUrl&&(c=document.location.protocol,c=-1!=c.search(/https?:/)?c:"http:",a.config.scayt_srcUrl=c+"//svc.webspellchecker.net/spellcheck31/wscbundle/wscbundle.js");"boolean"!==typeof CKEDITOR.config.scayt_handleCheckDirty&&(CKEDITOR.config.scayt_handleCheckDirty=
!0);"boolean"!==typeof CKEDITOR.config.scayt_handleUndoRedo&&(CKEDITOR.config.scayt_handleUndoRedo=!0);CKEDITOR.config.scayt_handleUndoRedo=CKEDITOR.plugins.undo?CKEDITOR.config.scayt_handleUndoRedo:!1;"boolean"!==typeof a.config.scayt_multiLanguageMode&&(a.config.scayt_multiLanguageMode=!1);"object"!==typeof a.config.scayt_multiLanguageStyles&&(a.config.scayt_multiLanguageStyles={});a.config.scayt_ignoreAllCapsWords&&"boolean"!==typeof a.config.scayt_ignoreAllCapsWords&&(a.config.scayt_ignoreAllCapsWords=
!1);a.config.scayt_ignoreDomainNames&&"boolean"!==typeof a.config.scayt_ignoreDomainNames&&(a.config.scayt_ignoreDomainNames=!1);a.config.scayt_ignoreWordsWithMixedCases&&"boolean"!==typeof a.config.scayt_ignoreWordsWithMixedCases&&(a.config.scayt_ignoreWordsWithMixedCases=!1);a.config.scayt_ignoreWordsWithNumbers&&"boolean"!==typeof a.config.scayt_ignoreWordsWithNumbers&&(a.config.scayt_ignoreWordsWithNumbers=!1);if(a.config.scayt_disableOptionsStorage){var c=CKEDITOR.tools.isArray(a.config.scayt_disableOptionsStorage)?
a.config.scayt_disableOptionsStorage:"string"===typeof a.config.scayt_disableOptionsStorage?[a.config.scayt_disableOptionsStorage]:void 0,e="all options lang ignore-all-caps-words ignore-domain-names ignore-words-with-mixed-cases ignore-words-with-numbers".split(" "),f=["lang","ignore-all-caps-words","ignore-domain-names","ignore-words-with-mixed-cases","ignore-words-with-numbers"],g=CKEDITOR.tools.search,k=CKEDITOR.tools.indexOf;a.config.scayt_disableOptionsStorage=function(a){for(var b=[],d=0;d<
a.length;d++){var c=a[d],p=!!g(a,"options");if(!g(e,c)||p&&g(f,function(a){if("lang"===a)return!1}))return;g(f,c)&&f.splice(k(f,c),1);if("all"===c||p&&g(a,"lang"))return[];"options"===c&&(f=["lang"])}return b=b.concat(f)}(c)}},addRule:function(a){var c=CKEDITOR.plugins.scayt,d=a.dataProcessor,b=d&&d.htmlFilter,e=a._.elementsPath&&a._.elementsPath.filters,d=d&&d.dataFilter,f=a.addRemoveFormatFilter,g=function(b){if(a.scayt&&(b.hasAttribute(c.options.data_attribute_name)||b.hasAttribute(c.options.problem_grammar_data_attribute)))return!1},
k=function(b){var d=!0;a.scayt&&(b.hasAttribute(c.options.data_attribute_name)||b.hasAttribute(c.options.problem_grammar_data_attribute))&&(d=!1);return d};e&&e.push(g);d&&d.addRules({elements:{span:function(a){var b=a.hasClass(c.options.misspelled_word_class)&&a.attributes[c.options.data_attribute_name],d=a.hasClass(c.options.problem_grammar_class)&&a.attributes[c.options.problem_grammar_data_attribute];c&&(b||d)&&delete a.name;return a}}});b&&b.addRules({elements:{span:function(a){var b=a.hasClass(c.options.misspelled_word_class)&&
a.attributes[c.options.data_attribute_name],d=a.hasClass(c.options.problem_grammar_class)&&a.attributes[c.options.problem_grammar_data_attribute];c&&(b||d)&&delete a.name;return a}}});f&&f.call(a,k)},scaytMenuDefinition:function(a){var c=this,d=CKEDITOR.plugins.scayt;a=a.scayt;return{scayt:{scayt_ignore:{label:a.getLocal("btn_ignore"),group:"scayt_control",order:1,exec:function(a){a.scayt.ignoreWord()}},scayt_ignoreall:{label:a.getLocal("btn_ignoreAll"),group:"scayt_control",order:2,exec:function(a){a.scayt.ignoreAllWords()}},
scayt_add:{label:a.getLocal("btn_addWord"),group:"scayt_control",order:3,exec:function(a){var d=a.scayt;setTimeout(function(){d.addWordToUserDictionary()},10)}},scayt_option:{label:a.getLocal("btn_options"),group:"scayt_control",order:4,exec:function(a){a.scayt.tabToOpen="options";d.openDialog(c.dialogName,a)},verification:function(a){return 1==a.config.scayt_uiTabs[0]?!0:!1}},scayt_language:{label:a.getLocal("btn_langs"),group:"scayt_control",order:5,exec:function(a){a.scayt.tabToOpen="langs";d.openDialog(c.dialogName,
a)},verification:function(a){return 1==a.config.scayt_uiTabs[1]?!0:!1}},scayt_dictionary:{label:a.getLocal("btn_dictionaries"),group:"scayt_control",order:6,exec:function(a){a.scayt.tabToOpen="dictionaries";d.openDialog(c.dialogName,a)},verification:function(a){return 1==a.config.scayt_uiTabs[2]?!0:!1}},scayt_about:{label:a.getLocal("btn_about"),group:"scayt_control",order:7,exec:function(a){a.scayt.tabToOpen="about";d.openDialog(c.dialogName,a)}}},grayt:{grayt_problemdescription:{label:"Grammar problem description",
group:"grayt_description",order:1,state:CKEDITOR.TRISTATE_DISABLED,exec:function(a){}},grayt_ignore:{label:a.getLocal("btn_ignore"),group:"grayt_control",order:2,exec:function(a){a.scayt.ignorePhrase()}},grayt_ignoreall:{label:a.getLocal("btn_ignoreAll"),group:"grayt_control",order:3,exec:function(a){a.scayt.ignoreAllPhrases()}}}}},buildSuggestionMenuItems:function(a,c,d){var b={},e={},f=d?"word":"phrase",g=d?"startGrammarCheck":"startSpellCheck",k=a.scayt;if(0<c.length&&"no_any_suggestions"!==c[0])if(d)for(d=
0;d<c.length;d++){var l="scayt_suggest_"+CKEDITOR.plugins.scayt.suggestions[d].replace(" ","_");a.addCommand(l,this.createCommand(CKEDITOR.plugins.scayt.suggestions[d],f,g));d<a.config.scayt_maxSuggestions?(a.addMenuItem(l,{label:c[d],command:l,group:"scayt_suggest",order:d+1}),b[l]=CKEDITOR.TRISTATE_OFF):(a.addMenuItem(l,{label:c[d],command:l,group:"scayt_moresuggest",order:d+1}),e[l]=CKEDITOR.TRISTATE_OFF,"on"===a.config.scayt_moreSuggestions&&(a.addMenuItem("scayt_moresuggest",{label:k.getLocal("btn_moreSuggestions"),
group:"scayt_moresuggest",order:10,getItems:function(){return e}}),b.scayt_moresuggest=CKEDITOR.TRISTATE_OFF))}else for(d=0;d<c.length;d++)l="grayt_suggest_"+CKEDITOR.plugins.scayt.suggestions[d].replace(" ","_"),a.addCommand(l,this.createCommand(CKEDITOR.plugins.scayt.suggestions[d],f,g)),a.addMenuItem(l,{label:c[d],command:l,group:"grayt_suggest",order:d+1}),b[l]=CKEDITOR.TRISTATE_OFF;else b.no_scayt_suggest=CKEDITOR.TRISTATE_DISABLED,a.addCommand("no_scayt_suggest",{exec:function(){}}),a.addMenuItem("no_scayt_suggest",
{label:k.getLocal("btn_noSuggestions")||"no_scayt_suggest",command:"no_scayt_suggest",group:"scayt_suggest",order:0});return b},menuGenerator:function(a,c){var d=a.scayt,b=this.scaytMenuDefinition(a),e={},f=a.config.scayt_contextCommands.split("|"),g=c.getAttribute(d.getLangAttribute())||d.getLang(),k,l,m,n;l=d.isScaytNode(c);m=d.isGraytNode(c);l?(b=b.scayt,k=c.getAttribute(d.getScaytNodeAttributeName()),d.fire("getSuggestionsList",{lang:g,word:k}),e=this.buildSuggestionMenuItems(a,CKEDITOR.plugins.scayt.suggestions,
l)):m&&(b=b.grayt,e=c.getAttribute(d.getGraytNodeAttributeName()),d.getGraytNodeRuleAttributeName?(k=c.getAttribute(d.getGraytNodeRuleAttributeName()),d.getProblemDescriptionText(e,k,g)):d.getProblemDescriptionText(e,g),n=d.getProblemDescriptionText(e,k,g),b.grayt_problemdescription&&n&&(n=n.replace(/([.!?])\s/g,"$1\x3cbr\x3e"),b.grayt_problemdescription.label=n),d.fire("getGrammarSuggestionsList",{lang:g,phrase:e,rule:k}),e=this.buildSuggestionMenuItems(a,CKEDITOR.plugins.scayt.suggestions,l));if(l&&
"off"==a.config.scayt_contextCommands)return e;for(var h in b)l&&-1==CKEDITOR.tools.indexOf(f,h.replace("scayt_",""))&&"all"!=a.config.scayt_contextCommands||m&&"grayt_problemdescription"!==h&&-1==CKEDITOR.tools.indexOf(f,h.replace("grayt_",""))&&"all"!=a.config.scayt_contextCommands||(e[h]="undefined"!=typeof b[h].state?b[h].state:CKEDITOR.TRISTATE_OFF,"function"!==typeof b[h].verification||b[h].verification(a)||delete e[h],a.addCommand(h,{exec:b[h].exec}),a.addMenuItem(h,{label:a.lang.scayt[b[h].label]||
b[h].label,command:h,group:b[h].group,order:b[h].order}));return e},createCommand:function(a,c,d){return{exec:function(b){b=b.scayt;var e={};e[c]=a;b.replaceSelectionNode(e);"startGrammarCheck"===d&&b.removeMarkupInSelectionNode({grammarOnly:!0});b.fire(d)}}}});
CKEDITOR.plugins.scayt={charsToObserve:[{charName:"cke-fillingChar",charCode:function(){var a=CKEDITOR.version.match(/^\d(\.\d*)*/),a=a&&a[0],c;if(a){c="4.5.7";var d,a=a.replace(/\./g,"");c=c.replace(/\./g,"");d=a.length-c.length;d=0<=d?d:0;c=parseInt(a)>=parseInt(c)*Math.pow(10,d)}return c?Array(7).join(String.fromCharCode(8203)):String.fromCharCode(8203)}()}],onLoadTimestamp:"",state:{scayt:{},grayt:{}},warningCounter:0,suggestions:[],options:{disablingCommandExec:{source:!0,newpage:!0,templates:!0},
data_attribute_name:"data-scayt-word",misspelled_word_class:"scayt-misspell-word",problem_grammar_data_attribute:"data-grayt-phrase",problem_grammar_class:"gramm-problem"},backCompatibilityMap:{scayt_service_protocol:"scayt_serviceProtocol",scayt_service_host:"scayt_serviceHost",scayt_service_port:"scayt_servicePort",scayt_service_path:"scayt_servicePath",scayt_customerid:"scayt_customerId"},openDialog:function(a,c){var d=c.scayt;d.isAllModulesReady&&!1===d.isAllModulesReady()||(c.lockSelection(),
c.openDialog(a))},alarmCompatibilityMessage:function(){5>this.warningCounter&&(console.warn("You are using the latest version of SCAYT plugin for CKEditor with the old application version. In order to have access to the newest features, it is recommended to upgrade the application version to latest one as well. Contact us for more details at support@webspellchecker.net."),this.warningCounter+=1)},isNewUdSupported:function(a){return a.getUserDictionary?!0:!1},reloadMarkup:function(a){var c;a&&(c=a.getScaytLangList(),
a.reloadMarkup?a.reloadMarkup():(this.alarmCompatibilityMessage(),c&&c.ltr&&c.rtl&&a.fire("startSpellCheck, startGrammarCheck")))},replaceOldOptionsNames:function(a){for(var c in a)c in this.backCompatibilityMap&&(a[this.backCompatibilityMap[c]]=a[c],delete a[c])},createScayt:function(a){var c=this,d=CKEDITOR.plugins.scayt;this.loadScaytLibrary(a,function(a){function e(a){return new SCAYT.CKSCAYT(a,function(){},function(){})}var f;a.window&&(f="BODY"==a.editable().$.nodeName?a.window.getFrame():a.editable());
if(f){f={lang:a.config.scayt_sLang,container:f.$,customDictionary:a.config.scayt_customDictionaryIds,userDictionaryName:a.config.scayt_userDictionaryName,localization:a.langCode,customer_id:a.config.scayt_customerId,customPunctuation:a.config.scayt_customPunctuation,debug:a.config.scayt_debug,data_attribute_name:c.options.data_attribute_name,misspelled_word_class:c.options.misspelled_word_class,problem_grammar_data_attribute:c.options.problem_grammar_data_attribute,problem_grammar_class:c.options.problem_grammar_class,
"options-to-restore":a.config.scayt_disableOptionsStorage,focused:a.editable().hasFocus,ignoreElementsRegex:a.config.scayt_elementsToIgnore,ignoreGraytElementsRegex:a.config.grayt_elementsToIgnore,minWordLength:a.config.scayt_minWordLength,multiLanguageMode:a.config.scayt_multiLanguageMode,multiLanguageStyles:a.config.scayt_multiLanguageStyles,graytAutoStartup:a.config.grayt_autoStartup,charsToObserve:d.charsToObserve};a.config.scayt_serviceProtocol&&(f.service_protocol=a.config.scayt_serviceProtocol);
a.config.scayt_serviceHost&&(f.service_host=a.config.scayt_serviceHost);a.config.scayt_servicePort&&(f.service_port=a.config.scayt_servicePort);a.config.scayt_servicePath&&(f.service_path=a.config.scayt_servicePath);"boolean"===typeof a.config.scayt_ignoreAllCapsWords&&(f["ignore-all-caps-words"]=a.config.scayt_ignoreAllCapsWords);"boolean"===typeof a.config.scayt_ignoreDomainNames&&(f["ignore-domain-names"]=a.config.scayt_ignoreDomainNames);"boolean"===typeof a.config.scayt_ignoreWordsWithMixedCases&&
(f["ignore-words-with-mixed-cases"]=a.config.scayt_ignoreWordsWithMixedCases);"boolean"===typeof a.config.scayt_ignoreWordsWithNumbers&&(f["ignore-words-with-numbers"]=a.config.scayt_ignoreWordsWithNumbers);var g;try{g=e(f)}catch(k){c.alarmCompatibilityMessage(),delete f.charsToObserve,g=e(f)}g.subscribe("suggestionListSend",function(a){for(var b={},d=[],c=0;c<a.suggestionList.length;c++)b["word_"+a.suggestionList[c]]||(b["word_"+a.suggestionList[c]]=a.suggestionList[c],d.push(a.suggestionList[c]));
CKEDITOR.plugins.scayt.suggestions=d});g.subscribe("selectionIsChanged",function(d){a.getSelection().isLocked&&"restoreSelection"!==d.action&&a.lockSelection();"restoreSelection"===d.action&&a.selectionChange(!0)});g.subscribe("graytStateChanged",function(c){d.state.grayt[a.name]=c.state});g.addMarkupHandler&&g.addMarkupHandler(function(d){var c=a.editable(),e=c.getCustomData(d.charName);e&&(e.$=d.node,c.setCustomData(d.charName,e))});a.scayt=g;a.fire("scaytButtonState",a.readOnly?CKEDITOR.TRISTATE_DISABLED:
CKEDITOR.TRISTATE_ON)}else d.state.scayt[a.name]=!1})},destroy:function(a){a.scayt&&a.scayt.destroy();delete a.scayt;a.fire("scaytButtonState",CKEDITOR.TRISTATE_OFF)},loadScaytLibrary:function(a,c){var d,b=function(){CKEDITOR.fireOnce("scaytReady");a.scayt||"function"===typeof c&&c(a)};"undefined"===typeof window.SCAYT||"function"!==typeof window.SCAYT.CKSCAYT?(d=a.config.scayt_srcUrl+"?"+this.onLoadTimestamp,CKEDITOR.scriptLoader.load(d,function(a){a&&b()})):window.SCAYT&&"function"===typeof window.SCAYT.CKSCAYT&&
b()}};
CKEDITOR.on("dialogDefinition",function(a){var c=a.data.name;a=a.data.definition.dialog;"scaytDialog"!==c&&"checkspell"!==c&&(a.on("show",function(a){a=a.sender&&a.sender.getParentEditor();var b=CKEDITOR.plugins.scayt,c=a.scayt;c&&b.state.scayt[a.name]&&c.setMarkupPaused&&c.setMarkupPaused(!0)}),a.on("hide",function(a){a=a.sender&&a.sender.getParentEditor();var b=CKEDITOR.plugins.scayt,c=a.scayt;c&&b.state.scayt[a.name]&&c.setMarkupPaused&&c.setMarkupPaused(!1)}));if("scaytDialog"===c)a.on("cancel",function(a){return!1},
this,null,-1);if("checkspell"===c)a.on("cancel",function(a){a=a.sender&&a.sender.getParentEditor();var b=CKEDITOR.plugins.scayt,c=a.scayt;c&&b.state.scayt[a.name]&&c.setMarkupPaused&&c.setMarkupPaused(!1);a.unlockSelection()},this,null,-2);if("link"===c)a.on("ok",function(a){var b=a.sender&&a.sender.getParentEditor();b&&setTimeout(function(){b.fire("reloadMarkupScayt",{removeOptions:{removeInside:!0,forceBookmark:!0},timeout:0})},0)});if("replace"===c)a.on("hide",function(a){a=a.sender&&a.sender.getParentEditor();
var b=CKEDITOR.plugins.scayt,c=a.scayt;a&&setTimeout(function(){c&&(c.fire("removeMarkupInDocument",{}),b.reloadMarkup(c))},0)})});
CKEDITOR.on("scaytReady",function(){if(!0===CKEDITOR.config.scayt_handleCheckDirty){var a=CKEDITOR.editor.prototype;a.checkDirty=CKEDITOR.tools.override(a.checkDirty,function(a){return function(){var b=null,c=this.scayt;if(CKEDITOR.plugins.scayt&&CKEDITOR.plugins.scayt.state.scayt[this.name]&&this.scayt){if(b="ready"==this.status)var f=c.removeMarkupFromString(this.getSnapshot()),c=c.removeMarkupFromString(this._.previousValue),b=b&&c!==f}else b=a.call(this);return b}});a.resetDirty=CKEDITOR.tools.override(a.resetDirty,
function(a){return function(){var b=this.scayt;CKEDITOR.plugins.scayt&&CKEDITOR.plugins.scayt.state.scayt[this.name]&&this.scayt?this._.previousValue=b.removeMarkupFromString(this.getSnapshot()):a.call(this)}})}if(!0===CKEDITOR.config.scayt_handleUndoRedo){var a=CKEDITOR.plugins.undo.Image.prototype,c="function"==typeof a.equalsContent?"equalsContent":"equals";a[c]=CKEDITOR.tools.override(a[c],function(a){return function(b){var c=b.editor.scayt,f=this.contents,g=b.contents,k=null;CKEDITOR.plugins.scayt&&
CKEDITOR.plugins.scayt.state.scayt[b.editor.name]&&b.editor.scayt&&(this.contents=c.removeMarkupFromString(f)||"",b.contents=c.removeMarkupFromString(g)||"");k=a.apply(this,arguments);this.contents=f;b.contents=g;return k}})}});(function(){CKEDITOR.plugins.add("stylescombo",{requires:"richcombo",init:function(c){var l=c.config,g=c.lang.stylescombo,f={},k=[],m=[];c.on("stylesSet",function(a){if(a=a.data.styles){for(var b,h,d,e=0,n=a.length;e<n;e++)(b=a[e],c.blockless&&b.element in CKEDITOR.dtd.$block||"string"==typeof b.type&&!CKEDITOR.style.customHandlers[b.type]||(h=b.name,b=new CKEDITOR.style(b),c.filter.customConfig&&!c.filter.check(b)))||(b._name=h,b._.enterMode=l.enterMode,b._.type=d=b.assignedTo||b.type,b._.weight=
e+1E3*(d==CKEDITOR.STYLE_OBJECT?1:d==CKEDITOR.STYLE_BLOCK?2:3),f[h]=b,k.push(b),m.push(b));k.sort(function(a,b){return a._.weight-b._.weight})}});c.ui.addRichCombo("Styles",{label:g.label,title:g.panelTitle,toolbar:"styles,10",allowedContent:m,panel:{css:[CKEDITOR.skin.getPath("editor")].concat(l.contentsCss),multiSelect:!0,attributes:{"aria-label":g.panelTitle}},init:function(){var a,b,c,d,e,f;e=0;for(f=k.length;e<f;e++)a=k[e],b=a._name,d=a._.type,d!=c&&(this.startGroup(g["panelTitle"+String(d)]),
c=d),this.add(b,a.type==CKEDITOR.STYLE_OBJECT?b:a.buildPreview(),b);this.commit()},onClick:function(a){c.focus();c.fire("saveSnapshot");a=f[a];var b=c.elementPath();if(a.group&&a.removeStylesFromSameGroup(c))c.applyStyle(a);else c[a.checkActive(b,c)?"removeStyle":"applyStyle"](a);c.fire("saveSnapshot")},onRender:function(){c.on("selectionChange",function(a){var b=this.getValue();a=a.data.path.elements;for(var h=0,d=a.length,e;h<d;h++){e=a[h];for(var g in f)if(f[g].checkElementRemovable(e,!0,c)){g!=
b&&this.setValue(g);return}}this.setValue("")},this)},onOpen:function(){var a=c.getSelection(),a=a.getSelectedElement()||a.getStartElement()||c.editable(),a=c.elementPath(a),b=[0,0,0,0];this.showAll();this.unmarkAll();for(var h in f){var d=f[h],e=d._.type;d.checkApplicable(a,c,c.activeFilter)?b[e]++:this.hideItem(h);d.checkActive(a,c)&&this.mark(h)}b[CKEDITOR.STYLE_BLOCK]||this.hideGroup(g["panelTitle"+String(CKEDITOR.STYLE_BLOCK)]);b[CKEDITOR.STYLE_INLINE]||this.hideGroup(g["panelTitle"+String(CKEDITOR.STYLE_INLINE)]);
b[CKEDITOR.STYLE_OBJECT]||this.hideGroup(g["panelTitle"+String(CKEDITOR.STYLE_OBJECT)])},refresh:function(){var a=c.elementPath();if(a){for(var b in f)if(f[b].checkApplicable(a,c,c.activeFilter))return;this.setState(CKEDITOR.TRISTATE_DISABLED)}},reset:function(){f={};k=[]}})}})})();(function(){function k(c){return{editorFocus:!1,canUndo:!1,modes:{wysiwyg:1},exec:function(d){if(d.editable().hasFocus){var e=d.getSelection(),b;if(b=(new CKEDITOR.dom.elementPath(e.getCommonAncestor(),e.root)).contains({td:1,th:1},1)){var e=d.createRange(),a=CKEDITOR.tools.tryThese(function(){var a=b.getParent().$.cells[b.$.cellIndex+(c?-1:1)];a.parentNode.parentNode;return a},function(){var a=b.getParent(),a=a.getAscendant("table").$.rows[a.$.rowIndex+(c?-1:1)];return a.cells[c?a.cells.length-1:
0]});if(a||c)if(a)a=new CKEDITOR.dom.element(a),e.moveToElementEditStart(a),e.checkStartOfBlock()&&e.checkEndOfBlock()||e.selectNodeContents(a);else return!0;else{for(var f=b.getAscendant("table").$,a=b.getParent().$.cells,f=new CKEDITOR.dom.element(f.insertRow(-1),d.document),g=0,h=a.length;g<h;g++)f.append((new CKEDITOR.dom.element(a[g],d.document)).clone(!1,!1)).appendBogus();e.moveToElementEditStart(f)}e.select(!0);return!0}}return!1}}}var h={editorFocus:!1,modes:{wysiwyg:1,source:1}},g={exec:function(c){c.container.focusNext(!0,
c.tabIndex)}},f={exec:function(c){c.container.focusPrevious(!0,c.tabIndex)}};CKEDITOR.plugins.add("tab",{init:function(c){for(var d=!1!==c.config.enableTabKeyTools,e=c.config.tabSpaces||0,b="";e--;)b+=" ";if(b)c.on("key",function(a){9==a.data.keyCode&&(c.insertText(b),a.cancel())});if(d)c.on("key",function(a){(9==a.data.keyCode&&c.execCommand("selectNextCell")||a.data.keyCode==CKEDITOR.SHIFT+9&&c.execCommand("selectPreviousCell"))&&a.cancel()});c.addCommand("blur",CKEDITOR.tools.extend(g,h));c.addCommand("blurBack",
CKEDITOR.tools.extend(f,h));c.addCommand("selectNextCell",k());c.addCommand("selectPreviousCell",k(!0))}})})();
CKEDITOR.dom.element.prototype.focusNext=function(k,h){var g=void 0===h?this.getTabIndex():h,f,c,d,e,b,a;if(0>=g)for(b=this.getNextSourceNode(k,CKEDITOR.NODE_ELEMENT);b;){if(b.isVisible()&&0===b.getTabIndex()){d=b;break}b=b.getNextSourceNode(!1,CKEDITOR.NODE_ELEMENT)}else for(b=this.getDocument().getBody().getFirst();b=b.getNextSourceNode(!1,CKEDITOR.NODE_ELEMENT);){if(!f)if(!c&&b.equals(this)){if(c=!0,k){if(!(b=b.getNextSourceNode(!0,CKEDITOR.NODE_ELEMENT)))break;f=1}}else c&&!this.contains(b)&&
(f=1);if(b.isVisible()&&!(0>(a=b.getTabIndex()))){if(f&&a==g){d=b;break}a>g&&(!d||!e||a<e)?(d=b,e=a):d||0!==a||(d=b,e=a)}}d&&d.focus()};
CKEDITOR.dom.element.prototype.focusPrevious=function(k,h){for(var g=void 0===h?this.getTabIndex():h,f,c,d,e=0,b,a=this.getDocument().getBody().getLast();a=a.getPreviousSourceNode(!1,CKEDITOR.NODE_ELEMENT);){if(!f)if(!c&&a.equals(this)){if(c=!0,k){if(!(a=a.getPreviousSourceNode(!0,CKEDITOR.NODE_ELEMENT)))break;f=1}}else c&&!this.contains(a)&&(f=1);if(a.isVisible()&&!(0>(b=a.getTabIndex())))if(0>=g){if(f&&0===b){d=a;break}b>e&&(d=a,e=b)}else{if(f&&b==g){d=a;break}b<g&&(!d||b>e)&&(d=a,e=b)}}d&&d.focus()};CKEDITOR.plugins.add("table",{requires:"dialog",init:function(a){function f(c){return CKEDITOR.tools.extend(c||{},{contextSensitive:1,refresh:function(c,b){this.setState(b.contains("table",1)?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED)}})}if(!a.blockless){var e=a.lang.table;a.addCommand("table",new CKEDITOR.dialogCommand("table",{context:"table",allowedContent:"table{width,height}[align,border,cellpadding,cellspacing,summary];caption tbody thead tfoot;th td tr[scope];"+(a.plugins.dialogadvtab?
"table"+a.plugins.dialogadvtab.allowedContent():""),requiredContent:"table",contentTransformations:[["table{width}: sizeToStyle","table[width]: sizeToAttribute"],["td: splitBorderShorthand"],[{element:"table",right:function(c){if(c.styles){var a;if(c.styles.border)a=CKEDITOR.tools.style.parse.border(c.styles.border);else if(CKEDITOR.env.ie&&8===CKEDITOR.env.version){var b=c.styles;b["border-left"]&&b["border-left"]===b["border-right"]&&b["border-right"]===b["border-top"]&&b["border-top"]===b["border-bottom"]&&
(a=CKEDITOR.tools.style.parse.border(b["border-top"]))}a&&a.style&&"solid"===a.style&&a.width&&0!==parseFloat(a.width)&&(c.attributes.border=1);"collapse"==c.styles["border-collapse"]&&(c.attributes.cellspacing=0)}}}]]}));a.addCommand("tableProperties",new CKEDITOR.dialogCommand("tableProperties",f()));a.addCommand("tableDelete",f({exec:function(a){var d=a.elementPath().contains("table",1);if(d){var b=d.getParent(),e=a.editable();1!=b.getChildCount()||b.is("td","th")||b.equals(e)||(d=b);a=a.createRange();
a.moveToPosition(d,CKEDITOR.POSITION_BEFORE_START);d.remove();a.select()}}}));a.ui.addButton&&a.ui.addButton("Table",{label:e.toolbar,command:"table",toolbar:"insert,30"});CKEDITOR.dialog.add("table",this.path+"dialogs/table.js");CKEDITOR.dialog.add("tableProperties",this.path+"dialogs/table.js");a.addMenuItems&&a.addMenuItems({table:{label:e.menu,command:"tableProperties",group:"table",order:5},tabledelete:{label:e.deleteTable,command:"tableDelete",group:"table",order:1}});a.on("doubleclick",function(a){a.data.element.is("table")&&
(a.data.dialog="tableProperties")});a.contextMenu&&a.contextMenu.addListener(function(){return{tabledelete:CKEDITOR.TRISTATE_OFF,table:CKEDITOR.TRISTATE_OFF}})}}});(function(){function q(d,f){function b(a){return f?f.contains(a)&&a.getAscendant("table",!0).equals(f):!0}function c(b){0<e.length||b.type!=CKEDITOR.NODE_ELEMENT||!F.test(b.getName())||b.getCustomData("selected_cell")||(CKEDITOR.dom.element.setMarker(a,b,"selected_cell",!0),e.push(b))}var e=[],a={};if(!d)return e;for(var g=d.getRanges(),k=0;k<g.length;k++){var h=g[k];if(h.collapsed)(h=h.getCommonAncestor().getAscendant({td:1,th:1},!0))&&b(h)&&e.push(h);else{var h=new CKEDITOR.dom.walker(h),l;for(h.guard=
c;l=h.next();)l.type==CKEDITOR.NODE_ELEMENT&&l.is(CKEDITOR.dtd.table)||(l=l.getAscendant({td:1,th:1},!0))&&!l.getCustomData("selected_cell")&&b(l)&&(CKEDITOR.dom.element.setMarker(a,l,"selected_cell",!0),e.push(l))}}CKEDITOR.dom.element.clearAllMarkers(a);return e}function r(d,f){for(var b=D(d)?d:q(d),c=b[0],e=c.getAscendant("table"),c=c.getDocument(),a=b[0].getParent(),g=a.$.rowIndex,b=b[b.length-1],k=b.getParent().$.rowIndex+b.$.rowSpan-1,b=new CKEDITOR.dom.element(e.$.rows[k]),g=f?g:k,a=f?a:b,
b=CKEDITOR.tools.buildTableMap(e),e=b[g],g=f?b[g-1]:b[g+1],b=b[0].length,c=c.createElement("tr"),k=0;e[k]&&k<b;k++){var h;1<e[k].rowSpan&&g&&e[k]==g[k]?(h=e[k],h.rowSpan+=1):(h=(new CKEDITOR.dom.element(e[k])).clone(),h.removeAttribute("rowSpan"),h.appendBogus(),c.append(h),h=h.$);k+=h.colSpan-1}f?c.insertBefore(a):c.insertAfter(a);return c}function B(d){if(d instanceof CKEDITOR.dom.selection){var f=d.getRanges(),b=q(d),c=b[0].getAscendant("table"),e=CKEDITOR.tools.buildTableMap(c),a=b[0].getParent().$.rowIndex,
b=b[b.length-1],g=b.getParent().$.rowIndex+b.$.rowSpan-1,b=[];d.reset();for(d=a;d<=g;d++){for(var k=e[d],h=new CKEDITOR.dom.element(c.$.rows[d]),l=0;l<k.length;l++){var m=new CKEDITOR.dom.element(k[l]),n=m.getParent().$.rowIndex;1==m.$.rowSpan?m.remove():(--m.$.rowSpan,n==d&&(n=e[d+1],n[l-1]?m.insertAfter(new CKEDITOR.dom.element(n[l-1])):(new CKEDITOR.dom.element(c.$.rows[d+1])).append(m,1)));l+=m.$.colSpan-1}b.push(h)}e=c.$.rows;f[0].moveToPosition(c,CKEDITOR.POSITION_BEFORE_START);a=new CKEDITOR.dom.element(e[g+
1]||(0<a?e[a-1]:null)||c.$.parentNode);for(d=b.length;0<=d;d--)B(b[d]);return c.$.parentNode?a:(f[0].select(),null)}d instanceof CKEDITOR.dom.element&&(c=d.getAscendant("table"),1==c.$.rows.length?c.remove():d.remove());return null}function v(d){for(var f=d.getParent().$.cells,b=0,c=0;c<f.length;c++){var e=f[c],b=b+e.colSpan;if(e==d.$)break}return b-1}function w(d,f){for(var b=f?Infinity:0,c=0;c<d.length;c++){var e=v(d[c]);if(f?e<b:e>b)b=e}return b}function u(d,f){for(var b=D(d)?d:q(d),c=b[0].getAscendant("table"),
e=w(b,1),b=w(b),a=f?e:b,g=CKEDITOR.tools.buildTableMap(c),c=[],e=[],b=[],k=g.length,h=0;h<k;h++)c.push(g[h][a]),e.push(f?g[h][a-1]:g[h][a+1]);for(h=0;h<k;h++)c[h]&&(1<c[h].colSpan&&e[h]==c[h]?(g=c[h],g.colSpan+=1):(a=new CKEDITOR.dom.element(c[h]),g=a.clone(),g.removeAttribute("colSpan"),g.appendBogus(),g[f?"insertBefore":"insertAfter"].call(g,a),b.push(g),g=g.$),h+=g.rowSpan-1);return b}function y(d){function f(a){var b,c,d;b=a.getRanges();if(1!==b.length)return a;b=b[0];if(b.collapsed||0!==b.endOffset)return a;
c=b.endContainer;d=c.getName().toLowerCase();if("td"!==d&&"th"!==d)return a;for((d=c.getPrevious())||(d=c.getParent().getPrevious().getLast());d.type!==CKEDITOR.NODE_TEXT&&"br"!==d.getName().toLowerCase();)if(d=d.getLast(),!d)return a;b.setEndAt(d,CKEDITOR.POSITION_BEFORE_END);return b.select()}CKEDITOR.env.webkit&&!d.isFake&&(d=f(d));var b=d.getRanges(),c=q(d),e=c[0],a=c[c.length-1],c=e.getAscendant("table"),g=CKEDITOR.tools.buildTableMap(c),k,h,l=[];d.reset();var m=0;for(d=g.length;m<d;m++)for(var n=
0,p=g[m].length;n<p;n++)void 0===k&&g[m][n]==e.$&&(k=n),g[m][n]==a.$&&(h=n);for(m=k;m<=h;m++)for(n=0;n<g.length;n++)a=g[n],e=new CKEDITOR.dom.element(c.$.rows[n]),a=new CKEDITOR.dom.element(a[m]),a.$&&(1==a.$.colSpan?a.remove():--a.$.colSpan,n+=a.$.rowSpan-1,e.$.cells.length||l.push(e));k=g[0].length-1>h?new CKEDITOR.dom.element(g[0][h+1]):k&&-1!==g[0][k-1].cellIndex?new CKEDITOR.dom.element(g[0][k-1]):new CKEDITOR.dom.element(c.$.parentNode);l.length==d&&(b[0].moveToPosition(c,CKEDITOR.POSITION_AFTER_END),
b[0].select(),c.remove());return k}function t(d,f){var b=d.getStartElement().getAscendant({td:1,th:1},!0);if(b){var c=b.clone();c.appendBogus();f?c.insertBefore(b):c.insertAfter(b)}}function z(d){if(d instanceof CKEDITOR.dom.selection){var f=d.getRanges(),b=q(d),c=b[0]&&b[0].getAscendant("table"),e;a:{var a=0;e=b.length-1;for(var g={},k,h;k=b[a++];)CKEDITOR.dom.element.setMarker(g,k,"delete_cell",!0);for(a=0;k=b[a++];)if((h=k.getPrevious())&&!h.getCustomData("delete_cell")||(h=k.getNext())&&!h.getCustomData("delete_cell")){CKEDITOR.dom.element.clearAllMarkers(g);
e=h;break a}CKEDITOR.dom.element.clearAllMarkers(g);a=b[0].getParent();(a=a.getPrevious())?e=a.getLast():(a=b[e].getParent(),e=(a=a.getNext())?a.getChild(0):null)}d.reset();for(d=b.length-1;0<=d;d--)z(b[d]);e?p(e,!0):c&&(f[0].moveToPosition(c,CKEDITOR.POSITION_BEFORE_START),f[0].select(),c.remove())}else d instanceof CKEDITOR.dom.element&&(f=d.getParent(),1==f.getChildCount()?f.remove():d.remove())}function p(d,f){var b=d.getDocument(),c=CKEDITOR.document;CKEDITOR.env.ie&&10==CKEDITOR.env.version&&
(c.focus(),b.focus());b=new CKEDITOR.dom.range(b);b["moveToElementEdit"+(f?"End":"Start")](d)||(b.selectNodeContents(d),b.collapse(f?!1:!0));b.select(!0)}function A(d,f,b){d=d[f];if("undefined"==typeof b)return d;for(f=0;d&&f<d.length;f++){if(b.is&&d[f]==b.$)return f;if(f==b)return new CKEDITOR.dom.element(d[f])}return b.is?-1:null}function x(d,f,b){var c=q(d),e;if((f?1!=c.length:2>c.length)||(e=d.getCommonAncestor())&&e.type==CKEDITOR.NODE_ELEMENT&&e.is("table"))return!1;var a;d=c[0];e=d.getAscendant("table");
var g=CKEDITOR.tools.buildTableMap(e),k=g.length,h=g[0].length,l=d.getParent().$.rowIndex,m=A(g,l,d);if(f){var n;try{var p=parseInt(d.getAttribute("rowspan"),10)||1;a=parseInt(d.getAttribute("colspan"),10)||1;n=g["up"==f?l-p:"down"==f?l+p:l]["left"==f?m-a:"right"==f?m+a:m]}catch(x){return!1}if(!n||d.$==n)return!1;c["up"==f||"left"==f?"unshift":"push"](new CKEDITOR.dom.element(n))}f=d.getDocument();var r=l,p=n=0,u=!b&&new CKEDITOR.dom.documentFragment(f),w=0;for(f=0;f<c.length;f++){a=c[f];var t=a.getParent(),
y=a.getFirst(),v=a.$.colSpan,z=a.$.rowSpan,t=t.$.rowIndex,B=A(g,t,a),w=w+v*z,p=Math.max(p,B-m+v);n=Math.max(n,t-l+z);b||(v=a,(z=v.getBogus())&&z.remove(),v.trim(),a.getChildren().count()&&(t==r||!y||y.isBlockBoundary&&y.isBlockBoundary({br:1})||(r=u.getLast(CKEDITOR.dom.walker.whitespaces(!0)),!r||r.is&&r.is("br")||u.append("br")),a.moveChildren(u)),f?a.remove():a.setHtml(""));r=t}if(b)return n*p==w;u.moveChildren(d);d.appendBogus();p>=h?d.removeAttribute("rowSpan"):d.$.rowSpan=n;n>=k?d.removeAttribute("colSpan"):
d.$.colSpan=p;b=new CKEDITOR.dom.nodeList(e.$.rows);c=b.count();for(f=c-1;0<=f;f--)e=b.getItem(f),e.$.cells.length||(e.remove(),c++);return d}function C(d,f){var b=q(d);if(1<b.length)return!1;if(f)return!0;var b=b[0],c=b.getParent(),e=c.getAscendant("table"),a=CKEDITOR.tools.buildTableMap(e),g=c.$.rowIndex,k=A(a,g,b),h=b.$.rowSpan,l;if(1<h){l=Math.ceil(h/2);for(var h=Math.floor(h/2),c=g+l,e=new CKEDITOR.dom.element(e.$.rows[c]),a=A(a,c),m,c=b.clone(),g=0;g<a.length;g++)if(m=a[g],m.parentNode==e.$&&
g>k){c.insertBefore(new CKEDITOR.dom.element(m));break}else m=null;m||e.append(c)}else for(h=l=1,e=c.clone(),e.insertAfter(c),e.append(c=b.clone()),m=A(a,g),k=0;k<m.length;k++)m[k].rowSpan++;c.appendBogus();b.$.rowSpan=l;c.$.rowSpan=h;1==l&&b.removeAttribute("rowSpan");1==h&&c.removeAttribute("rowSpan");return c}function E(d,f){var b=q(d);if(1<b.length)return!1;if(f)return!0;var b=b[0],c=b.getParent(),e=c.getAscendant("table"),e=CKEDITOR.tools.buildTableMap(e),a=A(e,c.$.rowIndex,b),g=b.$.colSpan;
if(1<g)c=Math.ceil(g/2),g=Math.floor(g/2);else{for(var g=c=1,k=[],h=0;h<e.length;h++){var l=e[h];k.push(l[a]);1<l[a].rowSpan&&(h+=l[a].rowSpan-1)}for(e=0;e<k.length;e++)k[e].colSpan++}e=b.clone();e.insertAfter(b);e.appendBogus();b.$.colSpan=c;e.$.colSpan=g;1==c&&b.removeAttribute("colSpan");1==g&&e.removeAttribute("colSpan");return e}var F=/^(?:td|th)$/,D=CKEDITOR.tools.isArray;CKEDITOR.plugins.tabletools={requires:"table,dialog,contextmenu",init:function(d){function f(a){return CKEDITOR.tools.extend(a||
{},{contextSensitive:1,refresh:function(a,b){this.setState(b.contains({td:1,th:1},1)?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED)}})}function b(a,b){var c=d.addCommand(a,b);d.addFeature(c)}var c=d.lang.table,e=CKEDITOR.tools.style.parse;b("cellProperties",new CKEDITOR.dialogCommand("cellProperties",f({allowedContent:"td th{width,height,border-color,background-color,white-space,vertical-align,text-align}[colspan,rowspan]",requiredContent:"table",contentTransformations:[[{element:"td",left:function(a){return a.styles.background&&
e.background(a.styles.background).color},right:function(a){a.styles["background-color"]=e.background(a.styles.background).color}},{element:"td",check:"td{vertical-align}",left:function(a){return a.attributes&&a.attributes.valign},right:function(a){a.styles["vertical-align"]=a.attributes.valign;delete a.attributes.valign}}],[{element:"tr",check:"td{height}",left:function(a){return a.styles&&a.styles.height},right:function(a){CKEDITOR.tools.array.forEach(a.children,function(b){b.name in{td:1,th:1}&&
(b.attributes["cke-row-height"]=a.styles.height)});delete a.styles.height}}],[{element:"td",check:"td{height}",left:function(a){return(a=a.attributes)&&a["cke-row-height"]},right:function(a){a.styles.height=a.attributes["cke-row-height"];delete a.attributes["cke-row-height"]}}]]})));CKEDITOR.dialog.add("cellProperties",this.path+"dialogs/tableCell.js");b("rowDelete",f({requiredContent:"table",exec:function(a){a=a.getSelection();(a=B(a))&&p(a)}}));b("rowInsertBefore",f({requiredContent:"table",exec:function(a){a=
a.getSelection();a=q(a);r(a,!0)}}));b("rowInsertAfter",f({requiredContent:"table",exec:function(a){a=a.getSelection();a=q(a);r(a)}}));b("columnDelete",f({requiredContent:"table",exec:function(a){a=a.getSelection();(a=y(a))&&p(a,!0)}}));b("columnInsertBefore",f({requiredContent:"table",exec:function(a){a=a.getSelection();a=q(a);u(a,!0)}}));b("columnInsertAfter",f({requiredContent:"table",exec:function(a){a=a.getSelection();a=q(a);u(a)}}));b("cellDelete",f({requiredContent:"table",exec:function(a){a=
a.getSelection();z(a)}}));b("cellMerge",f({allowedContent:"td[colspan,rowspan]",requiredContent:"td[colspan,rowspan]",exec:function(a,b){b.cell=x(a.getSelection());p(b.cell,!0)}}));b("cellMergeRight",f({allowedContent:"td[colspan]",requiredContent:"td[colspan]",exec:function(a,b){b.cell=x(a.getSelection(),"right");p(b.cell,!0)}}));b("cellMergeDown",f({allowedContent:"td[rowspan]",requiredContent:"td[rowspan]",exec:function(a,b){b.cell=x(a.getSelection(),"down");p(b.cell,!0)}}));b("cellVerticalSplit",
f({allowedContent:"td[rowspan]",requiredContent:"td[rowspan]",exec:function(a){p(E(a.getSelection()))}}));b("cellHorizontalSplit",f({allowedContent:"td[colspan]",requiredContent:"td[colspan]",exec:function(a){p(C(a.getSelection()))}}));b("cellInsertBefore",f({requiredContent:"table",exec:function(a){a=a.getSelection();t(a,!0)}}));b("cellInsertAfter",f({requiredContent:"table",exec:function(a){a=a.getSelection();t(a)}}));d.addMenuItems&&d.addMenuItems({tablecell:{label:c.cell.menu,group:"tablecell",
order:1,getItems:function(){var a=d.getSelection(),b=q(a);return{tablecell_insertBefore:CKEDITOR.TRISTATE_OFF,tablecell_insertAfter:CKEDITOR.TRISTATE_OFF,tablecell_delete:CKEDITOR.TRISTATE_OFF,tablecell_merge:x(a,null,!0)?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,tablecell_merge_right:x(a,"right",!0)?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,tablecell_merge_down:x(a,"down",!0)?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,tablecell_split_vertical:E(a,!0)?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,
tablecell_split_horizontal:C(a,!0)?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED,tablecell_properties:0<b.length?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED}}},tablecell_insertBefore:{label:c.cell.insertBefore,group:"tablecell",command:"cellInsertBefore",order:5},tablecell_insertAfter:{label:c.cell.insertAfter,group:"tablecell",command:"cellInsertAfter",order:10},tablecell_delete:{label:c.cell.deleteCell,group:"tablecell",command:"cellDelete",order:15},tablecell_merge:{label:c.cell.merge,
group:"tablecell",command:"cellMerge",order:16},tablecell_merge_right:{label:c.cell.mergeRight,group:"tablecell",command:"cellMergeRight",order:17},tablecell_merge_down:{label:c.cell.mergeDown,group:"tablecell",command:"cellMergeDown",order:18},tablecell_split_horizontal:{label:c.cell.splitHorizontal,group:"tablecell",command:"cellHorizontalSplit",order:19},tablecell_split_vertical:{label:c.cell.splitVertical,group:"tablecell",command:"cellVerticalSplit",order:20},tablecell_properties:{label:c.cell.title,
group:"tablecellproperties",command:"cellProperties",order:21},tablerow:{label:c.row.menu,group:"tablerow",order:1,getItems:function(){return{tablerow_insertBefore:CKEDITOR.TRISTATE_OFF,tablerow_insertAfter:CKEDITOR.TRISTATE_OFF,tablerow_delete:CKEDITOR.TRISTATE_OFF}}},tablerow_insertBefore:{label:c.row.insertBefore,group:"tablerow",command:"rowInsertBefore",order:5},tablerow_insertAfter:{label:c.row.insertAfter,group:"tablerow",command:"rowInsertAfter",order:10},tablerow_delete:{label:c.row.deleteRow,
group:"tablerow",command:"rowDelete",order:15},tablecolumn:{label:c.column.menu,group:"tablecolumn",order:1,getItems:function(){return{tablecolumn_insertBefore:CKEDITOR.TRISTATE_OFF,tablecolumn_insertAfter:CKEDITOR.TRISTATE_OFF,tablecolumn_delete:CKEDITOR.TRISTATE_OFF}}},tablecolumn_insertBefore:{label:c.column.insertBefore,group:"tablecolumn",command:"columnInsertBefore",order:5},tablecolumn_insertAfter:{label:c.column.insertAfter,group:"tablecolumn",command:"columnInsertAfter",order:10},tablecolumn_delete:{label:c.column.deleteColumn,
group:"tablecolumn",command:"columnDelete",order:15}});d.contextMenu&&d.contextMenu.addListener(function(a,b,c){return(a=c.contains({td:1,th:1},1))&&!a.isReadOnly()?{tablecell:CKEDITOR.TRISTATE_OFF,tablerow:CKEDITOR.TRISTATE_OFF,tablecolumn:CKEDITOR.TRISTATE_OFF}:null})},getCellColIndex:v,insertRow:r,insertColumn:u,getSelectedCells:q};CKEDITOR.plugins.add("tabletools",CKEDITOR.plugins.tabletools)})();
CKEDITOR.tools.buildTableMap=function(q,r,B,v,w){q=q.$.rows;B=B||0;v="number"===typeof v?v:q.length-1;w="number"===typeof w?w:-1;var u=-1,y=[];for(r=r||0;r<=v;r++){u++;!y[u]&&(y[u]=[]);for(var t=-1,z=B;z<=(-1===w?q[r].cells.length-1:w);z++){var p=q[r].cells[z];if(!p)break;for(t++;y[u][t];)t++;for(var A=isNaN(p.colSpan)?1:p.colSpan,p=isNaN(p.rowSpan)?1:p.rowSpan,x=0;x<p&&!(r+x>v);x++){y[u+x]||(y[u+x]=[]);for(var C=0;C<A;C++)y[u+x][t+C]=q[r].cells[z]}t+=A-1;if(-1!==w&&t>=w)break}}return y};(function(){function D(a){return CKEDITOR.plugins.widget&&CKEDITOR.plugins.widget.isDomWidget(a)}function z(a,b){var c=a.getAscendant("table"),d=b.getAscendant("table"),e=CKEDITOR.tools.buildTableMap(c),g=r(a),h=r(b),k=[],f={},l,p;c.contains(d)&&(b=b.getAscendant({td:1,th:1}),h=r(b));g>h&&(c=g,g=h,h=c,c=a,a=b,b=c);for(c=0;c<e[g].length;c++)if(a.$===e[g][c]){l=c;break}for(c=0;c<e[h].length;c++)if(b.$===e[h][c]){p=c;break}l>p&&(c=l,l=p,p=c);for(c=g;c<=h;c++)for(g=l;g<=p;g++)d=new CKEDITOR.dom.element(e[c][g]),
d.$&&!d.getCustomData("selected_cell")&&(k.push(d),CKEDITOR.dom.element.setMarker(f,d,"selected_cell",!0));CKEDITOR.dom.element.clearAllMarkers(f);return k}function I(a){if(a)return a=a.clone(),a.enlarge(CKEDITOR.ENLARGE_ELEMENT),(a=a.getEnclosedNode())&&a.is&&a.is(CKEDITOR.dtd.$tableContent)}function J(a){return(a=a.editable().findOne(".cke_table-faked-selection"))&&a.getAscendant("table")}function A(a,b){var c=a.editable().find(".cke_table-faked-selection"),d;a.fire("lockSnapshot");a.editable().removeClass("cke_table-faked-selection-editor");
for(d=0;d<c.count();d++)c.getItem(d).removeClass("cke_table-faked-selection");0<c.count()&&c.getItem(0).getAscendant("table").data("cke-table-faked-selection-table",!1);a.fire("unlockSnapshot");b&&(m={active:!1},a.getSelection().isInTable()&&a.getSelection().reset())}function t(a,b){var c=[],d,e;for(e=0;e<b.length;e++)d=a.createRange(),d.setStartBefore(b[e]),d.setEndAfter(b[e]),c.push(d);a.getSelection().selectRanges(c)}function K(a){var b=a.editable().find(".cke_table-faked-selection");1>b.count()||
(b=z(b.getItem(0),b.getItem(b.count()-1)),t(a,b))}function L(a,b,c){var d=v(a.getSelection(!0));b=b.is("table")?null:b;var e;(e=m.active&&!m.first)&&!(e=b)&&(e=a.getSelection().getRanges(),e=1<d.length||e[0]&&!e[0].collapsed?!0:!1);if(e)m.first=b||d[0],m.dirty=b?!1:1!==d.length;else if(m.active&&b&&m.first.getAscendant("table").equals(b.getAscendant("table"))){d=z(m.first,b);if(!m.dirty&&1===d.length&&!D(c.data.getTarget()))return A(a,"mouseup"===c.name);m.dirty=!0;m.last=b;t(a,d)}}function M(a){var b=
(a=a.editor||a.sender.editor)&&a.getSelection(),c=b&&b.getRanges()||[],d;if(b&&(A(a),b.isInTable()&&b.isFake)){1===c.length&&c[0]._getTableElement()&&c[0]._getTableElement().is("table")&&(d=c[0]._getTableElement());d=v(b,d);a.fire("lockSnapshot");for(b=0;b<d.length;b++)d[b].addClass("cke_table-faked-selection");0<d.length&&(a.editable().addClass("cke_table-faked-selection-editor"),d[0].getAscendant("table").data("cke-table-faked-selection-table",""));a.fire("unlockSnapshot")}}function r(a){return a.getAscendant("tr",
!0).$.rowIndex}function w(a){function b(a,b){return a&&b?a.equals(b)||a.contains(b)||b.contains(a)||a.getCommonAncestor(b).is(l):!1}function c(a){return!a.getAscendant("table",!0)&&a.getDocument().equals(e.document)}function d(a,d,e,f){return("mousedown"!==a.name||CKEDITOR.tools.getMouseButton(a)!==CKEDITOR.MOUSE_BUTTON_LEFT&&f)&&("mouseup"!==a.name||c(a.data.getTarget())||b(e,f))?!1:!0}if(a.data.getTarget().getName&&("mouseup"===a.name||!D(a.data.getTarget()))){var e=a.editor||a.listenerData.editor,
g=e.getSelection(1),h=J(e),k=a.data.getTarget(),f=k&&k.getAscendant({td:1,th:1},!0),k=k&&k.getAscendant("table",!0),l={table:1,thead:1,tbody:1,tfoot:1,tr:1,td:1,th:1};d(a,g,h,k)&&A(e,!0);!m.active&&"mousedown"===a.name&&CKEDITOR.tools.getMouseButton(a)===CKEDITOR.MOUSE_BUTTON_LEFT&&k&&(m={active:!0},CKEDITOR.document.on("mouseup",w,null,{editor:e}));(f||k)&&L(e,f||k,a);"mouseup"===a.name&&(CKEDITOR.tools.getMouseButton(a)===CKEDITOR.MOUSE_BUTTON_LEFT&&(c(a.data.getTarget())||b(h,k))&&K(e),m={active:!1},
CKEDITOR.document.removeListener("mouseup",w))}}function N(a){var b=a.data.getTarget().getAscendant({td:1,th:1},!0);b&&!b.hasClass("cke_table-faked-selection")&&(a.cancel(),a.data.preventDefault())}function O(a,b){function c(a){a.cancel()}var d=a.getSelection(),e=d.createBookmarks(),g=a.document,h=a.createRange(),k=g.getDocumentElement().$,f=CKEDITOR.env.ie&&9>CKEDITOR.env.version,l=a.blockless||CKEDITOR.env.ie?"span":"div",p,x,n,m;g.getById("cke_table_copybin")||(p=g.createElement(l),x=g.createElement(l),
x.setAttributes({id:"cke_table_copybin","data-cke-temp":"1"}),p.setStyles({position:"absolute",width:"1px",height:"1px",overflow:"hidden"}),p.setStyle("ltr"==a.config.contentsLangDirection?"left":"right","-5000px"),p.setHtml(a.getSelectedHtml(!0)),a.fire("lockSnapshot"),x.append(p),a.editable().append(x),m=a.on("selectionChange",c,null,null,0),f&&(n=k.scrollTop),h.selectNodeContents(p),h.select(),f&&(k.scrollTop=n),setTimeout(function(){x.remove();d.selectBookmarks(e);m.removeListener();a.fire("unlockSnapshot");
b&&(a.extractSelectedHtml(),a.fire("saveSnapshot"))},100))}function E(a){var b=a.editor||a.sender.editor;b.getSelection().isInTable()&&O(b,"cut"===a.name)}function q(a){this._reset();a&&this.setSelectedCells(a)}function B(a,b,c){a.on("beforeCommandExec",function(d){-1!==CKEDITOR.tools.array.indexOf(b,d.data.name)&&(d.data.selectedCells=v(a.getSelection()))});a.on("afterCommandExec",function(d){-1!==CKEDITOR.tools.array.indexOf(b,d.data.name)&&c(a,d.data)})}var m={active:!1},y,v,C,F,G;q.prototype=
{};q.prototype._reset=function(){this.cells={first:null,last:null,all:[]};this.rows={first:null,last:null}};q.prototype.setSelectedCells=function(a){this._reset();a=a.slice(0);this._arraySortByDOMOrder(a);this.cells.all=a;this.cells.first=a[0];this.cells.last=a[a.length-1];this.rows.first=a[0].getAscendant("tr");this.rows.last=this.cells.last.getAscendant("tr")};q.prototype.getTableMap=function(){var a=C(this.cells.first),b;a:{b=this.cells.last;var c=b.getAscendant("table"),d=r(b),c=CKEDITOR.tools.buildTableMap(c),
e;for(e=0;e<c[d].length;e++)if((new CKEDITOR.dom.element(c[d][e])).equals(b)){b=e;break a}b=void 0}return CKEDITOR.tools.buildTableMap(this._getTable(),r(this.rows.first),a,r(this.rows.last),b)};q.prototype._getTable=function(){return this.rows.first.getAscendant("table")};q.prototype.insertRow=function(a,b,c){if("undefined"===typeof a)a=1;else if(0>=a)return;for(var d=this.cells.first.$.cellIndex,e=this.cells.last.$.cellIndex,g=c?[]:this.cells.all,h,k=0;k<a;k++)h=F(c?this.cells.all:g,b),h=CKEDITOR.tools.array.filter(h.find("td, th").toArray(),
function(a){return c?!0:a.$.cellIndex>=d&&a.$.cellIndex<=e}),g=b?h.concat(g):g.concat(h);this.setSelectedCells(g)};q.prototype.insertColumn=function(a){function b(a){a=r(a);return a>=e&&a<=g}if("undefined"===typeof a)a=1;else if(0>=a)return;for(var c=this.cells,d=c.all,e=r(c.first),g=r(c.last),c=0;c<a;c++)d=d.concat(CKEDITOR.tools.array.filter(G(d),b));this.setSelectedCells(d)};q.prototype.emptyCells=function(a){a=a||this.cells.all;for(var b=0;b<a.length;b++)a[b].setHtml("")};q.prototype._arraySortByDOMOrder=
function(a){a.sort(function(a,c){return a.getPosition(c)&CKEDITOR.POSITION_PRECEDING?-1:1})};var H={onPaste:function(a){function b(a){return Math.max.apply(null,CKEDITOR.tools.array.map(a,function(a){return a.length},0))}function c(a){var b=d.createRange();b.selectNodeContents(a);b.select()}var d=a.editor,e=d.getSelection(),g=v(e),h=this.findTableInPastedContent(d,a.data.dataValue),k=e.isInTable(!0)&&this.isBoundarySelection(e),f,l;!g.length||1===g.length&&!I(e.getRanges()[0])&&!k||k&&!h||(g=g[0].getAscendant("table"),
f=new q(v(e,g)),d.once("afterPaste",function(){var a;if(l){a=new CKEDITOR.dom.element(l[0][0]);var b=l[l.length-1];a=z(a,new CKEDITOR.dom.element(b[b.length-1]))}else a=f.cells.all;t(d,a)}),h?(a.stop(),k?(f.insertRow(1,1===k,!0),e.selectElement(f.rows.first)):(f.emptyCells(),t(d,f.cells.all)),a=f.getTableMap(),l=CKEDITOR.tools.buildTableMap(h),f.insertRow(l.length-a.length),f.insertColumn(b(l)-b(a)),a=f.getTableMap(),this.pasteTable(f,a,l),d.fire("saveSnapshot"),setTimeout(function(){d.fire("afterPaste")},
0)):(c(f.cells.first),d.once("afterPaste",function(){d.fire("lockSnapshot");f.emptyCells(f.cells.all.slice(1));t(d,f.cells.all);d.fire("unlockSnapshot")})))},isBoundarySelection:function(a){a=a.getRanges()[0];var b=a.endContainer.getAscendant("tr",!0);if(b&&a.collapsed){if(a.checkBoundaryOfElement(b,CKEDITOR.START))return 1;if(a.checkBoundaryOfElement(b,CKEDITOR.END))return 2}return 0},findTableInPastedContent:function(a,b){var c=a.dataProcessor,d=new CKEDITOR.dom.element("body");c||(c=new CKEDITOR.htmlDataProcessor(a));
d.setHtml(c.toHtml(b),{fixForBody:!1});return 1<d.getChildCount()?null:d.findOne("table")},pasteTable:function(a,b,c){var d,e=C(a.cells.first),g=a._getTable(),h={},k,f,l,p;for(l=0;l<c.length;l++)for(k=new CKEDITOR.dom.element(g.$.rows[a.rows.first.$.rowIndex+l]),p=0;p<c[l].length;p++)if(f=new CKEDITOR.dom.element(c[l][p]),d=b[l]&&b[l][p]?new CKEDITOR.dom.element(b[l][p]):null,f&&!f.getCustomData("processed")){if(d&&d.getParent())f.replace(d);else if(0===p||c[l][p-1])(d=0!==p?new CKEDITOR.dom.element(c[l][p-
1]):null)&&k.equals(d.getParent())?f.insertAfter(d):0<e?k.$.cells[e]?f.insertAfter(new CKEDITOR.dom.element(k.$.cells[e])):k.append(f):k.append(f,!0);CKEDITOR.dom.element.setMarker(h,f,"processed",!0)}else f.getCustomData("processed")&&d&&d.remove();CKEDITOR.dom.element.clearAllMarkers(h)}};CKEDITOR.plugins.tableselection={getCellsBetween:z,keyboardIntegration:function(a){function b(a){var b=a.getEnclosedNode();b&&"function"===typeof b.is&&b.is({td:1,th:1})?b.setText(""):a.deleteContents();CKEDITOR.tools.array.forEach(a._find("td"),
function(a){a.appendBogus()})}var c=a.editable();c.attachListener(c,"keydown",function(a){function c(b,e){if(!e.length)return null;var l=a.createRange(),g=CKEDITOR.dom.range.mergeRanges(e);CKEDITOR.tools.array.forEach(g,function(a){a.enlarge(CKEDITOR.ENLARGE_ELEMENT)});var m=g[0].getBoundaryNodes(),n=m.startNode,m=m.endNode;if(n&&n.is&&n.is(h)){for(var q=n.getAscendant("table",!0),u=n.getPreviousSourceNode(!1,CKEDITOR.NODE_ELEMENT,q),r=!1,t=function(a){return!n.contains(a)&&a.is&&a.is("td","th")};u&&
!t(u);)u=u.getPreviousSourceNode(!1,CKEDITOR.NODE_ELEMENT,q);!u&&m&&m.is&&!m.is("table")&&m.getNext()&&(u=m.getNext().findOne("td, th"),r=!0);if(u)l["moveToElementEdit"+(r?"Start":"End")](u);else l.setStartBefore(n.getAscendant("table",!0)),l.collapse(!0);g[0].deleteContents();return[l]}if(n)return l.moveToElementEditablePosition(n),[l]}var g={37:1,38:1,39:1,40:1,8:1,46:1,13:1},h=CKEDITOR.tools.extend({table:1},CKEDITOR.dtd.$tableContent);delete h.td;delete h.th;return function(k){var f=k.data.getKey(),
l=k.data.getKeystroke(),h,m=37===f||38==f,n,q,r;if(g[f]&&(h=a.getSelection())&&h.isInTable()&&h.isFake){n=h.getRanges();q=n[0]._getTableElement();r=n[n.length-1]._getTableElement();if(13!==f||a.plugins.enterkey)k.data.preventDefault(),k.cancel();if(36<f&&41>f)n[0].moveToElementEditablePosition(m?q:r,!m),h.selectRanges([n[0]]);else if(13!==f||13===l||l===CKEDITOR.SHIFT+13){for(k=0;k<n.length;k++)b(n[k]);(k=c(q,n))?n=k:n[0].moveToElementEditablePosition(q);h.selectRanges(n);13===f&&a.plugins.enterkey?
(a.fire("lockSnapshot"),13===l?a.execCommand("enter"):a.execCommand("shiftEnter"),a.fire("unlockSnapshot"),a.fire("saveSnapshot")):13!==f&&a.fire("saveSnapshot")}}}}(a),null,null,-1);c.attachListener(c,"keypress",function(d){var c=a.getSelection(),g=d.data.$.charCode||13===d.data.getKey(),h;if(c&&c.isInTable()&&c.isFake&&g&&!(d.data.getKeystroke()&CKEDITOR.CTRL)){d=c.getRanges();g=d[0].getEnclosedNode().getAscendant({td:1,th:1},!0);for(h=0;h<d.length;h++)b(d[h]);g&&(d[0].moveToElementEditablePosition(g),
c.selectRanges([d[0]]))}},null,null,-1)},isSupportedEnvironment:!(CKEDITOR.env.ie&&11>CKEDITOR.env.version)};CKEDITOR.plugins.add("tableselection",{requires:"clipboard,tabletools",onLoad:function(){y=CKEDITOR.plugins.tabletools;v=y.getSelectedCells;C=y.getCellColIndex;F=y.insertRow;G=y.insertColumn;CKEDITOR.document.appendStyleSheet(this.path+"styles/tableselection.css")},init:function(a){CKEDITOR.plugins.tableselection.isSupportedEnvironment&&(a.addContentsCss&&a.addContentsCss(this.path+"styles/tableselection.css"),
a.on("contentDom",function(){var b=a.editable(),c=b.isInline()?b:a.document,d={editor:a};b.attachListener(c,"mousedown",w,null,d);b.attachListener(c,"mousemove",w,null,d);b.attachListener(c,"mouseup",w,null,d);b.attachListener(b,"dragstart",N);b.attachListener(a,"selectionCheck",M);CKEDITOR.plugins.tableselection.keyboardIntegration(a);CKEDITOR.plugins.clipboard&&!CKEDITOR.plugins.clipboard.isCustomCopyCutSupported&&(b.attachListener(b,"cut",E),b.attachListener(b,"copy",E))}),a.on("paste",H.onPaste,
H),B(a,"rowInsertBefore rowInsertAfter columnInsertBefore columnInsertAfter cellInsertBefore cellInsertAfter".split(" "),function(a,c){t(a,c.selectedCells)}),B(a,["cellMerge","cellMergeRight","cellMergeDown"],function(a,c){t(a,[c.commandData.cell])}),B(a,["cellDelete"],function(a){A(a,!0)}))}})})();(function(){var g=[CKEDITOR.CTRL+90,CKEDITOR.CTRL+89,CKEDITOR.CTRL+CKEDITOR.SHIFT+90],n={8:1,46:1};CKEDITOR.plugins.add("undo",{init:function(a){function b(a){d.enabled&&!1!==a.data.command.canUndo&&d.save()}function c(){d.enabled=a.readOnly?!1:"wysiwyg"==a.mode;d.onChange()}var d=a.undoManager=new e(a),l=d.editingHandler=new k(d),f=a.addCommand("undo",{exec:function(){d.undo()&&(a.selectionChange(),this.fire("afterUndo"))},startDisabled:!0,canUndo:!1}),h=a.addCommand("redo",{exec:function(){d.redo()&&
(a.selectionChange(),this.fire("afterRedo"))},startDisabled:!0,canUndo:!1});a.setKeystroke([[g[0],"undo"],[g[1],"redo"],[g[2],"redo"]]);d.onChange=function(){f.setState(d.undoable()?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED);h.setState(d.redoable()?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED)};a.on("beforeCommandExec",b);a.on("afterCommandExec",b);a.on("saveSnapshot",function(a){d.save(a.data&&a.data.contentOnly)});a.on("contentDom",l.attachListeners,l);a.on("instanceReady",function(){a.fire("saveSnapshot")});
a.on("beforeModeUnload",function(){"wysiwyg"==a.mode&&d.save(!0)});a.on("mode",c);a.on("readOnly",c);a.ui.addButton&&(a.ui.addButton("Undo",{label:a.lang.undo.undo,command:"undo",toolbar:"undo,10"}),a.ui.addButton("Redo",{label:a.lang.undo.redo,command:"redo",toolbar:"undo,20"}));a.resetUndo=function(){d.reset();a.fire("saveSnapshot")};a.on("updateSnapshot",function(){d.currentImage&&d.update()});a.on("lockSnapshot",function(a){a=a.data;d.lock(a&&a.dontUpdate,a&&a.forceUpdate)});a.on("unlockSnapshot",
d.unlock,d)}});CKEDITOR.plugins.undo={};var e=CKEDITOR.plugins.undo.UndoManager=function(a){this.strokesRecorded=[0,0];this.locked=null;this.previousKeyGroup=-1;this.limit=a.config.undoStackSize||20;this.strokesLimit=25;this.editor=a;this.reset()};e.prototype={type:function(a,b){var c=e.getKeyGroup(a),d=this.strokesRecorded[c]+1;b=b||d>=this.strokesLimit;this.typing||(this.hasUndo=this.typing=!0,this.hasRedo=!1,this.onChange());b?(d=0,this.editor.fire("saveSnapshot")):this.editor.fire("change");this.strokesRecorded[c]=
d;this.previousKeyGroup=c},keyGroupChanged:function(a){return e.getKeyGroup(a)!=this.previousKeyGroup},reset:function(){this.snapshots=[];this.index=-1;this.currentImage=null;this.hasRedo=this.hasUndo=!1;this.locked=null;this.resetType()},resetType:function(){this.strokesRecorded=[0,0];this.typing=!1;this.previousKeyGroup=-1},refreshState:function(){this.hasUndo=!!this.getNextImage(!0);this.hasRedo=!!this.getNextImage(!1);this.resetType();this.onChange()},save:function(a,b,c){var d=this.editor;if(this.locked||
"ready"!=d.status||"wysiwyg"!=d.mode)return!1;var e=d.editable();if(!e||"ready"!=e.status)return!1;e=this.snapshots;b||(b=new f(d));if(!1===b.contents)return!1;if(this.currentImage)if(b.equalsContent(this.currentImage)){if(a||b.equalsSelection(this.currentImage))return!1}else!1!==c&&d.fire("change");e.splice(this.index+1,e.length-this.index-1);e.length==this.limit&&e.shift();this.index=e.push(b)-1;this.currentImage=b;!1!==c&&this.refreshState();return!0},restoreImage:function(a){var b=this.editor,
c;a.bookmarks&&(b.focus(),c=b.getSelection());this.locked={level:999};this.editor.loadSnapshot(a.contents);a.bookmarks?c.selectBookmarks(a.bookmarks):CKEDITOR.env.ie&&(c=this.editor.document.getBody().$.createTextRange(),c.collapse(!0),c.select());this.locked=null;this.index=a.index;this.currentImage=this.snapshots[this.index];this.update();this.refreshState();b.fire("change")},getNextImage:function(a){var b=this.snapshots,c=this.currentImage,d;if(c)if(a)for(d=this.index-1;0<=d;d--){if(a=b[d],!c.equalsContent(a))return a.index=
d,a}else for(d=this.index+1;d<b.length;d++)if(a=b[d],!c.equalsContent(a))return a.index=d,a;return null},redoable:function(){return this.enabled&&this.hasRedo},undoable:function(){return this.enabled&&this.hasUndo},undo:function(){if(this.undoable()){this.save(!0);var a=this.getNextImage(!0);if(a)return this.restoreImage(a),!0}return!1},redo:function(){if(this.redoable()&&(this.save(!0),this.redoable())){var a=this.getNextImage(!1);if(a)return this.restoreImage(a),!0}return!1},update:function(a){if(!this.locked){a||
(a=new f(this.editor));for(var b=this.index,c=this.snapshots;0<b&&this.currentImage.equalsContent(c[b-1]);)--b;c.splice(b,this.index-b+1,a);this.index=b;this.currentImage=a}},updateSelection:function(a){if(!this.snapshots.length)return!1;var b=this.snapshots,c=b[b.length-1];return c.equalsContent(a)&&!c.equalsSelection(a)?(this.currentImage=b[b.length-1]=a,!0):!1},lock:function(a,b){if(this.locked)this.locked.level++;else if(a)this.locked={level:1};else{var c=null;if(b)c=!0;else{var d=new f(this.editor,
!0);this.currentImage&&this.currentImage.equalsContent(d)&&(c=d)}this.locked={update:c,level:1}}},unlock:function(){if(this.locked&&!--this.locked.level){var a=this.locked.update;this.locked=null;if(!0===a)this.update();else if(a){var b=new f(this.editor,!0);a.equalsContent(b)||this.update()}}}};e.navigationKeyCodes={37:1,38:1,39:1,40:1,36:1,35:1,33:1,34:1};e.keyGroups={PRINTABLE:0,FUNCTIONAL:1};e.isNavigationKey=function(a){return!!e.navigationKeyCodes[a]};e.getKeyGroup=function(a){var b=e.keyGroups;
return n[a]?b.FUNCTIONAL:b.PRINTABLE};e.getOppositeKeyGroup=function(a){var b=e.keyGroups;return a==b.FUNCTIONAL?b.PRINTABLE:b.FUNCTIONAL};e.ieFunctionalKeysBug=function(a){return CKEDITOR.env.ie&&e.getKeyGroup(a)==e.keyGroups.FUNCTIONAL};var f=CKEDITOR.plugins.undo.Image=function(a,b){this.editor=a;a.fire("beforeUndoImage");var c=a.getSnapshot();CKEDITOR.env.ie&&c&&(c=c.replace(/\s+data-cke-expando=".*?"/g,""));this.contents=c;b||(this.bookmarks=(c=c&&a.getSelection())&&c.createBookmarks2(!0));a.fire("afterUndoImage")},
h=/\b(?:href|src|name)="[^"]*?"/gi;f.prototype={equalsContent:function(a){var b=this.contents;a=a.contents;CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks)&&(b=b.replace(h,""),a=a.replace(h,""));return b!=a?!1:!0},equalsSelection:function(a){var b=this.bookmarks;a=a.bookmarks;if(b||a){if(!b||!a||b.length!=a.length)return!1;for(var c=0;c<b.length;c++){var d=b[c],e=a[c];if(d.startOffset!=e.startOffset||d.endOffset!=e.endOffset||!CKEDITOR.tools.arrayCompare(d.start,e.start)||!CKEDITOR.tools.arrayCompare(d.end,
e.end))return!1}}return!0}};var k=CKEDITOR.plugins.undo.NativeEditingHandler=function(a){this.undoManager=a;this.ignoreInputEvent=!1;this.keyEventsStack=new m;this.lastKeydownImage=null};k.prototype={onKeydown:function(a){var b=a.data.getKey();if(229!==b)if(-1<CKEDITOR.tools.indexOf(g,a.data.getKeystroke()))a.data.preventDefault();else if(this.keyEventsStack.cleanUp(a),a=this.undoManager,this.keyEventsStack.getLast(b)||this.keyEventsStack.push(b),this.lastKeydownImage=new f(a.editor),e.isNavigationKey(b)||
this.undoManager.keyGroupChanged(b))if(a.strokesRecorded[0]||a.strokesRecorded[1])a.save(!1,this.lastKeydownImage,!1),a.resetType()},onInput:function(){if(this.ignoreInputEvent)this.ignoreInputEvent=!1;else{var a=this.keyEventsStack.getLast();a||(a=this.keyEventsStack.push(0));this.keyEventsStack.increment(a.keyCode);this.keyEventsStack.getTotalInputs()>=this.undoManager.strokesLimit&&(this.undoManager.type(a.keyCode,!0),this.keyEventsStack.resetInputs())}},onKeyup:function(a){var b=this.undoManager;
a=a.data.getKey();var c=this.keyEventsStack.getTotalInputs();this.keyEventsStack.remove(a);if(!(e.ieFunctionalKeysBug(a)&&this.lastKeydownImage&&this.lastKeydownImage.equalsContent(new f(b.editor,!0))))if(0<c)b.type(a);else if(e.isNavigationKey(a))this.onNavigationKey(!0)},onNavigationKey:function(a){var b=this.undoManager;!a&&b.save(!0,null,!1)||b.updateSelection(new f(b.editor));b.resetType()},ignoreInputEventListener:function(){this.ignoreInputEvent=!0},activateInputEventListener:function(){this.ignoreInputEvent=
!1},attachListeners:function(){var a=this.undoManager.editor,b=a.editable(),c=this;b.attachListener(b,"keydown",function(a){c.onKeydown(a);if(e.ieFunctionalKeysBug(a.data.getKey()))c.onInput()},null,null,999);b.attachListener(b,CKEDITOR.env.ie?"keypress":"input",c.onInput,c,null,999);b.attachListener(b,"keyup",c.onKeyup,c,null,999);b.attachListener(b,"paste",c.ignoreInputEventListener,c,null,999);b.attachListener(b,"drop",c.ignoreInputEventListener,c,null,999);a.on("afterPaste",c.activateInputEventListener,
c,null,999);b.attachListener(b.isInline()?b:a.document.getDocumentElement(),"click",function(){c.onNavigationKey()},null,null,999);b.attachListener(this.undoManager.editor,"blur",function(){c.keyEventsStack.remove(9)},null,null,999)}};var m=CKEDITOR.plugins.undo.KeyEventsStack=function(){this.stack=[]};m.prototype={push:function(a){a=this.stack.push({keyCode:a,inputs:0});return this.stack[a-1]},getLastIndex:function(a){if("number"!=typeof a)return this.stack.length-1;for(var b=this.stack.length;b--;)if(this.stack[b].keyCode==
a)return b;return-1},getLast:function(a){a=this.getLastIndex(a);return-1!=a?this.stack[a]:null},increment:function(a){this.getLast(a).inputs++},remove:function(a){a=this.getLastIndex(a);-1!=a&&this.stack.splice(a,1)},resetInputs:function(a){if("number"==typeof a)this.getLast(a).inputs=0;else for(a=this.stack.length;a--;)this.stack[a].inputs=0},getTotalInputs:function(){for(var a=this.stack.length,b=0;a--;)b+=this.stack[a].inputs;return b},cleanUp:function(a){a=a.data.$;a.ctrlKey||a.metaKey||this.remove(17);
a.shiftKey||this.remove(16);a.altKey||this.remove(18)}}})();(function(){function m(a,d){CKEDITOR.tools.extend(this,{editor:a,editable:a.editable(),doc:a.document,win:a.window},d,!0);this.inline=this.editable.isInline();this.inline||(this.frame=this.win.getFrame());this.target=this[this.inline?"editable":"doc"]}function n(a,d){CKEDITOR.tools.extend(this,d,{editor:a},!0)}function p(a,d){var b=a.editable();CKEDITOR.tools.extend(this,{editor:a,editable:b,inline:b.isInline(),doc:a.document,win:a.window,container:CKEDITOR.document.getBody(),winTop:CKEDITOR.document.getWindow()},
d,!0);this.hidden={};this.visible={};this.inline||(this.frame=this.win.getFrame());this.queryViewport();var c=CKEDITOR.tools.bind(this.queryViewport,this),e=CKEDITOR.tools.bind(this.hideVisible,this),g=CKEDITOR.tools.bind(this.removeAll,this);b.attachListener(this.winTop,"resize",c);b.attachListener(this.winTop,"scroll",c);b.attachListener(this.winTop,"resize",e);b.attachListener(this.win,"scroll",e);b.attachListener(this.inline?b:this.frame,"mouseout",function(a){var b=a.data.$.clientX;a=a.data.$.clientY;
this.queryViewport();(b<=this.rect.left||b>=this.rect.right||a<=this.rect.top||a>=this.rect.bottom)&&this.hideVisible();(0>=b||b>=this.winTopPane.width||0>=a||a>=this.winTopPane.height)&&this.hideVisible()},this);b.attachListener(a,"resize",c);b.attachListener(a,"mode",g);a.on("destroy",g);this.lineTpl=(new CKEDITOR.template('\x3cdiv data-cke-lineutils-line\x3d"1" class\x3d"cke_reset_all" style\x3d"{lineStyle}"\x3e\x3cspan style\x3d"{tipLeftStyle}"\x3e\x26nbsp;\x3c/span\x3e\x3cspan style\x3d"{tipRightStyle}"\x3e\x26nbsp;\x3c/span\x3e\x3c/div\x3e')).output({lineStyle:CKEDITOR.tools.writeCssText(CKEDITOR.tools.extend({},
t,this.lineStyle,!0)),tipLeftStyle:CKEDITOR.tools.writeCssText(CKEDITOR.tools.extend({},q,{left:"0px","border-left-color":"red","border-width":"6px 0 6px 6px"},this.tipCss,this.tipLeftStyle,!0)),tipRightStyle:CKEDITOR.tools.writeCssText(CKEDITOR.tools.extend({},q,{right:"0px","border-right-color":"red","border-width":"6px 6px 6px 0"},this.tipCss,this.tipRightStyle,!0))})}function l(a){var d;if(d=a&&a.type==CKEDITOR.NODE_ELEMENT)d=!(r[a.getComputedStyle("float")]||r[a.getAttribute("align")]);return d&&
!u[a.getComputedStyle("position")]}CKEDITOR.plugins.add("lineutils");CKEDITOR.LINEUTILS_BEFORE=1;CKEDITOR.LINEUTILS_AFTER=2;CKEDITOR.LINEUTILS_INSIDE=4;m.prototype={start:function(a){var d=this,b=this.editor,c=this.doc,e,g,f,h,k=CKEDITOR.tools.eventsBuffer(50,function(){b.readOnly||"wysiwyg"!=b.mode||(d.relations={},(g=c.$.elementFromPoint(f,h))&&g.nodeType&&(e=new CKEDITOR.dom.element(g),d.traverseSearch(e),isNaN(f+h)||d.pixelSearch(e,f,h),a&&a(d.relations,f,h)))});this.listener=this.editable.attachListener(this.target,
"mousemove",function(a){f=a.data.$.clientX;h=a.data.$.clientY;k.input()});this.editable.attachListener(this.inline?this.editable:this.frame,"mouseout",function(){k.reset()})},stop:function(){this.listener&&this.listener.removeListener()},getRange:function(){var a={};a[CKEDITOR.LINEUTILS_BEFORE]=CKEDITOR.POSITION_BEFORE_START;a[CKEDITOR.LINEUTILS_AFTER]=CKEDITOR.POSITION_AFTER_END;a[CKEDITOR.LINEUTILS_INSIDE]=CKEDITOR.POSITION_AFTER_START;return function(d){var b=this.editor.createRange();b.moveToPosition(this.relations[d.uid].element,
a[d.type]);return b}}(),store:function(){function a(a,b,c){var e=a.getUniqueId();e in c?c[e].type|=b:c[e]={element:a,type:b}}return function(d,b){var c;b&CKEDITOR.LINEUTILS_AFTER&&l(c=d.getNext())&&c.isVisible()&&(a(c,CKEDITOR.LINEUTILS_BEFORE,this.relations),b^=CKEDITOR.LINEUTILS_AFTER);b&CKEDITOR.LINEUTILS_INSIDE&&l(c=d.getFirst())&&c.isVisible()&&(a(c,CKEDITOR.LINEUTILS_BEFORE,this.relations),b^=CKEDITOR.LINEUTILS_INSIDE);a(d,b,this.relations)}}(),traverseSearch:function(a){var d,b,c;do if(c=a.$["data-cke-expando"],
!(c&&c in this.relations)){if(a.equals(this.editable))break;if(l(a))for(d in this.lookups)(b=this.lookups[d](a))&&this.store(a,b)}while((!a||a.type!=CKEDITOR.NODE_ELEMENT||"true"!=a.getAttribute("contenteditable"))&&(a=a.getParent()))},pixelSearch:function(){function a(a,c,e,g,f){for(var h=0,k;f(e);){e+=g;if(25==++h)break;if(k=this.doc.$.elementFromPoint(c,e))if(k==a)h=0;else if(d(a,k)&&(h=0,l(k=new CKEDITOR.dom.element(k))))return k}}var d=CKEDITOR.env.ie||CKEDITOR.env.webkit?function(a,c){return a.contains(c)}:
function(a,c){return!!(a.compareDocumentPosition(c)&16)};return function(b,c,d){var g=this.win.getViewPaneSize().height,f=a.call(this,b.$,c,d,-1,function(a){return 0<a});c=a.call(this,b.$,c,d,1,function(a){return a<g});if(f)for(this.traverseSearch(f);!f.getParent().equals(b);)f=f.getParent();if(c)for(this.traverseSearch(c);!c.getParent().equals(b);)c=c.getParent();for(;f||c;){f&&(f=f.getNext(l));if(!f||f.equals(c))break;this.traverseSearch(f);c&&(c=c.getPrevious(l));if(!c||c.equals(f))break;this.traverseSearch(c)}}}(),
greedySearch:function(){this.relations={};for(var a=this.editable.getElementsByTag("*"),d=0,b,c,e;b=a.getItem(d++);)if(!b.equals(this.editable)&&b.type==CKEDITOR.NODE_ELEMENT&&(b.hasAttribute("contenteditable")||!b.isReadOnly())&&l(b)&&b.isVisible())for(e in this.lookups)(c=this.lookups[e](b))&&this.store(b,c);return this.relations}};n.prototype={locate:function(){function a(a,b){var c=a.element[b===CKEDITOR.LINEUTILS_BEFORE?"getPrevious":"getNext"]();return c&&l(c)?(a.siblingRect=c.getClientRect(),
b==CKEDITOR.LINEUTILS_BEFORE?(a.siblingRect.bottom+a.elementRect.top)/2:(a.elementRect.bottom+a.siblingRect.top)/2):b==CKEDITOR.LINEUTILS_BEFORE?a.elementRect.top:a.elementRect.bottom}return function(d){var b;this.locations={};for(var c in d)b=d[c],b.elementRect=b.element.getClientRect(),b.type&CKEDITOR.LINEUTILS_BEFORE&&this.store(c,CKEDITOR.LINEUTILS_BEFORE,a(b,CKEDITOR.LINEUTILS_BEFORE)),b.type&CKEDITOR.LINEUTILS_AFTER&&this.store(c,CKEDITOR.LINEUTILS_AFTER,a(b,CKEDITOR.LINEUTILS_AFTER)),b.type&
CKEDITOR.LINEUTILS_INSIDE&&this.store(c,CKEDITOR.LINEUTILS_INSIDE,(b.elementRect.top+b.elementRect.bottom)/2);return this.locations}}(),sort:function(){var a,d,b,c;return function(e,g){a=this.locations;d=[];for(var f in a)for(var h in a[f])if(b=Math.abs(e-a[f][h]),d.length){for(c=0;c<d.length;c++)if(b<d[c].dist){d.splice(c,0,{uid:+f,type:h,dist:b});break}c==d.length&&d.push({uid:+f,type:h,dist:b})}else d.push({uid:+f,type:h,dist:b});return"undefined"!=typeof g?d.slice(0,g):d}}(),store:function(a,
d,b){this.locations[a]||(this.locations[a]={});this.locations[a][d]=b}};var q={display:"block",width:"0px",height:"0px","border-color":"transparent","border-style":"solid",position:"absolute",top:"-6px"},t={height:"0px","border-top":"1px dashed red",position:"absolute","z-index":9999};p.prototype={removeAll:function(){for(var a in this.hidden)this.hidden[a].remove(),delete this.hidden[a];for(a in this.visible)this.visible[a].remove(),delete this.visible[a]},hideLine:function(a){var d=a.getUniqueId();
a.hide();this.hidden[d]=a;delete this.visible[d]},showLine:function(a){var d=a.getUniqueId();a.show();this.visible[d]=a;delete this.hidden[d]},hideVisible:function(){for(var a in this.visible)this.hideLine(this.visible[a])},placeLine:function(a,d){var b,c,e;if(b=this.getStyle(a.uid,a.type)){for(e in this.visible)if(this.visible[e].getCustomData("hash")!==this.hash){c=this.visible[e];break}if(!c)for(e in this.hidden)if(this.hidden[e].getCustomData("hash")!==this.hash){this.showLine(c=this.hidden[e]);
break}c||this.showLine(c=this.addLine());c.setCustomData("hash",this.hash);this.visible[c.getUniqueId()]=c;c.setStyles(b);d&&d(c)}},getStyle:function(a,d){var b=this.relations[a],c=this.locations[a][d],e={};e.width=b.siblingRect?Math.max(b.siblingRect.width,b.elementRect.width):b.elementRect.width;e.top=this.inline?c+this.winTopScroll.y-this.rect.relativeY:this.rect.top+this.winTopScroll.y+c;if(e.top-this.winTopScroll.y<this.rect.top||e.top-this.winTopScroll.y>this.rect.bottom)return!1;this.inline?
e.left=b.elementRect.left-this.rect.relativeX:(0<b.elementRect.left?e.left=this.rect.left+b.elementRect.left:(e.width+=b.elementRect.left,e.left=this.rect.left),0<(b=e.left+e.width-(this.rect.left+this.winPane.width))&&(e.width-=b));e.left+=this.winTopScroll.x;for(var g in e)e[g]=CKEDITOR.tools.cssLength(e[g]);return e},addLine:function(){var a=CKEDITOR.dom.element.createFromHtml(this.lineTpl);a.appendTo(this.container);return a},prepare:function(a,d){this.relations=a;this.locations=d;this.hash=Math.random()},
cleanup:function(){var a,d;for(d in this.visible)a=this.visible[d],a.getCustomData("hash")!==this.hash&&this.hideLine(a)},queryViewport:function(){this.winPane=this.win.getViewPaneSize();this.winTopScroll=this.winTop.getScrollPosition();this.winTopPane=this.winTop.getViewPaneSize();this.rect=this.getClientRect(this.inline?this.editable:this.frame)},getClientRect:function(a){a=a.getClientRect();var d=this.container.getDocumentPosition(),b=this.container.getComputedStyle("position");a.relativeX=a.relativeY=
0;"static"!=b&&(a.relativeY=d.y,a.relativeX=d.x,a.top-=a.relativeY,a.bottom-=a.relativeY,a.left-=a.relativeX,a.right-=a.relativeX);return a}};var r={left:1,right:1,center:1},u={absolute:1,fixed:1};CKEDITOR.plugins.lineutils={finder:m,locator:n,liner:p}})();(function(){function e(a){return a.getName&&!a.hasAttribute("data-cke-temp")}CKEDITOR.plugins.add("widgetselection",{init:function(a){if(CKEDITOR.env.webkit){var b=CKEDITOR.plugins.widgetselection;a.on("contentDom",function(a){a=a.editor;var c=a.editable();c.attachListener(c,"keydown",function(a){a.data.getKeystroke()==CKEDITOR.CTRL+65&&CKEDITOR.tools.setTimeout(function(){b.addFillers(c)||b.removeFillers(c)},0)},null,null,-1);a.on("selectionCheck",function(a){b.removeFillers(a.editor.editable())});
a.on("paste",function(a){a.data.dataValue=b.cleanPasteData(a.data.dataValue)});"selectall"in a.plugins&&b.addSelectAllIntegration(a)})}}});CKEDITOR.plugins.widgetselection={startFiller:null,endFiller:null,fillerAttribute:"data-cke-filler-webkit",fillerContent:"\x26nbsp;",fillerTagName:"div",addFillers:function(a){var b=a.editor;if(!this.isWholeContentSelected(a)&&0<a.getChildCount()){var d=a.getFirst(e),c=a.getLast(e);d&&d.type==CKEDITOR.NODE_ELEMENT&&!d.isEditable()&&(this.startFiller=this.createFiller(),
a.append(this.startFiller,1));c&&c.type==CKEDITOR.NODE_ELEMENT&&!c.isEditable()&&(this.endFiller=this.createFiller(!0),a.append(this.endFiller,0));if(this.hasFiller(a))return b=b.createRange(),b.selectNodeContents(a),b.select(),!0}return!1},removeFillers:function(a){if(this.hasFiller(a)&&!this.isWholeContentSelected(a)){var b=a.findOne(this.fillerTagName+"["+this.fillerAttribute+"\x3dstart]"),d=a.findOne(this.fillerTagName+"["+this.fillerAttribute+"\x3dend]");this.startFiller&&b&&this.startFiller.equals(b)?
this.removeFiller(this.startFiller,a):this.startFiller=b;this.endFiller&&d&&this.endFiller.equals(d)?this.removeFiller(this.endFiller,a):this.endFiller=d}},cleanPasteData:function(a){a&&a.length&&(a=a.replace(this.createFillerRegex(),"").replace(this.createFillerRegex(!0),""));return a},isWholeContentSelected:function(a){var b=a.editor.getSelection().getRanges()[0];return!b||b&&b.collapsed?!1:(b=b.clone(),b.enlarge(CKEDITOR.ENLARGE_ELEMENT),!!(b&&a&&b.startContainer&&b.endContainer&&0===b.startOffset&&
b.endOffset===a.getChildCount()&&b.startContainer.equals(a)&&b.endContainer.equals(a)))},hasFiller:function(a){return 0<a.find(this.fillerTagName+"["+this.fillerAttribute+"]").count()},createFiller:function(a){var b=new CKEDITOR.dom.element(this.fillerTagName);b.setHtml(this.fillerContent);b.setAttribute(this.fillerAttribute,a?"end":"start");b.setAttribute("data-cke-temp",1);b.setStyles({display:"block",width:0,height:0,padding:0,border:0,margin:0,position:"absolute",top:0,left:"-9999px",opacity:0,
overflow:"hidden"});return b},removeFiller:function(a,b){if(a){var d=b.editor,c=b.editor.getSelection().getRanges()[0].startPath(),f=d.createRange(),g,e;c.contains(a)&&(g=a.getHtml(),e=!0);c="start"==a.getAttribute(this.fillerAttribute);a.remove();g&&0<g.length&&g!=this.fillerContent?(b.insertHtmlIntoRange(g,d.getSelection().getRanges()[0]),f.setStartAt(b.getChild(b.getChildCount()-1),CKEDITOR.POSITION_BEFORE_END),d.getSelection().selectRanges([f])):e&&(c?f.setStartAt(b.getFirst().getNext(),CKEDITOR.POSITION_AFTER_START):
f.setEndAt(b.getLast().getPrevious(),CKEDITOR.POSITION_BEFORE_END),b.editor.getSelection().selectRanges([f]))}},createFillerRegex:function(a){var b=this.createFiller(a).getOuterHtml().replace(/style="[^"]*"/gi,'style\x3d"[^"]*"').replace(/>[^<]*</gi,"\x3e[^\x3c]*\x3c");return new RegExp((a?"":"^")+b+(a?"$":""))},addSelectAllIntegration:function(a){var b=this;a.editable().attachListener(a,"beforeCommandExec",function(d){var c=a.editable();"selectAll"==d.data.name&&c&&b.addFillers(c)},null,null,9999)}}})();(function(){function p(a){this.editor=a;this.registered={};this.instances={};this.selected=[];this.widgetHoldingFocusedEditable=this.focused=null;this._={nextId:0,upcasts:[],upcastCallbacks:[],filters:{}};I(this);J(this);this.on("checkWidgets",K);this.editor.on("contentDomInvalidated",this.checkWidgets,this);L(this);M(this);N(this);O(this);P(this)}function g(a,b,c,d,e){var f=a.editor;CKEDITOR.tools.extend(this,d,{editor:f,id:b,inline:"span"==c.getParent().getName(),element:c,data:CKEDITOR.tools.extend({},
"function"==typeof d.defaults?d.defaults():d.defaults),dataReady:!1,inited:!1,ready:!1,edit:g.prototype.edit,focusedEditable:null,definition:d,repository:a,draggable:!1!==d.draggable,_:{downcastFn:d.downcast&&"string"==typeof d.downcast?d.downcasts[d.downcast]:d.downcast}},!0);a.fire("instanceCreated",this);Q(this,d);this.init&&this.init();this.inited=!0;(a=this.element.data("cke-widget-data"))&&this.setData(JSON.parse(decodeURIComponent(a)));e&&this.setData(e);this.data.classes||this.setData("classes",
this.getClasses());this.dataReady=!0;r(this);this.fire("data",this.data);this.isInited()&&f.editable().contains(this.wrapper)&&(this.ready=!0,this.fire("ready"))}function q(a,b,c){CKEDITOR.dom.element.call(this,b.$);this.editor=a;this._={};b=this.filter=c.filter;CKEDITOR.dtd[this.getName()].p?(this.enterMode=b?b.getAllowedEnterMode(a.enterMode):a.enterMode,this.shiftEnterMode=b?b.getAllowedEnterMode(a.shiftEnterMode,!0):a.shiftEnterMode):this.enterMode=this.shiftEnterMode=CKEDITOR.ENTER_BR}function R(a,
b){a.addCommand(b.name,{exec:function(a,d){function e(){a.widgets.finalizeCreation(k)}var f=a.widgets.focused;if(f&&f.name==b.name)f.edit();else if(b.insert)b.insert();else if(b.template){var f="function"==typeof b.defaults?b.defaults():b.defaults,f=CKEDITOR.dom.element.createFromHtml(b.template.output(f)),h,l=a.widgets.wrapElement(f,b.name),k=new CKEDITOR.dom.documentFragment(l.getDocument());k.append(l);(h=a.widgets.initOn(f,b,d&&d.startupData))?(f=h.once("edit",function(b){if(b.data.dialog)h.once("dialog",
function(b){b=b.data;var d,f;d=b.once("ok",e,null,null,20);f=b.once("cancel",function(b){b.data&&!1===b.data.hide||a.widgets.destroy(h,!0)});b.once("hide",function(){d.removeListener();f.removeListener()})});else e()},null,null,999),h.edit(),f.removeListener()):e()}},allowedContent:b.allowedContent,requiredContent:b.requiredContent,contentForms:b.contentForms,contentTransformations:b.contentTransformations})}function S(a,b){function c(a,c){var d=b.upcast.split(","),e,f;for(f=0;f<d.length;f++)if(e=
d[f],e===a.name)return b.upcasts[e].call(this,a,c);return!1}function d(b,c,d){var e=CKEDITOR.tools.getIndex(a._.upcasts,function(a){return a[2]>d});0>e&&(e=a._.upcasts.length);a._.upcasts.splice(e,0,[CKEDITOR.tools.bind(b,c),c.name,d])}var e=b.upcast,f=b.upcastPriority||10;e&&("string"==typeof e?d(c,b,f):d(e,b,f))}function t(a,b){a.focused=null;if(b.isInited()){var c=b.editor.checkDirty();a.fire("widgetBlurred",{widget:b});b.setFocused(!1);!c&&b.editor.resetDirty()}}function K(a){a=a.data;if("wysiwyg"==
this.editor.mode){var b=this.editor.editable(),c=this.instances,d,e,f,h;if(b){for(d in c)c[d].isReady()&&!b.contains(c[d].wrapper)&&this.destroy(c[d],!0);if(a&&a.initOnlyNew)c=this.initOnAll();else{var l=b.find(".cke_widget_wrapper"),c=[];d=0;for(e=l.count();d<e;d++){f=l.getItem(d);if(h=!this.getByElement(f,!0)){a:{h=T;for(var k=f;k=k.getParent();)if(h(k)){h=!0;break a}h=!1}h=!h}h&&b.contains(f)&&(f.addClass("cke_widget_new"),c.push(this.initOn(f.getFirst(g.isDomWidgetElement))))}}a&&a.focusInited&&
1==c.length&&c[0].focus()}}}function u(a){if("undefined"!=typeof a.attributes&&a.attributes["data-widget"]){var b=v(a),c=w(a),d=!1;b&&b.value&&b.value.match(/^\s/g)&&(b.parent.attributes["data-cke-white-space-first"]=1,b.value=b.value.replace(/^\s/g,"\x26nbsp;"),d=!0);c&&c.value&&c.value.match(/\s$/g)&&(c.parent.attributes["data-cke-white-space-last"]=1,c.value=c.value.replace(/\s$/g,"\x26nbsp;"),d=!0);d&&(a.attributes["data-cke-widget-white-space"]=1)}}function v(a){return a.find(function(a){return 3===
a.type},!0).shift()}function w(a){return a.find(function(a){return 3===a.type},!0).pop()}function x(a,b,c){if(!c.allowedContent&&!c.disallowedContent)return null;var d=this._.filters[a];d||(this._.filters[a]=d={});a=d[b];a||(a=c.allowedContent?new CKEDITOR.filter(c.allowedContent):this.editor.filter.clone(),d[b]=a,c.disallowedContent&&a.disallow(c.disallowedContent));return a}function U(a){var b=[],c=a._.upcasts,d=a._.upcastCallbacks;return{toBeWrapped:b,iterator:function(a){var f,h,l,k,m;if("data-cke-widget-wrapper"in
a.attributes)return(a=a.getFirst(g.isParserWidgetElement))&&b.push([a]),!1;if("data-widget"in a.attributes)return b.push([a]),!1;if(m=c.length){if(a.attributes["data-cke-widget-upcasted"])return!1;k=0;for(f=d.length;k<f;++k)if(!1===d[k](a))return;for(k=0;k<m;++k)if(f=c[k],l={},h=f[0](a,l))return h instanceof CKEDITOR.htmlParser.element&&(a=h),a.attributes["data-cke-widget-data"]=encodeURIComponent(JSON.stringify(l)),a.attributes["data-cke-widget-upcasted"]=1,b.push([a,f[1]]),!1}}}}function y(a,b){return{tabindex:-1,
contenteditable:"false","data-cke-widget-wrapper":1,"data-cke-filter":"off","class":"cke_widget_wrapper cke_widget_new cke_widget_"+(a?"inline":"block")+(b?" cke_widget_"+b:"")}}function z(a,b,c){if(a.type==CKEDITOR.NODE_ELEMENT){var d=CKEDITOR.dtd[a.name];if(d&&!d[c.name]){var d=a.split(b),e=a.parent;b=d.getIndex();a.children.length||(--b,a.remove());d.children.length||d.remove();return z(e,b,c)}}a.add(c,b)}function A(a,b){return"boolean"==typeof a.inline?a.inline:!!CKEDITOR.dtd.$inline[b]}function T(a){return a.hasAttribute("data-cke-temp")}
function n(a,b,c,d){var e=a.editor;e.fire("lockSnapshot");c?(d=c.data("cke-widget-editable"),d=b.editables[d],a.widgetHoldingFocusedEditable=b,b.focusedEditable=d,c.addClass("cke_widget_editable_focused"),d.filter&&e.setActiveFilter(d.filter),e.setActiveEnterMode(d.enterMode,d.shiftEnterMode)):(d||b.focusedEditable.removeClass("cke_widget_editable_focused"),b.focusedEditable=null,a.widgetHoldingFocusedEditable=null,e.setActiveFilter(null),e.setActiveEnterMode(null,null));e.fire("unlockSnapshot")}
function V(a){a.contextMenu&&a.contextMenu.addListener(function(b){if(b=a.widgets.getByElement(b,!0))return b.fire("contextMenu",{})})}function W(a,b){return CKEDITOR.tools.trim(b)}function O(a){var b=a.editor,c=CKEDITOR.plugins.lineutils;b.on("dragstart",function(c){var e=c.data.target;g.isDomDragHandler(e)&&(e=a.getByElement(e),c.data.dataTransfer.setData("cke/widget-id",e.id),b.focus(),e.focus())});b.on("drop",function(c){var e=c.data.dataTransfer,f=e.getData("cke/widget-id"),h=e.getTransferType(b),
e=b.createRange();""!==f&&h===CKEDITOR.DATA_TRANSFER_CROSS_EDITORS?c.cancel():""!==f&&h==CKEDITOR.DATA_TRANSFER_INTERNAL&&(f=a.instances[f])&&(e.setStartBefore(f.wrapper),e.setEndAfter(f.wrapper),c.data.dragRange=e,delete CKEDITOR.plugins.clipboard.dragStartContainerChildCount,delete CKEDITOR.plugins.clipboard.dragEndContainerChildCount,c.data.dataTransfer.setData("text/html",b.editable().getHtmlFromRange(e).getHtml()),b.widgets.destroy(f,!0))});b.on("contentDom",function(){var d=b.editable();CKEDITOR.tools.extend(a,
{finder:new c.finder(b,{lookups:{"default":function(b){if(!b.is(CKEDITOR.dtd.$listItem)&&b.is(CKEDITOR.dtd.$block)&&!g.isDomNestedEditable(b)&&!a._.draggedWidget.wrapper.contains(b)){var c=g.getNestedEditable(d,b);if(c){b=a._.draggedWidget;if(a.getByElement(c)==b)return;c=CKEDITOR.filter.instances[c.data("cke-filter")];b=b.requiredContent;if(c&&b&&!c.check(b))return}return CKEDITOR.LINEUTILS_BEFORE|CKEDITOR.LINEUTILS_AFTER}}}}),locator:new c.locator(b),liner:new c.liner(b,{lineStyle:{cursor:"move !important",
"border-top-color":"#666"},tipLeftStyle:{"border-left-color":"#666"},tipRightStyle:{"border-right-color":"#666"}})},!0)})}function M(a){var b=a.editor;b.on("contentDom",function(){var c=b.editable(),d=c.isInline()?c:b.document,e,f;c.attachListener(d,"mousedown",function(c){var d=c.data.getTarget();e=d instanceof CKEDITOR.dom.element?a.getByElement(d):null;f=0;e&&(e.inline&&d.type==CKEDITOR.NODE_ELEMENT&&d.hasAttribute("data-cke-widget-drag-handler")?(f=1,a.focused!=e&&b.getSelection().removeAllRanges()):
g.getNestedEditable(e.wrapper,d)?e=null:(c.data.preventDefault(),CKEDITOR.env.ie||e.focus()))});c.attachListener(d,"mouseup",function(){f&&e&&e.wrapper&&(f=0,e.focus())});CKEDITOR.env.ie&&c.attachListener(d,"mouseup",function(){setTimeout(function(){e&&e.wrapper&&c.contains(e.wrapper)&&(e.focus(),e=null)})})});b.on("doubleclick",function(b){var d=a.getByElement(b.data.element);if(d&&!g.getNestedEditable(d.wrapper,b.data.element))return d.fire("doubleclick",{element:b.data.element})},null,null,1)}
function N(a){a.editor.on("key",function(b){var c=a.focused,d=a.widgetHoldingFocusedEditable,e;c?e=c.fire("key",{keyCode:b.data.keyCode}):d&&(c=b.data.keyCode,b=d.focusedEditable,c==CKEDITOR.CTRL+65?(c=b.getBogus(),d=d.editor.createRange(),d.selectNodeContents(b),c&&d.setEndAt(c,CKEDITOR.POSITION_BEFORE_START),d.select(),e=!1):8==c||46==c?(e=d.editor.getSelection().getRanges(),d=e[0],e=!(1==e.length&&d.collapsed&&d.checkBoundaryOfElement(b,CKEDITOR[8==c?"START":"END"]))):e=void 0);return e},null,
null,1)}function P(a){function b(b){a.focused&&B(a.focused,"cut"==b.name)}var c=a.editor;c.on("contentDom",function(){var a=c.editable();a.attachListener(a,"copy",b);a.attachListener(a,"cut",b)})}function L(a){var b=a.editor;b.on("selectionCheck",function(){a.fire("checkSelection")});a.on("checkSelection",a.checkSelection,a);b.on("selectionChange",function(c){var d=(c=g.getNestedEditable(b.editable(),c.data.selection.getStartElement()))&&a.getByElement(c),e=a.widgetHoldingFocusedEditable;e?e===d&&
e.focusedEditable.equals(c)||(n(a,e,null),d&&c&&n(a,d,c)):d&&c&&n(a,d,c)});b.on("dataReady",function(){C(a).commit()});b.on("blur",function(){var b;(b=a.focused)&&t(a,b);(b=a.widgetHoldingFocusedEditable)&&n(a,b,null)})}function J(a){var b=a.editor,c={};b.on("toDataFormat",function(b){var e=CKEDITOR.tools.getNextNumber(),f=[];b.data.downcastingSessionId=e;c[e]=f;b.data.dataValue.forEach(function(b){var c=b.attributes,d;if("data-cke-widget-white-space"in c){d=v(b);var e=w(b);d.parent.attributes["data-cke-white-space-first"]&&
(d.value=d.value.replace(/^&nbsp;/g," "));e.parent.attributes["data-cke-white-space-last"]&&(e.value=e.value.replace(/&nbsp;$/g," "))}if("data-cke-widget-id"in c){if(c=a.instances[c["data-cke-widget-id"]])d=b.getFirst(g.isParserWidgetElement),f.push({wrapper:b,element:d,widget:c,editables:{}}),"1"!=d.attributes["data-cke-widget-keep-attr"]&&delete d.attributes["data-widget"]}else if("data-cke-widget-editable"in c)return f[f.length-1].editables[c["data-cke-widget-editable"]]=b,!1},CKEDITOR.NODE_ELEMENT,
!0)},null,null,8);b.on("toDataFormat",function(a){if(a.data.downcastingSessionId){a=c[a.data.downcastingSessionId];for(var b,f,h,l,g,m;b=a.shift();){f=b.widget;h=b.element;l=f._.downcastFn&&f._.downcastFn.call(f,h);for(m in b.editables)g=b.editables[m],delete g.attributes.contenteditable,g.setHtml(f.editables[m].getData());l||(l=h);b.wrapper.replaceWith(l)}}},null,null,13);b.on("contentDomUnload",function(){a.destroyAll(!0)})}function I(a){var b=a.editor,c,d;b.on("toHtml",function(b){var d=U(a),h;
for(b.data.dataValue.forEach(d.iterator,CKEDITOR.NODE_ELEMENT,!0);h=d.toBeWrapped.pop();){var l=h[0],k=l.parent;k.type==CKEDITOR.NODE_ELEMENT&&k.attributes["data-cke-widget-wrapper"]&&k.replaceWith(l);a.wrapElement(h[0],h[1])}c=b.data.protectedWhitespaces?3==b.data.dataValue.children.length&&g.isParserWidgetWrapper(b.data.dataValue.children[1]):1==b.data.dataValue.children.length&&g.isParserWidgetWrapper(b.data.dataValue.children[0])},null,null,8);b.on("dataReady",function(){if(d)for(var c=b.editable().find(".cke_widget_wrapper"),
f,h,l=0,k=c.count();l<k;++l)f=c.getItem(l),h=f.getFirst(g.isDomWidgetElement),h.type==CKEDITOR.NODE_ELEMENT&&h.data("widget")?(h.replace(f),a.wrapElement(h)):f.remove();d=0;a.destroyAll(!0);a.initOnAll()});b.on("loadSnapshot",function(b){/data-cke-widget/.test(b.data)&&(d=1);a.destroyAll(!0)},null,null,9);b.on("paste",function(a){a=a.data;a.dataValue=a.dataValue.replace(X,W);a.range&&(a=g.getNestedEditable(b.editable(),a.range.startContainer))&&(a=CKEDITOR.filter.instances[a.data("cke-filter")])&&
b.setActiveFilter(a)});b.on("afterInsertHtml",function(d){d.data.intoRange?a.checkWidgets({initOnlyNew:!0}):(b.fire("lockSnapshot"),a.checkWidgets({initOnlyNew:!0,focusInited:c}),b.fire("unlockSnapshot"))})}function C(a){var b=a.selected,c=[],d=b.slice(0),e=null;return{select:function(a){0>CKEDITOR.tools.indexOf(b,a)&&c.push(a);a=CKEDITOR.tools.indexOf(d,a);0<=a&&d.splice(a,1);return this},focus:function(a){e=a;return this},commit:function(){var f=a.focused!==e,h,g;a.editor.fire("lockSnapshot");for(f&&
(h=a.focused)&&t(a,h);h=d.pop();)b.splice(CKEDITOR.tools.indexOf(b,h),1),h.isInited()&&(g=h.editor.checkDirty(),h.setSelected(!1),!g&&h.editor.resetDirty());f&&e&&(g=a.editor.checkDirty(),a.focused=e,a.fire("widgetFocused",{widget:e}),e.setFocused(!0),!g&&a.editor.resetDirty());for(;h=c.pop();)b.push(h),h.setSelected(!0);a.editor.fire("unlockSnapshot")}}}function D(a,b,c){var d=0;b=E(b);var e=a.data.classes||{},f;if(b){for(e=CKEDITOR.tools.clone(e);f=b.pop();)c?e[f]||(d=e[f]=1):e[f]&&(delete e[f],
d=1);d&&a.setData("classes",e)}}function F(a){a.cancel()}function B(a,b){var c=a.editor,d=c.document,e=CKEDITOR.env.edge&&16<=CKEDITOR.env.version;if(!d.getById("cke_copybin")){var f=!c.blockless&&!CKEDITOR.env.ie||e?"div":"span",e=d.createElement(f),h=d.createElement(f),f=CKEDITOR.env.ie&&9>CKEDITOR.env.version;h.setAttributes({id:"cke_copybin","data-cke-temp":"1"});e.setStyles({position:"absolute",width:"1px",height:"1px",overflow:"hidden"});e.setStyle("ltr"==c.config.contentsLangDirection?"left":
"right","-5000px");var g=c.createRange();g.setStartBefore(a.wrapper);g.setEndAfter(a.wrapper);e.setHtml('\x3cspan data-cke-copybin-start\x3d"1"\x3e​\x3c/span\x3e'+c.editable().getHtmlFromRange(g).getHtml()+'\x3cspan data-cke-copybin-end\x3d"1"\x3e​\x3c/span\x3e');c.fire("saveSnapshot");c.fire("lockSnapshot");h.append(e);c.editable().append(h);var k=c.on("selectionChange",F,null,null,0),m=a.repository.on("checkSelection",F,null,null,0);if(f)var n=d.getDocumentElement().$,p=n.scrollTop;g=c.createRange();
g.selectNodeContents(e);g.select();f&&(n.scrollTop=p);setTimeout(function(){b||a.focus();h.remove();k.removeListener();m.removeListener();c.fire("unlockSnapshot");b&&!c.readOnly&&(a.repository.del(a),c.fire("saveSnapshot"))},100)}}function E(a){return(a=(a=a.getDefinition().attributes)&&a["class"])?a.split(/\s+/):null}function G(){var a=CKEDITOR.document.getActive(),b=this.editor,c=b.editable();(c.isInline()?c:b.document.getWindow().getFrame()).equals(a)&&b.focusManager.focus(c)}function H(){CKEDITOR.env.gecko&&
this.editor.unlockSelection();CKEDITOR.env.webkit||(this.editor.forceNextSelectionCheck(),this.editor.selectionChange(1))}function Y(a){var b=null;a.on("data",function(){var a=this.data.classes,d;if(b!=a){for(d in b)a&&a[d]||this.removeClass(d);for(d in a)this.addClass(d);b=a}})}function Z(a){a.on("data",function(){if(a.wrapper){var b=this.getLabel?this.getLabel():this.editor.lang.widget.label.replace(/%1/,this.pathName||this.element.getName());a.wrapper.setAttribute("role","region");a.wrapper.setAttribute("aria-label",
b)}},null,null,9999)}function aa(a){if(a.draggable){var b=a.editor,c=a.wrapper.getLast(g.isDomDragHandlerContainer),d;c?d=c.findOne("img"):(c=new CKEDITOR.dom.element("span",b.document),c.setAttributes({"class":"cke_reset cke_widget_drag_handler_container",style:"background:rgba(220,220,220,0.5);background-image:url("+b.plugins.widget.path+"images/handle.png)"}),d=new CKEDITOR.dom.element("img",b.document),d.setAttributes({"class":"cke_reset cke_widget_drag_handler","data-cke-widget-drag-handler":"1",
src:CKEDITOR.tools.transparentImageData,width:15,title:b.lang.widget.move,height:15,role:"presentation"}),a.inline&&d.setAttribute("draggable","true"),c.append(d),a.wrapper.append(c));a.wrapper.on("dragover",function(a){a.data.preventDefault()});a.wrapper.on("mouseenter",a.updateDragHandlerPosition,a);setTimeout(function(){a.on("data",a.updateDragHandlerPosition,a)},50);if(!a.inline&&(d.on("mousedown",ba,a),CKEDITOR.env.ie&&9>CKEDITOR.env.version))d.on("dragstart",function(a){a.data.preventDefault(!0)});
a.dragHandlerContainer=c}}function ba(a){function b(){var b;for(q.reset();b=g.pop();)b.removeListener();var c=k;b=a.sender;var d=this.repository.finder,e=this.repository.liner,f=this.editor,h=this.editor.editable();CKEDITOR.tools.isEmpty(e.visible)||(c=d.getRange(c[0]),this.focus(),f.fire("drop",{dropRange:c,target:c.startContainer}));h.removeClass("cke_widget_dragging");e.hideVisible();f.fire("dragend",{target:b})}if(CKEDITOR.tools.getMouseButton(a)===CKEDITOR.MOUSE_BUTTON_LEFT){var c=this.repository.finder,
d=this.repository.locator,e=this.repository.liner,f=this.editor,h=f.editable(),g=[],k=[],m,n;this.repository._.draggedWidget=this;var p=c.greedySearch(),q=CKEDITOR.tools.eventsBuffer(50,function(){m=d.locate(p);k=d.sort(n,1);k.length&&(e.prepare(p,m),e.placeLine(k[0]),e.cleanup())});h.addClass("cke_widget_dragging");g.push(h.on("mousemove",function(a){n=a.data.$.clientY;q.input()}));f.fire("dragstart",{target:a.sender});g.push(f.document.once("mouseup",b,this));h.isInline()||g.push(CKEDITOR.document.once("mouseup",
b,this))}}function ca(a){var b,c,d=a.editables;a.editables={};if(a.editables)for(b in d)c=d[b],a.initEditable(b,"string"==typeof c?{selector:c}:c)}function da(a){if(a.mask){var b=a.wrapper.findOne(".cke_widget_mask");b||(b=new CKEDITOR.dom.element("img",a.editor.document),b.setAttributes({src:CKEDITOR.tools.transparentImageData,"class":"cke_reset cke_widget_mask"}),a.wrapper.append(b));a.mask=b}}function ea(a){if(a.parts){var b={},c,d;for(d in a.parts)c=a.wrapper.findOne(a.parts[d]),b[d]=c;a.parts=
b}}function Q(a,b){fa(a);ea(a);ca(a);da(a);aa(a);Y(a);Z(a);if(CKEDITOR.env.ie&&9>CKEDITOR.env.version)a.wrapper.on("dragstart",function(b){var d=b.data.getTarget();g.getNestedEditable(a,d)||a.inline&&g.isDomDragHandler(d)||b.data.preventDefault()});a.wrapper.removeClass("cke_widget_new");a.element.addClass("cke_widget_element");a.on("key",function(b){b=b.data.keyCode;if(13==b)a.edit();else{if(b==CKEDITOR.CTRL+67||b==CKEDITOR.CTRL+88){B(a,b==CKEDITOR.CTRL+88);return}if(b in ga||CKEDITOR.CTRL&b||CKEDITOR.ALT&
b)return}return!1},null,null,999);a.on("doubleclick",function(b){a.edit()&&b.cancel()});if(b.data)a.on("data",b.data);if(b.edit)a.on("edit",b.edit)}function fa(a){(a.wrapper=a.element.getParent()).setAttribute("data-cke-widget-id",a.id)}function r(a){a.element.data("cke-widget-data",encodeURIComponent(JSON.stringify(a.data)))}function ha(){function a(){}function b(a,b,c){return c&&this.checkElement(a)?(a=c.widgets.getByElement(a,!0))&&a.checkStyleActive(this):!1}var c={};CKEDITOR.style.addCustomHandler({type:"widget",
setup:function(a){this.widget=a.widget;if(this.group="string"==typeof a.group?[a.group]:a.group){a=this.widget;var b;c[a]||(c[a]={});for(var f=0,h=this.group.length;f<h;f++)b=this.group[f],c[a][b]||(c[a][b]=[]),c[a][b].push(this)}},apply:function(a){var b;a instanceof CKEDITOR.editor&&this.checkApplicable(a.elementPath(),a)&&(b=a.widgets.focused,this.group&&this.removeStylesFromSameGroup(a),b.applyStyle(this))},remove:function(a){a instanceof CKEDITOR.editor&&this.checkApplicable(a.elementPath(),
a)&&a.widgets.focused.removeStyle(this)},removeStylesFromSameGroup:function(a){var b,f,h=!1;if(!(a instanceof CKEDITOR.editor))return!1;f=a.elementPath();if(this.checkApplicable(f,a))for(var g=0,k=this.group.length;g<k;g++){b=c[this.widget][this.group[g]];for(var m=0;m<b.length;m++)b[m]!==this&&b[m].checkActive(f,a)&&(a.widgets.focused.removeStyle(b[m]),h=!0)}return h},checkActive:function(a,b){return this.checkElementMatch(a.lastElement,0,b)},checkApplicable:function(a,b){return b instanceof CKEDITOR.editor?
this.checkElement(a.lastElement):!1},checkElementMatch:b,checkElementRemovable:b,checkElement:function(a){return g.isDomWidgetWrapper(a)?(a=a.getFirst(g.isDomWidgetElement))&&a.data("widget")==this.widget:!1},buildPreview:function(a){return a||this._.definition.name},toAllowedContentRules:function(a){if(!a)return null;a=a.widgets.registered[this.widget];var b,c={};if(!a)return null;if(a.styleableElements){b=this.getClassesArray();if(!b)return null;c[a.styleableElements]={classes:b,propertiesOnly:!0};
return c}return a.styleToAllowedContentRules?a.styleToAllowedContentRules(this):null},getClassesArray:function(){var a=this._.definition.attributes&&this._.definition.attributes["class"];return a?CKEDITOR.tools.trim(a).split(/\s+/):null},applyToRange:a,removeFromRange:a,applyToObject:a})}CKEDITOR.plugins.add("widget",{requires:"lineutils,clipboard,widgetselection",onLoad:function(){void 0!==CKEDITOR.document.$.querySelectorAll&&(CKEDITOR.addCss(".cke_widget_wrapper{position:relative;outline:none}.cke_widget_inline{display:inline-block}.cke_widget_wrapper:hover\x3e.cke_widget_element{outline:2px solid #ffd25c;cursor:default}.cke_widget_wrapper:hover .cke_widget_editable{outline:2px solid #ffd25c}.cke_widget_wrapper.cke_widget_focused\x3e.cke_widget_element,.cke_widget_wrapper .cke_widget_editable.cke_widget_editable_focused{outline:2px solid #47a4f5}.cke_widget_editable{cursor:text}.cke_widget_drag_handler_container{position:absolute;width:15px;height:0;display:none;opacity:0.75;transition:height 0s 0.2s;line-height:0}.cke_widget_wrapper:hover\x3e.cke_widget_drag_handler_container{height:15px;transition:none}.cke_widget_drag_handler_container:hover{opacity:1}img.cke_widget_drag_handler{cursor:move;width:15px;height:15px;display:inline-block}.cke_widget_mask{position:absolute;top:0;left:0;width:100%;height:100%;display:block}.cke_editable.cke_widget_dragging, .cke_editable.cke_widget_dragging *{cursor:move !important}"),
ha())},beforeInit:function(a){void 0!==CKEDITOR.document.$.querySelectorAll&&(a.widgets=new p(a))},afterInit:function(a){if(void 0!==CKEDITOR.document.$.querySelectorAll){var b=a.widgets.registered,c,d,e;for(d in b)c=b[d],(e=c.button)&&a.ui.addButton&&a.ui.addButton(CKEDITOR.tools.capitalize(c.name,!0),{label:e,command:c.name,toolbar:"insert,10"});V(a)}}});p.prototype={MIN_SELECTION_CHECK_INTERVAL:500,add:function(a,b){b=CKEDITOR.tools.prototypedCopy(b);b.name=a;b._=b._||{};this.editor.fire("widgetDefinition",
b);b.template&&(b.template=new CKEDITOR.template(b.template));R(this.editor,b);S(this,b);return this.registered[a]=b},addUpcastCallback:function(a){this._.upcastCallbacks.push(a)},checkSelection:function(){var a=this.editor.getSelection(),b=a.getSelectedElement(),c=C(this),d;if(b&&(d=this.getByElement(b,!0)))return c.focus(d).select(d).commit();a=a.getRanges()[0];if(!a||a.collapsed)return c.commit();a=new CKEDITOR.dom.walker(a);for(a.evaluator=g.isDomWidgetWrapper;b=a.next();)c.select(this.getByElement(b));
c.commit()},checkWidgets:function(a){this.fire("checkWidgets",CKEDITOR.tools.copy(a||{}))},del:function(a){if(this.focused===a){var b=a.editor,c=b.createRange(),d;(d=c.moveToClosestEditablePosition(a.wrapper,!0))||(d=c.moveToClosestEditablePosition(a.wrapper,!1));d&&b.getSelection().selectRanges([c])}a.wrapper.remove();this.destroy(a,!0)},destroy:function(a,b){this.widgetHoldingFocusedEditable===a&&n(this,a,null,b);a.destroy(b);delete this.instances[a.id];this.fire("instanceDestroyed",a)},destroyAll:function(a,
b){var c,d,e=this.instances;if(b&&!a){d=b.find(".cke_widget_wrapper");for(var e=d.count(),f=0;f<e;++f)(c=this.getByElement(d.getItem(f),!0))&&this.destroy(c)}else for(d in e)c=e[d],this.destroy(c,a)},finalizeCreation:function(a){(a=a.getFirst())&&g.isDomWidgetWrapper(a)&&(this.editor.insertElement(a),a=this.getByElement(a),a.ready=!0,a.fire("ready"),a.focus())},getByElement:function(){function a(a){return a.is(b)&&a.data("cke-widget-id")}var b={div:1,span:1};return function(b,d){if(!b)return null;
var e=a(b);if(!d&&!e){var f=this.editor.editable();do b=b.getParent();while(b&&!b.equals(f)&&!(e=a(b)))}return this.instances[e]||null}}(),initOn:function(a,b,c){b?"string"==typeof b&&(b=this.registered[b]):b=this.registered[a.data("widget")];if(!b)return null;var d=this.wrapElement(a,b.name);return d?d.hasClass("cke_widget_new")?(a=new g(this,this._.nextId++,a,b,c),a.isInited()?this.instances[a.id]=a:null):this.getByElement(a):null},initOnAll:function(a){a=(a||this.editor.editable()).find(".cke_widget_new");
for(var b=[],c,d=a.count();d--;)(c=this.initOn(a.getItem(d).getFirst(g.isDomWidgetElement)))&&b.push(c);return b},onWidget:function(a){var b=Array.prototype.slice.call(arguments);b.shift();for(var c in this.instances){var d=this.instances[c];d.name==a&&d.on.apply(d,b)}this.on("instanceCreated",function(c){c=c.data;c.name==a&&c.on.apply(c,b)})},parseElementClasses:function(a){if(!a)return null;a=CKEDITOR.tools.trim(a).split(/\s+/);for(var b,c={},d=0;b=a.pop();)-1==b.indexOf("cke_")&&(c[b]=d=1);return d?
c:null},wrapElement:function(a,b){var c=null,d,e;if(a instanceof CKEDITOR.dom.element){b=b||a.data("widget");d=this.registered[b];if(!d)return null;if((c=a.getParent())&&c.type==CKEDITOR.NODE_ELEMENT&&c.data("cke-widget-wrapper"))return c;a.hasAttribute("data-cke-widget-keep-attr")||a.data("cke-widget-keep-attr",a.data("widget")?1:0);a.data("widget",b);(e=A(d,a.getName()))&&u(a);c=new CKEDITOR.dom.element(e?"span":"div");c.setAttributes(y(e,b));c.data("cke-display-name",d.pathName?d.pathName:a.getName());
a.getParent(!0)&&c.replace(a);a.appendTo(c)}else if(a instanceof CKEDITOR.htmlParser.element){b=b||a.attributes["data-widget"];d=this.registered[b];if(!d)return null;if((c=a.parent)&&c.type==CKEDITOR.NODE_ELEMENT&&c.attributes["data-cke-widget-wrapper"])return c;"data-cke-widget-keep-attr"in a.attributes||(a.attributes["data-cke-widget-keep-attr"]=a.attributes["data-widget"]?1:0);b&&(a.attributes["data-widget"]=b);(e=A(d,a.name))&&u(a);c=new CKEDITOR.htmlParser.element(e?"span":"div",y(e,b));c.attributes["data-cke-display-name"]=
d.pathName?d.pathName:a.name;d=a.parent;var f;d&&(f=a.getIndex(),a.remove());c.add(a);d&&z(d,f,c)}return c},_tests_createEditableFilter:x};CKEDITOR.event.implementOn(p.prototype);g.prototype={addClass:function(a){this.element.addClass(a);this.wrapper.addClass(g.WRAPPER_CLASS_PREFIX+a)},applyStyle:function(a){D(this,a,1)},checkStyleActive:function(a){a=E(a);var b;if(!a)return!1;for(;b=a.pop();)if(!this.hasClass(b))return!1;return!0},destroy:function(a){this.fire("destroy");if(this.editables)for(var b in this.editables)this.destroyEditable(b,
a);a||("0"==this.element.data("cke-widget-keep-attr")&&this.element.removeAttribute("data-widget"),this.element.removeAttributes(["data-cke-widget-data","data-cke-widget-keep-attr"]),this.element.removeClass("cke_widget_element"),this.element.replace(this.wrapper));this.wrapper=null},destroyEditable:function(a,b){var c=this.editables[a];c.removeListener("focus",H);c.removeListener("blur",G);this.editor.focusManager.remove(c);b||(this.repository.destroyAll(!1,c),c.removeClass("cke_widget_editable"),
c.removeClass("cke_widget_editable_focused"),c.removeAttributes(["contenteditable","data-cke-widget-editable","data-cke-enter-mode"]));delete this.editables[a]},edit:function(){var a={dialog:this.dialog},b=this;if(!1===this.fire("edit",a)||!a.dialog)return!1;this.editor.openDialog(a.dialog,function(a){var d,e;!1!==b.fire("dialog",a)&&(d=a.on("show",function(){a.setupContent(b)}),e=a.on("ok",function(){var d,e=b.on("data",function(a){d=1;a.cancel()},null,null,0);b.editor.fire("saveSnapshot");a.commitContent(b);
e.removeListener();d&&(b.fire("data",b.data),b.editor.fire("saveSnapshot"))}),a.once("hide",function(){d.removeListener();e.removeListener()}))});return!0},getClasses:function(){return this.repository.parseElementClasses(this.element.getAttribute("class"))},hasClass:function(a){return this.element.hasClass(a)},initEditable:function(a,b){var c=this._findOneNotNested(b.selector);return c&&c.is(CKEDITOR.dtd.$editable)?(c=new q(this.editor,c,{filter:x.call(this.repository,this.name,a,b)}),this.editables[a]=
c,c.setAttributes({contenteditable:"true","data-cke-widget-editable":a,"data-cke-enter-mode":c.enterMode}),c.filter&&c.data("cke-filter",c.filter.id),c.addClass("cke_widget_editable"),c.removeClass("cke_widget_editable_focused"),b.pathName&&c.data("cke-display-name",b.pathName),this.editor.focusManager.add(c),c.on("focus",H,this),CKEDITOR.env.ie&&c.on("blur",G,this),c._.initialSetData=!0,c.setData(c.getHtml()),!0):!1},_findOneNotNested:function(a){a=this.wrapper.find(a);for(var b,c,d=0;d<a.count();d++)if(b=
a.getItem(d),c=b.getAscendant(g.isDomWidgetWrapper),this.wrapper.equals(c))return b;return null},isInited:function(){return!(!this.wrapper||!this.inited)},isReady:function(){return this.isInited()&&this.ready},focus:function(){var a=this.editor.getSelection();if(a){var b=this.editor.checkDirty();a.fake(this.wrapper);!b&&this.editor.resetDirty()}this.editor.focus()},removeClass:function(a){this.element.removeClass(a);this.wrapper.removeClass(g.WRAPPER_CLASS_PREFIX+a)},removeStyle:function(a){D(this,
a,0)},setData:function(a,b){var c=this.data,d=0;if("string"==typeof a)c[a]!==b&&(c[a]=b,d=1);else{var e=a;for(a in e)c[a]!==e[a]&&(d=1,c[a]=e[a])}d&&this.dataReady&&(r(this),this.fire("data",c));return this},setFocused:function(a){this.wrapper[a?"addClass":"removeClass"]("cke_widget_focused");this.fire(a?"focus":"blur");return this},setSelected:function(a){this.wrapper[a?"addClass":"removeClass"]("cke_widget_selected");this.fire(a?"select":"deselect");return this},updateDragHandlerPosition:function(){var a=
this.editor,b=this.element.$,c=this._.dragHandlerOffset,b={x:b.offsetLeft,y:b.offsetTop-15};c&&b.x==c.x&&b.y==c.y||(c=a.checkDirty(),a.fire("lockSnapshot"),this.dragHandlerContainer.setStyles({top:b.y+"px",left:b.x+"px",display:"block"}),a.fire("unlockSnapshot"),!c&&a.resetDirty(),this._.dragHandlerOffset=b)}};CKEDITOR.event.implementOn(g.prototype);g.getNestedEditable=function(a,b){return!b||b.equals(a)?null:g.isDomNestedEditable(b)?b:g.getNestedEditable(a,b.getParent())};g.isDomDragHandler=function(a){return a.type==
CKEDITOR.NODE_ELEMENT&&a.hasAttribute("data-cke-widget-drag-handler")};g.isDomDragHandlerContainer=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&a.hasClass("cke_widget_drag_handler_container")};g.isDomNestedEditable=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&a.hasAttribute("data-cke-widget-editable")};g.isDomWidgetElement=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&a.hasAttribute("data-widget")};g.isDomWidgetWrapper=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&a.hasAttribute("data-cke-widget-wrapper")};
g.isDomWidget=function(a){return a?this.isDomWidgetWrapper(a)||this.isDomWidgetElement(a):!1};g.isParserWidgetElement=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&!!a.attributes["data-widget"]};g.isParserWidgetWrapper=function(a){return a.type==CKEDITOR.NODE_ELEMENT&&!!a.attributes["data-cke-widget-wrapper"]};g.WRAPPER_CLASS_PREFIX="cke_widget_wrapper_";q.prototype=CKEDITOR.tools.extend(CKEDITOR.tools.prototypedCopy(CKEDITOR.dom.element.prototype),{setData:function(a){this._.initialSetData||
this.editor.widgets.destroyAll(!1,this);this._.initialSetData=!1;a=this.editor.dataProcessor.toHtml(a,{context:this.getName(),filter:this.filter,enterMode:this.enterMode});this.setHtml(a);this.editor.widgets.initOnAll(this)},getData:function(){return this.editor.dataProcessor.toDataFormat(this.getHtml(),{context:this.getName(),filter:this.filter,enterMode:this.enterMode})}});var X=/^(?:<(?:div|span)(?: data-cke-temp="1")?(?: id="cke_copybin")?(?: data-cke-temp="1")?>)?(?:<(?:div|span)(?: style="[^"]+")?>)?<span [^>]*data-cke-copybin-start="1"[^>]*>.?<\/span>([\s\S]+)<span [^>]*data-cke-copybin-end="1"[^>]*>.?<\/span>(?:<\/(?:div|span)>)?(?:<\/(?:div|span)>)?$/i,
ga={37:1,38:1,39:1,40:1,8:1,46:1};CKEDITOR.plugins.widget=g;g.repository=p;g.nestedEditable=q})();(function(){function e(a,b,c){this.editor=a;this.notification=null;this._message=new CKEDITOR.template(b);this._singularMessage=c?new CKEDITOR.template(c):null;this._tasks=[];this._doneTasks=this._doneWeights=this._totalWeights=0}function d(a){this._weight=a||1;this._doneWeight=0;this._isCanceled=!1}CKEDITOR.plugins.add("notificationaggregator",{requires:"notification"});e.prototype={createTask:function(a){a=a||{};var b=!this.notification,c;b&&(this.notification=this._createNotification());c=this._addTask(a);
c.on("updated",this._onTaskUpdate,this);c.on("done",this._onTaskDone,this);c.on("canceled",function(){this._removeTask(c)},this);this.update();b&&this.notification.show();return c},update:function(){this._updateNotification();this.isFinished()&&this.fire("finished")},getPercentage:function(){return 0===this.getTaskCount()?1:this._doneWeights/this._totalWeights},isFinished:function(){return this.getDoneTaskCount()===this.getTaskCount()},getTaskCount:function(){return this._tasks.length},getDoneTaskCount:function(){return this._doneTasks},
_updateNotification:function(){this.notification.update({message:this._getNotificationMessage(),progress:this.getPercentage()})},_getNotificationMessage:function(){var a=this.getTaskCount(),b={current:this.getDoneTaskCount(),max:a,percentage:Math.round(100*this.getPercentage())};return(1==a&&this._singularMessage?this._singularMessage:this._message).output(b)},_createNotification:function(){return new CKEDITOR.plugins.notification(this.editor,{type:"progress"})},_addTask:function(a){a=new d(a.weight);
this._tasks.push(a);this._totalWeights+=a._weight;return a},_removeTask:function(a){var b=CKEDITOR.tools.indexOf(this._tasks,a);-1!==b&&(a._doneWeight&&(this._doneWeights-=a._doneWeight),this._totalWeights-=a._weight,this._tasks.splice(b,1),this.update())},_onTaskUpdate:function(a){this._doneWeights+=a.data;this.update()},_onTaskDone:function(){this._doneTasks+=1;this.update()}};CKEDITOR.event.implementOn(e.prototype);d.prototype={done:function(){this.update(this._weight)},update:function(a){if(!this.isDone()&&
!this.isCanceled()){a=Math.min(this._weight,a);var b=a-this._doneWeight;this._doneWeight=a;this.fire("updated",b);this.isDone()&&this.fire("done")}},cancel:function(){this.isDone()||this.isCanceled()||(this._isCanceled=!0,this.fire("canceled"))},isDone:function(){return this._weight===this._doneWeight},isCanceled:function(){return this._isCanceled}};CKEDITOR.event.implementOn(d.prototype);CKEDITOR.plugins.notificationAggregator=e;CKEDITOR.plugins.notificationAggregator.task=d})();(function(){CKEDITOR.plugins.add("uploadwidget",{requires:"widget,clipboard,filetools,notificationaggregator",init:function(a){a.filter.allow("*[!data-widget,!data-cke-upload-id]")}});CKEDITOR.fileTools||(CKEDITOR.fileTools={});CKEDITOR.tools.extend(CKEDITOR.fileTools,{addUploadWidget:function(a,c,f){var h=CKEDITOR.fileTools,b=a.uploadRepository,m=f.supportedTypes?10:20;if(f.fileToElement)a.on("paste",function(d){d=d.data;var l=a.widgets.registered[c],k=d.dataTransfer,f=k.getFilesCount(),g=l.loadMethod||
"loadAndUpload",e,n;if(!d.dataValue&&f)for(n=0;n<f;n++)if(e=k.getFile(n),!l.supportedTypes||h.isTypeSupported(e,l.supportedTypes)){var m=l.fileToElement(e);e=b.create(e,void 0,l.loaderType);m&&(e[g](l.uploadUrl,l.additionalRequestParameters),CKEDITOR.fileTools.markElement(m,c,e.id),"loadAndUpload"!=g&&"upload"!=g||l.skipNotifications||CKEDITOR.fileTools.bindNotifications(a,e),d.dataValue+=m.getOuterHtml())}},null,null,m);CKEDITOR.tools.extend(f,{downcast:function(){return new CKEDITOR.htmlParser.text("")},
init:function(){var d=this,c=this.wrapper.findOne("[data-cke-upload-id]").data("cke-upload-id"),k=b.loaders[c],f=CKEDITOR.tools.capitalize,g,e;k.on("update",function(b){if(d.wrapper&&d.wrapper.getParent()){a.fire("lockSnapshot");b="on"+f(k.status);if("function"!==typeof d[b]||!1!==d[b](k))e="cke_upload_"+k.status,d.wrapper&&e!=g&&(g&&d.wrapper.removeClass(g),d.wrapper.addClass(e),g=e),"error"!=k.status&&"abort"!=k.status||a.widgets.del(d);a.fire("unlockSnapshot")}else CKEDITOR.instances[a.name]&&
a.editable().find('[data-cke-upload-id\x3d"'+c+'"]').count()||k.abort(),b.removeListener()});k.update()},replaceWith:function(d,c){if(""===d.trim())a.widgets.del(this);else{var b=this==a.widgets.focused,f=a.editable(),g=a.createRange(),e,h;b||(h=a.getSelection().createBookmarks());g.setStartBefore(this.wrapper);g.setEndAfter(this.wrapper);b&&(e=g.createBookmark());f.insertHtmlIntoRange(d,g,c);a.widgets.checkWidgets({initOnlyNew:!0});a.widgets.destroy(this,!0);b?(g.moveToBookmark(e),g.select()):a.getSelection().selectBookmarks(h)}},
_getLoader:function(){var a=this.wrapper.findOne("[data-cke-upload-id]");return a?this.editor.uploadRepository.loaders[a.data("cke-upload-id")]:null}});a.widgets.add(c,f)},markElement:function(a,c,f){a.setAttributes({"data-cke-upload-id":f,"data-widget":c})},bindNotifications:function(a,c){function f(){h=a._.uploadWidgetNotificaionAggregator;if(!h||h.isFinished())h=a._.uploadWidgetNotificaionAggregator=new CKEDITOR.plugins.notificationAggregator(a,a.lang.uploadwidget.uploadMany,a.lang.uploadwidget.uploadOne),
h.once("finished",function(){var b=h.getTaskCount();0===b?h.notification.hide():h.notification.update({message:1==b?a.lang.uploadwidget.doneOne:a.lang.uploadwidget.doneMany.replace("%1",b),type:"success",important:1})})}var h,b=null;c.on("update",function(){!b&&c.uploadTotal&&(f(),b=h.createTask({weight:c.uploadTotal}));b&&"uploading"==c.status&&b.update(c.uploaded)});c.on("uploaded",function(){b&&b.done()});c.on("error",function(){b&&b.cancel();a.showNotification(c.message,"warning")});c.on("abort",
function(){b&&b.cancel();CKEDITOR.instances[a.name]&&a.showNotification(a.lang.uploadwidget.abort,"info")})}})})();(function(){function l(c){9>=c&&(c="0"+c);return String(c)}function n(c){var a=new Date,a=[a.getFullYear(),a.getMonth()+1,a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds()];e+=1;return"image-"+CKEDITOR.tools.array.map(a,l).join("")+"-"+e+"."+c}var e=0;CKEDITOR.plugins.add("uploadimage",{requires:"uploadwidget",onLoad:function(){CKEDITOR.addCss(".cke_upload_uploading img{opacity: 0.3}")},init:function(c){if(CKEDITOR.plugins.clipboard.isFileApiSupported){var a=CKEDITOR.fileTools,e=a.getUploadUrl(c.config,
"image");e&&(a.addUploadWidget(c,"uploadimage",{supportedTypes:/image\/(jpeg|png|gif|bmp)/,uploadUrl:e,fileToElement:function(){var b=new CKEDITOR.dom.element("img");b.setAttribute("src","data:image/gif;base64,R0lGODlhDgAOAIAAAAAAAP///yH5BAAAAAAALAAAAAAOAA4AAAIMhI+py+0Po5y02qsKADs\x3d");return b},parts:{img:"img"},onUploading:function(b){this.parts.img.setAttribute("src",b.data)},onUploaded:function(b){var a=this.parts.img.$;this.replaceWith('\x3cimg src\x3d"'+b.url+'" width\x3d"'+(b.responseData.width||
a.naturalWidth)+'" height\x3d"'+(b.responseData.height||a.naturalHeight)+'"\x3e')}}),c.on("paste",function(b){if(b.data.dataValue.match(/<img[\s\S]+data:/i)){b=b.data;var f=document.implementation.createHTMLDocument(""),f=new CKEDITOR.dom.element(f.body),m,g,k;f.data("cke-editable",1);f.appendHtml(b.dataValue);m=f.find("img");for(k=0;k<m.count();k++){g=m.getItem(k);var d=g.getAttribute("src"),h=d&&"data:"==d.substring(0,5),l=null===g.data("cke-realelement");h&&l&&!g.data("cke-upload-id")&&!g.isReadOnly(1)&&
(h=(h=d.match(/image\/([a-z]+?);/i))&&h[1]||"jpg",d=c.uploadRepository.create(d,n(h)),d.upload(e),a.markElement(g,"uploadimage",d.id),a.bindNotifications(c,d))}b.dataValue=f.getHtml()}}))}}})})();CKEDITOR.plugins.add("wsc",{requires:"dialog",parseApi:function(a){a.config.wsc_onFinish="function"===typeof a.config.wsc_onFinish?a.config.wsc_onFinish:function(){};a.config.wsc_onClose="function"===typeof a.config.wsc_onClose?a.config.wsc_onClose:function(){}},parseConfig:function(a){a.config.wsc_customerId=a.config.wsc_customerId||CKEDITOR.config.wsc_customerId||"1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk";a.config.wsc_customDictionaryIds=a.config.wsc_customDictionaryIds||
CKEDITOR.config.wsc_customDictionaryIds||"";a.config.wsc_userDictionaryName=a.config.wsc_userDictionaryName||CKEDITOR.config.wsc_userDictionaryName||"";a.config.wsc_customLoaderScript=a.config.wsc_customLoaderScript||CKEDITOR.config.wsc_customLoaderScript;a.config.wsc_interfaceLang=a.config.wsc_interfaceLang;CKEDITOR.config.wsc_cmd=a.config.wsc_cmd||CKEDITOR.config.wsc_cmd||"spell";CKEDITOR.config.wsc_version="v4.3.0-master-d769233";CKEDITOR.config.wsc_removeGlobalVariable=!0},onLoad:function(a){"moono-lisa"==
(CKEDITOR.skinName||a.config.skin)&&CKEDITOR.document.appendStyleSheet(this.path+"skins/"+CKEDITOR.skin.name+"/wsc.css")},init:function(a){var b=CKEDITOR.env;this.parseConfig(a);this.parseApi(a);a.addCommand("checkspell",new CKEDITOR.dialogCommand("checkspell")).modes={wysiwyg:!CKEDITOR.env.opera&&!CKEDITOR.env.air&&document.domain==window.location.hostname&&!(b.ie&&(8>b.version||b.quirks))};"undefined"==typeof a.plugins.scayt&&a.ui.addButton&&a.ui.addButton("SpellChecker",{label:a.lang.wsc.toolbar,
click:function(a){var b=a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE?a.container.getText():a.document.getBody().getText();(b=b.replace(/\s/g,""))?a.execCommand("checkspell"):alert("Nothing to check!")},toolbar:"spellchecker,10"});CKEDITOR.dialog.add("checkspell",this.path+(CKEDITOR.env.ie&&7>=CKEDITOR.env.version?"dialogs/wsc_ie.js":window.postMessage?"dialogs/wsc.js":"dialogs/wsc_ie.js"))}});CKEDITOR.config.plugins='dialogui,dialog,about,a11yhelp,dialogadvtab,basicstyles,bidi,blockquote,notification,button,toolbar,clipboard,panelbutton,panel,floatpanel,colorbutton,colordialog,templates,menu,contextmenu,copyformatting,div,resize,elementspath,enterkey,entities,popup,filetools,filebrowser,find,fakeobjects,flash,floatingspace,listblock,richcombo,font,forms,format,horizontalrule,htmlwriter,iframe,wysiwygarea,image,indent,indentblock,indentlist,smiley,justify,menubutton,language,link,list,liststyle,magicline,maximize,newpage,pagebreak,pastetext,pastefromword,preview,print,removeformat,save,selectall,showblocks,showborders,sourcearea,specialchar,scayt,stylescombo,tab,table,tabletools,tableselection,undo,lineutils,widgetselection,widget,notificationaggregator,uploadwidget,uploadimage,wsc';CKEDITOR.config.skin='moono-lisa';(function() {var setIcons = function(icons, strip) {var path = CKEDITOR.getUrl( 'plugins/' + strip );icons = icons.split( ',' );for ( var i = 0; i < icons.length; i++ )CKEDITOR.skin.icons[ icons[ i ] ] = { path: path, offset: -icons[ ++i ], bgsize : icons[ ++i ] };};if (CKEDITOR.env.hidpi) setIcons('about,0,,bold,24,,italic,48,,strike,72,,subscript,96,,superscript,120,,underline,144,,bidiltr,168,,bidirtl,192,,blockquote,216,,copy-rtl,240,,copy,264,,cut-rtl,288,,cut,312,,paste-rtl,336,,paste,360,,bgcolor,384,,textcolor,408,,templates-rtl,432,,templates,456,,copyformatting,480,,creatediv,504,,find-rtl,528,,find,552,,replace,576,,flash,600,,button,624,,checkbox,648,,form,672,,hiddenfield,696,,imagebutton,720,,radio,744,,select-rtl,768,,select,792,,textarea-rtl,816,,textarea,840,,textfield-rtl,864,,textfield,888,,horizontalrule,912,,iframe,936,,image,960,,indent-rtl,984,,indent,1008,,outdent-rtl,1032,,outdent,1056,,smiley,1080,,justifyblock,1104,,justifycenter,1128,,justifyleft,1152,,justifyright,1176,,language,1200,,anchor-rtl,1224,,anchor,1248,,link,1272,,unlink,1296,,bulletedlist-rtl,1320,,bulletedlist,1344,,numberedlist-rtl,1368,,numberedlist,1392,,maximize,1416,,newpage-rtl,1440,,newpage,1464,,pagebreak-rtl,1488,,pagebreak,1512,,pastetext-rtl,1536,,pastetext,1560,,pastefromword-rtl,1584,,pastefromword,1608,,preview-rtl,1632,,preview,1656,,print,1680,,removeformat,1704,,save,1728,,selectall,1752,,showblocks-rtl,1776,,showblocks,1800,,source-rtl,1824,,source,1848,,specialchar,1872,,scayt,1896,,table,1920,,redo-rtl,1944,,redo,1968,,undo-rtl,1992,,undo,2016,,spellchecker,2040,','icons_hidpi.png');else setIcons('about,0,auto,bold,24,auto,italic,48,auto,strike,72,auto,subscript,96,auto,superscript,120,auto,underline,144,auto,bidiltr,168,auto,bidirtl,192,auto,blockquote,216,auto,copy-rtl,240,auto,copy,264,auto,cut-rtl,288,auto,cut,312,auto,paste-rtl,336,auto,paste,360,auto,bgcolor,384,auto,textcolor,408,auto,templates-rtl,432,auto,templates,456,auto,copyformatting,480,auto,creatediv,504,auto,find-rtl,528,auto,find,552,auto,replace,576,auto,flash,600,auto,button,624,auto,checkbox,648,auto,form,672,auto,hiddenfield,696,auto,imagebutton,720,auto,radio,744,auto,select-rtl,768,auto,select,792,auto,textarea-rtl,816,auto,textarea,840,auto,textfield-rtl,864,auto,textfield,888,auto,horizontalrule,912,auto,iframe,936,auto,image,960,auto,indent-rtl,984,auto,indent,1008,auto,outdent-rtl,1032,auto,outdent,1056,auto,smiley,1080,auto,justifyblock,1104,auto,justifycenter,1128,auto,justifyleft,1152,auto,justifyright,1176,auto,language,1200,auto,anchor-rtl,1224,auto,anchor,1248,auto,link,1272,auto,unlink,1296,auto,bulletedlist-rtl,1320,auto,bulletedlist,1344,auto,numberedlist-rtl,1368,auto,numberedlist,1392,auto,maximize,1416,auto,newpage-rtl,1440,auto,newpage,1464,auto,pagebreak-rtl,1488,auto,pagebreak,1512,auto,pastetext-rtl,1536,auto,pastetext,1560,auto,pastefromword-rtl,1584,auto,pastefromword,1608,auto,preview-rtl,1632,auto,preview,1656,auto,print,1680,auto,removeformat,1704,auto,save,1728,auto,selectall,1752,auto,showblocks-rtl,1776,auto,showblocks,1800,auto,source-rtl,1824,auto,source,1848,auto,specialchar,1872,auto,scayt,1896,auto,table,1920,auto,redo-rtl,1944,auto,redo,1968,auto,undo-rtl,1992,auto,undo,2016,auto,spellchecker,2040,auto','icons.png');})();CKEDITOR.lang.languages={"af":1,"sq":1,"ar":1,"az":1,"eu":1,"bn":1,"bs":1,"bg":1,"ca":1,"zh-cn":1,"zh":1,"hr":1,"cs":1,"da":1,"nl":1,"en":1,"en-au":1,"en-ca":1,"en-gb":1,"eo":1,"et":1,"fo":1,"fi":1,"fr":1,"fr-ca":1,"gl":1,"ka":1,"de":1,"de-ch":1,"el":1,"gu":1,"he":1,"hi":1,"hu":1,"is":1,"id":1,"it":1,"ja":1,"km":1,"ko":1,"ku":1,"lv":1,"lt":1,"mk":1,"ms":1,"mn":1,"no":1,"nb":1,"oc":1,"fa":1,"pl":1,"pt-br":1,"pt":1,"ro":1,"ru":1,"sr":1,"sr-latn":1,"si":1,"sk":1,"sl":1,"es":1,"es-mx":1,"sv":1,"tt":1,"th":1,"tr":1,"ug":1,"uk":1,"vi":1,"cy":1};}());;

/** Mustache **/
(window.defineModule = (window.defineModule || {})).name = 'Mustache';
(function defineMustache(global,factory){if(typeof exports==="object"&&exports&&typeof exports.nodeName!=="string"){factory(exports)}else if(typeof define==="function"&&define.amd){define(["exports"],factory)}else{global.Mustache={};factory(Mustache)}})(this,function mustacheFactory(mustache){var objectToString=Object.prototype.toString;var isArray=Array.isArray||function isArrayPolyfill(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};function escapeHtml(string){return String(string).replace(/[&<>"'\/]/g,function fromEntityMap(s){return entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw new Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*");closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1]));closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template);var start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingTagRe)}if(!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&"){nonSpace=true}else if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return squashedTokens}function nestTokens(tokens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return nestedTokens}function Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function eos(){return this.tail===""};Scanner.prototype.scan=function scan(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return string};Scanner.prototype.scanUntil=function scanUntil(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index);this.tail=this.tail.substring(index)}this.pos+=match.length;return match};function Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function push(view){return new Context(view,this)};Context.prototype.lookup=function lookup(name){var cache=this.cache;var value;if(cache.hasOwnProperty(name)){value=cache[name]}else{var context=this,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){value=context.view;names=name.split(".");index=0;while(value!=null&&index<names.length){if(index===names.length-1)lookupHit=hasProperty(value,names[index]);value=value[names[index++]]}}else{value=context.view[name];lookupHit=hasProperty(context.view,name)}if(lookupHit)break;context=context.parent}cache[name]=value}if(isFunction(value))value=value.call(this.view);return value};function Writer(){this.cache={}}Writer.prototype.clearCache=function clearCache(){this.cache={}};Writer.prototype.parse=function parse(template,tags){var cache=this.cache;var tokens=cache[template];if(tokens==null)tokens=cache[template]=parseTemplate(template,tags);return tokens};Writer.prototype.render=function render(template,view,partials){var tokens=this.parse(template);var context=view instanceof Context?view:new Context(view);return this.renderTokens(tokens,context,partials,template)};Writer.prototype.renderTokens=function renderTokens(tokens,context,partials,originalTemplate){var buffer="";var token,symbol,value;for(var i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this.renderSection(token,context,partials,originalTemplate);else if(symbol==="^")value=this.renderInverted(token,context,partials,originalTemplate);else if(symbol===">")value=this.renderPartial(token,context,partials,originalTemplate);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context);else if(symbol==="text")value=this.rawValue(token);if(value!==undefined)buffer+=value}return buffer};Writer.prototype.renderSection=function renderSection(token,context,partials,originalTemplate){var self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else if(typeof value==="object"||typeof value==="string"||typeof value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections without the original template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return buffer};Writer.prototype.renderInverted=function renderInverted(token,context,partials,originalTemplate){var value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype.renderPartial=function renderPartial(token,context,partials){if(!partials)return;var value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return this.renderTokens(this.parse(value),context,partials,value)};Writer.prototype.unescapedValue=function unescapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function escapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return mustache.escape(value)};Writer.prototype.rawValue=function rawValue(token){return token[1]};mustache.name="mustache.js";mustache.version="2.1.3";mustache.tags=["{{","}}"];var defaultWriter=new Writer;mustache.clearCache=function clearCache(){return defaultWriter.clearCache()};mustache.parse=function parse(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function render(template,view,partials){if(typeof template!=="string"){throw new TypeError('Invalid template! Template should be a "string" '+'but "'+typeStr(template)+'" was given as the first '+"argument for mustache#render(template, view, partials)")}return defaultWriter.render(template,view,partials)};mustache.to_html=function to_html(template,view,partials,send){var result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer});
;

/** WB Uploader **/
(window.defineModule = (window.defineModule || {})).name = 'WB Uploader';

/**
 * Uploader class
 * 
 * @author Marius Tomas <marius@profis.lt>
 * @version 2.1.1, 2012-07-12
 */
function WB_Uploader() { this.__construct(); }

WB_Uploader.prototype.id = null;
WB_Uploader.prototype.element = null;
WB_Uploader.prototype.iframe = null;
WB_Uploader.prototype.form = null;
WB_Uploader.prototype.index = 0;
WB_Uploader.prototype.files = null;
WB_Uploader.prototype.currFile = null;
WB_Uploader.prototype.lastUrl = null;
WB_Uploader.prototype.urls = null;
WB_Uploader.prototype.currProgress = null;
WB_Uploader.prototype.multi = false;

WB_Uploader.prototype.uploadCallback = null;
WB_Uploader.prototype.callback = null;
WB_Uploader.prototype.params = null;
WB_Uploader.lastIndex = -1;

/**
 * Construct uploader
 */
WB_Uploader.prototype.__construct = function() {
	WB_Uploader.lastIndex++;
	this.id = "wb_uploader_" + WB_Uploader.lastIndex;

	this.params = {};
	this.element = document.createElement("div");
	this.element.id = this.id;
	this.element._class = this;
	$(this.element).addClass("ui-uploader");
	
	var tmp = document.createElement("div");
	tmp.innerHTML = '<iframe name="wb_uploader_ifrm_' + WB_Uploader.lastIndex +
		'" frameborder="0" style="width: 1px; height: 1px;"></iframe>';
	this.iframe = tmp.firstChild; tmp.removeChild(this.iframe);
	
	//this.iframe = document.createElement("iframe");
	//this.iframe.name = "wb_uploader_ifrm_" + WB_Uploader_lastIndex;
	//$(this.iframe).attr("frameborder", 0).css({"width": "1px", "height": "1px"});
	
	tmp = document.createElement("div");
	tmp.innerHTML = '<form action="' + wb_builder.baseUrl + "gallery/?id=" + this.id +
		'" target="' + this.iframe.name + '" method="post" enctype="multipart/form-data"></form>';
	this.form = tmp.firstChild; tmp.removeChild(this.form);
	
	/*this.form = document.createElement("form");
	$(this.form).attr({
		"action":	wb_builder.baseUrl + "gallery/?id=" + this.id,
		"target":	this.iframe.name,
		"method":	"post",
		"enctype":	"multipart/form-data"
	});*/
	this.reset();

	this.element.appendChild(this.form);
	this.element.appendChild(this.iframe);
};

WB_Uploader.prototype.setCallback = function(callback, object) {
	if( !callback )
		this.callback = null;
	else
		this.callback = {object: object, callback: callback};
};

WB_Uploader.prototype.setUploadCallback = function(callback, object) {
	if( !callback )
		this.uploadCallback = null;
	else
		this.uploadCallback = {object: object, callback: callback};
};

WB_Uploader.prototype.createParamElement = function(id, value) {
	
	var tmp = document.createElement("div");
	tmp.innerHTML = '<input type="hidden" name="' + id + '" value="' + value + '" />';
	var inp = tmp.firstChild; tmp.removeChild(inp);
	
	/*var inp = document.createElement("INPUT");
	inp.name = id;
	inp.type = "hidden";
	inp.value = value;*/
	this.params[id] = {
		element: inp,
		value: value
	};
	this.form.appendChild(inp);
};

WB_Uploader.prototype.setParam = function(id, value) {
	if(value !== null)
	{
		if( this.params[id] && this.params[id].element )
         this.params[id].element.parentNode.removeChild(this.params[id].element);
		this.createParamElement(id, value);
	}
	else if( this.params[id] )
	{
		this.form.removeChild(this.params[id].element);
		this.params[id] = null;
		delete this.params[id];
	}
};

WB_Uploader.prototype.reset = function() {
	$(this.form).empty();
	for( var i in this.params )
		this.createParamElement(i, this.params[i].value);
	this.files = {};
	this.urls = {};
	this.lastUrl = null;
	this.addFile();
};

WB_Uploader.prototype.getUrl = function() {
	return this.lastUrl;
};

WB_Uploader.prototype.addFile = function() {
	var thisClass = this;
	if (this.currFile) {
		this.currFile.style.display = "none";
	}
	this.currFile = document.createElement("div");
	$(this.currFile).css({ "overflow": "hidden" });
	
	var tmp = document.createElement("div");
	tmp.innerHTML = '<input type="file" name="upl_' + (this.index++) + '" size="4" />';
	var fl = tmp.firstChild; tmp.removeChild(fl);
	
	/*var fl = document.createElement("input");
	fl.name = 'upl_' + (this.index++);
	fl.type = "file";
	fl.size = "4";*/
	
	$(fl).bind("change", function() { thisClass.upload(this.name); });

	this.currFile.appendChild(fl);

	if (this.form.firstChild)
		this.form.insertBefore(this.currFile, this.form.firstChild);
	else
		this.form.appendChild(this.currFile);
	this.files[fl.name] = this.currFile;
};

WB_Uploader.prototype.upload = function(key) {
	if (!this.files[key]) return;
	var file = this.files[key];
	var input = file.firstChild;
	input.style.display = "none";
	if( this.uploadCallback )
	{
		if( this.uploadCallback.object )
			this.uploadCallback.callback.call(this.uploadCallback.object, this);
		else
			this.uploadCallback.callback(this);
	}

	this.currProgress = document.createElement("div");
	$(this.currProgress).addClass("wb_progress").progressbar({ value: 100 });

	file.insertBefore(this.currProgress, file.firstChild);
	this.form.submit();
	file.removeChild(input);
	if (this.multi)
		this.addFile();
};

WB_Uploader.prototype.remove = function(key) {
	if (!this.urls[key]) return;
	$.get(wb_builder.baseUrl + "gallery/?id=" + this.id + "&del=" + this.urls[key]);
};

WB_Uploader.prototype.display = function(url, relUrl) {
	for (var k in this.files) {
		this.onUpload(k, url, relUrl);
		break;
	}
};

WB_Uploader.prototype.onUpload = function(key, url, relUrl, param) {
	if (!this.files[key]) return;
	this.urls[key] = relUrl;
	var thisClass = this;
	var file = this.files[key];
	if (this.callback) {
		$(file).empty();
		if( this.callback.object )
			this.callback.callback.call(this.callback.object, this, key, url, relUrl, param);
		else
			this.callback.callback(this, key, url, relUrl, param);
	}
	else {
		// at this point param contains error code if there were any
		if (url.split("?")[0].match(/^.*\.swf$/i)) {
			$(file).empty();
			file.style.position = "relative";
			var xbtn = document.createElement("a");
			xbtn.className = "ui-uploader-xbtn";
			xbtn.innerHTML = '<span>&times;</span>';
			$(xbtn).css({ "position" : "absolute", "right": "4px", "margin": "4px 0 0 4px" })
				.bind("click", function() { thisClass.remove(key); thisClass.reset(); });
			file.appendChild(xbtn);
			$(file).append('<object style="width: 120px; height: 100px;" data="' + url + '" type="application/x-shockwave-flash">' +
					'<param name="movie" value="' + url + '" />' +
					'<param name="menu" value="false" />' +
				'</object>');
		} else {		
			var img = new Image();
			img.style.display = "none";
			img.onload = function() {
				var oWidth = this.width;
				var oHeight = this.height;
				var file = thisClass.files[key];
				$(file).empty();
				file.style.position = "relative";
				var xbtn = document.createElement("a");
				xbtn.className = "ui-uploader-xbtn";
				xbtn.innerHTML = '<span>&times;</span>';
				$(xbtn).css({ "position" : "absolute", "right": "4px", "margin": "4px 0 0 4px" })
					.bind("click", function() { thisClass.remove(key); thisClass.reset(); });
				file.appendChild(xbtn);
				$(file).addClass("ui-uploader-img").css("background", "#ffffff url(images/transparent.png)");
				file.appendChild(this);
				var tWidth = (oWidth < 120) ? oWidth : 120;
				var tHeight =  oHeight * tWidth / oWidth;
				this.style.display = "block";
				this.style.width = tWidth + "px";
				this.style.height = tHeight + "px";
				this.parentNode.style.width = "122px";
				if (tHeight < 26)
					this.parentNode.style.height = "26px";
			};
			img.onerror = function() {
				thisClass.reset();
				this.onload = null;
				return;
			};
			img.src = url;
		}
	}
	this.lastUrl = relUrl;
};
;

/** WB Dialog **/
(window.defineModule = (window.defineModule || {})).name = 'WB Dialog';

define('Dialog', ['UIComponent', 'Service', 'UserInput'], function(UIComponent, Service, UserInput) {
	'use strict';
	
/**
 * Dialog class
 * @param {string} title
 * @param {boolean} isStatic
 * @param {UIComponent.UIComponent} content content element
 * @param {boolean=} keepXBtn keep x btn in static mode
 * @class
 */
var Dialog = function(title, isStatic, content, keepXBtn) { if (title !== '%inherit%') this.__construct(title, isStatic, content, keepXBtn); };

Dialog.prototype.id = null;
Dialog.prototype.title = "";
Dialog.prototype.dialog = null;
Dialog.prototype.baseElem = null;
Dialog.prototype.content = null;
/** @type jQuery */
Dialog.prototype.headerElem = null;
/** @type jQuery */
Dialog.prototype.footerElem = null;
Dialog.prototype.xButton = null;
Dialog.prototype.fields = null;
Dialog.prototype.buttons = null;
/** @type JQuery */
Dialog.prototype.primaryButton = null;
Dialog.prototype.onOpen = null;
Dialog.prototype.onBeforeClose = null;
Dialog.prototype.onShown = null;
Dialog.prototype.onShow = null;
Dialog.prototype.onClose = null;
Dialog.prototype.onClosed = null;
/** @type Boolean */
Dialog.prototype.stopPropagation = false;
/** @type Boolean */
Dialog.prototype.ignoreEvent = false;
/** @type Boolean */
Dialog.prototype.isStatic = false;
/** @type Boolean */
Dialog.prototype.isVisible = false;
/** @type Boolean */
Dialog.prototype.autoResize = false;
/** @type Function */
Dialog.prototype.autoResizeFunc = null;
/** @type boolean */
Dialog.prototype.maximised = false;
Dialog.lastIndex = -1;
Dialog.stack = [];
Dialog.hasHotkey = null;
Dialog.hideEditors = true;

/**
 * Construct Dialog
 * @param {string} title dialog title
 * @param {boolean} isStatic no close on escape and no close on backbrop click
 * @param {UIComponent.UIComponent} content content element
 * @param {boolean=} keepXBtn keep x btn in static mode
 */
Dialog.prototype.__construct = function(title, isStatic, content, keepXBtn) {
	if (!Dialog.hasHotkey) {
		Dialog.hasHotkey = function() {
			if (Dialog.stack.length > 0 && !Dialog.stack[Dialog.stack.length - 1].isStatic) {
				Dialog.stack[Dialog.stack.length - 1].setVisible(false);
			}
		};
		UserInput.UserInput.addHotKey("esc", Dialog.hasHotkey);
	}
	
	Dialog.lastIndex++;
	this.id = "wb_dialog_" + Dialog.lastIndex;
	this.isStatic = isStatic ? true : false;
	this.dialog = $(
		'<div class="modal fade">' +
			'<div class="modal-dialog">' +
				'<div class="modal-content">' +
					'<div class="modal-header">' +
						((isStatic && !keepXBtn) ? '' : '<button type="button" class="close" data-dismiss="modal">&times;</button>') +
						'<h4 class="modal-title">&nbsp;</h4>' +
					'</div>' +
					'<div class="modal-body"><p>&nbsp;</p></div>' +
					'<div class="modal-footer"></div>' +
				'</div>' +
			'</div>' +
		'</div>'
	);
	this.dialog.attr("id", this.id);
	
	this.baseElem = $('.modal-dialog', this.dialog).eq(0);
	this.headerElem = $('.modal-header', this.dialog).eq(0);
	this.footerElem = $('.modal-footer', this.dialog).eq(0);
	
	this.title = $(".modal-header", this.dialog).children(".modal-title");
	this.xButton = $(".modal-header", this.dialog).children("button.close");
	
	this.content = $(".modal-body", this.dialog);
	
	this.buttons = $(".modal-footer", this.dialog);
	
	$(document.body).append(this.dialog);
	
	var opt = { show: false, keyboard: true };
	if (isStatic) {
		opt.keyboard = false;
		opt.backdrop = "static";
	}
	this.dialog.modal(opt);
	var thisClass = this;
	this.dialog.on('hidden.bs.modal', function() {
		if (typeof(thisClass.onClosed) === "function") thisClass.onClosed();
		if (Dialog.stack.length > 0) {
			if (!(Dialog.stack[0] instanceof WB_Preloader)) {
				$('body').addClass('modal-open');
			}
		} else {
			wb_builder.layoutManager.setVisible(wb_builder.showLayout);
		}
	});
	this.dialog.on("show.bs.modal", function() {
		if (typeof(thisClass.onShow) === "function") thisClass.onShow();
	});
	this.dialog.on("shown.bs.modal", function() {
		if (typeof(thisClass.onShown) === "function") thisClass.onShown();
    });
	this.dialog.on("hide.bs.modal", function() {
		if (thisClass.ignoreEvent) return;
		thisClass.setVisible(false, true);
		if (typeof(thisClass.onClose) === "function") thisClass.onClose();
		//console.log("Hidding: " + thisClass.id);
    });
	this.fields = {};
	
	
	
	/* var thisClass = this;
	$(".modal-header", this.dialog).children("button.close").bind("click", function() {
		//thisClass.setVisible(false, true);
		//if (typeof(thisClass.onClose) == "function") thisClass.onClose();
	});
	 */
	this.setTitle(title);
	if (content) this.setContent(content);
};

/**
 * Get dialogs property field.
 * Note: This is used by help system scenario player.
 * @param {string} field field identifier in this dialog.
 * @returns {UIComponent|null}
 */
Dialog.prototype.propertyDialogField = function(field) {
   var m;
   if (field === 'apply') {
	   return this.primaryButton ? {
		   _elem: this.primaryButton,
		   getElem: function() { return this._elem; }
	   } : null;
   } else if ((m = field.match(/^tab\-(.+)$/i)) && ('tabbedPane' in this)) {
	   for (var i = 0; i < this.tabbedPane.tabs.length; i++) {
		   var tabDef = this.tabbedPane.tabs[i];
		   if (tabDef.type === m[1]) return {
			   _control: this.tabbedPane,
			   _tab: tabDef,
			   select: function() { this._control.selectTab(null, this._tab); },
			   getElem: function() { return this._tab.btnElem; }
		   };
	   }
	   return null;
   }
   return (field in this.fields) ? this.fields[field] : null;
};

Dialog.prototype.propertyDialogClose = function() {
	if (typeof this.onClose === 'function') this.onClose.call(this.comDialog);
	this.hide();
};

/**
 * Apply changes in property dialog and close it (same as clicking dialogs apply button).
 * Note: This is used by help system scenario player.
 */
Dialog.prototype.propertyDialogApply = function(close) {
	if (close) {
		if (this.primaryButton) this.primaryButton.trigger('click');
	} else if (typeof this._applyFunc === 'function') this._applyFunc.call(this);
};

/** @param {Boolean} visible */
Dialog.prototype.setTitleVisible = function(visible) {
	if (visible) {
		this.headerElem.show();
	} else {
		this.headerElem.hide();
	}
};

/** @param {Boolean} visible */
Dialog.prototype.setFooterVisible = function(visible) {
	if (visible) {
		this.footerElem.show();
	} else {
		this.footerElem.hide();
	}
};

/**
 * Set dialog title
 * @param title dialog title
 */
Dialog.prototype.setTitle = function(title) {
	if (typeof(title) !== "undefined")
		this.title.html(title);
};

/**
 * Set dialog content HTML
 * @param htmlContent dialog content HTML
 * @param {boolean} keepFields
 */
Dialog.prototype.setContent = function(htmlContent, keepFields) {
	if (htmlContent && (htmlContent instanceof UIComponent.UIComponent)) {
		if (('fields' in htmlContent) && typeof htmlContent.fields === 'object') {
			if (!keepFields) this.fields = {};
			for (var k in htmlContent.fields) {
				this.fields[k] = htmlContent.fields[k];
			}
		}
		this.content.empty().append(htmlContent.getElem());
	} else if (htmlContent !== null && typeof(htmlContent) !== "undefined") {
		this.content.empty().append(htmlContent);
	}
};

/**
 * Add element to dialog content
 * @param elm element to add
 */
Dialog.prototype.addElement = function(elm) {
	this.content.append(elm);
	return elm;
};

Dialog.prototype.addNamedInput = function(title, type, id, name) {
	var div = document.createElement("div");
	var inp = document.createElement("input");
	var lbl = document.createElement("label");
	
	div.className = "ui-named-input";
	
	inp.type = type;
	if (name) inp.name = name;
	if (id) {
		inp.id = id;
		try {lbl.setAttribute("for", id);} catch (ex) {}
		try {lbl.setAttribute("htmlFor", id);} catch (ex) {}
	}
	$(lbl).html(title);
	
	if (type === "checkbox" || type === "radio") {
		div.appendChild(inp);
		div.appendChild(lbl);
	} else {
		div.appendChild(lbl);
		div.appendChild(inp);
	}
	$(this.dialog).append(div);
	if (id)
		this.fields[id] = inp;
	return inp;
};

/**
 * Set if dialog is maximised to the size of window
 * @param {boolean} maximised
 */
Dialog.prototype.setMaximised = function(maximised) {
	this.maximised = maximised;
	if (maximised) {
		this.dialog.css({paddingRight: 0, paddingLeft: 0});
		this.baseElem.css({width: 'auto', margin: 0});
		var wh = $(window).height(), h = wh - this.headerElem.outerHeight() - this.footerElem.outerHeight() - 2;
		this.content.css({height: h, maxHeight: wh});
	} else {
		this.dialog.css({paddingRight: 17, paddingLeft: 17});
		this.baseElem.css({width: '', margin: ''});
		this.content.css({height: ''});
	}
};

/**
 * Set dialog size
 * @param width dialog width in pixels
 * @param height dialog height in pixels
 */
Dialog.prototype.setSize = function(width, height) {
	if (width*1 && typeof(width) !== "undefined" && width !== null)
		this.baseElem.css({width: width});
	if (height*1 && typeof(height) !== "undefined" && height !== null)
		this.baseElem.height(height*1);
};

/**
 * Set dialog size
 * @param sizeClass should be one of bootstrap modal size classes: modal-sm, modal-md or modal-lg
 */
Dialog.prototype.setSizeClass = function(sizeClass) {
	this.baseElem.attr("class", "modal-dialog").addClass(sizeClass);
};

/**
 * Sets max height for dialog body
 * @param height max body height to set
 */
Dialog.prototype.setMaxBodyHeight = function(height) {
	if (WB_Builder.isset(height)) {
		this.content.css("max-height", height + "px");
	}
};

/**
 * Sets min height for dialog body
 * @param height min body height to set
 */
Dialog.prototype.setMinBodyHeight = function(height) {
	if (WB_Builder.isset(height)) {
		this.content.css("min-height", height + "px");
	}
};

/**
 * Removes scrolls on overflow and removes overflow hidden 
 */
Dialog.prototype.setNoScroll = function() {
	this.content.css({
		"overflow-x": "",
		"overflow-y": "",
		"overflow": "visible"
	});
};

/**
 * If set to true dialog will try to auto-resize to window size
 * @param {Boolean} autoResize
 * @param {Function} callback
 */
Dialog.prototype.setAutoResize = function(autoResize, callback) {
	var self = this;
	var thisCallback = callback;
	this.autoResize = autoResize;
	if (this.autoResize) {
		$(window).on('resize', (this.autoResizeFunc = function() {
			// console.log(self.headerElem.outerHeight(true), self.footerElem.outerHeight(true));
			var bh = ($(window).height()*0.9) - Math.max(self.headerElem.outerHeight(true), 49) - Math.max(self.footerElem.outerHeight(true), 60) - 60;
			self.setMaxBodyHeight(bh);
			if (typeof thisCallback === 'function') thisCallback.call(self, bh);
		}));
		this.autoResizeFunc();
	} else {
		if (typeof this.autoResizeFunc === 'function') $(window).off('resize', null, this.autoResizeFunc);
		this.autoResizeFunc = null;
	}
};

/**
 * Set if buttons are centered 
 * @param {Boolean} value
 */
Dialog.prototype.setCenterButtons = function(value) {
	if (value) {
		this.footerElem.css("text-align", "center");
	} else {
		this.footerElem.css("text-align", "");
	}
};

/**
 * Set dialog visibility
 * @param visible dialog visibility
 * @param noAction (optional) no show/hide action
 * @param ignoreEvent (optional) ignore event
 */
Dialog.prototype.setVisible = function(visible, noAction, ignoreEvent) {
	if (this.stopPropagation) return;
	this.stopPropagation = true;
	if (visible) {
		if (!ignoreEvent) {
			Service.contextMenu.hideAll();
			if (Dialog.hideEditors)
				if ('textArea' in Service) Service.textArea.hideEditors();
			if (Dialog.stack.length > 0) {
				Dialog.stack[Dialog.stack.length - 1].setVisible(false, false, true);
			}
			var add = true;
			for (var i in Dialog.stack) {
				if (Dialog.stack[i].id === this.id) {
					add = false;
					break;
				}
			}
			if (add) Dialog.stack.push(this);
		}
		if (!noAction) {
			if (ignoreEvent) this.ignoreEvent = true;
			this.dialog.modal("show");
			this.isVisible = true;
			if (ignoreEvent) this.ignoreEvent = false;
		}
	} else {
		if (!noAction) {
			if (ignoreEvent) this.ignoreEvent = true;
			$(document.body).css({paddingRight: ''});
			this.dialog.modal("hide");
			this.isVisible = false;
			if (ignoreEvent) this.ignoreEvent = false;
		}
		if (!ignoreEvent) {
			Dialog.stack.pop();
			if (Dialog.stack.length > 0) {
				Dialog.stack[Dialog.stack.length - 1].setVisible(true, false, true);
			}
		}
	}
	this.stopPropagation = false;
};

/**
 * Show dialog
 * @param {Object|String} htmlContent
 */
Dialog.prototype.show = function(htmlContent) {
	this.setContent(htmlContent);
	this.setVisible(true);
};

/**
 * Hide dialog
 */
Dialog.prototype.hide = function() {
	this.setVisible(false);
};

/**
 * Add button to dialog
 * @param name button title
 * @param callback button click callback function or null (if null button will close dialog)
 * @param primary mark button as primary
 * @param cssClass class to add to button
 * @return button as jQuery selector object
 */
Dialog.prototype.addButton = function(name, callback, primary, cssClass) {
	this.buttons[name] = callback;
	var btn = $('<button class="btn" type="button"></button>');
	btn.html(name);
	if (typeof(callback) === "function") {
		btn.bind("click", callback);
	} else {
		var thisClass = this;
		//btn.attr("data-dismiss", "modal");
		btn.bind("click", function() {
			thisClass.setVisible(false);
			//if (typeof(thisClass.onClose) == "function") thisClass.onClose();
		});
	}
	if (primary) {
		this.primaryButton = btn;
		btn.addClass("btn-success");
	} else {
		btn.addClass('btn-default');
	}
	if (cssClass) btn.addClass(cssClass);
	btn.attr("iid", name);
	this.buttons.append(btn);
	return btn;
};

/**
 * Get dialog button callback
 * @param {String} name
 */
Dialog.prototype.getButtonCallback = function(name) {
	if (this.buttons[name]) 
		return this.buttons[name];
	else
		return false;
};

/**
 * Remove button from dialog
 * @param name button title to remove button by
 */
Dialog.prototype.removeButton = function(name) {
   this.buttons.children("[iid='" + name + "']").remove();
};

/**
 * Remove all button from dialog
 */
Dialog.prototype.removeAllButtons = function() {
   this.buttons.children("[iid]").remove();
};

Dialog.closeAll = function() {
	if (Dialog.stack.length > 0) {
		Dialog.stack[Dialog.stack.length - 1].setVisible(false, false, true);
	}
	Dialog.stack.splice(0, Dialog.stack.length);
};

	window.WB_Dialog = Dialog;
	
	return Dialog;

});
;

/** WB MsgDialog **/
(window.defineModule = (window.defineModule || {})).name = 'WB MsgDialog';

define('MsgDialog', ['Dialog'], function(Dialog) {
	'use strict';

/**
 * Message Dialog class
 * Dialog used to view message
 * @param {string} dlg_title dialog title
 * @param {string} message message text
 * @param {string} title message title
 * @param {string} type message type (value one of: error, success, info, block)
 * @param {boolean} isStatic prevents dialog from reacting to esc button and from closing with X button
 */
var MsgDialog = function(dlg_title, message, title, type, isStatic, isPlain) {this.__construct(dlg_title, message, title, type, isStatic, isPlain);};

MsgDialog.prototype = new Dialog('%inherit%');
MsgDialog.prototype.constructor = MsgDialog;
MsgDialog.prototype.msg = null;

/**
 * Construct Message dialog 
 * @param {string} dlg_title dialog title
 * @param {string} message message text
 * @param {string} title message title
 * @param {string} type message type (value one of: error, success, info, block)
 * @param {boolean} isStatic prevents dialog from reacting to esc button and from closing with X button
 */
MsgDialog.prototype.__construct = function(dlg_title, message, title, type, isStatic, isPlain) {
	Dialog.prototype.__construct.call(this, dlg_title, isStatic);
	
	this.msg = $('<div class="alert alert-danger" style="margin: 0px;">' +
			'<span></span>' +
		'</div>');
	
	this.content.empty().append(this.msg);

	this.addButton(__("OK"));
	
	if (isPlain) {
		var thisSelf = this;
		this.setTitleVisible(false);
		this.setFooterVisible(false);
		this.dialog.on('click', function() { thisSelf.setVisible(false); });
	}
	
	if (message || title) {
		this.setMessage(message, title, type);
	}
	
};

/**
 * Set inline message
 * @param message message text
 * @param title message title
 * @param type message type (value one of: error, success, info, block)
 */
MsgDialog.prototype.setMessage = function(message, title, type) {
	var msg = (title ? ("<strong>" + title + "</strong> ") : "") + message;
	this.msg.children("span").html(msg);
	this.msg.removeClass("alert-error alert-danger alert-success alert-info alert-block alert-error-big");
	if (type === "error" || type === "danger" || type === "success" || type === "info" || type === "block") {
		this.msg.addClass("alert-" + ((type === 'error') ? 'danger' : type));
	} else if (type === "error-big") {
		this.msg.addClass("alert-error-big");
		var cErrMsg = wb_builder.commonErrorMessage ? wb_builder.commonErrorMessage : __('If you see this error once again, please contact us through the “Support“ section (lower left).');
		msg = (msg ? (msg + "<br><br>") : "") + __('If you see this message, it means that we are already informed and are working on it. We apologize for the inconvenience.')
			+ '<br><br>'
			+ '<strong>' + __('Relax for 5 minutes.') + '</strong>'
			+ '<br>'
			+ cErrMsg;
		this.msg.children("span").html(msg);
	} else {
		this.msg.addClass("alert-block");
	}
};

/**
 * Set dialog visibility
 * @param {Boolean} visible dialog visibility
 * @param {Boolean} noAction
 * @param {Boolean} ignoreEvent
 */
MsgDialog.prototype.setVisible = function(visible, noAction, ignoreEvent) {
	Dialog.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
};
	
	window.WB_MsgDialog = MsgDialog;
	
	return MsgDialog;
});
;

/** WB MediaLibrary **/
(window.defineModule = (window.defineModule || {})).name = 'WB MediaLibrary';

define('MediaLibrary', ['Dialog', 'Service', 'UIButton', 'FreeGallery', 'BuilderEvent'], function(Dialog, Service, UIButton, FreeGallery, BuilderEvent) {
	'use strict';

/**
 * Media Library class
 * Dialog used to select one or multiple images from library
 * @param {String} title
 * @param {Boolean} multi
 * @param {String} mode
 * @param {Boolean} showTabs
 * @param {Boolean} showFontAwesomeTab
 */
var MediaLibrary = function(title, multi, mode, showTabs, showFontAwesomeTab) {this.__construct(title, multi, mode, showTabs, showFontAwesomeTab);};

MediaLibrary.prototype = new Dialog('%inherit%');
MediaLibrary.prototype.constructor = MediaLibrary;

MediaLibrary.prototype.tabbedPane = null;
/** @type string|null */
MediaLibrary.prototype.tabActive = null;
MediaLibrary.prototype.myTab = null;
MediaLibrary.prototype.freeTab = null;
MediaLibrary.prototype.urlTab = null;
MediaLibrary.prototype.tagSelected = null;
MediaLibrary.prototype.tagMenu = null;
MediaLibrary.prototype.selectedFiles = null;
MediaLibrary.prototype.isMultiselect = false;
MediaLibrary.prototype.uploader = null;
MediaLibrary.prototype.uploaderForm = null;
MediaLibrary.prototype.uploaderCounter = 0;
MediaLibrary.prototype.gallery = null;
MediaLibrary.prototype.galleryLoaded = false;
MediaLibrary.prototype.selList = null;
MediaLibrary.prototype.thumb = null;
MediaLibrary.prototype.progress = null;
MediaLibrary.prototype.msg = null;
MediaLibrary.prototype.mode = 'all';				//all,image,sound,flash
MediaLibrary.prototype.showTabs = false;			//show other tabs except My Gallery and Font Awesome
MediaLibrary.prototype.customContent = null;
MediaLibrary.prototype.showFontAwesomeTab = false;		//show Font Awesome tab
MediaLibrary.prototype.galMsg = null;
MediaLibrary.prototype.flickrInfo = {};
MediaLibrary.prototype.flickrKey = '881fe8a1a99a491e17c4adf1f46b0350';
MediaLibrary.prototype.flickrListRandomUrl = 'https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&safe_search=1&sort=random&privacy_filter=1&per_page=25&format=json&jsoncallback=?';
MediaLibrary.prototype.flickrListUrl = 'https://api.flickr.com/services/rest/?method=flickr.photos.search&safe_search=1&license=7,9,10&extras=description,license,date_upload,date_taken,owner_name,icon_server,original_format,last_update,geo,tags,machine_tags,o_dims,views,media,path_alias,url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c,url_l,url_o&sort=relevance&privacy_filter=1&per_page=25&format=json&jsoncallback=?';
MediaLibrary.prototype.flickrImagesUrl = 'https://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&jsoncallback=?';
MediaLibrary.prototype.fontAwesomeInfo = {};
MediaLibrary.prototype.urlInfo = {};
MediaLibrary.prototype.requiresRevalidation = true; // forces to reload tag and item lists on next dialog open
MediaLibrary.prototype._freeGalleryLoaded = false;

MediaLibrary.fontAwesomeIcons = null;
MediaLibrary.flickrNudityRegex = /nackt|porn|whore|slut|suck|mature|nude|nudity|teen|pussy|masturb|dick|penis|cock|blowjob|xxx|naught|cum|hot|wife/i;
MediaLibrary.fuzzyPhoto = 'modules/builder/img/flickr-fuzzy.png';

/**
 * Construct media library
 * @param {string} title media library dialog title
 * @param {boolean} multi allow multi select
 * @param {string} mode filter list to show only one of (audio, images, flash...)
 * @param {boolean} showTabs show the rest tabs?
 * @param {boolean} showFontAwesomeTab show the font awesome tab?
 */
MediaLibrary.prototype.__construct = function(title, multi, mode, showTabs, showFontAwesomeTab) {
	Dialog.prototype.__construct.call(this, title);
	var thisClass = this;
	this.isMultiselect = multi ? true : false;
	this.mode = (typeof(mode) === 'undefined') ? 'all' : mode;
	this.showTabs = showTabs ? true : false;
	this.showFontAwesomeTab = showFontAwesomeTab ? true : false;
	this.selectedFiles = [];
	this.flickrInfo = {};
	this.urlInfo = {};
	var filters = [
		{title : __('All'), extensions : "jpg,jpeg,gif,png,svg,ico,psd,swf,mp3,aac,wav,ra,midi,ram,wma,ogg,ape,mp4,mpeg,avi,flv,mkv,mov,pdf,docx,doc,xls,xlsx,rtf,ppt,pptx,odt,txt,csv,html,xml,yml,rar,zip,eps,cdr"},
		{title : __('Images'), extensions : "jpg,jpeg,gif,png,svg"},
		{title : __('Favicon'), extensions : "jpg,jpeg,gif,png,ico"},
		{title : __('Flash'), extensions : "swf"},
		{title : __('Audio'), extensions : "mp3,aac,wav,ra,midi,ram,wma,ogg,ape"}
	];
	var modes = ["all", "image", "favicon", "flash", "audio"];
	if (this.mode !== 'all') {
		var idx = $.inArray(this.mode, modes);
		if (idx !== -1) filters = [filters[idx]];
	}
	var rt = ((!$.browser.msie && !$.browser.opera) ? 'html5,' : '') + 'flash,gears,html4';
	this.setContent(new Service.UIBuilder({
		type: 'TabbedPane', id: 'tabbedPane',
		tabs: [
			{name: __('Template Gallery'), type: 'gallery-main', children: [ // this.myTab
				{type: 'HorizontalLayout', columnWeights: ((this.mode !== 'image') ? null : [3, 9]), css: {marginTop: ((this.mode === 'all') ? 0 : 15)}, children: [
					{type: 'VerticalLayout', ignore: (this.mode !== 'image'), children: [
						{type: 'CustomContainer',
							ignore: (this.mode !== 'image'),
							styleClass: 'wb-list-control well wb-media-gallery-list-control',
							init: function() {
								var iBlock, iInput, eBlock, addCat;
								thisClass.tagMenu = $('<ul>').addClass('nav nav-pills nav-stacked tag-menu')
									.append('<li class="active"><a class="tag-item" href="javascript:void(0)"><i class="glyphicon glyphicon-folder-open"></i> ' + __('All') + '</a></li>')
									.on('click', '.tag-item', function() {
										thisClass.selectImageCat($(this).parent().data('tag'));
									})
									.on('click', '.btn-rem', function() {
										if (confirm(__("Remove this category? All files in it will be deleted!"))) {
											var thisBtn = $(this);
											var cat = $(this).closest('li').data('tag');
											$.post(wb_builder.getUrl('del_image_cat'), {cat: cat}, function(data) {
												if (data.status === 'ok') {
													var li = thisBtn.parents('li');
													if (li.hasClass('active')) {
														thisClass.tagMenu.find('li:first-child a').click();
													}
													li.remove();
													/* $.each(thisClass.gallery.find('.tag-sort'), function() {
														if ($(this).data('tag') === cat) {
															$(this).remove();
														}
													}); */
													thisClass.invalidate();
												} else {
													thisClass.showMessage(data.msg, '<i class="glyphicon glyphicon-warning-sign"></i>', 'error', eBlock);
												}
											});
										}
									})
									.sortable({
										items: 'li:not(:first)',
										update: function(e, ui) {
											$.post(wb_builder.getUrl('move_image_cat'), {
												cat: ui.item.data('tag'),
												newIndex: ui.item.index() - 1
											}, function(data) {});
											thisClass.invalidate();
										}
									})
									.appendTo(this._elem);
								if (!thisClass.customContent) {
									$('<button>').addClass('btn btn-link')
										.attr({type: 'button'})
										.css({marginLeft: '3px'})
										.append($('<i>').addClass('glyphicon glyphicon-plus')).append(' ' + __('New Item'))
										.on('click', function() {
											$(this).addClass('hide');
											iBlock.removeClass('hide');
											iInput.focus();
										})
										.appendTo(this._elem);
								}
								iBlock = $('<div>').addClass('input-group input-group-sm hide')
									.css({margin: '8px 0 0 8px'})
									.append(iInput = $('<input>').addClass('form-control')
												.attr({type: 'text'})
												.css({width: 100})
												.keyup(function(e) { if (e.keyCode === 13) addCat(); }))
									.append($('<span>').addClass('input-group-btn').append(
											$('<button>').addClass('btn btn-default')
												.append($('<i>').addClass('glyphicon glyphicon-plus'))
												.on('click', function() { addCat(); })))
									.appendTo(this._elem);
								eBlock = $('<div>').css({margin: '8px 0 0 -22px'}).appendTo(this._elem);
								addCat = function() {
									var v = $.trim(iInput.val());
									if (v) {
										$.post(wb_builder.getUrl('add_image_cat'), {cat: v}, function(data) {
											if (data.status === 'ok') {
												thisClass.addImageCat(data.cat);
												iInput.val('');
											} else {
												thisClass.showMessage(data.msg, '<i class="glyphicon glyphicon-warning-sign"></i>', 'error', eBlock);
											}
										});
									}
								};
								$('li', this.tagMenu).disableSelection();
							}
						},
						{type: 'CheckBox', id: 'showAllTagsBtn', label: __('Show All Tags'), visible: false,
							change: function() {
								if (this.getValue()) {
									wb_builder.setCookie('wb_show_all_tags', 'Y');
									this.defOriginalValue = thisClass.customContent;
									thisClass.customContent = null;
									thisClass.loadGallery();
								} else {
									wb_builder.setCookie('wb_show_all_tags', 'N');
									if (!thisClass.customContent && this.defOriginalValue) {
										thisClass.customContent = this.defOriginalValue;
									}
									thisClass.loadGallery();
								}
							}
						}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'FlowLayout', verticalAlign: 'middle', children: [
							{type: 'Label', id: 'galMsg', css: {lineHeight: '30px'}, text: (
								(this.mode === 'image' || this.mode === 'favicon')
									? (this.isMultiselect
										? __('Select pictures by clicking below or')
										: __('Select picture below or')
									  )
									: __('Select file below or')
							)},
							{type: 'Button', buttonStyle: UIButton.UIButton.STYLE_INFO,
								css: {marginTop: '-5px'},
								attr: {id: this.id + '_uploader'},
								text: (
									(this.mode === 'image' || this.mode === 'favicon')
										? __('Upload New Picture')
										: __('Upload New File')
								),
								init: function(def) {
									var extensions = [];
									for (var i = filters.length - 1; i >= 0; i--) {
										extensions.splice(0, 0, filters[i].extensions.split(','));
									}
									var extRegExp = new RegExp('(\\.|\\/)(' + extensions.join('|') + ')$');

									thisClass.uploaderForm = $('<form>')
										.append($('<input type="file" name="file" multiple="multiple" />').attr('accept', extensions.join(',')))
									;
									thisClass.uploader = this.getElem().fileupload({
										fileInput: thisClass.uploaderForm.find('input'),
										url: wb_builder.getUrl("upload") + ((thisClass.mode === 'favicon') ? ('?mode=' + thisClass.mode) : ''),
										dataType: 'json',
										sequentialUploads: true,
										autoUpload: true,
										disableImagePreview: true,
										disableImageResize: false,
										imageMaxWidth: 1920,
										imageMaxHeight: 1080,
										imageOrientation: true,
										loadImageMaxFileSize: 50000000, // max size in memory, not for upload
										maxFileSize: wb_builder.maxUploadFileSize,
										acceptFileTypes: extRegExp
									});
								}
							},
							{type: 'FlowLayout', css: {float: 'right'}, ignore: (this.mode !== 'all'), children: [
								{type: 'Label', text: (__('Show') + ':')},
								{type: 'DropdownBox',
									css: {marginTop: '-5px', maxWidth: 160},
									value: this.mode,
									options: [
										{name: __('All'), id: 'all'},
										{name: __('Images'), id: 'image'},
										{name: __('Audio'), id: 'audio'},
										{name: __('Flash'), id: 'flash'}
									],
									change: function() {
										thisClass.mode = this.getValue();
										thisClass.clearGallery();
										thisClass.loadGallery();
									}
								}
							]}
						]},
						{type: 'CustomContainer', id: 'gallery', tag: 'ul',
							styleClass: 'thumbnails wb_media_library',
							css: {marginTop: '15px'},
							attr: {id: 'galList' + this.id}
						}
					]}
				]}
			]},
			{name: __('Free Gallery'), type: 'gallery-free', ignore: !this.showTabs,
				init: function() { thisClass.loadFlickContent(this); }
			},
			{name: __('Picture URL'), type: 'gallery-url', ignore: !this.showTabs,
				init: function() { thisClass.loadUrlContent(this); }
			},
			{name: __('Font Awesome Icon'), type: 'gallery-icons', ignore: !this.showFontAwesomeTab,
				init: function() { thisClass.loadFontAwesomeContent(this); }
			}
		],
		change: function(fields, tab) {
			thisClass.hideProgress();
			var selTab = fields.tabbedPane.getSelectedTabDef();
			thisClass.tabActive = selTab ? selTab.type : null;
			if (thisClass.tabActive === 'gallery-free' && !thisClass.flickrInfo.galleryLoaded) {
				thisClass.loadFlickrGallery();
			}
		}
	}), true);
    this.setSize(760);
	
	this.gallery = this.fields.gallery.getElem();
	this.galMsg = this.fields.galMsg.getElem();

	thisClass.uploader.on('click', function(e) {
		thisClass.uploaderForm.find('input').trigger('click');
	});

	this.uploader.on('fileuploadadd', function(e, data) {
		if (thisClass.uploaderCounter === 0) {
			thisClass.hideMessage();
			thisClass.showProgress(0, true);
		}
		thisClass.uploaderCounter++;
	});

	this.uploader.on('fileuploadalways fileuploadprocessfail', function(e, data) {
		if (--thisClass.uploaderCounter <= 0) {
			thisClass.hideProgress(false, false);
		}
	});

	this.uploader.on('fileuploadsubmit', function(e, data) {
		if (typeof thisClass.tagSelected === 'string') {
			data.formData = {tag: thisClass.tagSelected};
		}
	});

	this.uploader.on('fileuploadprogressall', function(e, data) {
		var addMsg = thisClass.uploaderCounter ? (__('Files left:') + thisClass.uploaderCounter) : null;
		thisClass.showProgress(Math.floor(100 * (data.total ? (data.loaded / data.total) : 1)), true, addMsg);
	});

	this.uploader.on('fileuploaddone', function(e, data) {
		var r = data.result;
		if (typeof r === "object") {
			if ("error" in r) {
				if (r.error.verifySession) {
					wb_builder.verifySession(function(sess, req) {
						if (sess && req) thisClass.showMessage(__pr(r.error.message), __("Upload error"), "error");
					});
				} else {
					thisClass.showMessage(__pr(r.error.message), __("Upload error"), "error");
				}
			}
			else {
				var fileName = r.result ? r.result : data.files[0].name.toLowerCase();
				var thumbDir = (!r.hasOwnProperty("hasThumb") || r.hasThumb) ? 'thumbs/' : '';
				var thumb = thisClass.addThumb(wb_builder.userGalleyUrl + thumbDir + fileName , true);
				thumb.click();
				thisClass.invalidate();
			}
		}
	});

	this.uploader.on('fileuploadprocess', window.prepareAutoScaleOptions);


	this.progress = $('<div class="wb_media_progress_wrap">' +
				'<div class="wb_media_progress progress">' +
					'<div class="progress-bar progress-bar-striped active" style="width: 1%;">' +
						'<span class="sr-only"></span>' +
					'</div>' +
				'</div>' +
				'<div class="status"></div>' +
				'<div class="status2"></div>' +
			'</div>');
	
	this.msg = $('<div class="alert alert-danger">' +
			'<a class="close" data-dismiss="alert" href="#">&times;</a>' +
			'<span></span>' +
		'</div>');
	
	this.thumb = $('<li class="thumb-li">' +
			'<a href="javascript:void(0)" class="btn btn-default btn-xs" style="display: none;"><i class="glyphicon glyphicon-remove"></i></a>' +
			'<a href="javascript:void(0)" class="thumbnail">' +
				'<img src="" alt="" />' +
			'</a>' +
			'<span class="wb_thumb_name"></span>' +
		'</li>');
	
	//"Add New" thumb start
	var thumb = this.thumb.clone().addClass("firstThumb");
	var name = __("Add New");
	$("span", thumb).remove();
	$("img", thumb).remove();
	$("a.thumbnail", thumb).attr({"title": name, id:"addNewThumb"+this.id}).append('<span class="empty"><i class="glyphicon glyphicon-plus"></i><span class="name">'+name+'</span></span>');
	this.gallery.prepend(thumb);
	thumb.fadeIn();
	$('#addNewThumb'+this.id).on('click', function(e) {
		thisClass.uploaderForm.find('input').trigger('click');
	});
	Service.templates.addChangeListener(function() {
		thisClass.requiresRevalidation = true;
	});
};

MediaLibrary.prototype.setCustomContent = function(customContent) {
	this.customContent = customContent;
	if (this.fields.showAllTagsBtn) {
		this.fields.showAllTagsBtn.setVisible((this.customContent ? true : false));
		if (wb_builder.getCookie('wb_show_all_tags') === 'Y') {
			this.fields.showAllTagsBtn.defOriginalValue = this.customContent;
			this.customContent = null;
			this.fields.showAllTagsBtn.setValue(true);
		}
	}
};

MediaLibrary.prototype.sort = function(scrollToThumb) {
	var thumbs = this.gallery.find('.thumb-li:not(.firstThumb)').toArray();
	thumbs.sort(function(a, b) {
		var an = $(a).children('.wb_thumb_name').text(),
			bn = $(b).children('.wb_thumb_name').text();
		if (an === bn) return 0;
		return (an > bn) ? 1 : -1;
	});
	for (var i in thumbs) {
		this.gallery.append(thumbs[i]);
	}
	if (scrollToThumb) {
		var scroll = scrollToThumb.offset().top - this.gallery.offset().top;
		this.gallery.get(0).scrollTop = scroll;
	}
};

/**
 * Loads image url content to selected content
 * 
 * @param content Where to append Flick content
 */
MediaLibrary.prototype.loadUrlContent = function(content) {
	var thisClass = this, searchFunc;
	Service.UIBuilder.buildLayout({type: 'VerticalLayout', css: {marginTop: '15px'}, children: [
		{type: 'Label', text: __('Picture URL')},
		{type: 'FlowLayout', children: [
			{type: 'TextField', id: 'urlInput', value: 'http://', init: function() {
				this.on('keyup', function(e) {
					if (e.keyCode === 13) searchFunc();
				});
			}},
			{type: 'Button', text: __('Insert'),
				buttonStyle: UIButton.UIButton.STYLE_INFO,
				click: (searchFunc = function() {
					thisClass.loadUrlImage();
				})
			}
		]},
		{type: 'CustomContainer', tag: 'span', styleClass: 'help-block help-block-sm',
			content: (__('Example') + ': http://www.google.com/images/srpr/logo3w.<u>png</u>')
		},
		{type: 'CustomContainer', id: 'imgPreview',
			styleClass: 'thumbnail',
			css: {marginTop: 15, marginBottom: 0, minHeight: 190, maxHeight: 190, overflow: 'hidden'},
			init: function() {
				var img, prev, err;
				this.getElem()
					.append(img = $('<img>').css({minHeight: 170}).hide())
					.append(prev = $('<div>')
						.css({textAlign: 'center', marginTop: 76, color: '#999999'})
							.text(__('Preview')))
					.append(err = $('<span>').addClass('alert error').hide()
						.text(__('URL is incorrect. May be you forgot ".jpg" or ".png" at the end of URL')));
				
				this.setImage = function(url) {
					var ext = url.split('.'); 
					ext = ext[ext.length - 1];
					if (ext && (true || $.inArray(ext.toLowerCase(), ['jpg', 'jpeg', 'gif', 'png']) !== -1)) {
						img.get(0).src = thisClass.urlInfo.url = url;
						img.show();
						err.hide();
					} else {
						img.hide();
						err.show();
					}
					prev.addClass('hide');
					this.css({minHeight: 'auto'});
					thisClass.checkSelected();
				};
			}
		}
	]}, content, this.fields);
};

/**
 * Load image from url
 */
MediaLibrary.prototype.loadUrlImage = function() {
	this.fields.imgPreview.setImage(this.fields.urlInput.getValue());
};

/**
 * Loads flick media to selected content
 * 
 * @param content Where to append Flick content
 */
MediaLibrary.prototype.loadFlickContent = function(content) {
	var thisClass = this, searchFunc;
	Service.UIBuilder.buildLayout({type: 'VerticalLayout', css: {marginTop: '15px'}, children: [
		{type: 'FlowLayout', children: [
			{type: 'TextField', id: 'searchInput', init: function() {
					this.on('keyup', function(e) {
						if (e.keyCode === 13) searchFunc();
					});
			}},
			{type: 'Button', text: __('Search'),
				buttonStyle: UIButton.UIButton.STYLE_INFO,
				click: (searchFunc = function() {
					thisClass.flickrInfo.searchPhrase = thisClass.fields.searchInput.getValue();
					thisClass.loadFlickrGallery();
				})
			}
		]},
		{type: 'CustomContainer', id: 'flcrGallery', tag: 'ul',
			styleClass: 'thumbnails wb_media_library',
			css: {marginTop: '15px'},
			attr: {id: 'galList' + this.id +'_flcr'}
		}
	]}, content, this.fields);
	this.flickrInfo.gallery = this.fields.flcrGallery.getElem();
};

/**
 * Loads flick gallery, if we have this.flickrInfo.searchPhrase - will do the search, otherwise random images
 * @param reset
 */
MediaLibrary.prototype.loadFlickrGallery = function(noReset) {
	if (this.flickrInfo.galleryLoading) return false;
	this.flickrInfo.galleryLoading = true;
	var thisClass = this;
	if (!this._freeGalleryLoaded) {
		this._freeGalleryLoaded = true;
		FreeGallery.Module.init({
			perPage: 25,
			beforeForEach: function() {
				if (thisClass.flickrInfo.showMoreThumb) thisClass.flickrInfo.showMoreThumb.remove();
			},
			forEach: function(i, item) {
				thisClass.addThumb(item.thumb, false, thisClass.flickrInfo.gallery, { title: item.title, url: item.url, name: item.name });
				thisClass.showProgress(parseInt((i + 1) / FreeGallery.Module.current.totalImages * 100), true);
			},
			emptyList: function() {
				thisClass.showMessage(__("No images found."), '<i class="glyphicon glyphicon-warning-sign"></i>', "error", thisClass.flickrInfo.gallery);
				thisClass.flickrInfo.galleryLoading = false;
				thisClass.flickrInfo.galleryLoaded = true;
				thisClass.hideProgress();
			},
			afterForEach: function() {
				thisClass.flickrInfo.showMoreThumb = thisClass.thumb.clone();
				var name = __("Show more");
				$("span", thisClass.flickrInfo.showMoreThumb).remove();
				$("img", thisClass.flickrInfo.showMoreThumb).remove();
				$("a.thumbnail", thisClass.flickrInfo.showMoreThumb).attr({"title": name}).append('<span class="empty"><i class="glyphicon glyphicon-plus"></i><span class="name">'+name+'</span></span>').click(function() {
					FreeGallery.Module.load(thisClass.flickrInfo.searchPhrase);
				});
				thisClass.flickrInfo.gallery.append(thisClass.flickrInfo.showMoreThumb);
				thisClass.flickrInfo.showMoreThumb.fadeIn();
				thisClass.flickrInfo.galleryLoading = false;
				thisClass.flickrInfo.galleryLoaded = true;
				thisClass.hideProgress();
			}
		});
	}
	if (!noReset) {
		FreeGallery.Module.resetPages();
		this.flickrInfo.gallery.empty();
	}
	this.showProgress(0, true);
	FreeGallery.Module.load(thisClass.flickrInfo.searchPhrase);
};

/**
 * Loads Font Awesome media to selected content
 *
 * @param content Where to append Font Awesome content
 */
MediaLibrary.prototype.loadFontAwesomeContent = function(content) {
	var thisClass = this, searchFunc;
	Service.UIBuilder.buildLayout({type: 'VerticalLayout', css: {marginTop: '15px'}, children: [
		{type: 'FlowLayout', children: [
			{type: 'TextField', id: 'fontAwesomeSearchInput', init: function() {
				this.on('keyup', function(e) {
					searchFunc();
				});
			}},
			{type: 'Button', text: __('Search'),
				buttonStyle: UIButton.UIButton.STYLE_INFO,
				click: (searchFunc = function() {
					thisClass.fontAwesomeInfo.searchPhrase = thisClass.fields.fontAwesomeSearchInput.getValue();
					thisClass.renderFontAwesomeGallery();
				})
			}
		]},
		{type: 'CustomContainer', id: 'fontAwesomeGallery', tag: 'ul',
			styleClass: 'wb_media_library font_awesome_icons',
			css: {marginTop: '15px'},
			attr: {id: 'galList' + this.id +'_fontAwesome'}
		}
	]}, content, this.fields);
	this.fontAwesomeInfo.rendered = false;
	this.fontAwesomeInfo.searchPhrase = "";
	this.fontAwesomeInfo.gallery = this.fields.fontAwesomeGallery.getElem();
	thisClass.loadFontAwesomeGallery();
};

MediaLibrary.prototype.loadFontAwesomeGallery = function() {
	if( MediaLibrary.fontAwesomeIcons === null ) {
		MediaLibrary.fontAwesomeIcons = [];
		var thisClass = this;
		$.ajax({
			url: wb_builder.getFontAwesomeIconsUrl,
			success: function(data){
				if( typeof data === "object" && ("success" in data) && data.success ) {
					MediaLibrary.fontAwesomeIcons = data.icons;
					thisClass.renderFontAwesomeGallery();
				}
				else {
					MediaLibrary.fontAwesomeIcons = null;
					setTimeout(thisClass.loadFontAwesomeGallery.bind(thisClass), 60000); // retry loading in 1 minute
				}
			},
			error: function(data){
				setTimeout(thisClass.loadFontAwesomeGallery.bind(thisClass), 60000); // retry loading in 1 minute
			},
			dataType: "json"
		});
	}
	else
		this.renderFontAwesomeGallery();
};

MediaLibrary.prototype.renderFontAwesomeGallery = function() {
	if( !MediaLibrary.fontAwesomeIcons || !MediaLibrary.fontAwesomeIcons.length )
		return;

	var thisClass = this;
	var $container = this.fontAwesomeInfo.gallery;

	if( !this.fontAwesomeInfo.rendered ) {
		this.fontAwesomeInfo.rendered = true;
		for( var i = 0, il = MediaLibrary.fontAwesomeIcons.length; i < il; i++ ) {
			var icon = MediaLibrary.fontAwesomeIcons[i];
			var name = icon.names[0];
			$container.append($('<li>')
				.append($('<i class="fa fa-' + name + '"></i>'))
				.append($('<span>').text(name))
				.data("faIcon", icon)
				.attr("title", icon.names.join("\n"))
				.on("click touchend", function() {
					if (thisClass.isMultiselect) {
						$(this).toggleClass("active");
					} else {
						thisClass.dialog.find(".wb_media_library").children().removeClass("active");
						$(this).addClass("active");
					}
					thisClass.checkSelected();
				})
			);
		}
	}

	if( this.fontAwesomeInfo.searchPhrase === "" ) {
		$container.children().removeClass("hidden");
	}
	else {
		$container.children().each(function() {
			var $this = $(this);
			var icon = $this.data("faIcon");
			var visible = ($this.hasClass("active") || icon.character.indexOf(thisClass.fontAwesomeInfo.searchPhrase) >= 0);
			if( !visible ) {
				for( var i = 0; i < icon.names.length; i++ ) {
					if( icon.names[i].indexOf(thisClass.fontAwesomeInfo.searchPhrase) >= 0 ) {
						visible = true;
						break;
					}
				}
			}
			if( visible )
				$this.removeClass("hidden");
			else
				$this.addClass("hidden");
		});
	}
};

MediaLibrary.prototype.clearGallery = function() {
	this.gallery.children("li:not(.firstThumb)").remove();
	this.galleryLoaded = false;
	this.invalidate();
};

/**
 * Reload gallery
 * @param {null} cb
 */
MediaLibrary.prototype.loadGallery = function(cb) {
	var thisClass = this;
//	this.gallery.empty();
	this.hideMessage();
	this.showProgress(0).children(".progress-bar").animate({width: "100%"}, 10000);
	this.clearGallery();
	var thisData;
	$.get(wb_builder.getUrl("upload_list"), {mode:this.mode}, function(data) {
		var reselectTag = null;
		if (data && (typeof data === 'object') && ('error' in data)) {
			thisData = [];
			if (data.error.verifySession) {
				wb_builder.verifySession(function(sess, req) {
					if (sess && req) thisClass.showMessage(data.error.message, '<i class="icon-warning-sign"></i>', 'error');
				});
			} else {
				thisClass.showMessage(data.error.message, '<i class="icon-warning-sign"></i>', 'error');
			}
		} else {
			if (thisClass.mode === 'image' && WB_Builder.isset(data.list)) {
				thisData = data.list;
				if (thisClass.tagMenu) {
					thisClass.tagMenu.children('li:not(:first)').remove();
					if (thisClass.customContent && (typeof thisClass.customContent === 'object')) {
						for (var i in thisClass.customContent) {
							thisClass.addImageCat(i, true);
							if (!reselectTag) reselectTag = i;
						}
						thisData = thisClass.filterDataByCustomContent(thisData, thisClass.customContent);
					} else if (data.tags) {
						reselectTag = thisClass.tagMenu.children('li.active').data('tag');
						$.each(data.tags, function(i, el) {
							if (el === undefined || el === null || el === false) return;
							thisClass.addImageCat(el);
						});
					}
				}
			} else {
				thisData = data;
			}
		}
		thisClass.hideProgress(false, function() {
			if (thisData && thisData.length) {
				
//				thisClass.gallery.show();
				for (var i = 0; i < thisData.length; i++) {
					thisClass.addThumb(thisData[i]);
				}
				thisClass.setSelectedFiles(thisClass.selectedFiles);
				thisClass.checkSelected();
			} else {
				thisClass.showMessage(__("No files found."), '<i class="icon-info-sign"></i>', "info");
			}
			thisClass.selectImageCat(reselectTag);
			thisClass.requiresRevalidation = false;
		});
	}).error(function() {
		thisClass.hideProgress(false, function() {
			thisClass.showMessage(__("File loading failed."), '<i class="icon-warning-sign"></i>', "error");
		});
	});
	this.galleryLoaded = true;
};

MediaLibrary.prototype.filterDataByCustomContent = function(data, customContent) {
	var customImagesMap = {}, basename;
	for (var i in customContent) {
		for (var j = 0; j < customContent[i].length; j++) {
			basename = customContent[i][j].split('/').pop();
			customImagesMap[basename] = i;
		}
	}
	for (i = 0; i < data.length; i++) {
		basename = data[i].file.split('/').pop();
		if (basename in customImagesMap) {
			data[i].tag = customImagesMap[basename];
		}
	}
	return data;
};

/**
 * Check if any thumbs selected and disable primary button if needed
 */
MediaLibrary.prototype.checkSelected = function() {
	var selected = this.getSelectedFiles(true);
	if (!selected.length) {
		this.buttons.find(".btn-success").attr("disabled", "disabled");
	} else {
		this.buttons.find(".btn-success").removeAttr("disabled");
	}
};

/**
 * Add image thumb to gallery
 * 
 * @param {String} url image url
 * @param {Boolean} prepend if true thumb will be prepended, otherwise - appended to gallery
 * @param {Object} gallery where to insert thumbs, if undefined - this.gallery will be used
 * @param {Object} external image info
 * @param {number} size
 */
MediaLibrary.prototype.addThumb = function(url, prepend, gallery, external, size) {
	var thumb = this.thumb.clone();
	if (size) thumb.removeClass('span2').addClass('span' + size);
	var imgData = $.extend({
			width: 0, height: 0, size: 0
		}, ((typeof url === "object") ? url : { file: url }));
    var tag = this.tagSelected;
	if (typeof url === "object") {
        tag = WB_Builder.isset(url.tag) ? url.tag : null;
        url = url.file;
    }
    thumb.addClass('tag-sort');
    thumb.data('tag', tag);

	var name;
	if (external && ('name' in external) && external.name !== null) {
		name = external.name;
	} else {
		name = url.split("/");
		name = name[name.length - 1];
	}
	var title = name.replace(/-ts\d+/gi, "");
	if (imgData.width > 0 && imgData.height > 0) {
		title += " (" + imgData.width + "x" + imgData.height + ")";
	}
	
	if (!gallery) gallery = this.gallery;

	$("a.thumbnail", thumb).attr("title", (external ? external.title : title));
	$("span", thumb).html(name);
	var thumbUrl = url;
	var ext = url.split(".");
	ext = (ext.length > 1) ? ext[(ext.length - 1)] : "";
	if (ext === "swf") {
		thumbUrl = wb_builder.modBaseUrl + "img/file_flash.png";
	} else if ("mp3,aac,wav".indexOf(ext) >= 0) {
		thumbUrl = wb_builder.modBaseUrl + "img/file_audio.png";
	} else if (ext === "pdf") {
		thumbUrl = wb_builder.modBaseUrl + "img/file_pdf.png";
	} else if ("docx,doc,xls,xlsx,rtf,ppt,pptx,odt".indexOf(ext) >= 0) {
		thumbUrl = wb_builder.modBaseUrl + "img/file_doc.png";
	} else if (ext === "rar") {
		thumbUrl = wb_builder.modBaseUrl + "img/file_rar.png";
	} else if (ext === "zip") {
		thumbUrl = wb_builder.modBaseUrl + "img/file_zip.png";
	} else if ("mp4,mpeg,avi,flv,mkv,mov".indexOf(ext) >= 0) {
		thumbUrl = wb_builder.modBaseUrl + "img/file_video.png";
	} else if ("psd,csv,html,xml,yml,txt".indexOf(ext) >= 0) {
		thumbUrl = wb_builder.modBaseUrl + "img/file_doc.png";
	}
	$("img", thumb).attr("src", thumbUrl + "?ts=" + (new Date()).getTime());
	if (!external) {
		thumb.data("url", wb_builder.userGalleyUrl + name);
		thumb.data("wb_width", imgData.width);
		thumb.data("wb_height", imgData.height);
		thumb.data("wb_size", imgData.size);
	} else {
		thumb.data("url", external.url);
		thumb.data("external", 1);
		$("a.btn", thumb).remove();
	}
		
	//thumb.css("opacity", 0);
	var thisClass = this;
	thumb.on("click touchend", function() {
		if (thisClass.isMultiselect) {
			$(this).toggleClass("active");
		} else {
			thisClass.dialog.find(".wb_media_library").children().removeClass("active");
			$(this).addClass("active");
		}
		thisClass.checkSelected();
	}).bind("dblclick", function(e) {
		e.stopPropagation();
		if (!thisClass.isMultiselect) {
			thisClass.dialog.find(".wb_media_library").children().removeClass("active");
		}
		$(this).addClass("active");
		thisClass.buttons.find(".btn-success").click();
	}).hover(
		function() {
			$("a.btn", this).css("display", "block");
		}, function() {
			$("a.btn", this).css("display", "none");
		}
	);
	$("a.btn", thumb).bind("click touchend", function(e) {
		if (confirm(__("Remove this file?"))) {
			var url = wb_builder.makeRelUrl($("img", thumb).get(0).src.split("?", 2)[0]);
			$.get(wb_builder.getUrl("upload_remove"), { filename: name });
			thumb.remove();
			thisClass.invalidate();
		}
		e.stopPropagation();
		return false;
	});
	if (typeof(prepend) === "undefined") prepend = false;
	if (prepend) {
		if ($(".firstThumb", gallery).length) {
			$(".firstThumb", gallery).after(thumb);
		} else {
			gallery.prepend(thumb);
		}
	} else {
		gallery.append(thumb);
	}
	thumb.fadeIn();
	
	clearInterval(this.sortTimeInterval);
	this.sortTimeInterval = setTimeout(function() {
		thisClass.sort(thumb);
	}, 150);
	
	return thumb;
};

/**
 * Append free gallery images downloading to primary button.
 * 
 * @param {type} name
 * @param {type} callback
 * @param {type} primary
 * @param {type} cssClass
 * @returns {unresolved}
 */
MediaLibrary.prototype.addButton = function(name, callback, primary, cssClass) {
	if (primary) {
		var thisClass = this;
		var thisCallback = callback;
		callback = function() {
			if (thisClass.tabActive === 'gallery-free') {
				var items = thisClass.getSelectedFiles(), len = items.length;
				if (len > 0) thisClass.buttons.find('.btn-success').attr('disabled', 'disabled');
				var items_download = [], items_keep = [];
				for (var i=0; i < len; i++) {
					if (!/^gallery/i.test(items[i])) {
						items_download.push(items[i]);
					} else {
						items_keep.push(items[i]);
					}
				}
				var downloadImage, len_d = items_download.length, thumbs = [];
				var findLiByImgUrl = function(url) {
					var parts = url.split('/');
					var name = parts[parts.length-1];
					var pattern = new RegExp(name);
					var li = null;
					thisClass.dialog.find(".wb_media_library").find('img').each(function() {
						if (pattern.test(this.src)) {
							li = $(this).parent().parent(); return false; 
						}
					});
					return li;
				};
				(downloadImage = function(it) {
					if (it === undefined) it = 1;
					thisClass.showProgress(Math.round((it/len_d)*100), true, __('Downloading resources into gallery'));
					var url = items_download[it-1];
					$.post(wb_builder.getUrl('upload_download'), { url: url }, function(resp) {
						if (resp.ok && resp.src && resp.thumb) {
							thumbs.push(resp.thumb);
						}
						if (it === len_d) {
							thisClass.dialog.find(".wb_media_library").children(".active").removeClass('active');
							thisClass.buttons.find('.btn-success').removeAttr('disabled');
							thisClass.hideProgress(true);
							thisClass.fields.tabbedPane.selectTabByType('gallery-main');
							for (var i=0, len2=items_keep.length; i < len2; i++) {
								var li = findLiByImgUrl(items_keep[i]);
								if (li.length) li.addClass('active');
							}
							for (var i=0, len2=thumbs.length; i < len2; i++) {
								var thumb = thisClass.addThumb(thumbs[i]);
								thumb.addClass('active');
							}
							thisClass.sort();
							if (typeof(thisCallback) === 'function') thisCallback();
						} else {
							downloadImage(it+1);
						}
					});
				})();
			} else {
				if (typeof(thisCallback) === 'function') thisCallback();
			}
		};
	}
	return Dialog.prototype.addButton.call(this, name, callback, primary, cssClass);
};

/**
 * Add category to image tag menu
 *
 * @param {String} name tag name
 * @param {boolean} virtual
 */
MediaLibrary.prototype.addImageCat = function(name, virtual) {
    this.tagMenu.append('<li data-tag="'+ name +'">'
        + '<a class="tag-item" href="javascript:void(0)" title="'+ name +'">'
        + '<i class="glyphicon glyphicon-folder-open"></i> '+ name
        + '</a>'
        + (!virtual ? '<button class="btn btn-xs btn-link btn-rem"><i class="glyphicon glyphicon-remove"></i></button>' : '')
        + '</li>');
	this.invalidate();
};

/**
 * Switches view to one of image categories (tags)
 * @param {string} tagName
 */
MediaLibrary.prototype.selectImageCat = function(tagName) {
	if (this.tagMenu) {
		var $item = null;
		var thisClass = this;
		this.tagMenu.find('li').each(function() {
			var $this = $(this);
			$this.removeClass('active');
			if ($this.data('tag') === tagName || !$item) $item = $this;
		});
		$item.addClass('active');
		thisClass.tagSelected = $item.data('tag') ? ''+$item.data('tag') : null;
		if (thisClass.tagSelected) {
			thisClass.gallery.find('.tag-sort').each(function() {
				if ($(this).data('tag') === thisClass.tagSelected) {
					$(this).removeClass('hide');
				}
				else {
					$(this).addClass('hide');
				}
			});
		} else {
			thisClass.gallery.find('.tag-sort').removeClass('hide');
		}
	}
};

/**
 * Clear file selection (unselect all files)
 */
MediaLibrary.prototype.clearFileSelection = function() {
	this.dialog.find(".wb_media_library").children().removeClass("active");
//	this.gallery.children().removeClass("active");
};

/**
 * Set selected files
 * @param list list of relative file url's to select
 */
MediaLibrary.prototype.setSelectedFiles = function(list) {
	if (!list.length) return false;
	var selTabType = null;
	this.selectedFiles = list;
	this.dialog.find(".wb_media_library").children().removeClass("active");
	//1 external file selected
	if (this.showTabs && typeof this.selectedFiles[0] === "string" && this.selectedFiles[0].substr(0, 4) === 'http') {
		this.fields.urlInput.setValue(this.selectedFiles[0]);
		this.loadUrlImage();
		selTabType = 'gallery-url';
	}
	//might be multiple :F
	else {
		selTabType = 'gallery-main';
		this.dialog.find(".wb_media_library").children().each(function() {
			var k, $this = $(this);
			if( $this.data("faIcon") ) {
				var icon = $this.data("faIcon");
				for (k in list) {
					if (list.hasOwnProperty(k) && (typeof list[k] === "object") && ("faCharacter" in list[k]) && icon.character === list[k].faCharacter) {
						$this.addClass("active");
						selTabType = 'gallery-icons';
				}
			}
			}
			else {
				var url = $this.data("url") ? $this.data("url").split("?") : [""];
				url = wb_builder.makeRelUrl(url[0]);
				for (k in list) {
					if (list.hasOwnProperty(k) && (typeof list[k] === "string") && url === wb_builder.makeRelUrl(list[k])) {
						$this.addClass("active");
						selTabType = 'gallery-main';
				}
			}
			}
		});
	}
	var selTab = this.fields.tabbedPane.selectTabByType(selTabType);
	this.tabActive = selTab ? selTab.type : null;
};

/**
 * Get selected file list
 * @param {Object} asObject get selected files as object { file: ..., width: ..., height: ..., size: ... }
 * @return array of relative files url's
 */
MediaLibrary.prototype.getSelectedFiles = function(asObject) {
	var list = [];
	if (this.tabActive === 'gallery-url' && this.urlInfo.url) {
		this.clearFileSelection();
		if (asObject) {
			list[list.length] = { file: this.urlInfo.url, width: 0, height: 0, size: 0 };
		} else {
			list[list.length] = this.urlInfo.url;
		}
	}
	else {
		var thisAsObject = asObject;
		this.dialog.find(".wb_media_library").children(".active").each(function() {
			var url, $this = $(this);
			if ($this.data("faIcon")) {
				var icon = $this.data("faIcon");
				list.push({ faIcon: icon.names[0], faCharacter: icon.character });
			}
			else if ($this.data("external")) {
				url = $this.data("url");
				if (thisAsObject) {
					list[list.length] = { file: url, width: 0, height: 0, size: 0 };
				} else {
					list[list.length] = url;
				}
			}
			else {
				url = $this.data("url").split("?");
				if (thisAsObject) {
					list[list.length] = {
						file: wb_builder.makeRelUrl(url[0]),
						width: parseInt($this.data("wb_width"), 10),
						height: parseInt($this.data("wb_height"), 10),
						size: parseInt($this.data("wb_size"), 10)
					};
				} else {
					list[list.length] = wb_builder.makeRelUrl(url[0]);
				}
			}
		});
	}
	
	return list;
};

/**
 * Show progress bar
 * @param value progress bar value in percents
 * @param showVal
 * @param addMsg
 * @return progress jQuery object
 */
MediaLibrary.prototype.showProgress = function(value, showVal, addMsg) {
	//thumbnails
	if (typeof(showVal) === "undefined") showVal = false;
	this.progress.find(".progress-bar").stop().css("width", (value * 1) + "%");
	if (showVal) {
		this.progress.find(".progress-bar > span").text((value * 1) + "%");
		this.progress.children(".status").html((value * 1) + "%");
	}
	if (addMsg) {
		this.progress.children(".status2").html(addMsg);
	}
	this.dialog.find(".tab-content").fadeTo(0, 0.3);
	this.content.append(this.progress);
	this.progress.fadeIn();
	return this.progress;
};

/**
 * Hide progress bar
 * @param instant if true will be hidden instantly else with fadeout animation
 * @param callback callback to be called when hide is complete
 * @return progress jQuery object
 */
MediaLibrary.prototype.hideProgress = function(instant, callback) {
	var thisCallback = (callback && typeof(callback) === "function") ? callback : null;
	this.dialog.find(".tab-content").fadeTo(0, 1);
	this.progress.children(".status2").html('');
	if (instant) {
		this.progress.detach();
		if (thisCallback) thisCallback();
	} else {
		this.progress.fadeOut(function() {
			$(this).detach();
			if (thisCallback) thisCallback();
		});
	}
	return this.progress;
};

/**
 * Show inline message
 * @param {String} message message text
 * @param {String} title message title
 * @param {String} type message type (value one of: error, success, info, block)
 * @param {Object} container to add this message
 */
MediaLibrary.prototype.showMessage = function(message, title, type, container) {
	if (!container) container = this.gallery;
	var msg = (title ? ("<strong>" + title + "</strong> ") : "") + message;
	this.msg.children("span").html(msg);
	this.msg.removeClass("alert-error");
	this.msg.removeClass("alert-success");
	this.msg.removeClass("alert-info");
	this.msg.removeClass("alert-block");
	if (type === "error" || type === "success" || type === "info" || type === "block") {
		this.msg.addClass("alert-" + type);
	} else {
		this.msg.addClass("alert-block");
	}
	this.msg.css("opacity", 1);
	container.prepend(this.msg);
	this.msg.fadeIn();
};

/**
 * Hide inline message
 */
MediaLibrary.prototype.hideMessage = function() {
	this.msg.detach();
};

/**
 * Set dialog visibility
 * @param visible dialog visibility
 * @param noAction (optional) no show/hide action
 * @param ignoreEvent (optional) ignore event
 */
MediaLibrary.prototype.setVisible = function(visible, noAction, ignoreEvent) {
	if (visible && (!this.galleryLoaded || this.requiresRevalidation)) {
		this.loadGallery(this.checkSelected());
	}
	Dialog.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
};

MediaLibrary.prototype.createDefaultButtons = function() {
	if (this.mode !== "all") {
		var librartLink = $('<a href="javascript:void(0)" iid="fullMediaLibrary"></a>')
				.addClass('btn btn-default')
				.text(__("Full Media Library"))
				.on("click", function() {
					var lib = MediaLibrary.open(__("Upload media"), false, 'all');
					lib.galMsg.parent().hide();
					lib.addButton(__("Close"));
					lib.setVisible(true);
					return false;
				})
				.css({float: (wb_builder.rtl ? 'right' : 'left')});
		this.buttons.prepend(librartLink);
	}
};

/**
 * Updates media gallery state to reload information on next open.
 */
MediaLibrary.prototype.invalidate = function() {
	for (var i in MediaLibrary.dialogs) {
		MediaLibrary.dialogs[i].requiresRevalidation = true;
	}
};

// STATIC PROPERTIES AND METHODS

MediaLibrary.dialogs = {}; // instances of dialogs

MediaLibrary.metaCache = {};
MediaLibrary.metaRetreivalQueue = {
	timer: null,
	requests: {}
};

/**
 * Creates or returns an already existing instance of media library dialog.
 * @param {string} title
 * @param {boolean} multi
 * @param {string} mode Either "all", "image", "sound" or "flash".
 * @param {boolean} showTabs
 * @param {boolean} showFontAwesomeTab
 * @param {callback} customContentClb Should return object containing custom media contents
 * @returns {MediaLibrary}
 */
MediaLibrary.open = function(title, multi, mode, showTabs, showFontAwesomeTab, customContentClb) {
	var customContent = (typeof customContentClb === 'function') ? customContentClb() : null;
	var dtid = mode + ":" + (multi ? "1" : "0") + ":" + (showTabs ? "1" : "0") + ":" + (showFontAwesomeTab ? "1" : "0") + ":" + (customContent ? HasherUtil.crc32(JSON.stringify(customContent)) : "0");
	if( typeof(MediaLibrary.dialogs[dtid]) !== "object" ) {
		MediaLibrary.dialogs[dtid] = new MediaLibrary(title, multi, mode, showTabs, showFontAwesomeTab);
	}
	var dlg = MediaLibrary.dialogs[dtid];
	dlg.setCustomContent(customContent);
	dlg.setTitle(title);
	dlg.removeAllButtons();
	dlg.createDefaultButtons();
	dlg.clearFileSelection();
	return dlg;
};

MediaLibrary.reload = function() {
	for( var i in MediaLibrary.dialogs ) {
		if( !MediaLibrary.dialogs.hasOwnProperty(i) )
			continue;
		MediaLibrary.dialogs[i].loadGallery();
	}
};

/**
 * @param {String} path
 * @param {Function} successCallback
 * @param {Function} errorCallback
 */
MediaLibrary.getPathMeta = function(path, successCallback, errorCallback) {
	if( MediaLibrary.metaCache.hasOwnProperty(path) ) {
		if (typeof successCallback === 'function')
			successCallback(MediaLibrary.metaCache[path]);
		return;
	}

	// Wait until javascript engine enters idle state and then request all meta information in bulk instead of
	// making a request on each and every call of getPathMeta().
	if( !MediaLibrary.metaRetreivalQueue.requests.hasOwnProperty(path) )
		MediaLibrary.metaRetreivalQueue.requests[path] = [];
	MediaLibrary.metaRetreivalQueue.requests[path].push([successCallback, errorCallback]);
	if( !MediaLibrary.metaRetreivalQueue.timer ) {
		MediaLibrary.metaRetreivalQueue.timer = setTimeout(function() {
			MediaLibrary.metaRetreivalQueue.timer = null;
			var requests = MediaLibrary.metaRetreivalQueue.requests;
			MediaLibrary.metaRetreivalQueue.requests = {};
			var doCallbacks = function(cbIndex, data) {
				for( var i in requests ) {
					if( !requests.hasOwnProperty(i) )
						continue;
					var cbData = data ? ((cbIndex === 0) ? (data.hasOwnProperty(i) ? data[i] : void 0) : data) : void 0;
					for( var j = 0, jl = requests[i].length; j < jl; j++ )
						if( typeof requests[i][j][cbIndex] === "function" )
							requests[i][j][cbIndex](cbData);
					if( cbIndex === 0 )
						MediaLibrary.metaCache[i] = cbData;
				}
			};
			$.post(wb_builder.getUrl("upload_get_meta"), JSON.stringify({paths: Object.keys(requests)}), function(data) {
				if( data && (typeof data === 'object') ) {
					if ('error' in data)
						doCallbacks(1, data.error);
					else
						doCallbacks(0, data.meta);
				}
				else {
					doCallbacks(1);
				}
			}, "json").error(function(err) {
				doCallbacks(1, err);
			});
		}, 0);
	}
};

/**
 * @param {String} path
 * @param {object} meta
 * @param {Function} successCallback
 * @param {Function} errorCallback
 */
MediaLibrary.setPathMeta = function(path, meta, successCallback, errorCallback) {
	$.post(wb_builder.getUrl("upload_set_meta"), JSON.stringify({path: path, meta: meta}), function(data) {
		if( data && (typeof data === 'object') ) {
			if ('error' in data) {
				if (typeof errorCallback === 'function')
					errorCallback(data.error);
			}
			else {
				MediaLibrary.metaCache[data.path] = data.meta;
				var e = new BuilderEvent.MediaLibraryMetaChangedBuilderEvent(data.path, data.meta);
				BuilderEvent.GlobalEvents.triggerEvent("media.meta.changed", e);
				if (typeof successCallback === 'function')
					successCallback();
			}
		}
		else {
			if (typeof errorCallback === 'function')
				errorCallback();
		}
	}, "json").error(function(err) {
		if (typeof errorCallback === 'function')
			errorCallback(err);
	});
};

	Service.mediaLibrary = {
		open: MediaLibrary.open,
		reload: MediaLibrary.reload,
		getPathMeta: MediaLibrary.getPathMeta,
		setPathMeta: MediaLibrary.setPathMeta
	};
	
	return MediaLibrary;
});
;

/** WB PropertyDialog **/
(window.defineModule = (window.defineModule || {})).name = 'WB PropertyDialog';

define('PropertyDialog', ['Dialog', 'TabbedPane', 'Service'], function(Dialog, TabbedPane, Service) {
	'use strict';

/**
 * Property Dialog class
 * @param {string} title
 * @param {Object} uiDef property dialog definition object
 * @constructor
 */
var PropertyDialog = function(title, uiDef) { this.__construct(title, void 0, void 0, void 0, uiDef); };

PropertyDialog.prototype = new Dialog('%inherit%');
PropertyDialog.prototype.constructor = PropertyDialog;
/** @type TabbedPane */
PropertyDialog.prototype.tabbedPane = null;
PropertyDialog.prototype.bottomPane = null;
/**
 * @private
 * @type {TabbedPaneTabDef}
 */
PropertyDialog.prototype.generalTab = null;
/** @type {TabbedPaneTabDef} */
PropertyDialog.prototype.optionsTab = null;
/** @type {jQuery} */
PropertyDialog.prototype.tabElem = null;

/**
 * Construct Property dialog 
 * @param {string} title dialog title
 * @param {boolean|undefined} isStatic
 * @param {UIComponent|undefined} content
 * @param {boolean|undefined} keepXBtn
 * @param {Object} uiDef property dialog definition object
 */
PropertyDialog.prototype.__construct = function(title, isStatic, content, keepXBtn, uiDef) {
	Dialog.prototype.__construct.call(this, title, isStatic, content, keepXBtn);
	var thisClass = this;
	this.content.empty();
	
	this.tabbedPane = new TabbedPane();
	//this.tabbedPane.setFixedHeight(200);
	this.content.append(this.tabbedPane.getElem());
	this.tabElem = $('<div>').addClass('wb-prop-dlg-tabs').append($('<div>').addClass('wb-prop-dlg-tabs-wrap').append(this.tabbedPane.elemNav)).appendTo(this.headerElem);
	this.tabbedPane.on('nav-show', function() {
		thisClass.tabbedPane.addClass('wb-prop-dlg-tabs-cont');
	}).on('nav-hide', function() {
		thisClass.tabbedPane.removeClass('wb-prop-dlg-tabs-cont');
	});
	
	this.bottomPane = $('<div>');
	this.content.append(this.bottomPane);
	
	var hasTabs = false, i, itemDef, item;
	if (typeof uiDef === 'object' && uiDef) {
		if (typeof uiDef.size === 'object' && uiDef.size) {
			if (uiDef.size.sizeClass) this.setSizeClass(uiDef.size.sizeClass);
			if (uiDef.size.width) this.setSize(uiDef.size.width);
			if (uiDef.size.height) {
				this.tabbedPane.setFixedHeight(uiDef.size.height - 200);
			}
			if (uiDef.size.minBodyHeight) this.setMinBodyHeight(uiDef.size.minBodyHeight);
			if (uiDef.size.maxBodyHeight) this.setMaxBodyHeight(uiDef.size.maxBodyHeight);
		}
		if (uiDef.noScroll) {
			this.setNoScroll();
			this.tabbedPane.setNoScroll();
		}
		if (typeof uiDef.tabs === 'object' && uiDef.tabs && uiDef.tabs.length > 0) {
			uiDef.tabs.sort(function(a, b) {
				return (('priority' in a) ? a.priority : 0) - (('priority' in b) ? b.priority : 0);
			});
			for (i = 0; i < uiDef.tabs.length; i++) {
				itemDef = uiDef.tabs[i];
				item = this.tabbedPane.addTab(itemDef.name ? itemDef.name : __('General'), i);
				if (itemDef.general) {
					this.generalTab = item;
					this.generalTab.type = 'general';
				} else if (!itemDef.name && !this.generalTab) {
					this.generalTab = item;
					this.generalTab.type = 'general';
				}
				if (itemDef.options) {
					this.optionsTab = item;
					this.optionsTab.type = 'options';
				}
				if (!item.type && itemDef.type) item.type = itemDef.type;
				hasTabs = true;
				if (itemDef.children) Service.UIBuilder.buildLayout(itemDef.children, item.contentElem, this.fields);
			}
		}
		if (typeof uiDef.buttons === 'object' && uiDef.buttons && uiDef.buttons.length > 0) {
			for (i = 0; i < uiDef.buttons.length; i++) {
				itemDef = uiDef.buttons[i];
				this.addButton(
						itemDef.name,
						(('click' in itemDef && typeof itemDef.click === 'function') ? itemDef.click : null),
						(itemDef.primary ? true : false)
					);
			}
		}
		if (('open' in uiDef) && (typeof uiDef.open === 'function')) {
			this.onShown = function() { uiDef.open.call(thisClass, thisClass.fields); };
		}
		if (('close' in uiDef) && (typeof uiDef.close === 'function')) {
			this.onClose = function() { uiDef.close.call(thisClass, thisClass.fields); };
		}
	}
	if (hasTabs) this.tabbedPane.selectTab(0);
	
};

/**
 * Get general tab (if not exists will be created)
 * @returns {TabbedPaneTabDef} tab descriptor.
 */
PropertyDialog.prototype.getGeneralTab = function() {
	if (!this.generalTab) {
		this.generalTab = this.tabbedPane.addTab(__("General"), 0);
		this.tabbedPane.selectTab(null, this.generalTab);
	}
	return this.generalTab;
};

	window.WB_PropertyDialog = PropertyDialog;
	
	return PropertyDialog;
});
;

/** WB LinkDialog **/
(window.defineModule = (window.defineModule || {})).name = 'WB LinkDialog';

define('LinkDialog', ['Dialog', 'Service'], function(Dialog, Service) {
	'use strict';

/**
 * Link Dialog class
 * @param {String} title
 * @param {Object} linkInfo
 */
var LinkDialog = function(title, linkInfo) {this.__construct(title, linkInfo);};

LinkDialog.prototype = new Dialog('%inherit%');
LinkDialog.prototype.constructor = LinkDialog;
LinkDialog.prototype.libraryDlg = null;
LinkDialog.prototype.linkInfo = {};
LinkDialog.prototype.isInfoSet = false;

/**
 * Construct Property dialog 
 * 
 * @param title dialog title
 * @param linkInfo info about link (type,url,target,title)
 */
LinkDialog.prototype.__construct = function(title, linkInfo) {
	Dialog.prototype.__construct.call(this, title);
	
	var thisClass = this;
	var fields = this.fields;
	
	this.setContent(new Service.UIBuilder({
		type: 'HorizontalLayout',
		columnWeights: [7, 5],
		children: [
			{type: 'VerticalLayout', children: [
				{type: 'RadioBox', id: 'linkUrlR', label: __('Web Address'),
					group: 'linkType',
					css: {marginBottom: 5},
					change: function() { thisClass.changeType('url'); }
				},
				{type: 'TextField', id: 'linkUrl', value: 'http://',
					change: function() {
						if (/^www\./.test(this.getValue())) {
							this.setValue('http://' + this.getValue());
						}
					}
				},
				{type: 'RadioBox', id: 'linkPageR', label: __('Page on your Website'),
					group: 'linkType',
					css: {marginTop: 15, marginBottom: 5},
					change: function() { thisClass.changeType('page'); }
				},
				{type: 'MenuItemSelector', id: 'linkPage', anchorMode: true},

				{type: 'RadioBox', id: 'linkEmailR', label: __('Email Address'),
					group: 'linkType',
					css: {marginTop: 15, marginBottom: 5},
					change: function() { thisClass.changeType('email'); }
				},
				{type: 'TextField', id: 'linkEmail'},

				{type: 'RadioBox', id: 'linkFileR', label: __('File from your Website'),
					group: 'linkType',
					css: {marginTop: 15, marginBottom: 5},
					change: function() { thisClass.changeType('file'); }
				},
				{type: 'LinkEditSelector', id: 'linkFile',
					emptyMsg: __('No files selected'),
					click: function() {
						thisClass.changeType('file');
						thisClass.libraryDlg = Service.mediaLibrary.open(__('Select media'), false, 'all');
						thisClass.libraryDlg.addButton(__('Cancel'));
						thisClass.libraryDlg.addButton(__('Select'), function() {
							var list = thisClass.libraryDlg.getSelectedFiles();
							if (list.length > 0)
								fields.linkFile.setValue(list[0]);
							thisClass.libraryDlg.hide();
						}, true);

						thisClass.libraryDlg.show();
						return false;
					}
				},

				{type: 'Label', text: __('Link Title'),
					helpText: __('Link Title will pop up when you hover over the link'),
					css: {marginTop: 15}
				}, // title
				{type: 'TextField', id: 'linkTitle'}
			]},
			{type: 'VerticalLayout', children: [
				{type: 'CheckBox', id: 'linkTarget', label: __('Open in New Window')} // target
			]}
		]
	}, this.fields), true);
	
	if (linkInfo && linkInfo.type) {
		this.setInfo(linkInfo);
	} else {
		this.isInfoSet = false;
		setTimeout(function(){
			if (!thisClass.isInfoSet) {
				thisClass.changeType('url', true);
			}
		}, 100);
	}
	
};

/**
 * Change type for radio
 * @param {String} type
 * @param {boolean} noInfoSet
 */
LinkDialog.prototype.changeType = function(type, noInfoSet) {
	this.isInfoSet = (noInfoSet ? false : true);
	this.linkInfo.type = type;
	
	if (type === 'page') this.fields.linkPageR.setValue(true);
	else if (type === 'email') this.fields.linkEmailR.setValue(true);
	else if (type === 'file') this.fields.linkFileR.setValue(true);
	else {
		this.linkInfo.type = 'url';
		this.fields.linkUrlR.setValue(true);
	}
};

/**
 * Get type
 * 
 * @returns string Value of selected radio
 */
LinkDialog.prototype.getType = function() {
	return this.linkInfo.type;
};

/**
 * Set link info
 * @param {Object} info
 */
LinkDialog.prototype.setInfo = function(info) {
	this.clearInfo();
	if (info.type) {
		this.changeType(info.type);
		if (info.url) {
			var inp = 'link' + info.type.substring(0, 1).toUpperCase() + info.type.substring(1);
			if (this.fields[inp]) {
				if (info.type === 'page' && info.menuUID) {
					this.fields[inp].setExtendedValue({menuUID: info.menuUID, id: parseInt(info.url, 10), anchor: info.anchor});
				} else {
					this.fields[inp].setValue(("" + info.url).trim());
				}
			}
		}
		if (info.title) {
			this.fields.linkTitle.setValue(info.title);
		}
		if (info.target) {
			this.fields.linkTarget.setValue(info.target);
		}
	}
	this.linkInfo = info;
};

/**
 * Clear link info
 */
LinkDialog.prototype.clearInfo = function() {
	this.changeType(null);
	this.fields.linkUrl.setValue('http://');
	this.fields.linkPage.setValue(null);
	this.fields.linkEmail.setValue(null);
	this.fields.linkFile.clearValue();
	this.fields.linkTitle.setValue(null);
	this.fields.linkTarget.setValue(false);
};

/**
 * Get link info
 */
LinkDialog.prototype.getInfo = function() {
	var params = {
		type: null,
		url: null,
		target: null,
		title: null
	};
	
	var type = this.getType();
	if (type) {
		params.type = type;
		var inp = 'link' + type.substring(0, 1).toUpperCase() + type.substring(1);
		if (this.fields[inp]) {
			params.url = this.fields[inp].getValue();
			if (params.url) params.url = ("" + params.url).trim();
			if (type === 'page') {
				var extv = this.fields[inp].getExtendedValue();
				params.menuUID = extv.menuUID;
				params.anchor = ('anchor' in extv) ? extv.anchor : null;
			}
			params.title = this.fields.linkTitle.getValue();
			params.target = this.fields.linkTarget.getValue();
		}
	}
	return params;
};


/**
 * Set dialog visibility
 * @param {Boolean} visible dialog visibility
 * @param {Boolean} noAction
 * @param {Boolean} ignoreEvent
 */
LinkDialog.prototype.setVisible = function(visible, noAction, ignoreEvent) {
	if (visible) {
		this.fields.linkPage.reloadMenuList();
		if (this.linkInfo.type && this.linkInfo.type === "page" && this.linkInfo.url) {
			if (this.linkInfo.menuUID) {
				this.fields.linkPage.setExtendedValue({menuUID: this.linkInfo.menuUID, id: parseInt(this.linkInfo.url, 10), anchor: this.linkInfo.anchor});
			} else {
				this.fields.linkPage.setValue(this.linkInfo.url);
			}
		}
	}
	
	Dialog.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
};

	window.WB_LinkDialog = LinkDialog;
	
	return LinkDialog;
});
;

/** WB PasteDialog **/
(window.defineModule = (window.defineModule || {})).name = 'WB PasteDialog';

define('PasteDialog', ['Dialog'], function(Dialog) {
	'use strict';

/**
 * Text Paste Dialog class
 * @param {String} title
 * @param {Object} linkInfo
 */
var PasteDialog = function(title, linkInfo) {this.__construct(title, linkInfo);};

PasteDialog.prototype = new Dialog('%inherit%');
PasteDialog.prototype.constructor = PasteDialog;

/**
 * Construct Property dialog 
 * 
 * @param {string} title dialog title
 * @param {Object} linkInfo info about link (type,url,target,title)
 */
PasteDialog.prototype.__construct = function(title, linkInfo) {
	Dialog.prototype.__construct.call(this, title);
	
	var fields = this.fields;
	this.content.empty();
	
	var lbl = $('<label for="pasteText'+this.id+'"><small></small></label>');
	lbl.children("small").append(__("Please paste inside the following box using mouse or keyboard (Ctrl/Cmd+V) and hit Paste"));
	this.content.append(lbl);
	
	//TextArea
	fields.pasteText = new WB_TextAreaControl();
	fields.pasteText.input.css({"width": "510px", "height": "160px"}).attr("id", 'pasteText'+this.id);
	this.content.append(fields.pasteText.elem);
	
	//Check "Paste inside"
	fields.pasteInside = new WB_CheckBoxControl(__('Paste text inside selected element'));
	this.content.append(fields.pasteInside.elem);
};

/**
 * Show/Hide "Paste inside element" checkbox
 * @param {boolean} show
 */
PasteDialog.prototype.showCheck = function(show) {
	this.fields.pasteText.setValue('');
	this.fields.pasteInside.setValue(null);
	if (show) {
		this.fields.pasteInside.elem.show();
	}
	else {
		this.fields.pasteInside.elem.hide();
	}
		
};

/**
 * Get link info
 */
PasteDialog.prototype.getInfo = function() {
	var params = {
		text: this.fields.pasteText.getValue(),
		inside: this.fields.pasteInside.getValue()
	};
	
	return params;
};
	
	return PasteDialog;
});
;

/** WB Preloader **/
(window.defineModule = (window.defineModule || {})).name = 'WB Preloader';

define('Preloader', ['Dialog'], function(Dialog) {
	'use strict';

/**
 * Preloader class
 * Dialog used to view load/save progress
 * @param {String} title
 */
var Preloader = function(title) {this.__construct(title);};

Preloader.prototype = new Dialog('%inherit%');
Preloader.prototype.constructor = Preloader;
Preloader.prototype.progress = null;
Preloader.prototype.msg = null;
Preloader.prototype.cancelMonitoring = false;
Preloader.prototype.mon = null;
Preloader.prototype.loaderStack = null;
Preloader.prototype.stackIndex = -1;
Preloader.prototype._container = null;
Preloader.prototype._nContainer = null;

/**
 * Construct Preloader dialog
 * @param title dialog title
 */
Preloader.prototype.__construct = function(title) {
	Dialog.prototype.__construct.call(this, title, true);
	var thisClass = this;
	
	this.content.empty();
	this._container = $('<div>').appendTo(this.content);
	this._nContainer = ({
		elem: null,
		elems: null,
		title: null,
		message: null,
		init: function(content) {
			this.elem = $('<div>');
			this.elem.appendTo(content);
			this.elems = [];
			return this;
		},
		addMessage: function(message, title) {
			var elem = $('<div>').addClass('alert alert-info');
			if (title) {
				$('<strong>').text(title).appendTo(elem);
			}
			if (message) {
				$('<span>').text((title ? ' ' : '') + message).appendTo(elem);
			}
			if (title || message) {
				elem.appendTo(this.elem);
				this.elems.push(elem);
			}
		},
		clearMessages: function() {
			for (var i = 0; i < this.elems.length; i++) {
				this.elems[i].remove();
			}
			this.elems = [];
		}
	}).init(this.content);
	
	this.loaderStack = [];
	
	this.pushStack();
	
	this.xButton.hide();
	//this.addButton(__("Cancel"));
	this.onClose = function() {
		thisClass.cancelMonitoring = true;
	};
	
};

/**
 * Set notification message
 * @param {String} message
 * @param {String} title
 */
Preloader.prototype.setNotification = function(message, title) {
	this._nContainer.addMessage(message, title);
};

/**
 * Clear all notifications added with set notification.
 */
Preloader.prototype.clearNotifications = function() {
	this._nContainer.clearMessages();
};

/**
 * Query specified url until 100% or error
 * @param url url to query
 * @param callback callback to call on success or on error (ex. function(success) { ... })
 * @param noReset if true will not reset current process
 * @param keepOpen keep open on complete
 * @param errorHandler callback for error handling
 */
Preloader.prototype.monitor = function(url, callback, noReset, keepOpen, errorHandler) {
	var thisClass = this;
	var thisClallback = callback;
	var thisErrorHandler = (typeof errorHandler === 'function') ? errorHandler : null;
	if (typeof(url) !== "object") url = { "url": url };
	var thisUrl = url.url;
	var opts = (typeof(url.opts) === "object") ? url.opts : {};
	opts.ts = (new Date()).getTime();
	if (!noReset) {
		this.cancelMonitoring = false;
		opts.reset = 1;
	}
	var thisKeepOpen = keepOpen ? true : false;
	
	var logError = function(req, errorMsg, url) {
		var errorText = 'unknown error';
		if (req && req.status >= 400 && req.status < 600) {
			// Note: ignore 4xx and 5xx errors, since they give no useful info.
			return;
		}
		if (req && req.readyState >= 2 && req.readyState <= 4) {
			errorText = 'Response error (status: ' + req.status + ' ' + req.statusText + ')';
			if (req.readyState >= 3) {
				errorText += ' (res: ' + req.responseText + ')';
			}
		} else {
			var pfix = '';
			if (req && typeof req.getAllResponseHeaders === 'function') {
				var allHeaders = req.getAllResponseHeaders();
				pfix = '[' + (allHeaders ? 'Y' : 'N') + ']';
				if (req.status === 0 && req.statusText === 'error' && !allHeaders) {
					// Note: ignore as likely user initiated request aborts.
					return;
				}
			}
			errorText = 'Network error (' + (req ? req.readyState : '?') + ')' + pfix;
			if (req && (req.status !== 0 || req.statusText)) {
				errorText += ' (status: ' + req.status + ' ' + req.statusText + ')';
			}
		}
		if (errorMsg) errorText += ' :: ' + errorMsg;
		if (url) errorText += ' :URL: ' + url;
		try {
			$.ajax(wb_builder.baseUrl + 'error/log-js-error', {
				data: JSON.stringify({error: errorText}),
				contentType: 'application/json; charset=UTF-8',
				type: 'POST'
			}).fail(function(req, status, err) {
				console.error('Failed logging error: ' + err);
			});
		} catch (err) { console.error('Failed logging error: ' + err); }
	};
	
	var okfn = function(data, status, req) {
		if (thisClass.cancelMonitoring) return;
		if (!data || typeof(data) !== "object") {
			data = { complete: false, error: __("Server error") };
			logError(req, null, thisUrl);
		}
		if (data.error) {
			if (thisErrorHandler && thisErrorHandler(data.error)) return;
			var error = ((typeof data.error === 'object') && ('title' in data.error)) ? data.error.title : data.error;
			thisClass.setMessage(__pr(error), __("Error:"), "danger");
			setTimeout(function() {
				thisClass.setVisible(false);
				if (typeof(thisClallback) === "function") thisClallback(false, data.error);
			}, 500);
		} else if (data.complete) {
			thisClass.setMessage("", __("Complete"), "success");
			thisClass.setProgress(100);
			setTimeout(function() {
				if (!thisKeepOpen) thisClass.setVisible(false);
				if (typeof(thisClallback) === "function") thisClallback(true);
			}, 500);
		} else {
			if (thisClass.cancelMonitoring) return;
			if (typeof(data.text) !== "undefined")
				thisClass.setMessage(__pr(data.text));
			if (typeof(data.progress) !== "undefined")
				thisClass.setProgress(data.progress);
			
			setTimeout(function() {
				if (thisClass.cancelMonitoring) return;
				thisClass.monitor(thisUrl, thisClallback, true, null, thisErrorHandler);
			}, 5000);
		}
	};
	
	var errfn = function(req, status, error) {
		var msg = __("Server error") + ((req.status && req.status !== 200) ? ' (' + req.status + ')' : '');
		var errObj = ('responseJSON' in req) ? req.responseJSON : null;
		if (errObj && (typeof(errObj) === 'object') && ('error' in errObj) && errObj.error) {
			msg += ': ' + errObj.error;
		}
		thisClass.setMessage("", __("Server error"), "error");
		setTimeout(function() {
			thisClass.setVisible(false);
			if (typeof(thisClallback) === "function") thisClallback(false, msg);
		}, 500);
	};
	
	if (url.method === "post") {
		(this.mon = $.post(thisUrl, opts, okfn)).error(errfn);
	} else {
		(this.mon = $.get(thisUrl, opts, okfn)).error(errfn);
	}
};

/**
 * Get number of stacks
 * @return number of stacks
 */
Preloader.prototype.numStacks = function() {
	return this.loaderStack.length;
};

/**
 * Create and add new stack to this loader
 */
Preloader.prototype.pushStack = function() {
	var stack = {};
	stack.progress = $('<div class="progress">' +
			'<div class="progress-bar progress-bar-success progress-bar-striped active" style="width: 1%;"></div>' +
		'</div>');
	
	stack.msg = $('<div class="alert alert-danger">' +
			'<span></span>' +
		'</div>');
	
	this._container.append(stack.msg);
	this._container.append(stack.progress);
	
	this.loaderStack.push(stack);
	if (this.stackIndex < 0) this.selectStack(0);
};

/**
 * Remove last stack from this loader.
 * If there is only one stack left do nothing.
 * If removed stack is currently selected then first stack will be selected
 */
Preloader.prototype.popStack = function() {
	if (this.loaderStack.length === 1) return;
	var stack = this.loaderStack.pop();
	if (this.stackIndex >= this.loaderStack.length) this.selectStack(0);
	stack.progress.remove();
	stack.progress.empty();
	delete stack.progress;
	stack.msg.remove();
	stack.msg.empty();
	delete stack.msg;
};

/**
 * Select stack
 * @param idx stack index to select
 */
Preloader.prototype.selectStack = function(idx) {
	if (idx < 0 || idx >= this.loaderStack.length || !this.loaderStack[idx]) return;
	this.stackIndex = idx;
	this.progress = this.loaderStack[idx].progress;
	this.msg = this.loaderStack[idx].msg;
};

/**
 * Reset state
 */
Preloader.prototype.reset = function() {
	this.setProgress(0);
	this.setMessage(__("loading..."));
};

/**
 * Reset state for all stacks
 */
Preloader.prototype.resetAll = function() {
	var _idx = this.stackIndex;
	for (var i = 0; i < this.loaderStack.length; i++) {
		this.selectStack(i);
		this.setProgress(0);
		this.setMessage(__("loading..."));
	}
	this.selectStack(_idx);
};


/**
 * Set progress bar value
 * @param value progress bar value in percents
 */
Preloader.prototype.setProgress = function(value) {
	this.progress.children(".progress-bar").css("width", (value * 1) + "%");
};

/**
 * Set inline message
 * @param message message text
 * @param title message title
 * @param type message type (value one of: error, success, info, warning)
 */
Preloader.prototype.setMessage = function(message, title, type) {
	var msg = (title ? ("<strong>" + title + "</strong> ") : "") + message;
	if (type === 'block') type = 'warning';
	this.msg.children("span").html(msg);
	this.msg.removeClass("alert-danger");
	this.msg.removeClass("alert-success");
	this.msg.removeClass("alert-info");
	this.msg.removeClass("alert-warning");

	var progressBar = this.progress.children(".progress-bar");
	progressBar.removeClass("progress-bar-danger progress-bar-success");
	if( type === "danger" )
		progressBar.addClass("progress-bar-danger");
	else
		progressBar.addClass("progress-bar-success");

	if (type === "danger" || type === "success" || type === "info" || type === "warning") {
		this.msg.addClass("alert-" + type);
	} else {
		this.msg.addClass("alert-warning");
	}
};

/**
 * Set dialog visibility
 * @param visible dialog visibility
 */
Preloader.prototype.setVisible = function(visible, noAction, ignoreEvent) {
	Dialog.prototype.setVisible.call(this, visible, noAction, ignoreEvent);
};

	window.WB_Preloader = Preloader;
	
	return Preloader;
});
;

/** WB ContextMenu **/
(window.defineModule = (window.defineModule || {})).name = 'WB ContextMenu';

define('ContextMenu', ['Service', 'MobileToolbar'], function(Service, MobileToolbar) {
	'use strict';

/**
 * Context menu class
 * @param {String} id
 * @constructor
 */
var ContextMenu = function(id) {this.__construct(id);};

ContextMenu.prototype.id = null;
ContextMenu.prototype.menu = null;
ContextMenu.prototype.parentMenu = null;
ContextMenu.prototype.bindBtn = null;
ContextMenu.prototype.bindCont = null;
ContextMenu.prototype.onShow = null;
ContextMenu.prototype.pageX = null;
ContextMenu.prototype.pageY = null;
ContextMenu.prototype.items = null;
ContextMenu.lastIndex = 0;
ContextMenu.menuList = [];
ContextMenu.hideAllMenus = function() {
	MobileToolbar.Drawer.open(null, null, true);
	for (var i = 0; i < ContextMenu.menuList.length; i++) {
		ContextMenu.menuList[i].hide(true);
	}
};
ContextMenu.mobileLimit = 485;
ContextMenu.prototype.mobileDrawer = null;

$(function() {
	$('#site').on('mouseup touchstart', function(e) {
		// Safari context menu issue: safari opens context menu on mouse down,
		// other browsers open context menu on mouse up, this prevents closing
		// of context menu on sfari when right mouse button is released.
		if (e.button === 2) return;
		ContextMenu.hideAllMenus();
	});
	$(window).on('scroll', function() {
		ContextMenu.hideAllMenus();
	});
});

/**
 * Construct context menu
 * @param {string} id unique menu identificator
 */
ContextMenu.prototype.__construct = function(id) {	
	this.id = "wb_context_menu_" + ContextMenu.lastIndex++;
	if (id) this.id = id;
	this.menu = $('<ul></ul>').attr('id', (id ? id : null));
	this.menu.addClass("dropdown-menu");
	this.menu.wbSetClassInstance(this);
	this.items = [];
	ContextMenu.menuList[ContextMenu.menuList.length] = this;
};

/**
 * Show menu
 * @param {Object} e event object to get mouse position from
 * @param {boolean} isSubmenu tells if this called for submenu
 */
ContextMenu.prototype.show = function(e, isSubmenu) {
	var i;
	if ($(window).width() <= ContextMenu.mobileLimit) {
		ContextMenu.hideAllMenus();
		if (!this.mobileDrawer) {
			this.mobileDrawer = new MobileToolbar.Drawer('list');
			for (i = 0; i < this.items.length; i++) {
				if (!('id' in this.items[i])) continue;
				this.mobileDrawer.addItem(MobileToolbar.Toolbar.buildDrawerItem(this.items[i], this.mobileDrawer));
			}
			$(document.body).append(this.mobileDrawer.getElem());
		}
		MobileToolbar.Drawer.open(this.mobileDrawer, null, true);
		return;
	}
	if (e) {
		for (i = 0; i < ContextMenu.menuList.length; i++) {
			if (this.id === ContextMenu.menuList[i].id) continue;
			ContextMenu.menuList[i].hide(true);
		}
	}
	
	if (typeof(this.onShow) === "function") {
		this.onShow(this, e);
	}
	
	this.menu.parent().addClass("open");
	
	var vw = $(window).width();
	var vh = $(window).height();
	var mw = this.menu.outerWidth(true);
	var mh = this.menu.outerHeight(true);
	
	var px = 0, py = 0;
	
	if (e) {
		this.pageX = e.pageX;
		this.pageY = e.pageY;
		px = e.pageX + 10;
		py = e.pageY + 10;
		
		if (wb_builder.rtl) {
			if ((px - mw) < 0) {
				px = e.pageX + 10 + mw;
			}
		} else {
			if ((px + mw) > vw) {
				px = e.pageX - 10 - mw;
			}
		}
		if ((py + mh) > vh) {
			py = e.pageY - 10 - mh;
		}
		
		this.menu.parent().css({
			left: px + "px",
			top: py + "px"
		});
	} else if (isSubmenu) {
		var off = this.menu.parent().offset();
		var prw = this.menu.parent().width();
		px = 90;
		py = 0;
		if ((off.left + Math.ceil(prw * 0.9) + mw) > vw) {
			px = -90;
		}
		if ((off.top + mh) > vh) {
			py = -mh + 10;
		}
		this.menu.css({
			left: px + "%",
			top: py + "px"
		});
	}
};

/**
 * Hide menu
 * @param {boolean} instant if true menu will be hidden instantly else by fade out
 */
ContextMenu.prototype.hide = function(instant) {
	instant = true; //make always instant
	if (instant) {
		this.menu.parent().removeClass("open");
	} else {
		var thisClass = this;
		// neivyksta callback
		this.menu.fadeOut(function() {
			thisClass.menu.css("opacity", "");
			thisClass.menu.css("display", "");
			thisClass.menu.parent().removeClass("open");
		});
	}
};

/**
 * Bind context menu to element
 * @param {Object} elem element to bind menu to
 * @param {boolean} noClick no left mouse button click binding
 */
ContextMenu.prototype.bind = function(elem, noClick) {
	var cont = $('<div class="dropdown-btn-body"></div>');
	$(document.body).append(cont);
	var btn = $('<span class="dropdown-toggle-body"></span>');
	//$(elem).append(this.menu);
	$(elem).append(btn);
	cont.append(this.menu);
	var thisClass = this;
	btn.attr("data-toggle", "dropdown");
	btn.attr("data-target", "#x");
	if (!noClick) {
		btn.unbind("click").bind("click", function(e) {
			thisClass.show(e);
			e.stopPropagation();
			return false;
		});
	}
	btn.get(0).oncontextmenu = function(e) {
		if (!e) e = window.event;
		var ne = wb_builder.normalizeEvent(e);
		ne.type = "click";
		thisClass.show(ne);
		e.stopPropagation();
		return false;
	};
	this.bindBtn = btn;
	this.bindCont = cont;
};

/**
 * Unbind context menu from element
 */
ContextMenu.prototype.unbind = function() {
	//var elem = this.menu.parent();
	var btn = this.bindBtn;
	btn.removeAttr("data-toggle");
	btn.removeAttr("data-target");
	btn.unbind("click");
	btn.get(0).oncontextmenu = function() {};
	btn.remove();
	this.menu.detach();
};

/**
 * Bind pasively context menu to element
 * Note: you must normal bind first
 * @param {Object} elem element to bind menu to
 */
ContextMenu.prototype.pasiveBind = function(elem) {
	var thisClass = this;
	$(elem).get(0).oncontextmenu = function(e) {
		if (!e) e = window.event;
		var ne = wb_builder.normalizeEvent(e);
		ne.type = "click";
		thisClass.show(ne);
		e.stopPropagation();
		return false;
	};
};

/**
 * Unbind pasively bind'ed context menu from element
 * @param {Object} elem element to unbind menu from
 */
ContextMenu.prototype.pasiveUnbind = function(elem) {
	$(elem).get(0).oncontextmenu = null;
};

/**
 * Set max height of dropdown menu and add scroll if needed
 * @param {number} max height of dropdown menu
 */
ContextMenu.prototype.setHeight = function(height) {
	var h = height ? parseInt(height) : 0;
	if (!h) {
		this.menu.css({ maxHeight: '', overflow: '', overflowY: '' });
	} else {
		this.menu.css({ maxHeight: h + 'px', overflow: 'hidden', overflowY: 'auto' });
	}
};

/**
 * Remove all items
 */
ContextMenu.prototype.removeAllItems = function() {
	this.items.splice(0, this.items.length);
	this.menu.children().each(function() {
		$(this).remove();
	});
};

/**
 * Insert menu item at specified index
 * @param {number} index index to insert icon at
 * @param {string} id menu item identificator
 * @param {string} name menu item name
 * @param {Object} submenu submenu of the item ir callback
 * @param {boolean} selected if true menu item will be selected
 * @param {booelan} disabled if true menu item will be disabled
 * @param {mixed} param parameter that will be passed to callback function
 * @param {string} ico icon class
 * @param {boolean} multi true if this menu item can be used for multiple elements
 * @returns {jQuery} DOM element object of this menu item
 */
ContextMenu.prototype.insertItemAt = function(index, id, name, submenu, selected, disabled, param, ico, multi) {
	var item = {
		id: id,
		name: name,
		checked: (selected ? true : false),
		disabled: (selected ? true : false),
		icon: ico
	};
	if (submenu instanceof ContextMenu) {
		item.drawer = {type: 'list', items: submenu.items};
	} else if (typeof(submenu) === 'function') {
		(function(thisSelf, func, param) {
			item.click = function(e) { func.call(thisSelf, e, param); };
		})(this, submenu, param);
	}
	if (index >= 0 && index < this.items.length) {
		this.items.splice(index, 0, item);
	} else {
		this.items.push(item);
	}
	var thisClass = this;
	var mi = $('<li><a href="javascript:void(0)"></a></li>');
	mi.attr("iid", id);
	if (multi) {
		mi.addClass("wb-multi-mi");
		if( multi === "only" )
			mi.addClass("wb-multi-mi-only");
	}
	
	if (!name) name = '---';
	if (typeof(selected) === "undefined") selected = false;
	if (typeof(disabled) === "undefined") disabled = false;
	if (ico) {
		mi.children("a").append('<i class="' + ico + '"></i>');
		name = "&nbsp;" + name;
	}
	mi.children("a").append(name);	
	
	if (selected)
		mi.addClass("active");
	if (disabled)
		mi.addClass("disabled");
	
	if (submenu instanceof ContextMenu) {
		submenu.parentMenu = this;
		mi.addClass("dropdown-submenu");
//		var r = $('<i class="icon-chevron-right"></i>');
//		r.css({ position: "absolute", right: "4px", top: "4px" });
//		mi.append(r);
		mi.append(submenu.menu);
//		mi.css("position", "relative");
//		submenu.menu.css("top", "0px");
//		submenu.menu.css("left", "90%");
		var thisSubmenu = submenu;
		mi.hover(
			/** @param {jQuery.Event} e */
			function(e) {
				/*if (mi.children('.cover-disabler').length > 0) {
					e.stopPropagation(); e.preventDefault();
					thisSubmenu.menu.hide();
					return false;
				} else {
					thisSubmenu.menu.show();
				}*/
				var vw = $(window).width();
				//var vh = $(window).height();
				var mw = thisSubmenu.menu.outerWidth(true);
				//var mh = thisSubmenu.menu.outerHeight(true);

				var off = mi.offset();
				var prw = mi.width();
				
				var smenu = mi.children("ul.dropdown-menu");
				
				if (wb_builder.rtl) {
					if ((off.left - mw) < 0) {
						// drop right
						smenu.css({ right: (-smenu.width()) + "px"});
					}
				} else {
					if ((off.left + prw + mw) > vw) {
						// drop left
						mi.addClass("pull-left");
						var maxW = off.left - 20;
						smenu.css({
							left: (-Math.min(smenu.width(), maxW)) + "px",
							'max-width': maxW + 'px',
							'overflow-x': 'auto'
						});
					} else {
						mi.removeClass("pull-left");
					}
				}
				
				
				smenu.children('li').each(function(i) {
					if ($(this).hasClass('active')) {
						var ih = $(this).outerHeight(true);
						var mh = smenu.height();
						smenu.scrollTop(ih * i - mh / 2 + ih / 2);
						return false;
					}
				});
				/* if ((off.top + mh) > vh) {
					// dropup
				} */
				//thisSubmenu.show(null, true);
			},
			function() {
				var smenu = mi.children("ul.dropdown-menu");
				smenu.css({ left: '', height: '', 'max-width': '', 'overflow-x': '' });
				//thisSubmenu.hide(true);
			}
		);
	}
	if (typeof(submenu) === "function") {
		var _callback = submenu;
		var _callback_param = param ? param : null;
		mi.data("__WB_MI_DATA__", _callback_param);
		mi.children("a").bind("click", function(e, prm) {
			if (_callback(e, (typeof(prm) === "undefined") ? _callback_param : prm) !== false) {
				thisClass.hide();
				if (thisClass.parentMenu) {
					thisClass.parentMenu.hide();
					if (thisClass.parentMenu.parentMenu) {
						thisClass.parentMenu.parentMenu.hide();
					}
				}
			}
		});
	}
	if (index >= 0 && index < this.menu.children("li").size()) {
		this.menu.children("li").eq(index).before(mi);
	} else {
		this.menu.append(mi);
	}
	return mi;
};

ContextMenu.prototype.getIndexById = function(id) {
	var items = this.menu.children("[iid]");
	var idx = null;
	$.each(items, function(i, item) {
		if ($(item).attr('iid') === id) {
			idx = i;
			return;
		}
	});
	return ++idx;
};

/**
 * Add menu item
 * @param id menu item identificator
 * @param name menu item name
 * @param submenu submenu of the item ir callback
 * @param selected if true menu item will be selected
 * @param disabled if true menu item will be disabled
 * @param param parameter that will be passed to callback function
 * @param ico icon class
 * @param multi true if this menu item can be used for multiple elements
 * @returns jQuery DOM element object of this menu item
 */
ContextMenu.prototype.addItem = function(id, name, submenu, selected, disabled, param, ico, multi) {
	return this.insertItemAt(-1, id, name, submenu, selected, disabled, param, ico, multi);
};

ContextMenu.prototype.removeItem = function(id) {
	for (var i = (this.items.length - 1); i >= 0; i--) {
		if ('id' in this.items[i] && this.items[i].id === id) {
			this.items.splice(i, 1);
			break;
		}
	}
	var item = this.getItem(id);
	item.remove();
};

/**
 * Add item separator to this menu
 * @param {Number} index
 */
ContextMenu.prototype.addSeparator = function(index) {
	var item = {type: '-'};
	if (index >= 0 && index < this.items.length) {
		this.items.splice(index, 0, item);
	} else {
		this.items.push(item);
	}
	var mi = $('<li class="divider"></li>');
	if (!isNaN(index*1) && index >= 0 && index < this.menu.children("li").size()) {
		this.menu.children("li").eq(index).before(mi);
	} else {
		this.menu.append(mi);
	}
};

/**
 * Get menu item count
 * @returns item count
 */
ContextMenu.prototype.getSize = function() {
	return this.menu.children("li").size();
};

/**
 * Get menu item by id
 * @param id menu item id to get by
 * @returns jQuery DOM element object of this menu item
 */
ContextMenu.prototype.getItem = function(id) {
	var items = this.menu.children("[iid=" + id + "]");
	if (!items.size()) return null;
	return items.eq(0);
};

ContextMenu.prototype.getItems = function() {
	var items = [];
	this.menu.children('[iid]').each(function() {
		items.push({id: $(this).attr('iid'), elem: $(this)});
	});
	return items;
};

/**
 * Set menu item name
 * @param id menu item id
 * @param name item name to set
 */
ContextMenu.prototype.setName = function(id, name) {
	var mi = this.getItem(id);
	mi = mi ? $(mi).children("a") : null;
	if (!mi || mi.size() === 0) return;
	
	var ico = mi.children("i");
	if (ico.size() > 0) ico.detach();
	mi.empty();
	if (ico.size() > 0) {
		mi.append(ico);
		name = "&nbsp;" + name;
	}
	mi.append(name);
};

/**
 * Set menu item action
 * @param id menu item id
 * @param act action to set
 * @param unbind
 */
ContextMenu.prototype.setAction = function(id, act, unbind) {
	var mi = this.getItem(id);
	var thisClass = this;
	if (!mi || mi.size() === 0) return;
	
	if (act instanceof ContextMenu) {
		mi.append(act.menu);
	}
	if (typeof(act) === "function") {
		var _callback = act;
		var _callback_param = mi.data("__WB_MI_DATA__");
		if (unbind) {
			mi.children("a").unbind("click");
			mi.children("a").bind("click", function(e, prm) {
				thisClass.hide();
				if (thisClass.parentMenu) thisClass.parentMenu.hide();
			});
		}
			
		mi.children("a").bind("click", function(e, prm) {
			_callback(e, (typeof(prm) === "undefined") ? _callback_param : prm);
		});
	}
};

/**
 * Checks if item has submenu
 * 
 * @param id menu item id
 */
ContextMenu.prototype.hasSubmenu = function(id) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	
	return $(mi).find("ul").length;
};

ContextMenu.prototype.getSubmenu = function(id) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	var menu = $(mi).find("ul");
	return menu.length ? menu.wbGetClassInstance() : null;
};

/**
 * Set menu item submenu
 * 
 * @param id menu item id
 * @param submenu submenu of the item
 */
ContextMenu.prototype.setSubmenu = function(id, submenu) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	
	if (submenu instanceof ContextMenu) {
		this.removeSubmenu(id);
		submenu.parentMenu = this;
		mi.addClass("dropdown-submenu");
//		var r = $('<i class="icon-chevron-right"></i>');
//		r.css({ position: "absolute", right: "4px", top: "4px" });
//		mi.append(r);
		mi.append(submenu.menu);
//		mi.css("position", "relative");
//		submenu.menu.css("top", "0px");
//		submenu.menu.css("left", "90%");
		/*var thisSubmenu = submenu;
		mi.hover(
			function() {
				thisSubmenu.show(null, true);
			},
			function() {
				thisSubmenu.hide(true);
			}
		);*/
	}
};

/**
 * Remove menu item submenu
 * 
 * @param id menu item id
 */
ContextMenu.prototype.removeSubmenu = function(id) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	
	$(mi).find(".icon-chevron-right, ul").remove();
};

/**
 * Get menu location
 * @return location as object { left: ..., top: ... }
 */
ContextMenu.prototype.getLocation = function() {
	var loc = this.menu.parent().is("li") ? this.menu.position() : this.menu.parent().position();
	return loc;
};

/**
 * Set menu item selected state
 * @param id menu item id
 * @param selected selection state
 */
ContextMenu.prototype.setSelected = function(id, selected) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	
	if (selected)
		mi.addClass("active");
	else
		mi.removeClass("active");
};

/**
 * Set menu item disabled state
 * @param id menu item id
 * @param disabled disabled state
 */
ContextMenu.prototype.setDisabled = function(id, disabled) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	
	if (disabled) {
		if (mi.children('.cover').length === 0) {
			mi.css({position: 'relative'});
			mi.prepend($('<div>').addClass('cover cover-disabler').on('mousedown mouseup', function(e) { e.stopPropagation(); e.preventDefault(); return false; }));
		}
		//mi.addClass("disabled");
	} else {
		mi.children('.cover').remove();
		//mi.removeClass("disabled");
	}
};

/**
 * Set menu item visibility
 * @param id menu item id
 * @param visible visibility state
 */
ContextMenu.prototype.setVisible = function(id, visible) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	
	if (visible)
		mi.css("display", "block");
	else
		mi.css("display", "none");
};

/**
 * Trigger menu item callback
 * @param id menu item id
 * @param param param that will be passed to callback
 */
ContextMenu.prototype.trigger = function(id, param) {
	var mi = this.getItem(id);
	if (!mi || mi.size() === 0) return;
	
	mi.trigger("click", [param]);
};

/**
 * Enable/disable multi mode
 * @param value true to enable, false to disable
 */
ContextMenu.prototype.setMultiMode = function(value) {
	if (value) {
		this.menu.children("li").hide();
		this.menu.children(".wb-multi-mi").show();
	} else {
		this.menu.children("li").show();
		this.menu.children(".wb-multi-mi-only").hide();
	}
};

ContextMenu.Item = (function() {
	/**
	 * @class ContextMenu.Item
	 * @param {String} name menu item name
	 * @param {String} icon icon style class
	 * @param {String} id menu item identificator
	 * @param {Function} onClick
	 */
	var self = function(name, icon, id, onClick) {
		this.id = id;
		this.elem = $('<li>');
		this.elemA = $('<a>').appendTo(this.elem);
		this._elemIcon = $('<i>').attr('href', 'javascript:void(0)');
		this._elemText = $(document.createTextNode(name)).appendTo(this.elemA);
		this._elemSubmenu = $('<ul>').addClass('dropdown-menu');
		if (icon) this.setIcon(icon);
		this._items = [];
		this._onClick = (typeof onClick === 'function') ? onClick : null;
		var thisSelf = this;
		if (this._onClick) {
			this.elemA.on('click', function(e) {
				if (thisSelf._disabled) return false;
				thisSelf._onClick.call(thisSelf, e);
			});
		}
	};
	
	/** @type jQuery */
	self.prototype.elem = null;
	/** @type jQuery */
	self.prototype.elemA = null;
	/** @type jQuery */
	self.prototype._elemIcon = null;
	/** @type jQuery */
	self.prototype._elemText = null;
	/** @type String */
	self.prototype.id = null;
	/** @type ContextMenu.Item */
	self.prototype._items = null;
	/** @type Boolean */
	self.prototype._selected = false;
	/** @type Boolean */
	self.prototype._disabled = false;
	/** @type Boolean */
	self.prototype._multiSomething = false;
	/** @type Object */
	self.prototype._metaData = null;
	/** @type Function */
	self.prototype._onClick = null;
	
	self.prototype.removeAllItems = function() {
		var items = this._items.splice(0, this._items.length);
		for (var i = 0; i < items.length; i++) { items[i].elem.detach(); }
		this._elemSubmenu.detach();
	};
	
	/** @param {ContextMenu.Item} item */
	self.prototype.removeItem = function(item) {
		if (!(item instanceof self)) return;
		var idx = this._items.indexOf(item);
		if (idx >= 0) {
			this._items.splice(idx, 1);
			item.elem.detach();
			if (this._items.length <= 0) {
				this._elemSubmenu.detach();
			}
		}
	};
	
	/** @param {ContextMenu.Item[]} items */
	self.prototype.setItems = function(items) {
		for (var i = 0; i < items.length; i++) { this.addItem(items[i]); }
	};
	
	/** @param {ContextMenu.Item} item */
	self.prototype.addItem = function(item) {
		this.insertItemAt(-1, item);
	};
	
	/**
	 * @param {Number} index
	 * @param {ContextMenu.Item} item
	 */
	self.prototype.insertItemAt = function(index, item) {
		if (!(item instanceof self)) return;
		this._items.push(item);
		if (this._items.length > 0) {
			this._elemSubmenu.appendTo(this.elem);
		}
		var thisSelf = this;
		this.elem.hover(
			function() {
				if (thisSelf._disabled) return false;
				var vw = $(window).width();
				//var vh = $(window).height();
				var mw = thisSelf._elemSubmenu.outerWidth(true);
				//var mh = thisSelf._elemSubmenu.outerHeight(true);

				var off = thisSelf.elem.offset();
				var prw = thisSelf.elem.width();

				if ((off.left + prw + mw) > vw) {
					thisSelf.elem.addClass('pull-left');
					thisSelf._elemSubmenu.css({ left: (-thisSelf._elemSubmenu.width()) + 'px'});
				} else {
					thisSelf.elem.removeClass('pull-left');
				}
			},
			function() {
				if (thisSelf._disabled) return false;
			}
		);

		if (index >= 0 && index < this._elemSubmenu.children('li').length) {
			this._elemSubmenu.children('li').eq(index).before(item.elem);
		} else {
			this._elemSubmenu.append(item.elem);
		}

	};
	
	/** @param {Object} data */
	self.prototype.setMetaData = function(data) {
		this._metaData = data;
	};
	
	/** @param {Boolean} multiSomething */
	self.prototype.setMultiSomethind = function(multiSomething) {
		this._multiSomething = multiSomething;
		if (multiSomething) {
			this.elem.addClass('wb-multi-mi');
		} else {
			this.elem.removeClass('wb-multi-mi');
		}
	};
	
	/** @param {Boolean} disabled */
	self.prototype.setSelected = function(disabled) {
		this._disabled = disabled;
		if (disabled) {
			this.elem.addClass('disabled');
		} else {
			this.elem.removeClass('disabled');
		}
	};
	
	/** @param {Boolean} selected */
	self.prototype.setSelected = function(selected) {
		this._selected = selected;
		if (selected) {
			this.elem.addClass('active');
		} else {
			this.elem.removeClass('active');
		}
	};
	
	/** @param {String} icon */
	self.prototype.setIcon = function(icon) {
		this._elemIcon.addClass(icon);
		if (icon) {
			this._elemIcon.detach();
		} else {
			this._elemIcon.prependTo(this.elemA);
		}
	};
	
	/** @param {String} name */
	self.prototype.setName = function(name) {
		this._elemText.text(name);
	};
	
	return self;
})();
	
	Service.contextMenu = {
		hideAll: function() { ContextMenu.hideAllMenus(); }
	};
	
	return ContextMenu;
});
;

/** WB ColorPicker **/
(window.defineModule = (window.defineModule || {})).name = 'WB ColorPicker';

define('ColorPicker', ['BorderControl'], function(BorderControl) {

/**
 * ColorPicker component class
 * @param {Boolean} noTransparent
 * @param {Boolean} big
 * @param {Boolean} noFixedWidth
 */
function WB_ColorPicker(noTransparent, big, noFixedWidth) { this.__construct(noTransparent, big, noFixedWidth); }

WB_ColorPicker.prototype.elem = null;
WB_ColorPicker.prototype.noTransparent = false;
WB_ColorPicker.prototype.noAlpha = false;
WB_ColorPicker.prototype.input = null;
WB_ColorPicker.prototype.alphaOverlay = null;
WB_ColorPicker.prototype.colorCode = null;
WB_ColorPicker.prototype.color = null;
WB_ColorPicker.prototype.editBtn = null;
WB_ColorPicker.prototype.onChange = null;
WB_ColorPicker.prototype.colorSelectorClass = null;
WB_ColorPicker.prototype._colorSelectorWrapper = null;
//WB_ColorPicker.prototype.tranBtn = null;

/**
 * Chose more readable color from black and white
 * 
 * @param color background color to calc readability for
 */
WB_ColorPicker.readableColor = function(color) {
	var col = WB_ColorPicker.colorTextToObject(color);
	if( "h" in col ) {
		if( "b" in col )
			col = WB_ColorPicker.HSB2RGB(col);
		else
			col = WB_ColorPicker.HSL2RGB(col);
	}

	var na = 1 - col.a;
	col.r = col.r * col.a + 127.5 * na;
	col.g = col.g * col.a + 127.5 * na;
	col.b = col.b * col.a + 127.5 * na;

    r = Math.pow(col.r / 255, 2.2);
    g = Math.pow(col.g / 255, 2.2);
	b = Math.pow(col.b / 255, 2.2);
    
	var Y = 0.2126 * r + 0.7151 * g + 0.0721 * b;
	
	return (Y > 0.5) ? "#000000" : "#ffffff";
};

WB_ColorPicker.colorTextToObject = function(text) {
	var color, matches;
	if( text && typeof text === "object" ) {
		color = $.extend(true, {}, text);
	}
	else if( !text || text === "transparent" ) {
		color = {r: 255, g: 255, b: 255, a: 0};
	}
	else {
		text = text.trim();
		if( matches = text.match(/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i) )
			color = {
				r: parseInt(matches[1] + matches[1], 16),
				g: parseInt(matches[2] + matches[2], 16),
				b: parseInt(matches[3] + matches[3], 16),
				a: 1
			};
		else if( matches = text.match(/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i) ) {
			color = {
				r: parseInt(matches[1], 16),
				g: parseInt(matches[2], 16),
				b: parseInt(matches[3], 16),
				a: 1
			};
		}
		else if( matches = text.match(/^rgb\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)$/i) ) {
			color = {
				r: parseFloat(matches[1]),
				g: parseFloat(matches[2]),
				b: parseFloat(matches[3]),
				a: 1
			};
		}
		else if( matches = text.match(/^rgba\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)$/i) ) {
			color = {
				r: parseFloat(matches[1]),
				g: parseFloat(matches[2]),
				b: parseFloat(matches[3]),
				a: parseFloat(matches[4])
			};
		}
		else if( matches = text.match(/^hsl\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)%\s*,\s*([0-9\.]+)%\s*\)$/i) ) {
			color = WB_ColorPicker.HSL2RGB({
				h: parseFloat(matches[1]) / 360,
				s: parseFloat(matches[2]) / 100,
				l: parseFloat(matches[3]) / 100,
				a: 1
			});
		}
		else if( matches = text.match(/^hsla\s*\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)%\s*,\s*([0-9\.]+)%\s*,\s*([0-9\.]+)\s*\)$/i) ) {
			color = WB_ColorPicker.HSL2RGB({
				h: parseFloat(matches[1]) / 360,
				s: parseFloat(matches[2]) / 100,
				l: parseFloat(matches[3]) / 100,
				a: parseFloat(matches[4])
			});
		}
		else {
			color = {r: 255, g: 255, b: 255, a: 1};
		}
	}
	return color;
};

WB_ColorPicker.HSB2RGB = function (hsb) {
	var rgb = {};
	var h = Math.round(hsb.h);
	var s = Math.round(hsb.s * 255 / 100);
	var b = Math.round(hsb.b * 255 / 100);
	if(s === 0)
		rgb.r = rgb.g = rgb.b = b;
	else {
		var t1 = b;
		var t2 = (255 - s) * b / 255;
		var t3 = (t1 - t2) * (h % 60) / 60;
		if( h === 360 ) h = 0;
		if( h < 60 ) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3; }
		else if( h < 120 ) { rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3; }
		else if( h < 180 ) { rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3; }
		else if( h < 240 ) { rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3; }
		else if( h < 300 ) { rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3; }
		else if( h < 360 ) { rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3; }
		else { rgb.r = 0; rgb.g = 0; rgb.b = 0 }
	}
	return {r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b), a: ("a" in hsb) ? Math.round(hsb.a * 100) / 100 : 1};
};

WB_ColorPicker.HSL2RGB = function (hsl) {
	var rgb = {
		a: ("a" in hsl) ? Math.round(hsl.a * 100) / 100 : 1
	};

	if( hsl.s === 0 ){
		rgb.r = rgb.g = rgb.b = l; // achromatic
	}
	else {
		var hue2rgb = 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;
		};

		var q = hsl.l < 0.5 ? hsl.l * (1 + hsl.s) : hsl.l + hsl.s - hsl.l * hsl.s;
		var p = 2 * hsl.l - q;
		rgb.r = hue2rgb(p, q, hsl.h + 1/3);
		rgb.g = hue2rgb(p, q, hsl.h);
		rgb.b = hue2rgb(p, q, hsl.h - 1/3);
	}
	rgb.r = Math.round(rgb.r * 255);
	rgb.g = Math.round(rgb.g * 255);
	rgb.b = Math.round(rgb.b * 255);
	return rgb;
};

WB_ColorPicker.colorObjectToText = function(color, noAlpha) {
	if( !noAlpha && "a" in color && color.a < 0.998047 ) { // 0.998047 = 1 - threshold to avoid floating point errors
		if( color.a < 0.001953 ) // threshold to avoid scientific notation and negative numbers in output
			color.a = 0;
		if( color.a === 0 )
			return "transparent";
		if( "h" in color ) {
			if( "b" in color )
				color = WB_ColorPicker.HSB2RGB(color);
			else
				color = WB_ColorPicker.HSL2RGB(color);
		}
		return "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + color.a + ")";
	}
	if( "h" in color )
		return "hsb(" + color.h + ", " + color.s + ", " + color.b + ")";
	var r = Math.round(color.r).toString(16);
	var g = Math.round(color.g).toString(16);
	var b = Math.round(color.b).toString(16);
	if( r.length === 1 ) r = '0' + r;
	if( g.length === 1 ) g = '0' + g;
	if( b.length === 1 ) b = '0' + b;
	return '#' + r + g + b;
};

/**
 * Construct ColorPicker component
 * @param noTransparent no transparent color selector in picker
 * @param noAlpha no alpha channel in color picker
 * @param big big color picker
 * @param noFixedWidth
 */
WB_ColorPicker.prototype.__construct = function(noTransparent, noAlpha, big, noFixedWidth) {
	this.noTransparent = noTransparent ? true : false;
	this.noAlpha = (this.noTransparent || noAlpha) ? true : false;
	if (big) {
		var thumbSize = 60;
		this.elem = $('<table class="wb-colorpicker-controll">' +
				'<tr>' +
					'<td>' +
						'<a href="javascript:void(0)" class="thumbnail bg-transparent-wrapper" style="margin-' + (wb_builder.rtl ? 'left' : 'right') + ': 4px; width: ' + thumbSize + 'px; height: ' + thumbSize + 'px"><span class="bg-transparent"></span></a>' +
						'<div class="colorcode"></div>' +
					'</td>' +
					'<td style="vertical-align: top;"><div class="btn-group-vertical btn-group-sm">' +
						'<button class="btn btn-default ui-colorpicker-btn" type="button"><span class="glyphicon glyphicon-pencil"></span></button>' +
						// '<button class="btn btn-default ui-colorpicker-btn2" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
					'</div></td>' +
				'</tr>' +
			'</table>');
		this.input = this.elem.find(".thumbnail");
		this.colorCode = this.elem.find(".colorcode");
		this.colorCode.css("display", "none");
		this.editBtn = this.elem.find(".ui-colorpicker-btn");
		// this.tranBtn = this.elem.find(".ui-colorpicker-btn2");
	} else {
		this.elem = $('<div class="input-group wb-colorpicker-controll"' + (noFixedWidth ? '' : ' style="width: 70px;"') + '>' +
				'<div class="bg-transparent-wrapper">' +
					'<input type="text" class="form-control" readonly="readonly" />' +
					'<div class="bg-transparent"></div>' +
				'</div>' +
				'<div class="colorcode"></div>' +
				'<div class="input-group-btn">' +
					'<button class="btn btn-default ui-colorpicker-btn" type="button"><span class="glyphicon glyphicon-pencil"></span></button>' +
					// '<button class="btn btn-default ui-colorpicker-btn2" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
				'</div>' +
			'</div>');
		this.input = this.elem.find("input");
		this.colorCode = this.elem.children(".colorcode");
		this.colorCode.css("display", "none");
		this.editBtn = this.elem.find(".ui-colorpicker-btn");
		// this.tranBtn = this.elem.children(".ui-colorpicker-btn2");
	}
	this.alphaOverlay = this.elem.find('.bg-transparent');
	
	if (this.noTransparent) {
		// this.tranBtn.detach();
		this.alphaOverlay.css('opacity', 0);
	}
	
	var thisClass = this;
	
	this.editBtn.on('click', function(e) {
		BorderControl.onDocumentClick(e);
	});
	this.editBtn.ColorPicker({
		WB_ColorPicker: WB_ColorPicker,
		color: "#ffffff",
		trans: thisClass.noTransparent,
		allowAlpha: !thisClass.noAlpha,
		onShow: function (colpkr) {
			$(colpkr).fadeIn(250);
			var btnPos = thisClass.elem.offset(),
				btnH = thisClass.editBtn.outerHeight(true),
				cpW = $(colpkr).outerWidth(true),
				cpH = $(colpkr).outerHeight(true),
				left = btnPos.left - $(window).scrollLeft(),
				top = btnPos.top + btnH - $(window).scrollTop(),
				winW = $(window).width(),
				winH = $(window).height();
			if ((left + cpW) > winW) {
				if ((left - cpW) > (winW - left - cpW)) {
					left -= cpW;
				} else {
					left += (winW - left - cpW);
				}
				if (left < 0) left = 0;
			}
			if ((top + cpH) > winH) {
				if ((top - cpH - btnH) > (winH - top - cpH)) {
					top -= (cpH + btnH);
				} else {
					top += (winH - top - cpH);
				}
				if (top < 0) top = 0;
			}
			$(colpkr).css({position: 'fixed', left: left, top: top});
			if (!thisClass.noTransparent)
				$(colpkr).find(".colorpicker_transparent").show();
			
			if (thisClass._colorSelectorWrapper) {
				thisClass._colorSelectorWrapper.show();
			}
			return false;
		},
		onHide: function (colpkr) {
			$(colpkr).fadeOut(250);
			if (thisClass._colorSelectorWrapper) {
				thisClass._colorSelectorWrapper.hide();
			}
			return false;
		},
		onChange: function (hsb, hex, rgb) {
			
		},
		onSubmit: function(hsb, hex, rgb, el) {
			thisClass.setValue(rgb);
			$(el).ColorPickerHide();
			thisClass.elem.trigger("change");
			if (thisClass._colorSelectorWrapper) {
				thisClass._colorSelectorWrapper.hide();
			}
		},
		onBeforeShow: function (el) {
			$(this).ColorPickerSetColor((thisClass.color === null) ? {r: 0, g: 0, b: 0, a: 0} : thisClass.color);
			if (thisClass.colorSelectorClass && !thisClass._colorSelectorWrapper) {
				thisClass._colorSelectorWrapper = $('<div>').addClass(thisClass.colorSelectorClass).css({
					position: 'absolute', width: '100%', height: '100%', top: 0, left: 0, zIndex: 2000
				}).appendTo($(el).parent()).append(el);
			}
		}
	});
	this.input.on("click", function(e) {
		thisClass.editBtn.ColorPickerShow();
	}).on("keyup", function(e) {
		var val = $(this).val();
		if (val.length === 6 || val.length === 3) {
			thisClass.setValue(val);
		}
	});
	/*this.tranBtn.bind("click", function() {
		thisClass.setValue("transparent");
	});*/
};

/**
 * Get currently selected color
 * @return css hex color code (ex. #0f0f0f) or 'transparent'
 */
WB_ColorPicker.prototype.getValue = function() {
	return WB_ColorPicker.colorObjectToText(this.color, this.noTransparent);
};

/**
 * Set color
 * @param value css hex color code (ex. #0f0f0f) or 'transparent' or empty string (defaults to 'transparent')
 */
WB_ColorPicker.prototype.setValue = function(value) {
	var color = WB_ColorPicker.colorTextToObject(value);
	if (this.noAlpha) color.a = 1;

	this.color = color;
	if( color.a >= 0.001953 ) {
		//this.input.val(color);
		this.colorCode.html(WB_ColorPicker.colorObjectToText(color));
		this.alphaOverlay.css('opacity', 1 - color.a);
		this.input.css("background-color", WB_ColorPicker.colorObjectToText(color, true));
		this.input.css("color", WB_ColorPicker.readableColor(color));
	}
	else {
		//this.input.val("");
		this.colorCode.html("#" + __("Transparent"));
		this.alphaOverlay.css('opacity', 1);
		this.input.css("background-color", "");
		this.input.css("color", "");
	}
	if (typeof(this.onChange) === "function") {
		this.onChange.call(this);
	}
};

/**
 * Get currently selected color
 * NOTE: this is alias of getValue()
 * @return css hex color code (ex. #0f0f0f), rgba color if there is opacity (ex. rgba(15, 15, 15, 0.6)), or 'transparent'
 */
WB_ColorPicker.prototype.getColor = function() {
	return this.getValue();
};

/**
 * Set color
 * NOTE: this is alias of setValue(...)
 * @param color css hex color code (ex. #0f0f0f), rgba color if there is opacity (ex. rgba(15, 15, 15, 0.6)), or 'transparent', or empty string (defaults to 'transparent')
 */
WB_ColorPicker.prototype.setColor = function(color) {
	this.setValue(color);
};

/**
 * Show color picker popup
 */
WB_ColorPicker.prototype.showPicker = function() {
	this.editBtn.ColorPickerShow();
};

/**
 * Hide color picker popup
 */
WB_ColorPicker.prototype.hidePicker = function() {
	this.editBtn.ColorPickerHide();
};

WB_ColorPicker.prototype.setColorSelectorClass = function(colorSelectorClass) {
	this.colorSelectorClass = colorSelectorClass;
};

	return WB_ColorPicker;
});
;

/** WB ImagePicker **/
(window.defineModule = (window.defineModule || {})).name = 'WB ImagePicker';

define('ImagePicker', ['Service'], function(Service) {
	'use strict';

/**
 * ImagePicker component class
 * @param {string} mode
 * @param {number} thumbSize
 * @param {boolean} multiselect
 * @param {boolean} mediatabs
 * @param {boolean} fontAwesomeTab
 * @param {boolean} usePictureManager
 * @param {Function} callback
 */
var ImagePicker = function(mode, thumbSize, multiselect, mediatabs, fontAwesomeTab, usePictureManager, callback) { this.__construct(mode, thumbSize, multiselect, mediatabs, fontAwesomeTab, usePictureManager, callback); };

ImagePicker.prototype.elem = null;
ImagePicker.prototype.image = null;
ImagePicker.prototype.icon = null;
ImagePicker.prototype.selButton = null;
ImagePicker.prototype.clearButton = null;
ImagePicker.prototype.libraryDlg = null;
ImagePicker.prototype.counter = null;
ImagePicker.prototype.src = null;
ImagePicker.prototype.images = null;
ImagePicker.prototype.imagesInfo = null;
ImagePicker.prototype.mode = 'image';
ImagePicker.prototype.multiselect = false;
ImagePicker.prototype.mediatabs = false;
ImagePicker.prototype.customContent = null;
ImagePicker.prototype.fontAwesomeTab = false;
ImagePicker.prototype.usePictureManager = false;
ImagePicker.prototype.callback = null;

/**
 * Construct ImagePicker component
 * @param {string} mode
 * @param {number} thumbSize
 * @param {boolean} multiselect
 * @param {boolean} mediatabs
 * @param {boolean} fontAwesomeTab
 * @param {boolean} usePictureManager
 * @param {Function} callback
 */
ImagePicker.prototype.__construct = function(mode, thumbSize, multiselect, mediatabs, fontAwesomeTab, usePictureManager, callback) {
	this.callback = callback;
	if (mode)
		this.mode = mode;
	if (!thumbSize || isNaN(thumbSize*1)) {
		thumbSize = 60;
	} else {
		thumbSize = thumbSize*1;
	}
	this.multiselect = multiselect ? true : false;
	if (mediatabs)
		this.mediatabs = mediatabs;
	if (usePictureManager) {
		this.usePictureManager = usePictureManager;
		this.multiselect = usePictureManager;
	}
	this.fontAwesomeTab = (fontAwesomeTab && !usePictureManager) ? fontAwesomeTab : false;
	this.elem = $('<table class="wb-image-picker">' +
			'<tr>' +
				'<td>' +
					'<a href="javascript:void(0)" class="thumbnail" style="margin-' + (wb_builder.rtl ? 'left' : 'right') + ': 4px; width: ' + thumbSize + 'px; height: ' + thumbSize + 'px; position: relative">' +
						'<img src="" alt="" style="max-height: ' + (thumbSize - 10) + 'px; min-width: 1px;" />' +
						'<i class="fa" style="color: #222; font-size: ' + (thumbSize - 20) + 'px; text-align: center; position: absolute; left: 0; top: 10px; width: 100%; height: ' + (thumbSize - 20) + 'px; overflow: hidden;"></i>' +
						'<div class="wb_caption wb_caption_small wb_empty_msg"><div>' +
							(this.multiselect
								? ((this.mode === "image") ? __('Click to add picture(s)') : __('Click to add file(s)'))
								: ((this.mode === "image" || this.mode === "favicon") ? __('Click to select picture') : __('Click to select file'))
							) +
						'</div></div>' +
					'</a>' +
				'</td>' +
				'<td style="vertical-align: top;"><div class="btn-group-vertical btn-group-sm">' +
					'<a href="javascript:void(0)" class="btn btn-default"><span class="glyphicon glyphicon-pencil"></span></a>' +
					'<a href="javascript:void(0)" class="btn btn-default"><span class="glyphicon glyphicon-remove"></span></a>' +
				'</div></td>' +
			'</tr>' +
		'</table>');
	
	this.images = [];
	this.imagesInfo = [];
	
	var thisClass = this;
	$(".thumbnail", this.elem).css({ cursor: "pointer", textDecoration: "none" });
	this.image = $("img", this.elem);
	this.image.css("display", "none");
	this.icon = $("i.fa", this.elem);
	this.icon.css("display", "none");
	this.counter = $('<div class="wb_caption wb_caption_small"><div></div></div>');
	this.counter.css("visibility", "hidden");
	$(".thumbnail", this.elem).append(this.counter);
	if (!this.multiselect) this.counter.css({ display: "none" });
	this.selButton = $(".btn", this.elem).first();
	this.clearButton = $(".btn", this.elem).last();
	var selectImages = function() {
		if( thisClass.usePictureManager && thisClass.images.length ) {
			Service.GalleryPictureManager.setMediaLibraryOptions({
				showMediaTabs: thisClass.mediatabs,
				customContentCallback: thisClass.customContent
			});
			Service.GalleryPictureManager.setValue(thisClass.images);
			Service.GalleryPictureManager.setApplyCallback(function () {
				thisClass.setValues(Service.GalleryPictureManager.getValue());
				Service.GalleryPictureManager.setVisible(false);
			});
			Service.GalleryPictureManager.setVisible(true);
		}
		else {
			thisClass.libraryDlg = Service.mediaLibrary.open(__("Select media"), thisClass.multiselect, thisClass.mode, thisClass.mediatabs, thisClass.fontAwesomeTab, thisClass.customContent);
			thisClass.libraryDlg.addButton(__("Cancel"));
			thisClass.libraryDlg.addButton(__("Select"), function() {
				var list = thisClass.libraryDlg.getSelectedFiles(true);

				if (thisClass.multiselect) {
					thisClass.setValues(list);
				} else {
					thisClass.setImage((list.length > 0) ? list[0] : null);
				}
				thisClass.libraryDlg.hide();
				if( thisClass.usePictureManager && thisClass.images.length ) {
					selectImages();
				}
			}, true);

			if (thisClass.images.length > 0) {
				thisClass.libraryDlg.setSelectedFiles(thisClass.images);
			} else {
				thisClass.libraryDlg.clearFileSelection();
			}
			thisClass.libraryDlg.show();
		}
		return false;
	};
	this.selButton.bind("click", selectImages);
	this.clearButton.bind("click", function() {
		thisClass.setImage(null);
		thisClass.setValues([]);
		return false;
	});
	$(".thumbnail", this.elem).bind("click", function() { thisClass.selButton.trigger("click"); });
};

/**
 * Get currently selected image URL
 * @param {Boolean} asObject return selected file list as object { file: ..., width: ..., height: ..., size: ... }
 * @return relative image URL
 */
ImagePicker.prototype.getValues = function(asObject) {
	if (asObject) {
		return this.imagesInfo;
	}
	var list_ = [];
	for (var i = 0; i < this.list.length; i++) {
		if (!(i in this.imagesInfo)) continue;
		if( "faIcon" in this.imagesInfo[i] )
			list_.push(this.imagesInfo[i]);
		else
			list_.push(this.imagesInfo[i].file);
	}
	return list_;
};

/**
 * Set image URL's
 * @param list relative image URL list
 */
ImagePicker.prototype.setValues = function(list) {
	this.list = list;
	this.images = [];
	this.imagesInfo = [];
	this.src = null;
	var src;
	for (var i = 0; i < list.length; i++) {
		if( typeof list[i] === "object" && "faIcon" in list[i] ) {
			src = $.extend({}, list[i]);
			this.imagesInfo.push(src);
		}
		else {
			var url = (typeof list[i] === "object") ? list[i].file : list[i];
			var _url = (url && url !== "none") ? url : null;
			src = _url ? wb_builder.makeRelUrl(_url) : null;
			this.imagesInfo.push($.extend({}, list[i], { file: src }));
		}
		this.images.push(src);
		if (!this.src) this.src = src;
	}
	/*$(".thumbnail", this.elem).attr("title", (this.images.length > 0) ? this.images.length : __("No images selected"));
	if ($(".thumbnail", this.elem).data("__WB_TOOLTIP__")) {
		$(".thumbnail", this.elem).tooltip('destroy');
		$(".thumbnail", this.elem).data("__WB_TOOLTIP__", false);
	}
	$(".thumbnail", this.elem).tooltip();
	$(".thumbnail", this.elem).data("__WB_TOOLTIP__", true);*/
	this.counter.children('div').html(this.images.length + ' ' + __('picture(s) selected'));
	this.counter.css("visibility", ((this.images.length > 0) ? "visible" : "hidden"));
	
	if (this.images.length) {
		this.elem.find(".wb_empty_msg").addClass("hide2");
	} else {
		this.elem.find(".wb_empty_msg").removeClass("hide2");
	}
	if (typeof this.callback === "function") this.callback.call(this);
};

/**
 * Get currently selected image URL
 * @return relative image URL
 */
ImagePicker.prototype.getValue = function() {
	return this.src;
};

/**
 * Set image
 * @param url relative image URL
 */
ImagePicker.prototype.setValue = function(url) {
	this.images = [];
	this.imagesInfo = [];
	var urlInfo = (url && (typeof url === "object")) ? url : { file: url, width: 0, height: 0, size: 0 };
	var title = "";
	if( "faIcon" in urlInfo ) {
		this.src = $.extend({}, urlInfo);
		title = urlInfo.faIcon;
		this.icon.attr("class", "fa fa-" + urlInfo.faIcon);
		this.image.css("display", "none");
		this.icon.css("display", (this.src ? "block" : "none"));
		if (this.src) {
			this.images.push(this.src);
			this.imagesInfo.push(this.src);
		}
	}
	else {
		var _url = (urlInfo.file && urlInfo.file !== "none") ? urlInfo.file : null;
		this.src = _url ? wb_builder.makeRelUrl(_url) : null;
		if (this.src) {
			this.images.push(this.src);
			this.imagesInfo.push($.extend({}, urlInfo, { file: this.src}));
		}
		title = _url ? _url.split("/") : "";
		title = title ? title[title.length - 1] : "";
		title = title.split("%20").join(" ");

		var thumbUrl = this.src ? wb_builder.makeLocalUrl(this.src) : "";
		var ext = thumbUrl.split(".");
		ext = (ext.length > 1) ? ext[(ext.length - 1)] : "";
		if (ext === "swf") {
			thumbUrl = wb_builder.modBaseUrl + "img/file_flash.png";
		} else if (ext === "mp3") {
			thumbUrl = wb_builder.modBaseUrl + "img/file_audio.png";
		} else if (ext === "pdf") {
			thumbUrl = wb_builder.modBaseUrl + "img/file_pdf.png";
		} else if ("docx,doc,xls,xlsx,rtf,ppt,pptx,odt".indexOf(ext) >= 0) {
			thumbUrl = wb_builder.modBaseUrl + "img/file_doc.png";
		}

		this.image.get(0).src = thumbUrl;
		this.image.css("display", (this.src ? "block" : "none"));
		this.icon.css("display", "none");
	}

	$(".thumbnail", this.elem).attr("title", title);
	if ($(".thumbnail", this.elem).data("__WB_TOOLTIP__")) {
		$(".thumbnail", this.elem).tooltip('destroy');
		$(".thumbnail", this.elem).data("__WB_TOOLTIP__", false);
	}

	$(".thumbnail", this.elem).tooltip();
	$(".thumbnail", this.elem).data("__WB_TOOLTIP__", true);

	this.counter.children('div').html(this.images.length);
	this.counter.css("visibility", ((this.images.length > 0) ? "visible" : "hidden"));
	
	if (this.images.length) {
		this.elem.find(".wb_empty_msg").addClass("hide2");
	} else {
		this.elem.find(".wb_empty_msg").removeClass("hide2");
	}
	if (typeof this.callback === "function") this.callback.call(this);
};

/**
 * Get currently selected image URL
 * NOTE: alias of getValue()
 * @return relative image URL
 */
ImagePicker.prototype.getImage = function() {
	return this.getValue();
};

/**
 * Set image
 * NOTE: alias of setValue(...)
 * @param url relative image URL
 */
ImagePicker.prototype.setImage = function(url) {
	this.setValue(url);
};

	window.WB_ImagePicker = ImagePicker;
	
	return ImagePicker;
});
;

/** WB AlignSelector **/
(window.defineModule = (window.defineModule || {})).name = 'WB AlignSelector';

/**
 * AlignSelector component class
 * 
 * @author Marius Tomas <marius@profis.lt>
 * @version 1.2.0, 2012-07-23
 */
function WB_AlignSelector() { this.__construct(); }

WB_AlignSelector.index = 0;
WB_AlignSelector.prototype.elem = null;
WB_AlignSelector.prototype.hAlign = "left";
WB_AlignSelector.prototype.vAlign = "top";
WB_AlignSelector.prototype.callback = null;

/**
 * Construct AlignSelector component
 */
WB_AlignSelector.prototype.__construct = function() {
	//var idx = WB_AlignSelector.index;
	WB_AlignSelector.index++;
	this.elem = $('<table class="wb-align-controll">' +
			'<tr>' +
				'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>' +
			'</tr>' +
			'<tr>' +
				'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>' +
			'</tr>' +
			'<tr>' +
				'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>' +
			'</tr>' +
		'</table>');
	var thisClass = this;
	var tds = this.elem.find("td");
	tds.bind("click", function() {
		tds.removeClass("active");
		$(this).addClass("active");
		var x = $(this).index()*1;
		var y = $(this).parent().index()*1;
		thisClass.hAlign = (x > 0) ? ((x === 1) ? "center" : "right") : "left";
		thisClass.vAlign = (y > 0) ? ((y === 1) ? "center" : "bottom") : "top";
		if (typeof thisClass.callback === "function") thisClass.callback.call(thisClass);
	});
	// $("[rel=tooltip]", this.elem).tooltip();
};

/**
 * Get currently selected align
 * @return align align as string in format '[horizontal] [vertical]' (ex. 'left top')
 */
WB_AlignSelector.prototype.getValue = function() {
	return this.hAlign + " " + this.vAlign;
};

/**
 * Set align
 * @param align align as string in format '[horizontal] [vertical]' (ex. 'left top')
 */
WB_AlignSelector.prototype.setValue = function(align) {
	var a = (align + "").split(" ");
	this.hAlign = a[0] ? a[0] : "left";
	this.vAlign = (a.length > 1 && a[1]) ? a[1] : "top";
	var x = (this.hAlign === "right") ? 2 : ((this.hAlign === "center") ? 1 : 0);
	var y = (this.vAlign === "bottom") ? 2 : ((this.vAlign === "center") ? 1 : 0);
	var tds = this.elem.find("td");
	tds.removeClass("active");
	tds.eq(y*3 + x).addClass("active");
};

/**
 * Get currently selected align
 * NOTE: alias of getValue()
 * @return align align as string in format '[horizontal] [vertical]' (ex. 'left top')
 */
WB_AlignSelector.prototype.getAlign = function() {
	return this.getValue();
};

/**
 * Set align
 * NOTE: alias of setValue(...)
 * @param align align as string in format '[horizontal] [vertical]' (ex. 'left top')
 */
WB_AlignSelector.prototype.setAlign = function(align) {
	this.setValue(align);
};
;

/** WB HAlignSelector **/
(window.defineModule = (window.defineModule || {})).name = 'WB HAlignSelector';

/**
 * Horizontal AlignSelector component class
 * 
 * @author Marius Tomas <marius@profis.lt>
 * @version 1.2.0, 2012-07-23
 * @param {Boolean} justify Include Justify button
 */
function WB_HAlignSelector(justify) { this.__construct(justify); }

WB_HAlignSelector.prototype.elem = null;

/**
 * Construct Horizontal AlignSelector component
 */
WB_HAlignSelector.prototype.__construct = function(justify) {
	justify = justify ? true : false;
	this.elem = $('<div class="btn-group wb-halign-control">' +
			'<button class="btn btn-default active" data-value="left"><span class="glyphicon glyphicon-align-left"></span></button>' +
			'<button class="btn btn-default" data-value="center"><span class="glyphicon glyphicon-align-center"></span></button>' +
			'<button class="btn btn-default" data-value="right"><span class="glyphicon glyphicon-align-right"></span></button>' +
			(justify ? '<button class="btn btn-default" data-value="justify"><span class="glyphicon glyphicon-align-justify"></span></button>' : '') + 
		'</div>');
	$(".btn", this.elem).bind("click", function() {
		$(this).parent().children(".btn").removeClass("active");
		$(this).addClass("active");
	});
};

/**
 * Get currently selected align
 * @return align align as string (ex. 'left')
 */
WB_HAlignSelector.prototype.getValue = function() {
	var val = "left";
	this.elem.children(".active").each(function() {
		val = $(this).attr("data-value");
	});
	return val;
};

/**
 * Set align
 * @param align align as string (ex. 'left')
 */
WB_HAlignSelector.prototype.setValue = function(align) {
	this.elem.children().removeClass("active");
	this.elem.children("[data-value='" + align + "']").addClass("active");
};
;

/** WB SizeSelector **/
(window.defineModule = (window.defineModule || {})).name = 'WB SizeSelector';

define('SizeSelector', [], function() {
	'use strict';

/**
 * SizeSelector component class
 * @param {Boolean} noUnits hide units label
 * @param {Number} minValue custom min value
 * @param {Number} maxValue custom max value
 * @param {Number} step increment (decrement) by this value
 * @param {Boolean} noRepeat
 * @param {Boolean} noFixedWidth
 * @class
 */
var SizeSelector = function(noUnits, minValue, maxValue, step, noRepeat, noFixedWidth) { this.__construct(noUnits, minValue, maxValue, step, noRepeat, noFixedWidth); };

SizeSelector.toCSS = function(size) {
	var css = "";
	if ((typeof(size) === "object") && size.length) {
		for (var i = 0; i < Math.min(size.length, 4); i++) {
			css += (css ? " " : "") + size[i] + "px";
		}
	} else {
		css = size + "px";
	}
	return css;
};
SizeSelector.prototype.elem = null;
SizeSelector.prototype.input = null;
SizeSelector.prototype.minValue = 1;
SizeSelector.prototype.maxValue = 9999;
SizeSelector.prototype.noRepeat = false;
SizeSelector.prototype.precision = 0;
SizeSelector.prototype.clearTrailingZeroes = true;
SizeSelector.prototype._enabled = true;
SizeSelector.prototype.step = 1;
SizeSelector.prototype.buttonHoldData = null;

/**
 * Construct SizeSelector component
 * @param {Boolean} noUnits hide units label
 * @param {Number} minValue custom min value
 * @param {Number} maxValue custom max value
 * @param {Number} step increment (decrement) by this value
 * @param {Boolean} noRepeat
 * @param {Boolean} noFixedWidth
 */
SizeSelector.prototype.__construct = function(noUnits, minValue, maxValue, step, noRepeat, noFixedWidth) {
	if (!step) { step = 1; }
	if (minValue !== null && minValue !== undefined) { this.minValue = minValue; }
	if (maxValue !== null && maxValue !== undefined) { this.maxValue = maxValue; }
	this.noRepeat = (noRepeat === undefined) ? (maxValue === undefined ? true : this.noRepeat) : noRepeat;
	this.step = step;
	
	var thisClass = this;
	
	this.elem = $('<div class="wb-size-selector"><div class="input-group"' + (noFixedWidth ? '' : ' style="width: 70px;"') + '>' +
			'<input type="text" class="form-control" value="1" />' +
			'<div class="input-group-btn buttons">' +
				'<button class="btn btn-default btn-arrow arrow-up" type="button"><span class="caret"></span></button>' +
				'<button class="btn btn-default btn-arrow arrow-down" type="button"><span class="caret"></span></button>' +
			'</div>' +
		'</div>' + (noUnits ? '' : '<span class="units">px</span>') + '</div>');
	if (!noUnits) this.elem.children('.input-group').eq(0).css({marginRight: 20});
	this.input = $('input', this.elem);
	this.input.on('change', function() {
		var val = parseFloat(this.value.replace(",", "."));
		if (isNaN(val)) val = 0;
		val = Math.max(val, thisClass.minValue);
		val = Math.min(val, thisClass.maxValue);
		this.value = thisClass.numberToText(val);
	});
	this.input.on('keydown', function(e) {
		var keyCode = e.keyCode || e.which;
		if( thisClass.buttonHoldData && (keyCode === 38 || keyCode === 40) ) {
			e.stopImmediatePropagation();
			e.preventDefault();
			return;
		}
		if( keyCode === 38 ) thisClass.onArrowUp(true, e);
		else if( keyCode === 40 ) thisClass.onArrowDown(true, e);
	});
	$('button', this.elem).first().bind('mousedown touchstart', this.onArrowUp.bind(this, false));
	$('button', this.elem).last().bind('mousedown touchstart', this.onArrowDown.bind(this, false));
};

SizeSelector.prototype.onArrowUp = function(isKeyboard, e) {
	if (!this._enabled) return false;
	e.stopImmediatePropagation();
	e.preventDefault();
	this.onButtonPress(isKeyboard, 1);
};

SizeSelector.prototype.onArrowDown = function(isKeyboard, e) {
	if (!this._enabled) return false;
	e.stopImmediatePropagation();
	e.preventDefault();
	this.onButtonPress(isKeyboard, -1);
};

SizeSelector.prototype.modifyByStep = function(direction) {
	var val = this.input.val()*1 + this.step * direction;
	if (isNaN(val)) val = Math.min(Math.max(0, this.minValue), this.maxValue);
	else if (val < this.minValue) val = !this.noRepeat ? this.maxValue : this.minValue;
	else if (val > this.maxValue) val = !this.noRepeat ? this.minValue : this.maxValue;
	this.input.val(this.numberToText(val));
	this.input.trigger('change');
};

SizeSelector.prototype.onButtonPress = function(isKeyboard, direction) {
	if( this.buttonHoldData )
		this.onButtonRelease();
	this.buttonHoldData = {
		nextTime: 500,
		direction: direction,
		eventHandler: this.onButtonRelease.bind(this),
		timeoutHandler: this.onButtonHold.bind(this)
	};
	$(document.body).on(isKeyboard ? "keyup" : "mouseup touchend touchcancel", this.buttonHoldData.eventHandler);
	this.buttonHoldData.timer = setTimeout(this.buttonHoldData.timeoutHandler, this.buttonHoldData.nextTime);
	this.modifyByStep(direction);
};

SizeSelector.prototype.onButtonHold = function() {
	if( !this.buttonHoldData )
		return;
	this.modifyByStep(this.buttonHoldData.direction);
	this.buttonHoldData.nextTime = Math.max(10, this.buttonHoldData.nextTime * 0.66);
	this.buttonHoldData.timer = setTimeout(this.buttonHoldData.timeoutHandler, this.buttonHoldData.nextTime);
};

SizeSelector.prototype.onButtonRelease = function(e) {
	if( !this.buttonHoldData )
		return;
	if( e && e.type === 'keyup' ) {
		var keyCode = e.keyCode || e.which;
		if( keyCode !== 38 && keyCode !== 40 )
			return;
	}
	e.stopImmediatePropagation();
	e.preventDefault();
	$(document.body).off("keyup mouseup touchend touchcancel", this.buttonHoldData.eventHandler);
	clearTimeout(this.buttonHoldData.timer);
	this.buttonHoldData = null;
};

/**
 * Set new maximum value.
 * @param {Number} maxValue new maximum value to set (must be bigger than minimum value).
 */
SizeSelector.prototype.setMaxValue = function(maxValue) {
	if (maxValue <= this.minValue) return;
	this.maxValue = maxValue;
};

/**
 * Set if this control is enabled.
 * @param {Boolean} enabled if true then enabled else not.
 */
SizeSelector.prototype.setEnabled = function(enabled) {
	this._enabled = enabled ? true : false;
	if (this._enabled) {
		this.input.removeClass('disabled');
		this.input.removeAttr('disabled');
		$('button', this.elem).removeClass('disabled');
	} else {
		this.input.addClass('disabled');
		this.input.attr({disabled: 'disabled'});
		$('button', this.elem).addClass('disabled');
	}
};

/**
 * Get if this control is enabled.
 * @returns {Boolean} if true then enabled else not.
 */
SizeSelector.prototype.getEnabled = function() {
	return this._enabled;
};

/**
 * Set unit name
 * @param {String} unit
 */
SizeSelector.prototype.setUnit = function(unit) {
	this.elem.find('.units').text(unit);
};

/**
 * Get precision of number in input
 * @return {Number}
 */
SizeSelector.prototype.getPrecision = function() {
	return this.precision;
};

/**
 * Set precision of number in input
 * @param {Number} precision
 */
SizeSelector.prototype.setPrecision = function(precision) {
	this.precision = precision;
	this.setValue(this.getValue());
};

/**
 * Get option value for clearing zeroes at the end of the number
 * @return {Boolean}
 */
SizeSelector.prototype.getClearTrailingZeroes = function() {
	return this.clearTrailingZeroes;
};

/**
 * Set option value for clearing zeroes at the end of the number
 * @param {Boolean} clear
 */
SizeSelector.prototype.setClearTrailingZeroes = function(clear) {
	this.clearTrailingZeroes = clear;
	this.setValue(this.getValue());
};

/**
 * Get currently selected size
 * @return {Number} size in pixels
 */
SizeSelector.prototype.getValue = function() {
	var res = parseFloat(this.input.val().replace(",", "."));
	return (isNaN(res) ? this.minValue : res);
};

/**
 * Set size
 * @param {Number} size size in pixels
 */
SizeSelector.prototype.setValue = function(size) {
	var val = size ? size : 0;
	if ((typeof(val) === 'object') && val.length) {
		val = size[0]*1;
	} else {
		val = size*1;
	}
	if (isNaN(val)) val = this.minValue;
	this.input.val(this.numberToText(val));
};

SizeSelector.prototype.roundValue = function(value) {
	var mul = Math.pow(10, this.precision);
	return Math.round(value * mul) / mul;
};

SizeSelector.prototype.numberToText = function(val) {
	val = this.roundValue(val).toFixed(this.precision);
	if( this.clearTrailingZeroes )
		val = val.replace(/\.0+$/, '').replace(/(\.[0-9]*?)0+$/, '$1');
	return val;
};

/**
 * Attach a handler to controll input fields
 * @param {String} eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names
 * @param {Object|Function} eventData A map of data that will be passed to the event handler
 * @param {Boolean} preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true
 */
SizeSelector.prototype.bind = function(eventType, eventData, preventBubble) {
	this.input.bind(eventType, eventData, preventBubble);
};

/**
 * Remove a previously-attached event handler from controll input fields
 * @param {String} eventType a string containing a JavaScript event type, such as click or submit
 */
SizeSelector.prototype.unbind = function(eventType) {
	this.input.unbind(eventType);
};

	return SizeSelector;
});
;

/** WB ComboBox **/
(window.defineModule = (window.defineModule || {})).name = 'WB ComboBox';

define('ComboBox', ['Service'], function(Service) {
	'use strict';

/**
 * ComboBox component class
 * @param {Object} options
 * @param {String} selected
 * @param {Number} zIndex
 */
var ComboBox = function(options, selected, zIndex) { this.__construct(options, selected, zIndex); };

ComboBox.prototype.elem = null;
ComboBox.prototype.input = null;
ComboBox.prototype.button = null;
ComboBox.prototype.menu = null;
ComboBox.prototype.options = null;
ComboBox.prototype.optionsData = null;
ComboBox.prototype.onChange = null;
ComboBox.prototype.onBeforeChange = null;
ComboBox.elemList = [];
ComboBox.closeAll = function(excludeMe) {
	for (var i = 0; i < ComboBox.elemList.length; i++) {
		if (excludeMe && excludeMe == ComboBox.elemList[i]) continue;
		ComboBox.elemList[i].menu.parent().removeClass("open");
	}
};
ComboBox.onDocumentClick = function(e) {
	var t = $(e.target);
	var activeComboBox = null;
	if (t.is('.wb-combobox-controll *')) {
		t = t.parents('.wb-combobox-controll');
		
		$.each(ComboBox.elemList, function() {
			if (t.get(0) == this.elem.get(0)) {
				activeComboBox = this;
				return;
			}
		});
	}
	ComboBox.closeAll(activeComboBox);
	Service.contextMenu.hideAll();
};

/**
 * Construct ComboBox component
 * @param {Object} options combo box option list as object = {key: value, ...}
 * @param {String} selected key of the option to select by default
 * @param {Number} zIndex if true make dropdown list visible when element itself is within fixed element
 */
ComboBox.prototype.__construct = function(options, selected, zIndex) {
	this.elem = $('<div class="input-group wb-combobox-controll">' +
			'<input type="text" class="form-control" readonly="readonly" />' +
			'<div class="input-group-btn">' +
				'<button class="btn btn-default dropdown-toggle" type="button"><span class="caret"></span></button>' +
				'<ul class="dropdown-menu"></ul>' +
			'</div>' +
		'</div>');
	this.input = this.elem.children("input");
	this.menu = this.elem.find("ul");
	
	this.button = this.elem.find("button");
	var thisClass = this, clickClb;
	
	this.input.bind("click", clickClb = function() {
		var w = thisClass.input.outerWidth(),
			mw = thisClass.menu.width(),
			ew = thisClass.elem.outerWidth();
		if (mw < ew) thisClass.menu.width(ew);
		if (wb_builder.rtl) {
			thisClass.menu.css({ marginRight: (-w) + "px" });
		} else {
			thisClass.menu.css({ marginLeft: (-w) + "px" });
		}
		if (zIndex) { thisClass.fixDropdownPosition(zIndex); }
		thisClass.button.parent().toggleClass("open");
		
		thisClass.menu.children('li').each(function(i) {
			if ($(this).hasClass('active')) {
				var ih = $(this).outerHeight(true);
				var mh = thisClass.menu.height();
				thisClass.menu.scrollTop(ih * i - mh / 2 + ih / 2);
				return false;
			}
		});
		
		var it = thisClass.input.offset().top;
		var ws = window.scrollY;
		var mh = Math.round(thisClass.input.outerHeight(true) + thisClass.menu.outerHeight(true));
		var wh = $(window).height();
		
		if (it - ws + mh > wh) {
			thisClass.button.parent().addClass("dropup");
		} else {
			thisClass.button.parent().removeClass("dropup");
		}
	});
	this.button.bind("click", clickClb);
	
	this.options = {};
	this.optionsData = {};
	if (options) {
		for (var key in options) {
			this.options[key] = options[key];
			this.addOption(key, options[key], (key === selected));
		}
	}
	ComboBox.elemList.push(this);
};

ComboBox.prototype.fixDropdownPosition = function(zIndex) {
	if ($.browser.msie) return;
	var thisClass = this;
	var offset = this.elem.offset(), css;
	if (!offset.top || !offset.left) {
		setTimeout(function() {
			thisClass.fixDropdownPosition(zIndex);
		}, 20);
		return;
	}
	css = {
		top: (this.elem.offset().top - window.scrollY + 30) + 'px',
		marginLeft: 0,
		zIndex: zIndex,
		position: 'fixed'
	};
	if (wb_builder.rtl) {
		css.right = this.elem.offset().left + this.elem.outerWidth(true) + 'px';
	} else {
		css.left = this.elem.offset().left + 'px';
	}
	this.menu.css(css);
};

/**
 * Get additional data assigned to selected option
 * @returns {Object}
 */
ComboBox.prototype.getValueData = function() {
	var sel = this.menu.children('li.active');
	var val = (sel.size() > 0) ? sel.attr('data-value') : null;
	return val ? this.optionsData[val].data : null;
};

/**
 * Get currently selected option key
 * @return {String} key of selected option
 */
ComboBox.prototype.getValue = function() {
	var sel = this.menu.children("li.active");
	var val = (sel.size() > 0) ? sel.attr("data-value") : null;
	if (val === null) {
		for (var k in this.options) {
			val = this.options[k];
			break;
		}
	}
	return val;
};

/**
 * Set size
 * @param {String} key of the option to select
 */
ComboBox.prototype.setValue = function(key) {
	var has = false, k;
	for (k in this.options) {
		if (key === k) {
			has = true;
			break;
		}
	}
	if (key !== null && key !== undefined) {
		if (!has) {
			for (k in this.options) {
				this.menu.children("li[data-value='" + key.replace(/(['"])/g, '\\$1') + "']").trigger("click", true);
				return k;
			}
		} else {
			this.menu.children("li[data-value='" + key.replace(/(['"])/g, '\\$1') + "']").trigger("click", true);
		}
	}
	return key;
};

/**
 * Add option to combo box
 * @param {String} key option key (ID)
 * @param {String} value option value (label)
 * @param {Boolean} selected if true option will be selected
 * @param {Object} data additianl data to be assigned to option
 * @param {Boolean} isEmpty
 */
ComboBox.prototype.addOption = function(key, value, selected, data, isEmpty) {
	this.options[key] = value;
	var opt = $('<li>' + (isEmpty ? '' : '<a href="javascript:void(0)"></a>') + '</li>');
	this.optionsData[key] = {data: data, elem: opt};
	opt.attr("data-value", key);
	if (!isEmpty) {
		opt.children("a").html(value);
		var thisClass = this;
		opt.bind("click", function(e, skipOnChange) {
			var proceed = true;
			if (typeof thisClass.onBeforeChange === 'function') {
				proceed = thisClass.onBeforeChange.call(this, e, data);
			}
			if (proceed) {
				thisClass.menu.children("li").removeClass("active");
				$(this).addClass("active");
				var val = value.replace(/<[^>]*>/g, "").replace(/\&nbsp;/g, " ");
				thisClass.input.val($.trim(val));
				thisClass.menu.parent().removeClass("open");
				if (!skipOnChange && typeof(thisClass.onChange) === "function") {
					thisClass.onChange.call(this, e);
				}
				thisClass.elem.trigger("change");
			}
			e.stopPropagation();
			return false;
		});
		if (selected || this.menu.children("li").length === 0) {
			opt.trigger("click", true);
		}
	}
	this.menu.append(opt);
	return opt;
};

/** @return {JQuery} */
ComboBox.prototype.addSeparator = function() {
	var divider = $('<li class="divider"></li>');
	this.menu.append(divider);
	return divider;
};

/**
 * Get options data
 * @returns {Object[]}
 */
ComboBox.prototype.getOptions = function() {
	return this.options;
};

/**
 * Get options data
 * @returns {Object[]}
 */
ComboBox.prototype.getOptionsData = function() {
	var key, list = [];
	for (key in this.options) {
		list.push({
			name: this.options[key],
			data: ((key in this.optionsData) ? this.optionsData[key].data : null)
		});
	}
	return list;
};

/**
 * Get option by key
 * @param {String} key option key (ID)
 * @return {jQuery} jQuery selector object
 */
ComboBox.prototype.getOption = function(key) {
	return this.menu.children("li[data-value='" + key.replace(/(['"])/g, '\\$1') + "']");
};

/**
 * Remove all options from combo box
 */
ComboBox.prototype.removeAllOptions = function() {
	this.menu.empty();
	this.input.val('');
	this.options = {};
	this.optionsData = {};
};

/**
 * Get selected option label
 * @return {String} selected label
 */
ComboBox.prototype.getSelectedLabel = function() {
	return this.input.val();
};

/**
 * Set option option label
 * @param {String} key option key (ID)
 * @param {String} value option value (label)
 */
ComboBox.prototype.setOptionLabel = function(key, value) {
	var li = this.menu.children("li[data-value='" + key.replace(/(['"])/g, '\\$1') + "']");
	li.children("a").html(value ? value : "---");
	if (li.hasClass("active")) {
		this.input.val(value ? value : "---");
	}
};

ComboBox.prototype.setWidth = function(width) {
	this.elem.css({width: width});
};

/**
 * Get currently selected option key
 * NOTE: alias of getValue()
 * @return {String} key of selected option
 */
ComboBox.prototype.getSelected = function() {
	return this.getValue();
};

/**
 * Set size
 * NOTE: alias of setValue()
 * @param {String} key of the option to select
 */
ComboBox.prototype.setSelected = function(key) {
	this.setValue(key);
};

	return ComboBox;
});;

/** WB RadioBox **/
(window.defineModule = (window.defineModule || {})).name = 'WB RadioBox';

/**
 * RadioBox control class
 * @param {Object} options
 * @param {boolean} selected
 * @param {string} name
 */
function WB_RadioBox(options, selected, name) { this.__construct(options, selected, name); }

WB_RadioBox.lastIndex = 0;
WB_RadioBox.prototype.name = null;
WB_RadioBox.prototype.elem = null;
WB_RadioBox.prototype.input = null;
WB_RadioBox.prototype.options = null;

/**
 * Construct RadioBox control
 * @param {Object} options radio box option list as object = {key: value, ...}
 * @param {boolean} selected key of the option to select by default
 * @param {string} name
 */
WB_RadioBox.prototype.__construct = function(options, selected, name) {
	var _options = options;
	var _selected = selected;
	var _name = name;
	if (typeof options !== "object") {
		_name = options;
		_options = selected;
		_selected = name;
	}
	this.name = _name ? _name : "radiobox_group" + (WB_RadioBox.lastIndex++);
	this.options = {};
	this.input = this.elem = $('<span></span>');
	if (_options) {
		for (var key in _options) {
			this.options[key] = _options[key];
			this.addOption(key, _options[key], (key === _selected));
		}
	}
};

/**
 * Get currently selected option key
 * @return key of selected option
 */
WB_RadioBox.prototype.getValue = function() {
	var val = this.input.find("input:checked").val();
	if (val === null) {
		for (var k in this.options) {
			val = this.options[k];
			break;
		}
	}
	return val;
};

/**
 * Set size
 * @param key of the option to select
 */
WB_RadioBox.prototype.setValue = function(key) {
	this.input.find("input[value='"+ key +"']").attr("checked", "checked");
};

/**
 * Add option to radio box
 * @param key option key (ID)
 * @param value option value (label)
 * @param selected if true option will be selected
 */
WB_RadioBox.prototype.addOption = function(key, value, selected) {
	this.options[key] = value;
	var opt = $('<div class="radio"><label><input type="radio" name="'+this.name+'" value="'+key+'">'
			+ ' ' + value + ' '
			+ '</label></div>');
	if (selected) opt.find("input").attr("checked", "checked");
	
	this.input.append(opt);
};

/**
 * Remove all options from radio box
 */
WB_RadioBox.prototype.removeAllOptions = function() {
	this.input.empty();
	this.options = {};
};

/**
 * Get selected option label
 * @return selected label
 */
WB_RadioBox.prototype.getSelectedLabel = function() {
	return this.input.find("input:checked").parent().text();
};

/**
 * Get currently selected option key
 * NOTE: alias of getValue()
 * @return key of selected option
 */
WB_RadioBox.prototype.getSelected = function() {
	return this.getValue();
};

/**
 * Set size
 * NOTE: alias of setValue()
 * @param key of the option to select
 */
WB_RadioBox.prototype.setSelected = function(key) {
	this.setValue(key);
};
;

/** WB FontControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB FontControl';

define('FontControl', ['ComboBox', 'EditFontsDialog', 'FontManager', 'BuilderEvent'], function(ComboBox, EditFontsDialog, FontManager, BuilderEvent) {
	'use strict';

/**
 * Font Control class
 * @param {Boolean} noFixedWidth
 */
var FontControl = function(noFixedWidth) { this.__construct(noFixedWidth); };

FontControl.prototype.elem = null;
FontControl.prototype.input = null;
FontControl.prototype._elem = null;

/**
 * Construct Font controll
 * @param {Boolean} noFixedWidth
 */
FontControl.prototype.__construct = function(noFixedWidth) {
	this._elem = new ComboBox();
	if (!noFixedWidth) this._elem.elem.css({width: 100});

	this.selectedValue = this.getDefaultFont(); // default
	this.updateOptions();
	this.setValue(this.selectedValue);

	this.input = this._elem.input;
	this.elem = this._elem.elem;
	this._elem.onChange = this.inputValueChanged.bind(this);

	var _this = this;
	BuilderEvent.GlobalEvents.on("fonts.changed", function() {
		_this.updateOptions();
	});
};

FontControl.editFontsDialog = null;
FontControl.editFontsErrorDialog = null;

FontControl.getPrimaryFontName = function(fontValue) {
	return fontValue ? fontValue.split(',')[0].replace(/["']/g, '').trim().toLowerCase() : null;
};

/**
 * Callback for event when a different font is being selected.
 * @type {function}|null
 */
FontControl.prototype.onChange = null;
FontControl.prototype.selectedValue = null;

FontControl.prototype.getDefaultFont = function() {
	return "Arial,Helvetica,sans-serif";
};

FontControl.prototype.updateOptions = function() {
	var list = [
		{value: "Arial,Helvetica,sans-serif", label: "Arial"},
		{value: "Batang,serif", label: "Batang", data: null},
		{value: "'Capture it'", label: "Capture it", data: null},
		{value: "Comic Sans MS,Helvetica,Arial,Verdana,cursive", label: "Comic Sans", data: null},
		{value: "Courier New,monospace", label: "Courier New", data: null},
		{value: "Dotum,sans-serif", label: "Dotum", data: null},
		//{value: "'Exo 2',sans-serif", label: "Exo 2", data: null},
		{value: "Georgia,serif", label: "Georgia", data: null},
		{value: "Gulim,sans-serif", label: "Gulim", data: null},
		{value: "Helvetica,Arial,sans-serif", label: "Helvetica", data: null},
		{value: "'Microsoft JhengHei',sans-serif", label: "JhengHei", data: null},
		{value: "'Malgun Gothic',sans-serif", label: "Malgun Gothic", data: null},
		{value: "MingLiU,sans-serif", label: "MingLiU", data: null},
		{value: "Myriad Set Pro,Lucida Grande,Helvetica Neue,Verdana,sans-serif", label: "Myriad Set Pro", data: null},
		{value: "'Nanum Gothic',sans-serif", label: "Nanum Gothic", data: null},
		{value: "Lucida Grande,Lucida Sans Unicode,Helvetica,Arial,Verdana,sans-serif", label: "Lucida Grande", data: null},
		//{value: "'Open Sans',sans-serif", label: "Open Sans", data: null},
		//{value: "'Open Sans Condensed',sans-serif", label: "Open Sans Condensed", data: null},
		{value: "PMingLiU,sans-serif", label: "PMingLiU", data: null},
		//{value: "'PT Sans',sans-serif", label: "PT Sans", data: null},
		//{value: "'PT Sans Caption',sans-serif", label: "PT Sans Caption", data: null},
		//{value: "'PT Sans Narrow',sans-serif", label: "PT Sans Narrow", data: null},
		//{value: "'Roboto',sans-serif", label: "Roboto", data: null},
		//{value: "'Roboto Condensed',sans-serif", label: "Roboto Condensed", data: null},
		//{value: "'Roboto Slab',sans-serif", label: "Roboto Slab", data: null},
		{value: "Tahoma,Geneva,sans-serif", label: "Tahoma", data: null},
		{value: "Times New Roman,Times,serif", label: "Times New Roman", data: null},
		{value: "Trebuchet MS,sans-serif", label: "Trebuchet", data: null},
		{value: "Sylfaen", label: "Sylfaen", data: null}
	];

	this._elem.removeAllOptions();

	for( var i in wb_builder.site.usedCustomFonts ) {
		var uf = wb_builder.site.usedCustomFonts[i];
		list.push({value: uf.font.getCssFontFamily(), label: uf.font.family, data: null});
	}

	list.sort(function(a, b) {
		if( a.label === b.label )
			return 0;
		return (a.label < b.label) ? -1 : 1;
	});

	var selected = false;
	var searchFont = FontControl.getPrimaryFontName(this.selectedValue);
	for( i = 0; i < list.length; i++ ) {
		var thisSelected = FontControl.getPrimaryFontName(list[i].value);
		selected = selected || thisSelected;
		var opt = this._elem.addOption(list[i].value, list[i].label, thisSelected, list[i].data);
		opt.css("font-family", list[i].value);
	}

	this._elem.addOption("edit-fonts", '<i class="glyphicon glyphicon-pencil"></i> ' + __('Edit fonts'), false, "edit-fonts-dialog");

	if( !selected )
		this.setValue(this.getDefaultFont());
};

FontControl.prototype.openEditFontsDialog = function() {
	if( FontControl.editFontsDialog === null && FontManager.FontManager.ready ) {
		FontControl.editFontsDialog = new EditFontsDialog.EditFontsDialog(__('Edit fonts'));
	} else if (FontControl.editFontsErrorDialog === null && FontManager.FontManager.error) {
		FontControl.editFontsErrorDialog = new EditFontsDialog.EditFontsErrorDialog(__('Edit fonts'));
	}
	if (FontManager.FontManager.ready) {
		FontControl.editFontsDialog.fontsControl = this;
		// FontControl.editFontsDialog.updateList(); // this is not really needed since dialog currently has only one instance
		FontControl.editFontsDialog.setVisible(true);
	} else if (FontManager.FontManager.error) {
		FontControl.editFontsErrorDialog.setVisible(true);
	}
};

FontControl.prototype.inputValueChanged = function() {
	var data = this._elem.getValueData();
	if( data === "edit-fonts-dialog" ) {
		this._elem.setValue(this.selectedValue);
		this.openEditFontsDialog();
	}
	else {
		this.selectedValue = this._elem.getValue();
		if( typeof this.onChange === "function" )
			this.onChange.call(this);
	}
};

/**
 * Get value
 * @return {string}
 */
FontControl.prototype.getValue = function() {
	return this._elem.getValue();
};

/**
 * Set value
 * @param {string} value value to set
 */
FontControl.prototype.setValue = function(value) {
	this.selectedValue = value;
	var selValue = value;
	var searchFont = FontControl.getPrimaryFontName(value);
	var options = this._elem.getOptions();
	for( var key in options ) {
		if( options.hasOwnProperty(key) ) {
			if( FontControl.getPrimaryFontName(key) === searchFont ) {
				selValue = key;
				break;
			}
		}
	}
	this._elem.setValue(selValue);
};
	
	return FontControl;
});
;

/** WB FontStyleControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB FontStyleControl';

/**
 * Font Style Control class
 * 
 * @author Marius Tomas <marius@profis.lt>
 * @version 1.0.0, 2012-12-15
 */
function WB_FontStyleControl() { this.__construct(); }

WB_FontStyleControl.prototype.elem = null;
WB_FontStyleControl.prototype.input = null;

/**
 * Construct Font Style controll
 */
WB_FontStyleControl.prototype.__construct = function() {	
	this.elem = $('<div class="btn-group">' +
			'<button class="btn btn-default" data-value="bold"><span class="glyphicon glyphicon-bold"></span></button>' +
			'<button class="btn btn-default" data-value="italic"><span class="glyphicon glyphicon-italic"></span></button>' +
			'<button class="btn btn-default" data-value="underline"><strong style="text-decoration: underline;">U</strong></button>' +
		'</div>');
	var lastTime = 0;
	this.elem.children('button').on('click touchend', function() {
		var nowTime = (new Date()).getTime();
		if (lastTime < (nowTime - 1000)) {
			lastTime = nowTime;
			$(this).toggleClass('active');
		}
	});
	this.input = this.elem;
};

/**
 * Get value
 * @return value
 */
WB_FontStyleControl.prototype.getValue = function() {
	var o = {};
	this.elem.children(".active").each(function() {
		o[$(this).attr("data-value")] = true;
	});
	o.css = {};
	o.css["font-weight"] = o.bold ? "bold" : "normal";
	o.css["font-style"] = o.italic ? "italic" : "normal";
	o.css["text-decoration"] = o.underline ? "underline" : "none";
	return o;
};

/**
 * Set value
 * @param value value to set
 */
WB_FontStyleControl.prototype.setValue = function(value) {
	var o = value ? value : {};
	this.elem.children().removeClass("active");
	this.elem.children().each(function() {
		if (o[$(this).attr("data-value")]) {
			$(this).addClass("active");
		}
	});
};
;

/** WB TextControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB TextControl';
define('TextControl', ['Service', 'ColorPicker'], function(Service, ColorPicker) {
	'use strict';

/**
 * TextControl component class
 * @param {boolean} needLineHeight
 * @param {string} ttplacement
 * @param {boolean} needPreview
 * @param {boolean} noStyle if true style selector will not be shown
 * @param {boolean} noAlign if true align selector will not ne shown
 * @param {boolean} horizontal if true controls will be layout in one line
 */
var TextControl = function(needLineHeight, ttplacement, needPreview, noStyle, noAlign, horizontal) { this.__construct(needLineHeight, ttplacement, needPreview, noStyle, noAlign, horizontal); };

TextControl.combine = function(_font, _size, _color, _style, _align, _letterSpacing) {
	var style = (_style ? _style.getValue() : {});
	var css = {
		font: ((style.italic ? "italic" : "normal") +
			" " + (style.bold ? "bold" : "normal") + " " + (_size ? _size.getValue() : 12) + "px" +
			(_font ? (" " + _font.getValue()) : "")),
		"text-align": (_align ? _align.getValue() : "left"),
		"text-decoration": (style.underline ? "underline" : "none"),
		color: (_color ? _color.getValue() : "#000000")
	};
	
	var val = _size ? (_size.getValue() + 2) : 14;
	if (val === 0) val = "normal"; else val = val + "px";
	css["line-height"] = val;

	var lsVal = _letterSpacing ? _letterSpacing.getValue() : 0;
	if (lsVal)
		css["letter-spacing"] = lsVal + "px";

	return {
		color: (_color ? _color.getValue() : "#000000"),
		size: (_size ? _size.getValue() : 12),
		decoration: (style.underline ? "underline" : "none"),
		font: (_font ? _font.getValue() : null),
		style: (_style ? _style.getValue() : null),
		align: (_align ? _align.getValue() : "left"),
		lineHeight: (_size ? (_size.getValue() + 2) : 14),
		letterSpacing: lsVal,
		css: css
	};
};
/**
 * Build CSS for style definition object
 * @param {Object} styleDef
 * @param {FontControl=} fontFamily
 * @param {SizeSelector=} fontSize
 * @param {ColorPicker=} fontColor
 * @param {FontStyleControl=} fontStyle
 * @param {AlignSelector=} textAlign
 * @param {SizeSelector=} lineHeight
 * @param {SizeSelector=} letterSpacing
 * @returns {Object}
 */
TextControl.buildCss = function(styleDef, fontFamily, fontSize, fontColor, fontStyle, textAlign, lineHeight, letterSpacing) {
	var style = (styleDef ? styleDef : {}),
		res = {
			color: (style.color ? style.color : null),
			size: (style.size ? style.size : 0),
			font: (style.font ? style.font : null),
			style: ((typeof style.style === 'object' || style.style !== null) ? style.style : {}),
			align: (style.align ? style.align : null),
			lineHeight: (style.lineHeight ? style.lineHeight : null),
			letterSpacing: (style.letterSpacing ? style.letterSpacing : 0),
			css: {}
		};
	if (fontFamily) res.font = fontFamily.getValue();
	if (fontSize) res.size = fontSize.getValue();
	if (fontColor) res.color = fontColor.getValue();
	if (fontStyle) res.style = fontStyle.getValue();
	if (textAlign) res.align = textAlign.getValue();
	if (lineHeight) res.lineHeight = lineHeight.getValue();
	if (letterSpacing) res.letterSpacing = letterSpacing.getValue();
	res.css['font-size'] = res.size + 'px';
	var fontStyle = (res.style ? ((res.style.italic ? 'italic' : 'normal') +
			' ' + (res.style.bold ? 'bold' : 'normal') + ' ') : '');
	if (fontStyle) res.css['font-style'] = fontStyle;
	res.css.font = (
			(res.style ? ((res.style.italic ? 'italic' : 'normal') +
			' ' + (res.style.bold ? 'bold' : 'normal') + ' ') : '') +
			res.size + 'px' + (res.font ? (' ' + res.font) : '')
		);
	if (res.color) res.css.color = res.color;
	if (res.style) res.css['text-decoration'] = (res.style.underline ? 'underline' : 'none');
	if (res.align) res.css['text-align'] = res.align;
	if (res.lineHeight) {
		res.css['line-height'] = ((res.lineHeight === 0) ? 'normal' : (res.lineHeight + 'px'));
	}
	if (res.letterSpacing) res.css['letter-spacing'] = res.letterSpacing + 'px';
	return $.extend(true, {}, res);
};
TextControl.prototype._uiElem = null;
TextControl.prototype.elem = null;
TextControl.prototype.color = null;
TextControl.prototype.size = null;
TextControl.prototype.decoration = null;
TextControl.prototype.font = null;
TextControl.prototype.style = null;
TextControl.prototype.align = null;
TextControl.prototype.lineHeight = null;
TextControl.prototype.letterSpacing = null;
TextControl.prototype.previewText = null;

/**
 * Construct TextControl component
 * @param {boolean} needLineHeight if true line height controll will be visible
 * @param {string} ttplacement tooltip placement
 * @param {boolean} needPreview if true preview box will be shown
 * @param {boolean} noStyle if true style selector will not be shown
 * @param {boolean} noAlign if true align selector will not ne shown
 * @param {boolean} horizontal if true controls will be layout in one line
 */
TextControl.prototype.__construct = function(needLineHeight, ttplacement, needPreview, noStyle, noAlign, horizontal) {
	var thisClass = this;
	var changeFunc = (needPreview ? function() { thisClass.updatePreview(); } : null);
	this._uiElem = new Service.UIBuilder((horizontal ? (
		{type: 'FlowLayout', children: [
			{type: 'VerticalLayout', children: [
				{type: 'Label', text: __('Font')},
				{type: 'FlowLayout', spacing: -1, children: [
					{type: 'FontFamilySelector', id: 'font', css: {width: 200}, change: changeFunc},
					{type: 'Button', icon: "glyphicon glyphicon-pencil", click: function(e, fields) {
						fields.font.getWrappedControl().openEditFontsDialog();
					}}
				]}
			]},
			{type: 'VerticalLayout', children: [
				{type: 'Label', text: __('Size')},
				{type: 'SizeSelector', id: 'size', min: 8, change: changeFunc}
			]},
			{type: 'VerticalLayout', ignore: !needLineHeight, children: [
				{type: 'Label', text: __('Line height'),
					/*helpText: __('Line height 0 means line height "normal" (will be calculated by font size).'),*/
					helpPlacement: ttplacement
				},
				{type: 'SizeSelector', id: 'lineHeight', min: 8, change: changeFunc}
			]},
			{type: 'VerticalLayout', children: [
				{type: 'Label', text: __('Letter spacing')},
				{type: 'SizeSelector', id: 'letterSpacing', min: -100, precision: 2, step: 0.01, change: changeFunc}
			]},
			{type: 'VerticalLayout', ignore: noStyle, children: [
				{type: 'Label', text: __('Style')},
				{type: 'FontStyleSelector', id: 'style', change: changeFunc}
			]},
			{type: 'VerticalLayout', ignore: noAlign, children: [
				{type: 'Label', text: __('Align')},
				{type: 'HAlignSelector', id: 'align', change: changeFunc}
			]},
			{type: 'VerticalLayout', children: [
				{type: 'Label', text: __('Color')},
				{type: 'ColorSelector', id: 'color', noTransparent: true, change: changeFunc}
			]}
		]}
		) : (
		{type: 'VerticalLayout', spacing: 15, children: [
			{type: 'HorizontalLayout', columnWeights: [8], columnWeightsSmall: [8], children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Font')},
					{type: 'FlowLayout', spacing: -1, children: [
						{type: 'FontFamilySelector', id: 'font', css: {width: 230}, change: changeFunc},
						{type: 'Button', icon: "glyphicon glyphicon-pencil", click: function(e, fields) {
							fields.font.getWrappedControl().openEditFontsDialog();
						}}
					]}
				]}
			]},
			{type: 'HorizontalLayout', columnWeights: [4, 4, 4], columnWeightsSmall: [4, 4, 4], children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Size')},
					{type: 'SizeSelector', id: 'size', min: 8, change: changeFunc}
				]},
				{type: 'VerticalLayout', ignore: !needLineHeight, children: [
					{type: 'Label', text: __('Line height'),
						/*helpText: __('Line height 0 means line height "normal" (will be calculated by font size).'),*/
						helpPlacement: ttplacement
					},
					{type: 'SizeSelector', id: 'lineHeight', min: 8, change: changeFunc}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Letter spacing')},
					{type: 'SizeSelector', id: 'letterSpacing', min: -100, precision: 2, step: 0.01, change: changeFunc}
				]}
			]},
			{type: 'HorizontalLayout', columnWeights: [4, 4, 4], columnWeightsSmall: [4, 4, 4], children: [
				{type: 'VerticalLayout', ignore: noAlign, children: [
					{type: 'Label', text: __('Align')},
					{type: 'HAlignSelector', id: 'align', change: changeFunc}
				]},
				{type: 'VerticalLayout', ignore: noStyle, children: [
					{type: 'Label', text: __('Style')},
					{type: 'FontStyleSelector', id: 'style', change: changeFunc}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Color')},
					{type: 'ColorSelector', id: 'color', noTransparent: true, change: changeFunc}
				]}
			]},
			{type: 'VerticalLayout', id: 'previewBlock', visible: needPreview, children: [
				{type: 'Label', text: __('Preview')},
				{type: 'CustomContainer', id: 'previewText',
					css: {
						height: 103,
						overflow: 'hidden',
						padding: '10px',
						border: '1px solid lightgray'
					},
					init: function() {
						this.html = function(html) {
							this.getElem().html(html);
						};
					}
				}
			]}
		]}
	)));
	this.elem = this._uiElem.getElem();
	
	this.font = this._uiElem.fields.font;
	this.size = this._uiElem.fields.size;
	this.lineHeight = this._uiElem.fields.lineHeight;
	this.letterSpacing = this._uiElem.fields.letterSpacing;
	this.align = this._uiElem.fields.align;
	this.style = this._uiElem.fields.style;
	this.color = this._uiElem.fields.color;
	this.previewText = this._uiElem.fields.previewText;
};

/**
 * Get value object
 * @return object = {
 *    color: ...,
 *    size: ...,
 *    decoration: ...,
 *    font: ...,
 *    style: ...,
 *    align: ...,
 *    lineHeight: ...,
 *    letterSpacing: ...,
 *    css: ...
 * }
 */
TextControl.prototype.getValue = function() {
	return TextControl.buildCss(null, this.font, this.size, this.color, this.style, this.align, this.lineHeight, this.letterSpacing);
};

/**
 * Set value object
 * @param obj object = {
 *    color: ...,
 *    size: ...,
 *    decoration: ...,
 *    font: ...,
 *    style: ...,
 *    align: ...,
 *    lineHeight: ...,
 *    letterSpacing: ...
 * }
 */
TextControl.prototype.setValue = function(obj) {
	var _obj = obj ? $.extend(true, {
		letterSpacing: 0
	}, obj) : null;
	if (!_obj) _obj = {
			color: "#000000", size: 12, decoration: "none", font: "Arial,sans-serif",
			style: {}, align: "left", lineHeight: null, letterSpacing: 0
	};
	this.color.setValue(_obj.color);
	this.size.setValue(_obj.size ? _obj.size : 12);
	//this.decoration.setValue(_obj.decoration);
	this.font.setValue(_obj.font);
	if (this.style) this.style.setValue(_obj.style);
	if (this.align) this.align.setValue(_obj.align);
	if (this.lineHeight) {
		this.lineHeight.setValue(_obj.lineHeight);
	}
	if (this.letterSpacing) this.letterSpacing.setValue(_obj.letterSpacing);
	if (this.previewText) this.updatePreview();
};

TextControl.prototype.previewTag = null;
TextControl.prototype.setPreviewTag = function(tag) {
	this.previewTag = tag ? tag : 'div';
	this.updatePreview();
};

TextControl.prototype.updatePreview = function() {
	var vals = this.getValue();
	var txt = document.createElement(this.previewTag ? this.previewTag : 'div');
	$(txt).append(__('Preview text') + '<br>' + __('Preview text')).css("margin", 0).css(vals.css);
	if (this.previewText) {
		this.previewText.html(txt);
		this.previewText.css({
			backgroundColor: ColorPicker.readableColor(vals.color)
		});
	}
};

	return TextControl;
});
;

/** WB BackgroundControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB BackgroundControl';

define('BackgroundControl', ['Service'], function(Service) {
	'use strict';

/**
 * BackgroundControl component class
 * @param {object} options { useColor: boolean, useImage: boolean, usePosition: boolean, useRepeat: boolean, useAttachment: boolean, useSize: boolean }
 */
var BackgroundControl = function(options) { this.__construct(options); };

BackgroundControl.index = 0;
/**
 * Checks if background is set
 * @param {Object} data
 * @returns {Boolean}
 */
BackgroundControl.isSet = function(data) {
	if (data === null || typeof data !== "object") return false;
	var img = data.image;
	if (!img || img === "null" || img === "none") img = null;
	var color = data.color;
	if (!color || color === "transparent") color = null;
	return (img || color);
};
BackgroundControl.prototype.elemUi = null;
BackgroundControl.prototype.elem = null;
BackgroundControl.prototype.onChange = null;
/**
 * @type {Boolean}
 */
BackgroundControl.prototype.options = null;

BackgroundControl.defaultOptions = {
	useColor: true,
	useImage: true,
	usePosition: true,
	useRepeat: true,
	useAttachment: false,
	useSize: false,
	useFullWidth: false
};

/**
 * Construct BackgroundControl component
 * @param {object} options
 */
BackgroundControl.prototype.__construct = function(options) {
	this.options = $.extend(true, {}, BackgroundControl.defaultOptions, options);
	var bgCtlIndex = BackgroundControl.index++;

	var thisClass = this, cfunc = function(fields) {
		if ("sizeContCustom" in fields && "size_custom" in fields)
			fields.sizeContCustom.setVisible(fields.size_custom.getValue());
		if ("size_horizontal_auto" in fields) {
			var vis = !fields.size_horizontal_auto.getValue();
			fields.size_horizontal.setVisible(vis);
			fields.size_horizontal_type.setVisible(vis);
			vis = !fields.size_vertical_auto.getValue();
			fields.size_vertical.setVisible(vis);
			fields.size_vertical_type.setVisible(vis);
		}
		if (thisClass.onChange && typeof thisClass.onChange === 'function') {
			thisClass.onChange.call(thisClass, fields);
		}
	};
	this.elemUi = new Service.UIBuilder({
		type: 'VerticalLayout', children: [
			{type: 'FlowLayout', spacing: 0, children: [
				{type: 'VerticalLayout', id: "cont_useColor", visible: this.options.useColor, css: {"margin": "0 25px 5px 0"}, children: [
					{type: 'Label', text: __('Color')},
					{type: 'ColorSelector', id: 'color', noTrasparent: false,
						big: true,
						change: cfunc
					}
				]},
				{type: 'VerticalLayout', id: "cont_useImage", visible: this.options.useImage, css: {"margin": "0 25px 5px 0"}, children: [
					{type: 'Label', text: __('Image')},
					{type: 'ImageSelector', id: 'image', select: cfunc}
				]},
				{type: 'VerticalLayout', id: "cont_usePosition", visible: this.options.usePosition, css: {"margin": "0 25px 5px 0"}, children: [
					{type: 'Label', text: __('Position')},
					{type: 'AlignSelector', id: 'position', change: cfunc}
				]},
				{type: 'VerticalLayout', id: 'cont_useRepeat', visible: this.options.useRepeat, css: {"margin": "0 25px 5px 0"},
					children: [
						{type: 'Label', text: __('Repeat')},
						{type: 'CheckBox', id: 'horiz', label: __('Horizontally'),
							css: {marginTop: 0},
							change: cfunc
						},
						{type: 'CheckBox', id: 'vert', label: __('Vertically'),
							change: cfunc
						},
						{type: 'CheckBox', id: 'attachment', label: __("Don't scroll background"),
							change: cfunc,
							visible: this.options.useAttachment
						},
						{type: 'CheckBox', id: 'fullWidth', label: __("Full screen width"),
							change: cfunc,
							visible: this.options.useFullWidth
						}
					],
					init: function(def, fields) {
						this.getValue = function() {
							var repeat = "no-repeat";
							if (fields.horiz.getValue() && fields.vert.getValue()) {
								repeat = "repeat";
							} else if (fields.horiz.getValue()) {
								repeat = "repeat-x";
							} else if (fields.vert.getValue()) {
								repeat = "repeat-y";
							}
							return repeat;
						};
						this.setValue = function(val) {
							fields.horiz.setValue((val === "repeat-x" || val === "repeat"));
							fields.vert.setValue((val === "repeat-y" || val === "repeat"));
						};
					}
				}
			]},
			{type: 'VerticalLayout', id: 'sizeCont', visible: this.options.useSize, children: [
				{type: 'VerticalLayout', css: {"margin-bottom": "5px"}, children: [
					{type: 'Label', text: __('Size')/*, helpText: __("This tells if background image will scroll with content or stay fixed. This is useful only for main site/page background. If you don't know what to chose set it to scroll.")*/},
					{type: 'FlowLayout', spacing: 20, children: [
						{type: 'RadioBox', id: 'size_custom', group: 'bgSize[' + bgCtlIndex + ']', html: __("Auto") + '<br /><img src="modules/builder/img/ico_bg_size_custom2.png" width="58" height="58" />', change: cfunc},
						{type: 'RadioBox', id: 'size_contain', group: 'bgSize[' + bgCtlIndex + ']', html: __("Contain") + '<br /><img src="modules/builder/img/ico_bg_size_contain2.png" width="58" height="58" />', change: cfunc},
						{type: 'RadioBox', id: 'size_cover', group: 'bgSize[' + bgCtlIndex + ']', html: __("Cover") + '<br /><img src="modules/builder/img/ico_bg_size_cover2.png" width="80" height="58" />', change: cfunc}
					]}
				]},
				{type: 'FlowLayout', id: "sizeContCustom", spacing: 25, children: [
					{type: 'VerticalLayout', css: {"margin-bottom": "5px"}, children: [
						{type: 'Label', text: __('Width'), css: {"max-width": "142px"}},
						{type: 'CheckBox', id: 'size_horizontal_auto', label: __("Auto"), change: cfunc},
						{type: 'FlowLayout', spacing: -1, children: [
							{type: 'SizeSelector', id: 'size_horizontal', min: 0, noFixedWidth: true, css: {width: "74px"}, change: cfunc},
							{type: 'DropdownBox', id: 'size_horizontal_type', css: {width: "70px"}, change: cfunc, options: [
								{id: "%", name: "%"},
								{id: "px", name: "px"}
							]}
						]}
					]},
					{type: 'VerticalLayout', css: {"margin-bottom": "5px"}, children: [
						{type: 'Label', text: __('Height'), css: {"max-width": "142px"}},
						{type: 'CheckBox', id: 'size_vertical_auto', label: __("Auto"), change: cfunc},
						{type: 'FlowLayout', spacing: -1, children: [
							{type: 'SizeSelector', id: 'size_vertical', min: 0, noFixedWidth: true, css: {width: "74px"}, change: cfunc},
							{type: 'DropdownBox', id: 'size_vertical_type', css: {width: "70px"}, change: cfunc, options: [
								{id: "%", name: "%"},
								{id: "px", name: "px"}
							]}
						]}
					]}
				]}
			]}
		]
	});
	this.elem = this.elemUi.getElem();
};

/**
 * Get value object
 * @return {Object} object = {color: ..., image: ..., position: ..., repeat: ..., css: ...}
 */
BackgroundControl.prototype.getValue = function() {
	var fields = this.elemUi.fields;
	var img = fields.image.getValue();
	if (!img || img === "null") img = "none";

	var size = "auto auto";
	if( fields.size_contain.getValue() )
		size = "contain";
	else if( fields.size_cover.getValue() )
		size = "cover";
	else if( fields.size_custom.getValue() ) {
		var sizeVal = [
			this.getSizePropertyValue(fields.size_horizontal_auto, fields.size_horizontal, fields.size_horizontal_type),
			this.getSizePropertyValue(fields.size_vertical_auto, fields.size_vertical, fields.size_vertical_type)
		];
		size = sizeVal.join(" ");
	}

	var val = {
		color: fields.color.getValue(),
		image: fields.image.getValue(),
		attachment: fields.attachment.getValue() ? "fixed" : "scroll",
		position: fields.position.getValue(),
		repeat: fields.cont_useRepeat.getValue(),
		size: size,
		fullWidth: fields.fullWidth.getValue()
	};

	var css = val.css = {
		background: (
			(this.options.useColor ? (val.color + " ") : "") +
			(this.options.useImage ? ((img === "none") ? img : ("url('" + WB_Builder.urlEncode(wb_builder.makeRelUrl(img), true) + "')")) + " " : "") +
			(this.options.useRepeat ? (val.repeat + " ") : "") +
			(this.options.useAttachment ? (val.attachment + " ") : "") +
			(this.options.usePosition ? (val.position + " ") : "")
		).trim()
	};

	if( this.options.useSize )
		css["background-size"] = val.size;
	return val;
};

/**
 * Set value object
 * @param {Object} obj value object = {color: ..., image: ..., position: ..., repeat: ...}
 */
BackgroundControl.prototype.setValue = function(obj) {
	var fields = this.elemUi.fields;
	if (!obj) obj = {
		color: "transparent",
		image: "none",
		position: "left top",
		attachment: "scroll",
		repeat: "repeat",
		size: "auto auto",
		fullWidth: false
	};
	if (!("color" in obj)) obj.color = "transparent";
	if (!("image" in obj)) obj.image = "none";
	if (!("position" in obj)) obj.position = "left top";
	if (!("attachment" in obj)) obj.attachment = "scroll";
	if (!("repeat" in obj)) obj.repeat = "repeat";
	if (!("size" in obj)) obj.size = "auto auto";
	if (!("fullWidth" in obj)) obj.fullWidth = false;

	fields.color.setValue(obj.color);
	fields.image.setValue(obj.image);
	fields.attachment.setValue((obj.attachment === "fixed"));
	fields.position.setValue(obj.position);
	fields.cont_useRepeat.setValue(obj.repeat);
	fields.fullWidth.setValue(obj.fullWidth);

	var sizeVal = ["auto", "auto"];
	switch(obj.size) {
		case "contain":
			fields.sizeContCustom.setVisible(false);
			fields.size_contain.setValue(true);
			break;
		case "cover":
			fields.sizeContCustom.setVisible(false);
			fields.size_cover.setValue(true);
			break;
		default:
			fields.sizeContCustom.setVisible(true);
			sizeVal = obj.size.split(" ");
			if( sizeVal.length < 2 )
				sizeVal[1] = sizeVal[0];
			fields.size_custom.setValue(true);
	}
	this.setSizePropertyValue(fields.size_horizontal_auto, fields.size_horizontal, fields.size_horizontal_type, sizeVal[0]);
	this.setSizePropertyValue(fields.size_vertical_auto, fields.size_vertical, fields.size_vertical_type, sizeVal[1]);
};

BackgroundControl.prototype.setSizePropertyValue = function(autoField, sizeField, typeField, value) {
	if( value === "auto" ) {
		autoField.setValue(true);
		sizeField.setVisible(false);
		typeField.setVisible(false);
		sizeField.setValue("100");
		typeField.setValue("%");
	}
	else {
		autoField.setValue(false);
		sizeField.setVisible(true);
		typeField.setVisible(true);
		var matches = value.match(/^(-?[0-9]+)(%|[a-z]+)$/);
		if( matches && matches.length ) {
			sizeField.setValue(matches[1]);
			typeField.setValue(matches[2]);
		}
		else {
			sizeField.setValue(value);
			typeField.setValue("%");
		}
	}
};

BackgroundControl.prototype.getSizePropertyValue = function(autoField, sizeField, typeField) {
	if( autoField.getValue() )
		return "auto";
	return sizeField.getValue() + typeField.getValue();
};

/**
 * Checks if background is set
 * @returns {Boolean}
 */
BackgroundControl.prototype.isSet = function() {
	return BackgroundControl.isSet(this.getValue());
};

BackgroundControl.prototype.setOption = function(name, value) {
	if( name in this.options ) {
		var fieldName;
		switch (name) {
			case 'useAttachment':
				fieldName = 'attachment'; break;
			case 'useFullWidth':
				fieldName = 'fullWidth'; break;
			default:
				fieldName = 'cont_' + name; break;
		}
		if( fieldName in this.elemUi.fields ) {
			this.options[name] = !!value;
			this.elemUi.fields[fieldName].setVisible(!!value);
		}
		else {
			this.options[name] = false;
		}
	}
};

	return BackgroundControl;
});
;

/** WB BorderControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB BorderControl';

define('BorderControl', ['Service', 'UIButton'], function(Service, UIButton) {
	'use strict';

/**
 * BorderControl component class
 * @param {string} placement
 * @param {boolean} showRadius
 * @param {boolean} noTransparent
 */
var BorderControl = function(placement, showRadius, noTransparent) { this.__construct(placement, showRadius, noTransparent); };

/**
 * Build CSS for style definition object
 * @param {Object} styleDef
 * @param {CheckBoxControl=} differentBorders
 * @param {ColorPicker=} borderColor
 * @param {DropdownBox=} borderStyle
 * @param {SizeSelector=} borderWeight
 * @param {SizeSelector=} borderRadius
 * @returns {Object}
 */
BorderControl.buildCss = function(styleDef, differentBorders, borderColor, borderStyle, borderWeight, borderRadius) {
	var style = (styleDef ? styleDef : {}),
		res = {
			differ: (style.differ ? style.differ : false),
			color: (style.color ? BorderControl.normalizeStylePropertyValue(style.color, null) : null),
			style: (style.style ? BorderControl.normalizeStylePropertyValue(style.style, 'none;') : 'none'),
			weight: (style.weight ? BorderControl.normalizeStylePropertyValue(style.weight, 0) : 0),
			radius: ((typeof style.radius === 'undefined' || style.radius === null) ? null : (style.radius ? BorderControl.normalizeStylePropertyValue(style.radius, 0) : 0)),
			css: {}
		};

	if (differentBorders) res.differ = differentBorders.getValue();
	if (borderColor) res.color = [borderColor[0].getValue(), borderColor[1].getValue(), borderColor[2].getValue(), borderColor[3].getValue()];
	if (borderStyle) res.style = [borderStyle[0].getValue(), borderStyle[1].getValue(), borderStyle[2].getValue(), borderStyle[3].getValue()];
	if (borderWeight) res.weight = [borderWeight[0].getValue(), borderWeight[1].getValue(), borderWeight[2].getValue(), borderWeight[3].getValue()];
	if (borderRadius) res.radius = [borderRadius[0].getValue(), borderRadius[1].getValue(), borderRadius[2].getValue(), borderRadius[3].getValue()];

	if( res.differ ) {
		res.css["border-top"] = (res.weight[0] + 'px ' + (res.style[0] ? res.style[0] : 'none') + (res.color[0] ? (' ' + res.color[0]) : ''));
		res.css["border-right"] = (res.weight[1] + 'px ' + (res.style[0] ? res.style[1] : 'none') + (res.color[1] ? (' ' + res.color[1]) : ''));
		res.css["border-bottom"] = (res.weight[2] + 'px ' + (res.style[0] ? res.style[2] : 'none') + (res.color[2] ? (' ' + res.color[2]) : ''));
		res.css["border-left"] = (res.weight[3] + 'px ' + (res.style[0] ? res.style[3] : 'none') + (res.color[3] ? (' ' + res.color[3]) : ''));
		if (typeof res.radius !== 'undefined' && res.radius !== null) {
			res.css['border-radius'] =
			res.css['-webkit-border-radius'] =
			res.css['-moz-border-radius'] = res.radius[0] + 'px ' + res.radius[1] + 'px ' + res.radius[2] + 'px ' + res.radius[3] + 'px';
		}
	}
	else {
		res.css.border = (res.weight[0] + 'px ' + (res.style[0] ? res.style[0] : 'none') + (res.color[0] ? (' ' + res.color[0]) : ''));
		if (typeof res.radius !== 'undefined' && res.radius !== null) {
			res.css['border-radius'] =
			res.css['-webkit-border-radius'] =
			res.css['-moz-border-radius'] = res.radius[0] + 'px';
		}
	}

	return $.extend(true, {}, res);
};

/**
 * Closes all opened border controls
 * @param {JQuery} exclude '.wb-border-controll' element
 */
BorderControl.closeAll = function(exclude) {
	$('.wb-border-controll').each(function() {
		if (exclude && this === exclude.get(0)) return true;
		var t = $(this).children('span.pop');
		if (t.data('__WB_HAS_POPOVER__')) {
			t.popover("destroy");
			t.data("__WB_HAS_POPOVER__", false);
		}
	});
};
BorderControl.onDocumentClick = function(e) {
	var t = $(e.target);
	if (t.is('.colorpicker-border-controll, .colorpicker-border-controll *')) return;
	var activeBorderControl;
	if (t.is('.wb-border-controll *')) {
		activeBorderControl = t.parents('.wb-border-controll');
	}
	BorderControl.closeAll(activeBorderControl);
};

BorderControl.prototype.elem = null;
BorderControl.prototype.btn = null;
BorderControl.prototype.preview = null;
BorderControl.prototype.panel = null;
BorderControl.prototype.differentBorders = null;
BorderControl.prototype.color = null;
BorderControl.prototype.style = null;
BorderControl.prototype.weight = null;
BorderControl.prototype.radius = null;
BorderControl.prototype.placement = "bottom";
BorderControl.prototype.showRadius = false;
BorderControl.prototype.noTransparent = true;
BorderControl.prototype.onChange = null;

/**
 * Construct BorderControl component
 * @param {string} placement
 * @param {boolean} showRadius
 * @param {boolean} noTransparent
 */
BorderControl.prototype.__construct = function(placement, showRadius, noTransparent) {
	var thisClass = this;
	this.placement = placement ? placement : this.placement;
	this.showRadius = showRadius ? showRadius : this.showRadius;
	this.noTransparent = (noTransparent !== null) ? noTransparent : this.noTransparent;
	this.elem = $('<div class="wb-border-controll"><div class="input-group">' +
			'<input type="text" class="form-control" readonly="readonly" />' +
			'<div class="input-group-btn">' +
				'<button class="btn btn-default" type="button"><span class="caret"></span></button>' +
			'</div>' +
		'</div><span class="pop"> </span><div class="prev-wrp"><span class="prev"> </span></div></div>');
	this.btn = this.elem.find("button");
	this.preview = this.elem.find("span.prev");
	this.panel = new Service.UIBuilder({type: 'VerticalLayout', children: [
		{type: 'Label', id:"topSideLabel", text: __('Top side'), visible: false},
		{type: 'FlowLayout', children: [
			{type: 'VerticalLayout', children: [
				{type: 'Label', text: __('Weight')},
				{type: 'SizeSelector', id: 'weight', min: 0, units: 'px'}
			]},
			{type: 'VerticalLayout', children: [
				{type: 'Label', text: __('Style')},
				{type: 'DropdownBox', id: 'style', css: {width: 96},
					options: [
						{id: 'none', name: __('None')},
						{id: 'solid', name: __('Solid'), html: __('Solid') + '<span class="wb-style-span-solid"></span>'},
						{id: 'dashed', name: __('Dashed'), html: __('Dashed') + '<span class="wb-style-span-dashed"></span>'},
						{id: 'dotted', name: __('Dotted'), html: __('Dotted') + '<span class="wb-style-span-dotted"></span>'},
						{id: 'double', name: __('Double'), html: __('Double') + '<span class="wb-style-span-double"></span>'}
					],
					init: function() { this.addMenuStyleClass('rel'); }
				}
			]},
			{type: 'VerticalLayout', children: [
				{type: 'Label', text: __('Color')},
				{type: 'ColorSelector', id: 'color', colorSelectorClass: 'colorpicker-border-controll', noTransparent: this.noTransparent}
			]},
			{type: 'VerticalLayout', ignore: (!this.showRadius), children: [
				{type: 'Label', id: 'radiusLabel1', text: __('Radius')},
				{type: 'Label', id: 'radiusLabel2', text: __('Radius') + " ↖", visible: false},
				{type: 'SizeSelector', id: 'radius', min: 0, units: 'px'}
			]}
		]},
		{type: "VerticalLayout", id: "otherBordersCont", visible: false, children: [
			{type: 'Label', text: __('Right side'), css: {marginTop: 15}},
			{type: 'FlowLayout', children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Weight')},
					{type: 'SizeSelector', id: 'weightRight', min: 0, units: 'px'}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Style')},
					{type: 'DropdownBox', id: 'styleRight', css: {width: 96},
						options: [
							{id: 'none', name: __('None')},
							{id: 'solid', name: __('Solid'), html: __('Solid') + '<span class="wb-style-span-solid"></span>'},
							{id: 'dashed', name: __('Dashed'), html: __('Dashed') + '<span class="wb-style-span-dashed"></span>'},
							{id: 'dotted', name: __('Dotted'), html: __('Dotted') + '<span class="wb-style-span-dotted"></span>'},
							{id: 'double', name: __('Double'), html: __('Double') + '<span class="wb-style-span-double"></span>'}
						],
						init: function() { this._menu.addClass('rel'); }
					}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Color')},
					{type: 'ColorSelector', id: 'colorRight', colorSelectorClass: 'colorpicker-border-controll', noTransparent: this.noTransparent}
				]},
				{type: 'VerticalLayout', ignore: (!this.showRadius), children: [
					{type: 'Label', text: __('Radius') + " ↗"},
					{type: 'SizeSelector', id: 'radiusRightTop', min: 0, units: 'px'}
				]}
			]},
			{type: 'Label', text: __('Bottom side'), css: {marginTop: 15}},
			{type: 'FlowLayout', children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Weight')},
					{type: 'SizeSelector', id: 'weightBottom', min: 0, units: 'px'}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Style')},
					{type: 'DropdownBox', id: 'styleBottom', css: {width: 96},
						options: [
							{id: 'none', name: __('None')},
							{id: 'solid', name: __('Solid'), html: __('Solid') + '<span class="wb-style-span-solid"></span>'},
							{id: 'dashed', name: __('Dashed'), html: __('Dashed') + '<span class="wb-style-span-dashed"></span>'},
							{id: 'dotted', name: __('Dotted'), html: __('Dotted') + '<span class="wb-style-span-dotted"></span>'},
							{id: 'double', name: __('Double'), html: __('Double') + '<span class="wb-style-span-double"></span>'}
						],
						init: function() { this._menu.addClass('rel'); }
					}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Color')},
					{type: 'ColorSelector', id: 'colorBottom', colorSelectorClass: 'colorpicker-border-controll', noTransparent: this.noTransparent}
				]},
				{type: 'VerticalLayout', ignore: (!this.showRadius), children: [
					{type: 'Label', text: __('Radius') + " ↘"},
					{type: 'SizeSelector', id: 'radiusRightBottom', min: 0, units: 'px'}
				]}
			]},
			{type: 'Label', text: __('Left side'), css: {marginTop: 15}},
			{type: 'FlowLayout', children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Weight')},
					{type: 'SizeSelector', id: 'weightLeft', min: 0, units: 'px'}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Style')},
					{type: 'DropdownBox', id: 'styleLeft', css: {width: 96},
						options: [
							{id: 'none', name: __('None')},
							{id: 'solid', name: __('Solid'), html: __('Solid') + '<span class="wb-style-span-solid"></span>'},
							{id: 'dashed', name: __('Dashed'), html: __('Dashed') + '<span class="wb-style-span-dashed"></span>'},
							{id: 'dotted', name: __('Dotted'), html: __('Dotted') + '<span class="wb-style-span-dotted"></span>'},
							{id: 'double', name: __('Double'), html: __('Double') + '<span class="wb-style-span-double"></span>'}
						],
						init: function() { this._menu.addClass('rel'); }
					}
				]},
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Color')},
					{type: 'ColorSelector', id: 'colorLeft', colorSelectorClass: 'colorpicker-border-controll', noTransparent: this.noTransparent}
				]},
				{type: 'VerticalLayout', ignore: (!this.showRadius), children: [
					{type: 'Label', text: __('Radius') + " ↙"},
					{type: 'SizeSelector', id: 'radiusLeftBottom', min: 0, units: 'px'}
				]}
			]}
		]},
		{type: "CheckBox", id: "differentBorders", label: __('Use different borders'), css: {marginTop: 15}, change: thisClass.updateFieldVisibility.bind(thisClass) },
		{type: 'FlowLayout', spacing: 4, css: {marginTop: 4, textAlign: 'right'}, children: [
			{type: 'Button', text: __('Cancel'), styleClass: 'btn-sm',
				buttonStyle: UIButton.UIButton.STYLE_DEFAULT,
				click: function() {
					var t = thisClass.elem.children('span.pop');
					t.popover('hide');
					t.popover('destroy');
					t.data('__WB_HAS_POPOVER__', false);
				}
			},
			{type: 'Button', text: __('Apply'), styleClass: 'btn-sm',
				buttonStyle: UIButton.UIButton.STYLE_SUCCESS,
				click: function() {
					var t = thisClass.elem.children('span.pop');
					t.popover('hide');

					thisClass.updatePreview();

					t.popover('destroy');
					t.data('__WB_HAS_POPOVER__', false);
					thisClass._triggerOnChange();
				}
			}
		]}
	]});

	this.differentBorders = this.panel.fields.differentBorders;
	this.weight = [this.panel.fields.weight, this.panel.fields.weightRight, this.panel.fields.weightBottom, this.panel.fields.weightLeft];
	this.style = [this.panel.fields.style, this.panel.fields.styleRight, this.panel.fields.styleBottom, this.panel.fields.styleLeft];
	this.color = [this.panel.fields.color, this.panel.fields.colorRight, this.panel.fields.colorBottom, this.panel.fields.colorLeft];
	this.radius = [this.panel.fields.radius, this.panel.fields.radiusRightTop, this.panel.fields.radiusRightBottom, this.panel.fields.radiusLeftBottom];

	var pop = this.elem.children("span.pop");
	if (this.placement === "bottom") {
		pop.css({ right: "15px" });
	} else if (this.placement === "right" || this.placement === "left") {
		pop.css({ top: "50%" });
	}
	
	this.elem.children(".input-group").bind("click", function() {
		var t = thisClass.elem.children("span.pop");
		if (t.data("__WB_HAS_POPOVER__")) {
			t.popover("destroy");
			t.data("__WB_HAS_POPOVER__", false);
			return;
		}
		t.data("__WB_HAS_POPOVER__", true);
		t.popover({
			html: true,
			title: __("Border"),
			content: function() { return thisClass.panel.getElem(); },
			trigger: "manual",
			placement: thisClass.placement
		});
		t.popover("show");
		var pop = t.parent().children('.popover').eq(0),
			btn = thisClass.elem.find('.btn').eq(0),
			winW = $(window).width(),
			winSl = $(window).scrollLeft(),
			elemLeft = thisClass.elem.offset().left - winSl,
			elemOff = (btn.offset().left - winSl - elemLeft) + (btn.outerWidth(true) / 2),
			popNewW = (thisClass.showRadius ? 420 : 320),
			popL;
		if (thisClass.placement === 'top' || thisClass.placement === 'bottom') {
			if (popNewW > winW) popNewW = winW;
			popL = elemOff - (popNewW / 2);
			if ((elemLeft + popL + popNewW) > winW) popL += (winW - (elemLeft + popL + popNewW));
			if ((elemLeft + popL) < 0) popL -= (elemLeft + popL);
			pop.css({left: popL, width: popNewW, maxWidth: popNewW});
			pop.find('.arrow').eq(0).css({left: (popL * -1) + elemOff});
		} else {
			pop.css({width: popNewW, maxWidth: popNewW});
		}
	});
};

/**
 * Trigger on change callback.
 * @protected
 */
BorderControl.prototype._triggerOnChange = function() {
	if (typeof this.onChange === 'function') {
		this.onChange.call(this);
	}
};

BorderControl.prototype.updateFieldVisibility = function() {
	if( this.panel && this.panel.fields ) {
		var vis = this.differentBorders.getValue();
		if( "otherBordersCont" in this.panel.fields )
			this.panel.fields.otherBordersCont.setVisible(vis);
		if( "topSideLabel" in this.panel.fields )
			this.panel.fields.topSideLabel.setVisible(vis);
		if( "radiusLabel1" in this.panel.fields )
			this.panel.fields.radiusLabel1.setVisible(!vis);
		if( "radiusLabel2" in this.panel.fields )
			this.panel.fields.radiusLabel2.setVisible(vis);
	}
};

/**
 * Get value object
 * @return object = {color: ..., style: ..., weight: ..., css: ...}
 */
BorderControl.prototype.getValue = function() {
	return BorderControl.buildCss(null, this.differentBorders, this.color, this.style, this.weight, (this.showRadius ? this.radius : null));
};

/**
 * Set value object
 * @param value object = {color: ..., style: ..., weight: ..., css: ...}
 */
BorderControl.prototype.setValue = function(value) {
	var obj = $.extend({
		differ: false,
		color: "#000000",
		style: "solid",
		weight: 1
	}, value);

	this.differentBorders.setValue(obj.differ);
	this.setPropertyValue(this.color, obj.color, "#000000");
	this.setPropertyValue(this.style, obj.style, "solid");
	this.setPropertyValue(this.weight, obj.weight, 1);
	if (this.showRadius)
		this.setPropertyValue(this.radius, obj.radius, 0);

	this.updatePreview();
	this.updateFieldVisibility();
};

BorderControl.normalizeStylePropertyValue = function(value, defaultValue) {
	if( value === null || value === undefined )
		return [defaultValue, defaultValue, defaultValue, defaultValue];
	if( typeof value !== "object" )
		return [value, value, value, value];
	if( "length" in value ) {
		if( value.length === 0 )
			return [defaultValue, defaultValue, defaultValue, defaultValue];
		if( value.length === 1 )
			return [value[0], value[0], value[0], value[0]];
		if( value.length === 2 )
			return [value[0], value[1], value[0], value[1]];
		if( value.length === 3 )
			return [value[0], value[1], value[2], value[1]];
		return [value[0], value[1], value[2], value[3]];
	}
	return [value.top, value.right, value.bottom, value.left];
};

BorderControl.prototype.setPropertyValue = function(fields, value, defaultValue) {
	var val = BorderControl.normalizeStylePropertyValue(value, defaultValue);
	for( var i = 0; i < 4; i++ )
		fields[i].setValue(val[i]);
};

BorderControl.prototype.updatePreview = function() {
	var css;
	if( this.differentBorders.getValue() ) {
		var wt = this.weight[0].getValue();
		var wr = this.weight[1].getValue();
		var wb = this.weight[2].getValue();
		var wl = this.weight[3].getValue();
		var sum;

		if( (sum = wt + wb) > 20 ) {
			wt = 20 * wt / sum;
			wb = 20 * wb / sum;
		}

		if( (sum = wl + wr) > 51 ) {
			wl = 51 * wl / sum;
			wr = 51 * wr / sum;
		}
		css = {
			marginTop: "",
			borderTop: wt + 'px ' + this.style[0].getValue() + ' ' + this.color[0].getValue(),
			borderRight: wr + 'px ' + this.style[1].getValue() + ' ' + this.color[1].getValue(),
			borderBottom: wb + 'px ' + this.style[2].getValue() + ' ' + this.color[2].getValue(),
			borderLeft: wl + 'px ' + this.style[3].getValue() + ' ' + this.color[3].getValue()
		};
		if( this.showRadius ) {
			css['border-radius'] =
			css['-webkit-border-radius'] =
			css['-moz-border-radius'] = this.radius[0].getValue() + 'px ' + this.radius[1].getValue() + 'px ' + this.radius[2].getValue() + 'px ' + this.radius[3].getValue() + 'px';
		}
		this.preview.addClass("bc-spb");
	}
	else {
		css = {
			marginTop: -this.weight[0].getValue()/2,
			borderTop: "none",
			borderRight: "none",
			borderBottom: this.weight[0].getValue() + 'px ' + this.style[0].getValue() + ' ' + this.color[0].getValue(),
			borderLeft: "none"
		};
		if( this.showRadius ) {
			css['border-radius'] =
			css['-webkit-border-radius'] =
			css['-moz-border-radius'] = '0';
		}
		this.preview.removeClass("bc-spb");
	}
	this.preview.css(css);
};

BorderControl.getBorderWidth = function(b, side) {
	var style = (typeof b.style === "object") ? (b.differ ? b.style[side] : b.style[0]) : b.style;
	if( style === "none" )
		return 0;
	return 1*((typeof b.weight === "object") ? (b.differ ? b.weight[side] : b.weight[0]) : b.weight);
};

	return BorderControl;
});
;

/** WB TextAreaControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB TextAreaControl';

/**
 * Text Area Control class
 * @param {string=} name
 * @param {string=} value
 * @param {string=} resizable
 */
function WB_TextAreaControl(name, value, resizable) { this.__construct(name, value, resizable); }

WB_TextAreaControl.prototype.elem = null;
WB_TextAreaControl.prototype.input = null;

/**
 * Construct Text Area controll
 * @param {string=} name text area name
 * @param {string=} value text area value
 * @param {string=} resizable make text area resizable (posible values: true, "both", "vertical", "horizontal", false)
 */
WB_TextAreaControl.prototype.__construct = function(name, value, resizable) {
	this.input = this.elem = $('<textarea class="form-control"></textarea>');
	
	if (WB_Builder.isset(name)) this.elem.attr("name", name);
	if (WB_Builder.isset(value)) this.elem.val(value);
	if (!resizable) {
		this.input.css("resize", "none");
	} else if (resizable === "vertical" || resizable === "horizontal" || resizable === "both") {
		this.input.css("resize", resizable);
	}
};

/**
 * Get value
 * @return value
 */
WB_TextAreaControl.prototype.getValue = function() {
	return this.elem.val();
};

/**
 * Set value
 * @param value value to set
 */
WB_TextAreaControl.prototype.setValue = function(value) {
	this.elem.val(value);
};
;

/** WB CheckBoxControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB CheckBoxControl';

/**
 * CheckBox Control class
 * @param {string=} label
 * @param {string=} name
 * @param {string=} value
 */
function WB_CheckBoxControl(label, name, value) { this.__construct(label, name, value); }

WB_CheckBoxControl.prototype.elem = null;
WB_CheckBoxControl.prototype.input = null;

/**
 * Construct Checkbox controll
 * @param {string=} label checkbox label
 * @param {string=} name checkbox name
 * @param {string=} value checkbox value
 */
WB_CheckBoxControl.prototype.__construct = function(label, name, value) {
	this.elem = $('<div class="checkbox"></div>');
	var labelElem = $('<label>').appendTo(this.elem);
	this.input = $('<input type="checkbox" />').appendTo(labelElem);
	
	if (WB_Builder.isset(label)) labelElem.append(label);
	if (WB_Builder.isset(name)) this.input.attr("name", name);
	if (WB_Builder.isset(value)) this.setValue(value);
};

/**
 * Get value
 * @return {boolean}
 */
WB_CheckBoxControl.prototype.getValue = function() {
	return this.input.get(0).checked ? true : false;
};

/**
 * Set value
 * @param {boolean} value value to set
 */
WB_CheckBoxControl.prototype.setValue = function(value) {
	this.input.get(0).checked = value ? true : false;
};
;

/** WB RadioBoxControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB RadioBoxControl';

/**
 * RadioBox Control class
 * @param {string=} label
 * @param {string=} name
 * @param {string=} value
 * @param {string=} inputValue
 */
function WB_RadioBoxControl(label, name, value, inputValue) { this.__construct(label, name, value, inputValue); }

WB_RadioBoxControl.prototype.elem = null;
WB_RadioBoxControl.prototype.input = null;

/**
 * Construct Radiobox controll
 * @param {string=} label radiobox label
 * @param {string=} name radiobox name
 * @param {string=} value radiobox value
 * @param {string=} inputValue radiobox input value
 */
WB_RadioBoxControl.prototype.__construct = function(label, name, value, inputValue) {
	this.elem = $('<div class="radio"></div>');
	var labelElem = $('<label>').appendTo(this.elem);
	this.input = $('<input type="radio" />').appendTo(labelElem);
	
	if (WB_Builder.isset(label)) labelElem.append(label);
	if (WB_Builder.isset(name)) this.input.attr("name", name);
	if (WB_Builder.isset(value)) this.setValue(value);
	if (WB_Builder.isset(inputValue)) this.input.val(inputValue);
};

/**
 * Get value
 * @return value
 */
WB_RadioBoxControl.prototype.getValue = function() {
	return this.input.get(0).checked ? true : false;
};

/**
 * Set value
 * @param value value to set
 */
WB_RadioBoxControl.prototype.setValue = function(value) {
	this.input.get(0).checked = value ? true : false;
};
;

/** WB LinkEditControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB LinkEditControl';

/**
 * LinkEditControl component class
 * @param {string=} value text field value
 * @param {string=} emptyMsg msg to display if no value
 * @param {string} langCode
 */
function WB_LinkEditControl(value, emptyMsg, langCode) {
	this.__construct(value, emptyMsg, langCode);
}

WB_LinkEditControl.prototype.elem = null;
WB_LinkEditControl.prototype.link = null;
WB_LinkEditControl.prototype.input = null;
WB_LinkEditControl.prototype.value = null;
WB_LinkEditControl.prototype.editBtn = null;
WB_LinkEditControl.prototype.remBtn = null;
WB_LinkEditControl.prototype.emptyMsg = __("No link selected");

/**
 * Construct Text field controll
 * @param {string=} value text field value
 * @param {string=} emptyMsg msg to display if no value
 * @param {string} langCode
 */
WB_LinkEditControl.prototype.__construct = function(value, emptyMsg, langCode) {
	var thisClass = this;
	
	this.elem = $('<a class="wb_link" href="javascript:void(0);"></a>');
	this.input = $('<span class="txt"></span>');
	this.editBtn = $('<span class="btn btn-default btn-xs"><span class="glyphicon glyphicon-pencil"></span></span>');
	this.remBtn = $('<span class="btn btn-default btn-xs hide" style="margin-left:5px;"><span class="glyphicon glyphicon-remove"></span></span>');
	
	this.remBtn.click(function(e) {
		e.stopPropagation();
		thisClass.clearValue();
	});
	
	this.elem.append(this.input).append(this.editBtn).append(this.remBtn);
	this.link = this.elem;
	if (langCode) {
		this.elem.wrap('<div data-lang="' + langCode + '" style="margin-bottom: 4px;"></div>');
		this.elem.before('<span>' + langCode.toUpperCase() + ': </span>');
		this.elem = this.elem.parent();
		for (var i=0, lang; (lang = wb_builder.site.languages[i]); i++) {
			if (lang.code === langCode && lang.isDefault) {
				this.elem.append('<span style="margin-left: 4px;">(' + __('Default') + ')</span>');
				break;
			}
		}
	}
	
	if (emptyMsg)
		this.emptyMsg = emptyMsg;
	if (value)
		this.setValue(value);
	else
		this.clearValue();
};

/**
 * Get value
 * @return value
 */
WB_LinkEditControl.prototype.getValue = function() {
	return this.value;
};

/**
 * Set value
 * @param value to set
 */
WB_LinkEditControl.prototype.setValue = function(value) {
	this.input.html(value).removeClass("inactive");
	this.value = value;
	this.remBtn.removeClass("hide");
};

/**
 * Remove value
 */
WB_LinkEditControl.prototype.clearValue = function() {
	
	this.input.html(this.emptyMsg).addClass("inactive");
	this.value = null;
	this.remBtn.addClass("hide");
};

/**
 * Set enabled state
 * @param {Boolean} enabled
 */
WB_LinkEditControl.prototype.setEnabled = function(enabled) {
	if( enabled )
		this.elem.removeClass("wb_link_disabled");
	else
		this.elem.addClass("wb_link_disabled");
};

/**
 * @return {Boolean}
 */
WB_LinkEditControl.prototype.getEnabled = function() {
	return !this.elem.is(".wb_link_disabled");
};
;

/** WB ToolTipControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB ToolTipControl';

define('ToolTipControl', [], function() {
	'use strict';

/**
 * ToolTip Control class
 * @param {string} label
 * @param {string} tip
 * @param {string} placement
 */
var ToolTipControl = function(label, tip, placement) { this.__construct(label, tip, placement); };

ToolTipControl.prototype.elem = null;

/**
 * Construct ToolTip controll
 * @param {string} label tooltip label text
 * @param {string} tip tooltip tip text
 * @param {string} placement tooltip placement (one of "left", "right", "top", "bottom")
 */
ToolTipControl.prototype.__construct = function(label, tip, placement) {
	this.elem = $('<span class="badge wb_badge_help">?</span>');
	
	this.elem.html(label);
	this.elem.removeAttr('title');
	this.elem.css({marginLeft: '6px', cursor: 'default' });
	var thisSelf = this, tipOver = false, initiated = false, closeTimeout = null;
	this.elem.on('mouseover focus', function() {
		if (tipOver) return;
		tipOver = true;
		thisSelf.elem.tooltip('show');
	}).on('mouseout blur', function() {
		if (!tipOver) return;
		tipOver = false;
		if (closeTimeout) clearTimeout(closeTimeout);
		closeTimeout = setTimeout(function() { if (!tipOver) thisSelf.elem.tooltip('hide'); }, 100);
	}).on('shown.bs.tooltip', function() {
		if (initiated) return;
		initiated = true;
		var tip = $(this).parent().children('.tooltip').eq(0);
		tip.on('mouseout', function() {
			if (!tipOver) return;
			tipOver = false;
			if (closeTimeout) clearTimeout(closeTimeout);
			closeTimeout = setTimeout(function () { if (!tipOver) thisSelf.elem.tooltip('hide'); }, 100);
		}).on('mouseover', function() { tipOver = true; });
	});
	if (wb_builder.rtl) {
		if (placement === 'left') placement = 'right';
		else if (placement === 'right') placement = 'left';
	}
	this.elem.tooltip({
		trigger: 'manual',
		html: true,
		title: tip,
		placement: (placement ? placement : 'top')
	});
};
	
	return ToolTipControl;
});
;

/** WB SpacingControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB SpacingControl';

define('SpacingControl', ['SizeSelector'], function(SizeSelector) {
	'use strict';

/**
 * Spacing control class
 */
var SpacingControl = function() { this.__construct(); };

SpacingControl.prototype.elem = null;
SpacingControl.prototype.margin = null;
SpacingControl.prototype.padding = null;
SpacingControl.prototype.panel = null;
SpacingControl.prototype.value = null;
SpacingControl.prototype.popover = null;
SpacingControl.prototype.hasPopover = false;
SpacingControl.prototype.pType = null;
SpacingControl.prototype.pPos = null;

/**
 * Construct Spacing control
 */
SpacingControl.prototype.__construct = function() {
	this.elem = $('<div class="wb-spacing-control">' +
			'<span class="lbl">' + __("margin") + '</span>' +
			'<div class="padding">' +
				'<span class="lbl">' + __("padding") + '</span>' +
				'<span class="l">0</span>' +
				'<span class="r">0</span>' +
				'<span class="t">0</span>' +
				'<span class="b">0</span>' +
				'<a href="javascript:void(0)" class="la"></a>' +
				'<a href="javascript:void(0)" class="ra"></a>' +
				'<a href="javascript:void(0)" class="ta"></a>' +
				'<a href="javascript:void(0)" class="ba"></a>' +
				'<div class="itm">' +
					'<span class="l">0</span>' +
					'<span class="r">0</span>' +
					'<span class="t">0</span>' +
					'<span class="b">0</span>' +
					'<a href="javascript:void(0)" class="la"></a>' +
					'<a href="javascript:void(0)" class="ra"></a>' +
					'<a href="javascript:void(0)" class="ta"></a>' +
					'<a href="javascript:void(0)" class="ba"></a>' +
				'</div>' +
			'</div>' +
		'</div>');
	
	this.margin = this.elem.children(".padding");
	this.padding = this.elem.children(".padding").children(".itm");
	
	var thisClass = this;
	
	this.margin.children("a.la").bind("click", function() {
		thisClass.showPopover("margin", "l");
		return false;
	});
	this.margin.children("a.ra").bind("click", function() {
		thisClass.showPopover("margin", "r");
		return false;
	});
	this.margin.children("a.ta").bind("click", function() {
		thisClass.showPopover("margin", "t");
		return false;
	});
	this.margin.children("a.ba").bind("click", function() {
		thisClass.showPopover("margin", "b");
		return false;
	});
	
	this.padding.children("a.la").bind("click", function() {
		thisClass.showPopover("padding", "l");
		return false;
	});
	this.padding.children("a.ra").bind("click", function() {
		thisClass.showPopover("padding", "r");
		return false;
	});
	this.padding.children("a.ta").bind("click", function() {
		thisClass.showPopover("padding", "t");
		return false;
	});
	this.padding.children("a.ba").bind("click", function() {
		thisClass.showPopover("padding", "b");
		return false;
	});
	
	this.panel = $('<div></div>');
	this.panel.append((this.value = new SizeSelector(false, 0, null, null, true)).elem);
	this.value.elem.css({display: 'inline-block'});
	var buttons = $('<div style="text-align: right;"></div>');
	this.panel.append(buttons);
	var cancelBtn = $('<button class="btn btn-default" type="button"></button>');
	cancelBtn.html(__("Cancel"));
	buttons.append(cancelBtn);
	cancelBtn.bind("click", function() {
		thisClass.popover.popover("hide");
		thisClass.popover.popover("destroy");
		thisClass.hasPopover = false;
	});
	
	var saveBtn = $('<button class="btn btn-success" type="button"></button>');
	saveBtn.html(__("Apply"));
	saveBtn.css({ marginLeft: "10px" });
	buttons.append(saveBtn);
	saveBtn.bind("click", function() {
		thisClass.popover.popover("hide");
		var src = thisClass[thisClass.pType].children("." + thisClass.pPos);
		src.html(thisClass.value.getValue());
		thisClass.popover.popover("destroy");
		thisClass.hasPopover = false;
	});
};

SpacingControl.prototype.showPopover = function(type, pos) {
	var t = this[type].children("a." + pos + "a");
	if (this.hasPopover) {
		this.popover.popover("destroy");
		this.hasPopover = false;
	}
	this.hasPopover = true;
	this.pType = type;
	this.pPos = pos;
	var src = this[this.pType].children("." + this.pPos);
	this.value.setValue(src.html());
	var placement = "bottom";
	if (pos === "r") placement = "right";
	else if (pos === "l") placement = "left";
	else if (pos === "t") placement = "top";
	var thisClass = this;
	t.popover({
		html: true,
		title: __("Value"),
		content: function() { return thisClass.panel; },
		trigger: "manual",
		placement: placement
	});
	t.popover("show");
	t.parent().children(".popover").width(240);
	this.popover = t;
};

SpacingControl.prototype.parseInt = function(val) {
	var n = parseInt(val, 10);
	return isNaN(n) ? 0 : n;
};

/**
 * Get value
 * @return value
 */
SpacingControl.prototype.getValue = function() {
	var ml = this.parseInt(this.margin.children(".l").html());
	var mr = this.parseInt(this.margin.children(".r").html());
	var mt = this.parseInt(this.margin.children(".t").html());
	var mb = this.parseInt(this.margin.children(".b").html());
	var pl = this.parseInt(this.padding.children(".l").html());
	var pr = this.parseInt(this.padding.children(".r").html());
	var pt = this.parseInt(this.padding.children(".t").html());
	var pb = this.parseInt(this.padding.children(".b").html());
	var css = {
		margin: (mt + "px " + mr + "px " + mb + "px " + ml + "px"),
		padding: (pt + "px " + pr + "px " + pb + "px " + pl + "px")
	};
	return {
		marginTop: mt,
		marginRight: mr,
		marginBottom: mb,
		marginLeft: ml,
		paddingTop: pt,
		paddingRight: pr,
		paddingBottom: pb,
		paddingLeft: pl,
		css: css
	};
};

/**
 * Set value
 * @param value
 */
SpacingControl.prototype.setValue = function(value) {
	var val = value ? value : {};
	this.margin.children(".l").html(this.parseInt(val.marginLeft));
	this.margin.children(".r").html(this.parseInt(val.marginRight));
	this.margin.children(".t").html(this.parseInt(val.marginTop));
	this.margin.children(".b").html(this.parseInt(val.marginBottom));
	this.padding.children(".l").html(this.parseInt(val.paddingLeft));
	this.padding.children(".r").html(this.parseInt(val.paddingRight));
	this.padding.children(".t").html(this.parseInt(val.paddingTop));
	this.padding.children(".b").html(this.parseInt(val.paddingBottom));
};

	return SpacingControl;
});
;

/** WB StyleControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB StyleControl';

define('StyleControl', ['ComboBox'], function(ComboBox) {
	'use strict';

/**
 * Style Control class
 * @param {boolean} emptyChoice include none options
 */
var StyleControl = function(emptyChoice) { this.__construct(emptyChoice); };

StyleControl.prototype.elem = null;
StyleControl.prototype.input = null;
StyleControl.prototype._elem = null;
StyleControl.prototype.emptyChoice = false;
/**
 * Callback for event when a different style is being selected.
 * @type {function}|null
 */
StyleControl.prototype.onChange = null;

/**
 * Construct Style controll
 * @param {boolean} emptyChoice include none options
 */
StyleControl.prototype.__construct = function(emptyChoice) {	
	this._elem = new ComboBox();
	
	this.input = this._elem.input;
	this.elem = this._elem.elem;
	if (emptyChoice)
		this.emptyChoice = true;
	var thisSelf = this;
	this._elem.onChange = function() { thisSelf._triggerOnChange(); };
	this.update();
};

/**
 * Trigger on change callback.
 * @protected
 */
StyleControl.prototype._triggerOnChange = function() {
	if (typeof this.onChange === 'function') {
		this.onChange.call(this);
	}
};

StyleControl.prototype.update = function() {
	this._elem.removeAllOptions();
	if (this.emptyChoice)
		this._elem.addOption('', ' - ');
	for (var i = 0; i < wb_builder.site.styles.length; i++) {
		var s = wb_builder.site.styles[i];
		var spc = (s.ident) ? ((s.ident*10) + 20) : 0;
		var li = this._elem.addOption(s.selector.substring(1), s.name);
		if (spc) li.children("a").css({ paddingLeft: spc + "px" });
	}
};

/**
 * Get value
 * @return {string}
 */
StyleControl.prototype.getValue = function() {
	return this._elem.getValue();
};

/**
 * Set value
 * @param {string} value value to set
 */
StyleControl.prototype.setValue = function(value) {
	this._elem.setValue(value);
};

	return StyleControl;
});
;

/** WB URLControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB URLControl';

define('URLControl', ['LinkDialog', 'util/MenuList'], function(LinkDialog, MenuList) {
	'use strict';

/**
 * URL Control component class
 * @param {Boolean} multilang
 */
var URLControl = function(multilang) { this.__construct(multilang); };

URLControl.prototype._elem = null;
URLControl.prototype.elem = null;
URLControl.prototype.linkDialog = null;
URLControl.prototype.value = null;
/** @type {Boolean} */
URLControl.prototype.multilang = null;
/**
 * On change callback function.
 * @type {function}
 */
URLControl.prototype.onChange = null;
URLControl.prototype.enabled = true;

URLControl.elemList = [];
URLControl.reloadAll = function() {
	for (var i=0, elem; (elem = URLControl.elemList[i]); i++) {
		elem.reload();
	}
};
URLControl.getUrl = function(value) {
	var url = null;
	if (value) {
		if ('url' in value) {
			url = value.url;
		} else if (typeof value === 'object') {
			url = value[wb_builder.site.currSelLang].url;
		}
		if (value.type === "page") {
			var mi = MenuList.getItemInfo(value.url, null, value.menuUID);
			if (mi) {
				url = (mi.type === 'internal' || mi.type === 'page') ? ('mi:' + (value.menuUID ? ('' + value.menuUID + '_') : '') + mi.id + '/') : mi.url;
			}
		} else if (value.type === "email") {
			url = "mailto:" + url;
		} else if (value.type === "file") {

		}
	}
	return url;
};
URLControl.getName = function(value) {
	var name = null;
	if (value) {
		if (value.type === 'page') {
			var mi = MenuList.getItemInfo(value.url, null, value.menuUID);
			if (mi) {
				name = __tr(mi.name);
			}
		} else {
			name = value.url ? value.url.replace(/^(?:https?:\/\/|gallery\/)/i, '') : null;
		}
	}
	return name;
};

/**
 * Construct URL controll
 * @param {Boolean} multilang
 */
URLControl.prototype.__construct = function(multilang) {
	this.elem = $('<div class="wb-url-controll"></div>');
	this.multilang = multilang;
	this.init();
	URLControl.elemList.push(this);
};

URLControl.prototype._triggerOnChange = function() {
	if (typeof this.onChange === 'function') {
		this.onChange.call(this);
	}
};

URLControl.prototype.reload = function() {
	this._elem = null;
	this.elem.empty();
	this.init();
};

URLControl.prototype.init = function() {
	var thisClass = this;
	var langs = window.wb_builder.site.languages;
	if (langs.length && this.multilang) {
		this._elem = {};
		for (var i=0, lang; (lang = langs[i]); i++) {
			var el = new WB_LinkEditControl(null, null, lang.code);
			el.link.bind('click', function() {
				thisClass.__onClick(null, $(this).parent().attr('data-lang'));
				return false;
			});
			el.remBtn.bind('click', function() {
				thisClass.setValue(null, $(this).parent().parent().attr('data-lang'));
				thisClass._triggerOnChange();
			});
			this._elem[lang.code] = el;
			this.elem.append(this._elem[lang.code].elem);
		}
	} else {
		this._elem = new WB_LinkEditControl();
		this._elem.link.bind('click', function() {
			thisClass.__onClick();
			return false;
		});
		this._elem.remBtn.bind('click', function() {
			thisClass.setValue(null);
			thisClass._triggerOnChange();
		});
		this.elem.append(this._elem.elem);
	}
	this.setValue();
	this.setEnabled(this.enabled);
};

URLControl.prototype.__onClick = function(onChange, langCode) {
	if( !this.enabled )
		return;
	var thisClass = this;
	var thisCallback = (typeof onChange === "function") ? onChange : null;
	if (!this.linkDialog) {
		this.linkDialog = new LinkDialog(__("Link properties"));
		this.linkDialog.addButton(__("Cancel"));
		this.linkDialog.addButton(__("Apply"), function() {
			thisClass.setValue(thisClass.linkDialog.getInfo(), thisClass.linkDialog.langCode);
			thisClass.linkDialog.hide();
			if (thisCallback) { thisCallback.call(thisClass); }
			thisClass._triggerOnChange();
		}, true);
	}
	this.linkDialog.langCode = langCode;
	this.linkDialog.setInfo(this.getValue(langCode));
	this.linkDialog.show();
};

/**
 * Get value
 * @param {String} langCode
 * @return {Object}
 */
URLControl.prototype.getValue = function(langCode) {
	return (langCode) ? this.value[langCode] : this.value;
};

/**
 * Set value
 * @param {Object} value to set
 * @param {String} langCode language to set value to
 * @param {WB_LinkEditControl}
 */
URLControl.prototype.setValue = function(value, langCode, _elem) {
	var i, defLang, val;
	if (!_elem) {
		val = $.extend(true, {}, this.value);
		if (wb_builder.site.languages.length && this.multilang) {
			if (langCode) {
				val[langCode] = this.setValue(value, langCode, this._elem[langCode]);
			} else {
				val = {};
				if (value && typeof value === 'object' && Object.keys(value).length > 0) {
					if ('type' in value) {
						defLang = wb_builder.site.getLastDefLang();
						for (i in this._elem) {
							if( !this._elem.hasOwnProperty(i) )
								continue;
							val[i] = this.setValue((i === defLang) ? value : null, i, this._elem[i]);
						}
					} else {
						for (i in this._elem) {
							if( !this._elem.hasOwnProperty(i) )
								continue;
							val[i] = this.setValue(value.hasOwnProperty(i) ? value[i] : null, i, this._elem[i]);
						}
					}
				} else {
					for (i in this._elem) {
						if( !this._elem.hasOwnProperty(i) )
							continue;
						val[i] = this.setValue(null, null, this._elem[i]);
					}
				}
			}
		} else {
			if (value && typeof value === 'object') {
				if ('type' in value) {
					val = this.setValue(value, null, this._elem);
				} else {
					defLang = wb_builder.site.getLastDefLang();
					val = this.setValue(value[defLang], null, this._elem);
				}
			} else {
				val = this.setValue(null, null, this._elem);
			}
		}
		this.value = val;	
	}
	else {
		val = (value && typeof(value) === "object") ? $.extend(true, {}, value) : {};
		if (!val.type) val.type = "url";
		if (!val.url) val.url = null;
		if (!val.menuUID) val.menuUID = null;
		if (!val.anchor) val.anchor = null;
		if (!val.target) val.target = null;
		if (!val.title) val.title = null;
		val.finalUrl = URLControl.getUrl(val);
		val.name = URLControl.getName(val);
		
		if (val.type === "page") {
			var mi = val.anchor ? {name: '#' + val.anchor} : MenuList.getItemInfo(val.url, null, val.menuUID);
			if (mi) {
				_elem.setValue(__tr(mi.name, wb_builder.site.getLastDefLang()));
			} else {
				_elem.clearValue();
			}
		} else {
			if (val.url) {
				_elem.setValue(val.url);
			} else {
				_elem.clearValue();
			}
		}
		return val;
	}
};

/**
 * This callback is called for each link edit control handled by URLControl component.
 * @callback enumControlsCallback
 * @param {WB_LinkEditControl} control Instance of WB_LinkEditControl class.
 * @param {String|null} langCode Null if there are no languages or language code associated with the control.
 */
/**
 * @param {enumControlsCallback} callback
 */
URLControl.prototype.enumControls = function(callback) {
	if( typeof callback !== "function" )
		return;
	var langs = window.wb_builder.site.languages;
	if (langs.length && this.multilang) {
		for (var i=0, lang; (lang = langs[i]); i++) {
			if( this._elem.hasOwnProperty(lang.code) )
				callback(this._elem[lang.code], lang.code);
		}
	} else {
		callback(this._elem, null);
	}
};

URLControl.prototype.setEnabled = function(enabled) {
	var _this = this;
	this.enabled = enabled;
	this.enumControls(function(control, langCode) {
		control.setEnabled(_this.enabled);
	});
};

URLControl.prototype.getEnabled = function() {
	return this.enabled;
};

URLControl.prototype.getUrlTitle = function() {
	if ('title' in this.value) {
		return this.value.title;
	} else if (typeof this.value === 'object') {
		return this.value[wb_builder.site.currSelLang].title;
	}
};

URLControl.prototype.getUrlTarget = function() {
	var target = null;
	if ('target' in this.value) {
		target = this.value.target;
	} else if (typeof this.value === 'object') {
		target = this.value[wb_builder.currSelLang].target;
	}
	if ((typeof target !== "string") && target) target = "_blank";
	return target;
};

URLControl.prototype.getUrl = function() {
	return URLControl.getUrl(this.value);	
};
URLControl.prototype.getName = function() {
	return URLControl.getName(this.value);
};

	window.WB_URLControl = URLControl;
	
	return URLControl;

});
;

/** WB ListControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB ListControl';

/**
 * List Control class
 * @param {Object} opt
 */
function WB_ListControl(opt) { this.__construct(opt); }

WB_ListControl.prototype.elem = null;
WB_ListControl.prototype.list = null;
WB_ListControl.prototype.input = null;
WB_ListControl.prototype.addBtn = null;
WB_ListControl.prototype.initiated = false;
WB_ListControl.prototype.options = null;
WB_ListControl.prototype.lastSelected = null;
WB_ListControl.prototype.lastSelectedLi = null;

WB_ListControl.prototype._itemClickHandler = null;

/**
 * Construct Font controll
 * @param {Object} opt
 */
WB_ListControl.prototype.__construct = function(opt) {
	this.options = $.extend(true, {deleteRequireConfirm: true}, opt);
	this.elem = $('<div class="wb-list-control well"></div>');
	this.list = $('<ul class="nav nav-pills nav-stacked"></ul>');
	this.list.hide();
	this.elem.append(this.list);
	this.input = this.elem;
	var thisClass = this;
	if (!("editable" in this.options) || this.options.editable) {
		this.addBtn = $('<a class="wb-add-btn" href="javascript:void(0)"><span class="glyphicon glyphicon-plus"></span></a>');
		this.addBtn.append((("newItemButtonText" in this.options) && this.options.newItemButtonText !== null) ? this.options.newItemButtonText : __("Add item"));
		this.elem.append(this.addBtn);
		this.addBtn.bind("click", function() {
			var cls = (thisClass.options.type && typeof(thisClass.options.type) === "function") ? thisClass.options.type : (function() {});
			var obj = new cls();
			thisClass.addItem(obj);
		});
		if( !("sortable" in this.options) || this.options.sortable )
			this.elem.append('<div class="wb-page-tree-notice"><small><span class="glyphicon glyphicon-exclamation-sign"></span>' + __("Use Drag and Drop to sort items") + '</small></div>');
	} else {
		this.elem.css("height", "auto");
	}
};

WB_ListControl.prototype.setHeight = function(height) {
	this.list.css({ height: height, maxHeight: height });
	if (height) this.list.show();
};		

WB_ListControl.prototype.updateStyle = function() {
	if ((!("editable" in this.options) || this.options.editable) && (!("sortable" in this.options) || this.options.sortable)) {
		if (this.initiated) {
			this.list.sortable("destroy");
		}
		var thisClass = this;
		this.list.sortable({
			distance: 3,
			axis: "y",
			//containment: "parent",
			items: "> li",
			cursor: "move",
			start: function(e, ui) { thisClass.onSortStart(e, ui); },
			stop: function(e, ui) { thisClass.onSortStop(e, ui); }
		});
	}
	this.initiated = true;
	if (this.list.children("li").size() > 0) {
		this.list.show();
	} else {
		this.list.hide();
	}
};

WB_ListControl.prototype.onSortStart = function(e, ui) {
	if (this.lastSelected) {
		this.lastSelectedLi.trigger("click");
	}
	this.lastSelected = null;
	this.lastSelectedLi = null;
};

WB_ListControl.prototype.onSortStop = function(e, ui) {
	this.lastSelected = null;
	this.lastSelectedLi = null;
};

WB_ListControl.prototype.setItemIcon = function(li, icon) {
	$(li).find("span.lc-icon").attr('class', "lc-icon " + icon);
};

WB_ListControl.prototype.addItem = function(item, noStyleUpdate, icon, disabled) {
	var cls = (this.options.type && typeof(this.options.type) === "function") ? this.options.type : (function() {});
	var data = item.serialize();
	data.virtual = true;
	var obj = new cls(data);
	var thisClass = this;
	var xbtn = null;
	var objName = obj.name ? __tr(obj.name, '__DEFAULT__', __('New Item'), true, true) : __('New Item');
	var objTitle = (obj.hasOwnProperty("title") && obj.title) ? __tr(obj.title, '__DEFAULT__') : objName;
	var span = $('<span>').addClass("lc-icon " + (icon ? icon : 'glyphicon glyphicon-folder-open'));
	var link = $('<a href="javascript:void(0)"></a>').attr("title", objTitle);
	var li = $('<li>');
	link.append(span);
	li.append(link);
	if (!("editable" in this.options) || this.options.editable) {
		xbtn = $('<span class="wb-x-btn glyphicon glyphicon-remove"></span>');
		xbtn.bind("click", function() {
			if (!thisClass.options.deleteRequireConfirm || confirm(__('Are you sure you want to delete this menu?'))) {
				thisClass.removeItem(li);
			}
		});
	}
	link.append(" " + objName);
	if (!("editable" in this.options) || this.options.editable) {
		if (xbtn) link.append(xbtn);
	}
	li.wbSetClassInstance(obj);
	if (disabled) {
		li.addClass('disabled');
	} else {
		li.on("click", this._itemClickHandler = function() {
			$(this).parent().children("li").removeClass("active");
			$(this).addClass("active");
			var obj = null;
			if (thisClass.options.onSelect && typeof(thisClass.options.onSelect) === "function") {
				obj = $(this).wbGetClassInstance();
				thisClass.options.onSelect.call($(this).get(0), obj);
			}
			if (thisClass.lastSelectedLi) thisClass.updateItem(thisClass.lastSelectedLi);
			thisClass.lastSelected = obj;
			thisClass.lastSelectedLi = $(this);
		});
	}
	if( !noStyleUpdate && ("addNewItemsToBeginning" in this.options) && this.options.addNewItemsToBeginning )
		this.list.prepend(li);
	else
		this.list.append(li);
	if (this.options.onAdd && typeof(this.options.onAdd) === "function") {
		this.options.onAdd.call(li, li.wbGetClassInstance());
	}
	if (!noStyleUpdate) this.updateStyle();
	return li;
};

WB_ListControl.prototype.addSeparator = function() {
	this.list.append('<li class="divider"></li>');
};

WB_ListControl.prototype.updateItem = function(li) {
	var obj = li.wbGetClassInstance();
	var i = li.children("a").children("span.glyphicon");
	i.detach();
	li.children("a").empty();
	li.children("a").append(i.eq(0));
	li.children("a").append(" " + (obj.name ? __tr(obj.name, '__DEFAULT__', __("New Item"), true, true) : __("New Item")));
	li.children("a").append(i.eq(1));
};

WB_ListControl.prototype.removeItem = function(li, noStyleUpdate) {
	var obj = li.wbGetClassInstance();
	if (this.options.onRemove && typeof(this.options.onRemove) === "function") {
		this.options.onRemove.call(li, obj);
	}
	if (li.hasClass("active")) {
		this.lastSelected = null;
		this.lastSelectedLi = null;
	}
	if (!noStyleUpdate) {
		var switchToLi = li.next('li');
		if (!switchToLi.length) switchToLi = li.prev('li');
	}
	li.remove();
	li.empty();
	li.wbSetClassInstance(null);
	if (!noStyleUpdate) {
		this.selectItemLi(switchToLi);
		this.updateStyle();
	}
};

WB_ListControl.prototype.removeAllItems = function() {
	var thisClass = this;
	this.list.children("li").each(function() {
		if ($(this).hasClass('divider')) {
			$(this).detach();
			$(this).remove();
		} else {
			thisClass.removeItem($(this), true);
		}
	});
	this.lastSelected = null;
	this.lastSelectedLi = null;
	this.updateStyle();
};

WB_ListControl.prototype.selectFirst = function() {
	this.selectItemLi(this.elem.find("li").eq(0));
};

WB_ListControl.prototype.selectItemLi = function(li) {
	if (li && li.length > 0) {
		li.trigger("click");
	} else if (this.options.onSelectNone && typeof(this.options.onSelectNone) === "function") {
		this.options.onSelectNone.call();
	}
};

WB_ListControl.prototype.setItemLiEnabled = function(li, enabled) {
	if (enabled) {
		li.removeClass('disabled').on('click', this._itemClickHandler);	
	} else {
		li.addClass('disabled').off('click', this._itemClickHandler);
	}
};

WB_ListControl.prototype.getItemsLi = function() {
	return this.list.children('li');
};

WB_ListControl.prototype.getItems = function(asInst) {
	var items = this.getItemsLi();
	if (asInst) {
		var instList = [];
		items.each(function() {
			var inst = $(this).wbGetClassInstance();
			if (inst) instList.push(inst);
		});
		return instList;
	}
	return items;
};

/**
 * Get value
 * @return value
 */
WB_ListControl.prototype.getValue = function() {
	var cls = (this.options.type && typeof(this.options.type) === "function") ? this.options.type : (function() {});
	var list = [];
	this.list.children("li").each(function() {
		var obj = $(this).wbGetClassInstance();
		var data = obj.serialize();
		data.virtual = false;
		list.push(new cls(data));
	});
	return list;
};

/**
 * Set value
 * @param value value to set
 */
WB_ListControl.prototype.setValue = function(value) {
	this.removeAllItems();
	for (var i = 0; i < value.length; i++) {
		this.addItem(value[i], true);
	}
	this.selectFirst();
	this.updateStyle();
};
;

/** WB RoundCornersControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB RoundCornersControl';

define('RoundCornersControl', ['SizeSelector'], function(SizeSelector) {
	'use strict';

/**
 * Font Control class
 */
var RoundCornersControl = function() { this.__construct(); };

RoundCornersControl.prototype.elem = null;
RoundCornersControl.prototype.input = null;
RoundCornersControl.prototype._lt = null;
RoundCornersControl.prototype._rt = null;
RoundCornersControl.prototype._rb = null;
RoundCornersControl.prototype._lb = null;
RoundCornersControl.prototype._lt_p = null;
RoundCornersControl.prototype._rt_p = null;
RoundCornersControl.prototype._rb_p = null;
RoundCornersControl.prototype._lb_p = null;
RoundCornersControl.prototype.onChange = null;

/**
 * Construct Font controll
 */
RoundCornersControl.prototype.__construct = function() {	
	this.elem = $('<table class="wb-roundcorner-control">' +
			"<tr><td></td><td></td><td></td><td></td></tr>" +
			"<tr><td></td><td></td><td></td><td></td></tr>" +
		"</table>");
	
	var tds = this.elem.find("td"), idx = 0, td = null;
	
	var thisClass = this;
	
	td = tds.eq(idx++);
	td.append((this._lt = new SizeSelector()).elem);
	this._lt.minValue = 0;
	this._lt.bind("change", function() { thisClass.updateStyle(); thisClass._triggerOnChange(); });
	td = tds.eq(idx++);
	td.append(this._lt_p = $('<div class="wb-roundcorner-control-clt"></div>'));
	td = tds.eq(idx++);
	td.append(this._rt_p = $('<div class="wb-roundcorner-control-crt"></div>'));
	td = tds.eq(idx++);
	td.append((this._rt = new SizeSelector()).elem);
	this._rt.minValue = 0;
	this._rt.bind("change", function() { thisClass.updateStyle(); thisClass._triggerOnChange(); });
	td = tds.eq(idx++);
	td.append((this._lb = new SizeSelector()).elem);
	this._lb.minValue = 0;
	this._lb.bind("change", function() { thisClass.updateStyle(); thisClass._triggerOnChange(); });
	td = tds.eq(idx++);
	td.append(this._lb_p = $('<div class="wb-roundcorner-control-clb"></div>'));
	td = tds.eq(idx++);
	td.append(this._rb_p = $('<div class="wb-roundcorner-control-crb"></div>'));
	td = tds.eq(idx++);
	td.append((this._rb = new SizeSelector()).elem);
	this._rb.minValue = 0;
	this._rb.bind("change", function() { thisClass.updateStyle(); thisClass._triggerOnChange(); });
	
	this.input = this.elem.find("input");
};

/**
 * Trigger on change callback.
 * @protected
 */
RoundCornersControl.prototype._triggerOnChange = function() {
	if (typeof this.onChange === 'function') {
		this.onChange.call(this);
	}
};

RoundCornersControl.prototype.updateStyle = function() {
	this._lt_p.css("border-radius", this._lt.getValue() + "px 0 0 0");
	this._rt_p.css("border-radius", "0 " + this._rt.getValue() + "px 0 0");
	this._rb_p.css("border-radius", "0 0 " + this._rb.getValue() + "px 0");
	this._lb_p.css("border-radius", "0 0 0 " + this._lb.getValue() + "px");
};

/**
 * Get value
 * @return value
 */
RoundCornersControl.prototype.getValue = function() {
	var rad = this._lt.getValue() + "px" +
		" " + this._rt.getValue() + "px" +
		" " + this._rb.getValue() + "px" +
		" " + this._lb.getValue() + "px";
	var css = {
		"border-radius": rad,
		"-moz-border-radius": rad,
		"-webkit-border-radius": rad
	};
	return {
		lt: this._lt.getValue(),
		rt: this._rt.getValue(),
		rb: this._rb.getValue(),
		lb: this._lb.getValue(),
		css: css
	};
};

/**
 * Set value
 * @param value value to set
 */
RoundCornersControl.prototype.setValue = function(value) {
	var obj = value;
	if (!obj) obj = {
		lt: 0, rt: 0, rb: 0, lb: 0
	};
	this._lt.setValue(obj.lt);
	this._rt.setValue(obj.rt);
	this._rb.setValue(obj.rb);
	this._lb.setValue(obj.lb);
	this.updateStyle();
};
	
	return RoundCornersControl;
});
;

/** WB WB_LayoutblocksControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB WB_LayoutblocksControl';

/**
 * Layout blocks Control class
 * 
 * @version 1.0.0, 2013-03-15
 */
function WB_LayoutblocksControl() { this.__construct(); }

WB_LayoutblocksControl.prototype.elem = null;
WB_LayoutblocksControl.prototype.block = "template";
WB_LayoutblocksControl.prototype.active = true;

/**
 * Construct Layout blocks Control
 */
WB_LayoutblocksControl.prototype.__construct = function() {	
	this.elem = $('<table class="lbTb active">' +
			'<tr><td data-block="template" class="template side active" rowspan="3"></td><td data-block="top" class="top"></td><td data-block="template" class="side template active" rowspan="3"></td></tr>' +
			'<tr><td data-block="middle" class="middle"></td></tr>' +
			'<tr><td data-block="bottom" class="bottom"></td></tr>' +
		"</table>");
	var thisClass = this;
	
	this.elem.find(".side").on("mouseenter", function() {
		thisClass.elem.find(".side").addClass("hover");
	}).on("mouseleave", function() {
		thisClass.elem.find(".side").removeClass("hover");
	});
	
	var tds = this.elem.find("td");
	tds.on("click", function() {
		if (thisClass.active) {
			thisClass.setValue($(this).data("block"));
		}
	});
};

/**
 * Get block list
 * @returns {Array}
 */
WB_LayoutblocksControl.prototype.getBlocks = function() {
	var blocks = [];
	this.elem.find("td[data-block]").each(function() {
		blocks.push($(this).attr("data-block"));
	});
	return blocks;
};

/**
 * Make block isset or not
 * @param {Boolean} isSet
 * @param {String} block
 */
WB_LayoutblocksControl.prototype.setIsSet = function(isSet, block) {
	if (!block) block = this.block;
	var val = (block === "template") ? "side" : block;
	if (isSet) {
		this.elem.find("." + val).addClass("isset");
	} else {
		this.elem.find("." + val).removeClass("isset");
	}
};

/**
 * Make block active or inactive
 * @param {Boolean} active
 */
WB_LayoutblocksControl.prototype.setActive = function(active) {
	this.active = active;
	if (active)
		this.elem.addClass("active");
	else 
		this.elem.removeClass("active");
};

WB_LayoutblocksControl.prototype.updateStyle = function() {
	
};

WB_LayoutblocksControl.prototype.onChange = function() {
	
};

/**
 * Get value
 * @return {String} value
 */
WB_LayoutblocksControl.prototype.getValue = function() {
	return this.block;
};

/**
 * Set value
 * @param {String} value value to set
 */
WB_LayoutblocksControl.prototype.setValue = function(value) {
	this.block = value;
	var tds = this.elem.find("td");
	tds.removeClass("active");
	if (value === "template")
		this.elem.find(".side").addClass("active");
	else
		this.elem.find("." + value).addClass("active");
	this.onChange();
};
;

/** WB UploadFieldControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB UploadFieldControl';

/**
 * Upload Field Control class
 * @param {string=} name upload field name
 * @param {string=} accept extension list
 */
function WB_UploadFieldControl(name, accept) {
	this.__construct(name, accept);
}

WB_UploadFieldControl.prototype.elem = null;
WB_UploadFieldControl.prototype._elemSub = null;
WB_UploadFieldControl.prototype.input = null;
WB_UploadFieldControl.prototype.file = null;
WB_UploadFieldControl.prototype.button = null;
WB_UploadFieldControl.prototype.onChange = null;

/**
 * Construct Upload field controll
 * @param name (optional) upload field name
 */
WB_UploadFieldControl.prototype.__construct = function(name, accept) {
	var thisClass = this;
	
	this.elem = $('<div>').addClass('wb-upload-field-control');
	this._elemSub = $('<div>').addClass('input-group').appendTo(this.elem);
	this.input = $('<input type="text" readonly="readonly" class="form-control" />');
	this.file = $('<input type="file" size="1" />');
	if (accept) this.file.attr('accept', accept);
	if (WB_Builder.isset(name)) this.file.attr("name", name);
	this.file.on("change", function() {
		var val = this.value;
		val = val.split(/[\\/]/);
		thisClass.input.val(val[val.length - 1]);
		if (typeof thisClass.onChange === 'function') thisClass.onChange.call(this);
	});
	
	this._elemSub.append(this.input);
	this._elemSub.append(this.file);
	this._elemSub.append($('<span>').addClass('input-group-btn').append(this.button = $('<button class="btn btn-default" type="button"></button>')));
	
	this.button.html(__('Browse...'));
	
	this.elem.on("mousemove", function(e) {
		var mx = e.pageX - $(this).offset().left, my = e.pageY - $(this).offset().top;
		thisClass.file.css({
			left: (mx - thisClass.file.width() / 2) + "px",
			top: (my - thisClass.file.height() / 2) + "px"
		});
		return false;
	});
};

/**
 * Get value
 * @return value
 */
WB_UploadFieldControl.prototype.getValue = function() {
	return this.input.val();
};

/**
 * Set value
 * @param value value to set
 */
WB_UploadFieldControl.prototype.setValue = function(value) {
	this.input.val(value);
	this.file.value = value;
};
;

/** WB FontTransformControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB FontTransformControl';

define('FontTransformControl', ['ComboBox'], function(ComboBox) {
	'use strict';

/**
 * Font Transform Control class
 */
var FontTransformControl = function() { this.__construct(); };

FontTransformControl.prototype._elem = null;
FontTransformControl.prototype.elem = null;
FontTransformControl.prototype.input = null;

/**
 * Construct Font Transform controll
 */
FontTransformControl.prototype.__construct = function() {	
	this._elem = new ComboBox({
		"none": __("None"),
		"capitalize": __("Capitalize"),
		"uppercase": __("Upper Case"),
		"lowercase": __("Lower Case")
	}, "none");
	this._elem.elem.css({width: 100});
	
	this.input = this._elem.input;
	this.elem = this._elem.elem;
};

/**
 * Get value
 * @return {Object}
 */
FontTransformControl.prototype.getValue = function() {
	return { value: this._elem.getValue(), css: {
		"text-transform": this._elem.getValue()
	}};
};

/**
 * Set value
 * @param {Object} value value to set
 */
FontTransformControl.prototype.setValue = function(value) {
	this._elem.setValue((value && (typeof(value) === "object")) ? value.value : value);
};
	
	return FontTransformControl;
});
;

/** WB LangInputControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB LangInputControl';

define('LangInputControl', ['TextField'], function(TextField) {
	'use strict';

/**
 * LangInputControl Control class
 * @param {String} name
 * @param {String} value
 * @param {Boolean} isTextarea
 * @param {Boolean} resizable
 * @param {Callback} onReload
 */
function LangInputControl(name, value, isTextarea, resizable, onReload) {
	if (name !== '%inherit%') { this.__construct(name, value, isTextarea, resizable, onReload); }
}

LangInputControl.prototype.elem = null;
LangInputControl.prototype._elem = null;
LangInputControl.prototype._elemBtn = null;
LangInputControl.prototype._elemList = null;
LangInputControl.prototype.name = false;
LangInputControl.prototype.placeholder = false;
LangInputControl.prototype.zIndex = false;
LangInputControl.prototype.isTextarea = false;
LangInputControl.prototype.resizable = false;
LangInputControl.prototype.events = null;
LangInputControl.prototype.simpleControl = null;
LangInputControl.prototype.onChange = null;
LangInputControl.prototype.onReload = null;
LangInputControl.prototype.modified = null;
LangInputControl.prototype.prevValue = null;
LangInputControl.elemList = [];
LangInputControl.reloadAll = function() {
	for (var i=0, langInput; (langInput = LangInputControl.elemList[i]); i++) {
		langInput.reload();
	}
};
LangInputControl.closeAll = function(except) {
	for (var i=0, langInput; (langInput = LangInputControl.elemList[i]); i++) {
		if (except === langInput) { continue; }
		langInput._elem.removeClass('open');
	}
};
LangInputControl.onDocumentClick = function(e) {
	var t = $(e.target);
	var activeLangInputControl = null;
	if (t.is('.wb-langinput-controll *')) {
		t = t.parents('.wb-langinput-controll');
		
		$.each(LangInputControl.elemList, function() {
			if (t.get(0) == this.elem.get(0)) {
				activeLangInputControl = this;
				return;
			}
		});
	}
	LangInputControl.closeAll(activeLangInputControl);
};

LangInputControl.prototype.__construct = function(name, value, isTextarea, resizable, onReload) {
	this.name = name;
	this.isTextarea = isTextarea;
	if (!$.browser.msie) this.zIndex = 1050;
	this.resizable = (resizable === undefined && this.isTextarea) ? 'vertical' : resizable;
	this.onReload = onReload;
	this.events = {};
	this.elem = $('<div class="wb-langinput-controll"></div>');
	this.init();
	if (value) { this.setValue(value); }
	LangInputControl.elemList.push(this);
};

LangInputControl.prototype.reload = function() {
	//var width = this.getWidth();
	if (this._elem) {
		this._elem.remove();
		this._elem.empty();
		this._elem = null;
		this.elem.find('.exc-mark').remove();
		this.elem.removeClass('exc-mark-show');
		this.simpleControl = null;
	}
	this.init();
	//this.setWidth(width);
};

LangInputControl.normalizeValue = function(value, langCode) {
	var result, i, len;
	var langs = wb_builder.site.languages,
		defLang = wb_builder.site.getLastDefLang();
	langCode = langCode || defLang;
	if (langs.length > 0) {
		result = {};
		for (i=0, len=langs.length; i < len; i++) {
			result[langs[i].code] = null;
		}
		if (typeof(value) === 'object') {
			for (i in value) {
				result[i] = value[i];
			}
		} else {
			result[langCode] = value;
		}
	} else {
		result = __tr(value, langCode, null, true, true);
	}
	return result;
};

LangInputControl.prototype.addItem = function(langCode, asVirtual, asMain) {
	var thisClass = this, input;
	if (!this.simpleControl) {
		var item = $('<div class="input' + (asVirtual ? ' virtual' : '') + (asMain ? ' main' : '') + '" data-lang="' + langCode + '">' +
				(this.isTextarea ? '<textarea class="form-control"></textarea>' : '<input class="form-control" type="text" />') +
				'<span class="lang-label">' + (langCode.toUpperCase()) + '</span>' +
			'</div>');
		if (asMain) {
			this._elem.prepend(item);
		} else {
			this._elemList.append(item);
		}
		input = item.children('input, textarea').eq(0);
		
		if (this.isTextarea) {
			if (!this.resizable) {
				input.css('resize', 'none');
			} else if (this.resizable === 'vertical' || this.resizable === 'horizontal' || this.resizable === 'both') {
				input.css('resize', this.resizable);
			}
		}
	} else {
		input = this.simpleControl.input;
	}
	input.bind('change', function(e) {
		thisClass.checkFilled();
		if (typeof thisClass.onChange === 'function')
			thisClass.onChange.call(thisClass, e, this.value, (thisClass.simpleControl ? null : $(this).parent().attr('data-lang')));
	});
	input.bind('focus keydown', function() {
		thisClass.modified = true;
	});
	this.reloadEvents(input);
};

LangInputControl.prototype.removeVirtualItems = function() {
	this._elemList.children('.input.virtual').remove();
};

LangInputControl.prototype.existsItem = function(langCode) {
	var exists = false;
	this.getInputs(true).each(function() {
		var ln = $(this).attr('data-lang');
		if (ln === langCode) {
			exists = true;
			return false;
		}
	});
	return exists;
};

LangInputControl.prototype.init = function() {
	var thisClass = this;
	var langs = wb_builder.site.languages;
	if (langs.length) {
		this._elem = $('<div class="input-group">' +
				'<div class="input-list dropdown-menu"></div>' +
				'<span class="input-group-btn">' +
					'<button class="btn btn-default dropdown-toggle" type="button"><span class="caret"></span></button>' +
				'</span>' +
			'</div>');
		this._elemList = this._elem.find('.input-list').eq(0);
		this._elemBtn = this._elem.find('button').eq(0);
		this._elemBtn.attr('disabled', (langs.length === 1)).bind('click', function() {
			thisClass._elem.toggleClass('open');
			thisClass.fixDropdownPosition();
		});
		for (var i=0, lang; (lang = langs[i]); i++) {
			this.addItem(lang.code, false, (lang.isDefault));
		}
	} else {
		if (thisClass.isTextarea) {
			this.simpleControl = new WB_TextAreaControl(this.name, this.value, this.resizable);
		} else {
			this.simpleControl = new TextField(this.value);
			this.simpleControl.setName(this.name);
		}
		this._elem = this.simpleControl.elem;
		this.addItem();
	}
	this.elem.append(this._elem);
	this.setPlaceholder(this.placeholder);
	
	this.modified = false;
	if (typeof this.onReload === 'function') {
		this.onReload.call(this);
	}
};

LangInputControl.prototype.getMainInput = function(getParent) {
	if (this.simpleControl) {
		return (getParent ? this.simpleControl.elem : this.simpleControl.input);
	} else {
		return this.getInputs(getParent).eq(0);
	}
};

LangInputControl.prototype.reloadEvents = function(input) {
	input = input || this.getInputs();
	for (var i in this.events) {
		input.unbind(i, this.events[i]).bind(i, this.events[i]);
	}
};

LangInputControl.prototype.setEvent = function(event, handler) {
	if (typeof handler !== 'function') return;
	this.events[event] = handler;
	this.reloadEvents();
};

LangInputControl.prototype.fixDropdownPosition = function() {
	this._elemList.css({
		width: (this.elem.outerWidth() - this._elemBtn.outerWidth())
	});
};

LangInputControl.prototype.getInputs = function(getParents, langCode) {
	if (this.simpleControl) {
		return this.simpleControl.input;
	} else {
		return this._elem.find('.input' + (langCode ? '[data-lang="' + langCode + '"]' : '') + (!getParents ? (this.isTextarea ? ' textarea' : ' input') : ''));
	}
};

LangInputControl.prototype.getWidth = function() {
	if (this.simpleControl) {
		return this._elem.outerWidth();
	} else {
		return this.getMainInput().outerWidth() + 26;
	}
};

LangInputControl.prototype.setWidth = function(width) {
	var iow, iiw, btnw, thisClass = this;
	if (this.simpleControl) {
		iow = this._elem.outerWidth();
		iiw = this._elem.width();
		if (!iow || !iiw) {
			setTimeout(function() {
				thisClass.setWidth(width);
			}, 20);
			return;
		}
		this._elem.css('width', (width - iow + iiw) + 'px');
	} else {
		var mainInput = this.getMainInput();
		iow = mainInput.outerWidth();
		iiw = mainInput.width();
		btnw = 26;
		if (!iow || !iiw) {
			setTimeout(function() {
				thisClass.setWidth(width);
			}, 20);
			return;
		}
		this.getInputs().css('width', (width - btnw - iow + iiw) + 'px');
	}
};

LangInputControl.prototype.setVisibleExcMark = function(visible) {
	if (this.simpleControl) { return; }
	//this.elem.find('.exc-mark').remove();
	if (visible) {
		//var excMark = $('<div class="exc-mark" title="' + __('Missing some translations') + '" data-placement="top">!</div>');
		//excMark.tooltip();
		//this.elem.append(excMark);
		this.elem.find(".dropdown-toggle").attr("title", __('Missing some translations')).tooltip();
		this.elem.addClass('exc-mark-show');
	} else {
		this.elem.find(".dropdown-toggle").attr("title", "").tooltip("destroy");
		this.elem.removeClass('exc-mark-show');
	}
	this.fixDropdownPosition();
};

LangInputControl.prototype.getValue = function() {
	if (!this.modified)
		return this.prevValue;
	
	if (this.simpleControl) {
		return this.simpleControl.getValue();
	} else {
		var thisClass = this;
		var value = {};
		this.getInputs(true).each(function() {
			var ln = $(this).attr('data-lang');
			value[ln] = thisClass.getInputs(false, ln).val();
		});
		return value;
	}
};

LangInputControl.prototype.setValue = function(value, langCode, noReset) {
	this.prevValue = value;
	var normValue = LangInputControl.normalizeValue(value, langCode);
	if (this.simpleControl) {
		this.simpleControl.setValue(normValue);
	} else {
		if (!noReset) this.reset();
		this.removeVirtualItems();
		for (var i in normValue) {
			if (!this.existsItem(i) && normValue[i]) {
				this.addItem(i, true);
			}
			if (!langCode || langCode === i) {
				this.getInputs(false, i).val(normValue[i]);
			}
		}
		this.checkFilled();
	}
};

LangInputControl.prototype.setPlaceholder = function(placeholder, toAll) {
	if (placeholder) {
		if (this.simpleControl) {
			this.getMainInput().attr('placeholder', __tr(placeholder));
		} else {
			this.getInputs().each(function() {
				var parent = $(this).parent(), inputLangCode = parent.attr('data-lang');
				$(this).attr('placeholder', __tr(placeholder, inputLangCode, (toAll ? __tr(placeholder, wb_builder.site.getLastDefLang()) : '')));
			});
		}
	} else {
		this.getInputs().attr('placeholder', '');
	}
};

LangInputControl.prototype.setDisabled = function(disabled) {
	var thisClass = this;
	if (!disabled) {
		this.getInputs().each(function() {
			$(this).removeAttr('disabled');
			thisClass.checkFilled();
		});
	} else {
		this.getInputs().each(function() {
			$(this).attr('disabled', 'disabled');
			thisClass.setVisibleExcMark(false);
		});
	}
};

LangInputControl.prototype.reset = function() {
	if (this.simpleControl) {
		this.simpleControl.setValue('');
	} else {
		var inputs = this.getInputs();
		for (var i=0, input; (input = inputs[i]); i++) {
			$(input).val('');
		}
		this.setVisibleExcMark(true);
	}
};

LangInputControl.prototype.checkFilled = function() {
	var filled = true;
	this.getInputs().each(function() {
		var $this = $(this);
		if (!$this.is("[disabled]") && !$this.val()) {
			filled = false;
			return;
		}
	});
	this.setVisibleExcMark(!filled);
};

LangInputControl.prototype.focus = function() {
	this.getMainInput().focus();
};

	return LangInputControl;
});
;

/** WB ContactFormControl **/
(window.defineModule = (window.defineModule || {})).name = 'WB ContactFormControl';

define('ContactFormControl', ['UIComponent', 'Form'], function(UIComponent, Form) {
	'use strict';
	
	var ContactFormControl = function() {
		UIComponent.UIComponent.prototype.constructor.call(this);
		var thisSelf = this;
		this._elem.addClass('input-group');
		this._inputElem = $('<input>').addClass('form-control')
				.attr({type: 'text', disabled: 'disabled', placeholder: __('E-mail is required')})
				.appendTo(this._elem);
		var btn = $('<button>').addClass('btn btn-default')
				.attr({type: 'button'})
				.append($('<span>').addClass('glyphicon glyphicon-pencil'))
				.on('click', function() {
					if (thisSelf._form) thisSelf._form.comProperties();
				});
		$('<div>').addClass('input-group-btn')
				.append(btn)
				.appendTo(this._elem);
		this.setValue(null);
	};
	
	ContactFormControl.prototype = Object.create(UIComponent.UIComponent.prototype);
	ContactFormControl.prototype.constructor = ContactFormControl;
	
	ContactFormControl.prototype._inputElem = null;
	ContactFormControl.prototype._form = null;
	
	/** @returns {Object} */
	ContactFormControl.prototype.getValue = function() {
		return this._form ? this._form.serialize() : null;
	};
	
	/** @param {Object} value */
	ContactFormControl.prototype.setValue = function(value) {
		var thisSelf = this;
		this._form = new Form((value && typeof value === 'object') ? value : {content: {}}, true, true);
		this._form.updateStyle = function() {
			thisSelf._inputElem.val(this.serialize().content.email);
			Form.prototype.updateStyle.call(this);
		};
		this._form.updateStyle();
	};
	
	return ContactFormControl;
});
;

/** WB TabbedPane **/
(window.defineModule = (window.defineModule || {})).name = 'WB TabbedPane';

define('TabbedPane', ['UIComponent'], function(UIComponent) {
	'use strict';

/**
 * Tabbed pane tab descriptor.
 * @typedef {Object} TabbedPaneTabDef
 * @property {string} id unique id of the tab element.
 * @property {string} type tab type identifier.
 * @property {JQuery} btnElem tab button element.
 * @property {JQuery} btnAnchorElem tab buttons anchor element.
 * @property {JQuery} contentElem tab content element.
 */

/**
 * Tabbed pane controll class
 * @constructor
 */
var TabbedPane = function() { this.__construct(); };
TabbedPane.prototype = new UIComponent.UIComponent('%inherit%');
TabbedPane.prototype.constructor = TabbedPane;

/** @type {jQuery} */
TabbedPane.prototype.elem = null;
/** @type {jQuery} */
TabbedPane.prototype.elemNav = null;
/** @type {jQuery} */
TabbedPane.prototype.elemContent = null;
/** @type {string} */
TabbedPane.prototype.id = null;
/** @type {number} */
TabbedPane.prototype.tabIndex = 0;
/** @type {boolean} */
TabbedPane.prototype.locked = false;
/** @type {number} */
TabbedPane.paneIndex = 0;
/** @type {Object[]} */
TabbedPane.prototype._events = null;
/** @type {boolean} */
TabbedPane.prototype._navVisible = false;
TabbedPane.prototype._shownTabFunc = null;
/** @type {function} */
TabbedPane.prototype.onChange = null;
/**
 * Tab descriptor lists.
 * @type {TabbedPaneTabDef[]}
 */
TabbedPane.prototype.tabs = null;
/**
 * Selected tab descriptor.
 * @type {TabbedPaneTabDef|null}
 */
TabbedPane.prototype.tab = null;

/**
 * Construct Tabbed pane controll
 */
TabbedPane.prototype.__construct = function() {
	UIComponent.UIComponent.prototype.constructor.call(this);
	this.id = "wb_tab_pane_" + TabbedPane.paneIndex++;
	this.tabs = [];
	this._elem.addClass('tabbable');
	this.elemNav = $('<ul>').addClass('nav nav-tabs').appendTo(this._elem);
	this.elemContent = $('<div>').addClass('tab-content').appendTo(this._elem);
	this.elemNav.hide();
	this._navVisible = false;
	this.elem = this._elem;
	this._events = [];
	this.trigger('nav-hide');
	var thisClass = this;
	this._shownTabFunc = function(e, tabDef) {
		if (typeof thisClass.onChange === 'function') {
			thisClass.onChange.call(thisClass, e.target, e.relatedTarget, tabDef);
		}
	};
};

/**
 * Dissable tab switching
 * @param {boolean} locked
 */
TabbedPane.prototype.setLocked = function(locked) {
	this.locked = locked;
};

/**
 * Add new tab
 * Note: if no index specified tab will be appended to the end
 * @param {string} title tab title
 * @param {number} index (optional) index to add tab at
 * @return {TabbedPaneTabDef} tab descriptor object.
 */
TabbedPane.prototype.addTab = function(title, index) {
	var thisSelf = this;
	var id = this.id + "_tab" + this.tabIndex++;
	var tabNav = $('<li><a data-toggle="tab"></a></li>');
	var tabContent = $('<div>').addClass('tab-pane');
	tabContent.attr("id", id);
	var tab = {
		id: id,
		type: null,
		btnElem: tabNav,
		btnAnchorElem: tabNav.children('a').eq(0),
		contentElem: tabContent
	};
	tabNav.children("a")
			.on('shown.bs.tab', function(e) {
				thisSelf.tab = tab;
				thisSelf._shownTabFunc.call(this, e, tab);
			})
			.attr({href: '#' + id})
			.html(title);
	if (typeof(index) === "undefined" || index === null
			|| index >= this.elemNav.children().size()) {
		this.elemNav.append(tabNav);
		this.elemContent.append(tabContent);
		this.tabs.push(tab);
	} else {
		this.elemNav.children().eq(index).before(tabNav);
		this.elemContent.children().eq(index).before(tabContent);
		if (index <= 0) {
			this.tabs.unshift(tab);
		} else if (index >= this.tabs.length) {
			this.tabs.push(tab);
		} else {
			this.tabs.splice(index, 0, tab);
		}
	}
	if (this.elemNav.children('li').size() > 1 && !this.locked) {
		if (!this._navVisible) {
			this.elemNav.show();
			this.trigger('nav-show');
		}
	}
	return tab;
};

/**
 * @param {boolean} visible
 * @param {boolean} force
 */
TabbedPane.prototype.setNavVisible = function(visible, force) {
	if (visible && (this.elemNav.children('li').length > 1 || force)) {
		if (!this._navVisible) {
			this.elemNav.show();
			this._navVisible = true;
			this.trigger('nav-show');
		}
	} else {
		if (this._navVisible) {
			this.elemNav.hide();
			this._navVisible = false;
			this.trigger('nav-hide');
		}
	}
};

/**
 * Set tab visibility
 * @param {TabbedPaneTabDef} tabDef tab definition.
 * @param {boolean} visible tab visibility
 */
TabbedPane.prototype.setTabVisible = function(tabDef, visible) {
	if (!tabDef) return;
	var elNav = tabDef.btnElem;
	var elCont = tabDef.contentElem;
	if (visible) {
		elNav.css({display: ''});
		elCont.css({display: ''});
	} else {
		elNav.css({display: 'none'});
		elCont.css({display: 'none'});
	}
};

TabbedPane.prototype.getTabByType = function(type) {
	for (var i = 0; i < this.tabs.length; i++)
		if (this.tabs[i].type === type)
			return this.tabs[i];
	return null;
};

/**
 * Select tab
 * @param {number} index tab index to select
 * @param {TabbedPaneTabDef=} tabDef if is set then it will ignore index and use this to select tab.
 */
TabbedPane.prototype.selectTab = function(index, tabDef) {
	if (this.locked) return;
	this.elemNav.children().removeClass("active");
	this.elemContent.children().removeClass("active");
	this.tab = tabDef ? tabDef : ((index >= 0 && index < this.tabs.length) ? this.tabs[index] : null);
	if (this.tab) {
		this.tab.btnElem.addClass("active");
		this.tab.contentElem.addClass("active");
	}
};

/**
 * @param {string} type
 * @return TabbedPaneTabDef|null
 */
TabbedPane.prototype.selectTabByType = function(type) {
	var tab = this.getTabByType(type);
	if( tab )
		this.selectTab(-1, tab);
	return tab;
};

/** @return {TabbedPaneTabDef} */
TabbedPane.prototype.getSelectedTabDef = function() {
	return this.tab;
};

/**
 * Get selected tab
 * @return {jQuery} selected tab content element as jQuery selector object
 */
TabbedPane.prototype.getSelectedTab = function() {
	return this.tab.btnElem;
};

/**
 * Set fixed height for tab content
 * Note: if tab content exeeds this height scroll will appier
 * @param {number} height of the tab content 
 */
TabbedPane.prototype.setFixedHeight = function(height) {
	this.elemContent.css({
		height: height + "px",
		"overflow-y": "auto"
	});
};

/**
 * Removes scrolls on overflow and removes overflow hidden 
 */
TabbedPane.prototype.setNoScroll = function() {
	this.elemContent.css({
		"overflow-x": "",
		"overflow-y": "",
		"overflow": "visible"
	});
};

TabbedPane.prototype.on = function(event, func) {
	if (event === 'nav-show' || event === 'nav-hide') {
		this._events.push({id: event, func: func});
	} else {
		UIComponent.UIComponent.prototype.on.call(this, event, func);
	}
	return this;
};

TabbedPane.prototype.off = function(event, func) {
	if (event === 'nav-show' || event === 'nav-hide') {
		for (var i = (this._events.length - 1); i >= 0; i--) {
			if (this._events[i].func === func) this._events.splice(i, 1);
		}
	} else {
		UIComponent.UIComponent.prototype.off.call(this, event, func);
	}
	return this;
};

TabbedPane.prototype.trigger = function(event, extraParameters) {
	if (event === 'nav-show' || event === 'nav-hide') {
		for (var i = 0; i < this._events.length; i++) {
			if (this._events[i].id === event) this._events[i].func(this, extraParameters);
		}
	} else {
		UIComponent.UIComponent.prototype.trigger.call(this, event, extraParameters);
	}
	return this;
};
	
	window.WB_TabbedPane = TabbedPane;
	
	return TabbedPane;
});
;

/** WB Site **/
(window.defineModule = (window.defineModule || {})).name = 'WB Site';

define('Site', [
	'IdIndexedList',
	'Dialog',
	'BackgroundControl',
	'Service',
	'URLControl',
	'UIButton',
	'FontManager',
	'LangInputControl',
	'util/MenuList',
	'ModeManager',
	'BuilderEvent',
	'TextControl',
	'Guides'
], function(IdIndexedList, Dialog,
			BackgroundControl,
			Service, URLControl, UIButton, FontManager, LangInputControl, MenuList,
			ModeManager, BuilderEvent, TextControl, Guides) {
	'use strict';

	/**
	 * Builder site class
	 * @param {Object} data
	 * @class WB_Site
	 */
	var Site = function(data) { if (data) this.__construct(data); };

	Site.DEFAULT_BUILDER_WIDTH = 992;

	Site.RENDER_MODE_ABSOLUTE = 'absolute';
	Site.RENDER_MODE_RESPONSIVE1 = 'responsive1';
	Site.RENDER_MODE_RESPONSIVE2 = 'responsive2';
	
	/** @type Page[] */
	Site.prototype.pages = null;
	Site.prototype.defFixedHeight = null;
	Site.prototype.defNoPageBg = null;
	Site.prototype.languages = null;
	Site.prototype.lastDefLang = null;
	Site.prototype.currSelLang = null;
	Site.prototype.prevSelLang = null;
	Site.prototype.frontPage = null;
	Site.prototype.styles = null;
	Site.prototype.anchors = null;
	Site.prototype.stylesElem = null;
	Site.prototype.changeDlg = null;
	Site.prototype.siteSEODlg = null;
	Site.prototype.changeBgDlg = null;
	Site.prototype.changeSiteBgDlg = null;
	Site.prototype.faviconDlg = null;
	Site.prototype.analyticsId = null;
	Site.prototype.anonymizeIp = null;
	Site.prototype.webmasterId = null;
	Site.prototype.favicon = null;
	Site.prototype.translations = null;
	/** @type Boolean */
	Site.prototype.publishWithForcedHttps = false;
	/** @type {number} */
	Site.prototype.publishWithForcedHttpsPort = 0;
	/** @type Boolean */
	Site.prototype.forceRedirectEnabled = false;
	/** @type Boolean */
	Site.prototype.forceRedirectWww = false;
	/** @type Boolean */
	Site.prototype.forceSlashes = false;
	/**
	 * HTML to be added to published websites head tag
	 * @type {string}
	 */
	Site.prototype.metaHtml = null;
	/**
	 * If true then publish robots.txt else not.
	 * @type {boolean}
	 */
	Site.prototype.robotsTxtEnable = null;
	/**
	 * Content of robots.txt file.
	 * @type {string}
	 */
	Site.prototype.robotsTxt = null;
	/** @type Object */
	Site.prototype.modes = null;
	/** @type Object */
	Site.prototype.modesEnabled = null;
	Site.prototype.landing = null;
	/**
	 * If true then add dir="rtl" on site body.
	 * @type {boolean}
	 */
	Site.prototype.rtl = false;
	// Site.prototype.landingContentOffset = null;

	Site.prototype.builderWidth = Site.DEFAULT_BUILDER_WIDTH;
	Site.prototype.renderMode = Site.RENDER_MODE_RESPONSIVE2;

	Site.prototype.usedCustomFonts = null;

	Site.prototype.cookiePolicyEnabled = false;
	Site.prototype.cookiePolicyFont = 'Arial,Helvetica,sans-serif';
	Site.prototype.cookiePolicyFontSize = 14;
	Site.prototype.cookiePolicyMessage = null;
	Site.prototype.cookiePolicyButtonText = null;
	Site.prototype.cookiePolicyBg = "rgba(0, 0, 0, 0.66)";
	Site.prototype.cookiePolicyMessageColor = "#FFFFFF";
	Site.prototype.cookiePolicyButtonBg = "#5cb85c";
	Site.prototype.cookiePolicyButtonColor = "#FFFFFF";

	Site.prototype.eventListeners = null;

	/**
	 * Construct builder site
	 * @param {Object} data site information data object
	 */
	Site.prototype.__construct = function(data) {
		this.eventListeners = {};
		Site.AnchorUtil.init(wb_builder, this);
		this.applyData(data);
	};

	/**
	 * Switch to mode (one of ModeManager.MODE_* constants)
	 * @param {String} fromMode
	 * @param {String} toMode
	 */
	Site.prototype.switchMode = function(fromMode, toMode, initial) {
		for (var i = 0; i < this.styles.length; i++) { this.styles[i].switchMode(fromMode, toMode, initial); }
		if (!toMode || !Service.modeManager.getUseModes()) return;
		if (!(fromMode in this.modes)) this.modes[fromMode] = new Site.Mode();
		this.modes[fromMode].store(this);
		if (!(toMode in this.modes)) {
			this.modes[toMode] = new Site.Mode();
			this.modes[toMode].copy(this.modes[fromMode]);
		}
		if (initial || fromMode !== toMode) {
			this.modes[toMode].applyTo(this);
		}
	};

	/**
	 * Apply data on site object
	 * @param {Object} data data to apply
	 */
	Site.prototype.applyData = function(data) {
		this.frontPage = null;
		this.pages = {};
		var list = data.content.pages ? data.content.pages : [];

		var oldAnchorData = {};
		var page = null, p;
		var cc = 0, i, hasFront = false, firstPage;
		for (i = 0; i < list.length; i++) {
			if (list[i].anchors) oldAnchorData[''+list[i].id] = list[i].anchors;
			page = new Site.Page($.extend(true, list[i], {saved: true}));
			page.copyFrom = null;
			page.copyClearHeader = null;
			page.copyClearBody = null;
			page.copyClearFooter = null;
			if (page.isFront)
				hasFront = true;
			if (!firstPage)
				firstPage = page;
			this.addPage(page);
			cc++;
		}
		if (!hasFront) {
			p = this.getPage(1);
			if (p) {
				p.isFront = true;
			} else if (firstPage) {
				firstPage.isFront = true;
			}
		}

		if (cc === 0) {
			page = new Site.Page({
				id: 1, isFront: true, title: __("Home"), layout: "Empty"
			});
			this.addPage(page);
		}

		this.defFixedHeader = data.content.defFixedHeader ? data.content.defFixedHeader : false;
		this.defNoPageBg = data.content.defNoPageBg ? data.content.defNoPageBg : false;
		this.languages = data.content.languages ? data.content.languages : [];
		this.lastDefLang = data.content.lastDefLang ? data.content.lastDefLang : null;
		this.currSelLang = this.languages.length > 0 ? this.getLastDefLang() : null;
		this.rtl = (data.content.rtl ? true : false);
		if (this.languages && (this.languages instanceof Array) && this.languages.length) {
			for (var i in this.languages) {
				var langDefCode = '' + this.languages[i].code;
				var langDef = wb_builder.getLanguageByCode(langDefCode);
				// If language definition not found we forge locale code for compatibility.
				this.languages[i].locale = (langDef ? langDef.locale : (langDefCode.toLowerCase() + '_' + langDefCode.toUpperCase()));
			}
		}

		this.styles = [];
		list = data.content.styles ? data.content.styles : [];
		var needExtend = false;
		if (!list || !list.length) {
			list = Site.Style.defaults;
			needExtend = true;
		}
		for (i = 0; i < Site.Style.defaults.length; i++) {
			var found = false;
			for (var n = 0; n < list.length; n++) {
				if (Site.Style.defaults[i].selector === list[n].selector) {
					found = true;
					break;
				};
			}
			if (!found) {
				list.push(Site.Style.defaults[i]);
				needExtend = true;
			}
		}
		for (i = 0; i < list.length; i++) {
			this.styles.push(new Site.Style((needExtend ? $.extend(true, {}, list[i]) : list[i])));
		}
		// reset fixed properties
		for (i = 0; i < this.styles.length; i++) {
			for (n = 0; n < Site.Style.defaults.length; n++) {
				if (Site.Style.defaults[n].selector !== this.styles[i].selector) continue;
				this.styles[i].tag = Site.Style.defaults[n].tag;
				this.styles[i].ident = Site.Style.defaults[n].ident;
				break;
			}
		}
		
		this.anchors = data.content.anchors ? data.content.anchors : Site.AnchorUtil.fixOldData(oldAnchorData);

		this.favicon = data.content.favicon ? data.content.favicon : null;
		this.analyticsId = data.content.analyticsId ? data.content.analyticsId : null;
		this.anonymizeIp = data.content.anonymizeIp ? true : false;
		this.webmasterId = data.content.webmasterId ? data.content.webmasterId : null;
		this.metaHtml = data.content.metaHtml ? data.content.metaHtml : null;
		this.headSnippetsHtml = data.content.headSnippetsHtml ? data.content.headSnippetsHtml : null;
		this.bodySnippetsHtml = data.content.bodySnippetsHtml ? data.content.bodySnippetsHtml : null;
		this.bodyStartSnippetsHtml = data.content.bodyStartSnippetsHtml ? data.content.bodyStartSnippetsHtml : null;
		this.robotsTxtEnable = data.content.robotsTxtEnable ? true : false;
		this.robotsTxt = data.content.robotsTxt ? data.content.robotsTxt : null;
		this.landing = data.content.landing ? true : false;
		this.translations = {};

		this.renderMode = data.renderMode;

		this.updateStyle();

		if ('publishWithForcedHttps' in data.content) this.publishWithForcedHttps = data.content.publishWithForcedHttps ? true : false;
		if ('publishWithForcedHttpsPort' in data.content) this.publishWithForcedHttpsPort = parseInt(data.content.publishWithForcedHttpsPort, 10);
		if ('forceRedirectEnabled' in data.content) this.forceRedirectEnabled = data.content.forceRedirectEnabled ? true : false;
		if ('forceRedirectWww' in data.content) this.forceRedirectWww = data.content.forceRedirectWww ? true : false;
		this.forceSlashes = (!('forceSlashes' in data.content) || data.content.forceSlashes);

		if (wb_builder.isB2C) {
			this.forceRedirectEnabled = true;
		}

		this.modes = {}; if (data.modes) for (var k in data.modes) { this.modes[k] = new Site.Mode(data.modes[k]); }
		this.modesEnabled = (('modesEnabled' in data.content) && (typeof data.content.modesEnabled === 'object')) ? data.content.modesEnabled : {};

		this.usedCustomFonts = {};
		FontManager.FontManager.forceCustomFontsUsage();
		if( data.content.hasOwnProperty("usedCustomFonts") ) {
			for( i = 0; i < data.content.usedCustomFonts.length; i++ ) {
				var uf = FontManager.GoogleFontUsage.fromJson(data.content.usedCustomFonts[i]);
				this.usedCustomFonts[uf.font.family] = uf;
				FontManager.FontManager.createFontLinkElementForFont(uf.font);
			}
		}

		this.cookiePolicyEnabled = ('cookiePolicyEnabled' in data.content)
			? data.content.cookiePolicyEnabled
			: this.cookiePolicyEnabled;
		this.cookiePolicyFont = ('cookiePolicyFont' in data.content)
			? data.content.cookiePolicyFont
			: this.cookiePolicyFont;
		this.cookiePolicyFontSize = ('cookiePolicyFontSize' in data.content)
			? data.content.cookiePolicyFontSize
			: this.cookiePolicyFontSize;
		this.cookiePolicyMessage = ('cookiePolicyMessage' in data.content)
			? data.content.cookiePolicyMessage
			: __("We use cookies (and gather certain personal information) to provide you with a better online experience. By visiting our site you accept our terms.");
		this.cookiePolicyButtonText = ('cookiePolicyButtonText' in data.content)
			? data.content.cookiePolicyButtonText
			: __("Got it");
		this.cookiePolicyBg = ('cookiePolicyBg' in data.content)
			? data.content.cookiePolicyBg
			: this.cookiePolicyBg;
		this.cookiePolicyMessageColor = ('cookiePolicyMessageColor' in data.content)
			? data.content.cookiePolicyMessageColor
			: this.cookiePolicyMessageColor;
		this.cookiePolicyButtonBg = ('cookiePolicyButtonBg' in data.content)
			? data.content.cookiePolicyButtonBg
			: this.cookiePolicyButtonBg;
		this.cookiePolicyButtonColor = ('cookiePolicyButtonColor' in data.content)
			? data.content.cookiePolicyButtonColor
			: this.cookiePolicyButtonColor;
	};

	Site.prototype.getLastDefLang = function() {
		if (!this.lastDefLang) {
			for (var i=0, lang; (lang = this.languages[i]); i++) {
				if (lang.isDefault) {
					this.lastDefLang = lang.code;
					break;
				}
			}
		}
		return this.lastDefLang;
	};

	Site.prototype.setLastDefLang = function(langCode) {
		this.lastDefLang = langCode;
	};
	
	Site.prototype.isRtlLang = function(langCode) {
		langCode = langCode || this.currSelLang;
		return (langCode && (langCode in wb_builder.rtlLanguages) && wb_builder.rtlLanguages[langCode]);
	};

	/**
	 * Serialize this instance
	 * @return {Object} object
	 */
	Site.prototype.serialize = function(onSave) {
		if (Service.modeManager.getUseModes()) {
			var mode = ModeManager.getMode();
			this.switchMode(mode, mode);
		}
		var modes = {}; for (var k in this.modes) { modes[k] = this.modes[k].serialize(); }

		var pagesList = [], i;
		for (i in this.pages) {
			if (!this.pages[i]) continue;
			pagesList.push(this.pages[i].serialize(onSave));
		}
		var stylesList = [];
		for (i = 0; i < this.styles.length; i++) {
			if (!this.styles[i]) continue;
			stylesList.push(this.styles[i].serialize());
		}
		var usedCustomFonts = [];
		for( i in this.usedCustomFonts ) {
			if( this.usedCustomFonts.hasOwnProperty(i) )
				usedCustomFonts.push(this.usedCustomFonts[i].serialize());
		}
		return {
			"class": "Site",
			content: {
				"pages": pagesList,
				defFixedHeader: this.defFixedHeader,
				defNoPageBg: this.defNoPageBg,
				modesEnabled: Service.modeManager.serialize(),
				"languages": this.languages,
				"styles": stylesList,
				anchors: Site.AnchorUtil.serialize(),
				"analyticsId": this.analyticsId,
				anonymizeIp: this.anonymizeIp,
				"webmasterId": this.webmasterId,
				"favicon": this.favicon,
				publishWithForcedHttps: this.publishWithForcedHttps,
				publishWithForcedHttpsPort: this.publishWithForcedHttpsPort,
				forceRedirectEnabled: this.forceRedirectEnabled,
				forceRedirectWww: this.forceRedirectWww,
				forceSlashes: this.forceSlashes,
				metaHtml: this.metaHtml,
				headSnippetsHtml: this.headSnippetsHtml,
				bodySnippetsHtml: this.bodySnippetsHtml,
				bodyStartSnippetsHtml: this.bodyStartSnippetsHtml,
				robotsTxtEnable: this.robotsTxtEnable,
				robotsTxt: this.robotsTxt,
				'lastDefLang': this.getLastDefLang(),
				'landing': this.landing,
				rtl: this.rtl,
				usedCustomFonts: usedCustomFonts,
				cookiePolicyEnabled: this.cookiePolicyEnabled,
				cookiePolicyFont: this.cookiePolicyFont,
				cookiePolicyFontSize: this.cookiePolicyFontSize,
				cookiePolicyMessage: this.cookiePolicyMessage,
				cookiePolicyButtonText: this.cookiePolicyButtonText,
				cookiePolicyBg: this.cookiePolicyBg,
				cookiePolicyMessageColor: this.cookiePolicyMessageColor,
				cookiePolicyButtonBg: this.cookiePolicyButtonBg,
				cookiePolicyButtonColor: this.cookiePolicyButtonColor
			},
			modes: modes,
			builderWidth: wb_builder.bodyInstance.siteWidth,
			renderMode: this.renderMode
		};
	};

	Site.prototype.updatePageList = function(list) {
		var i, c, pA, pB, k, cf, hasFront = false;
		if (list instanceof IdIndexedList) {
			for (i = 0, c = list.getItemCount(); i < c; i++) {
				pA = list.getItem(i);
				pB = this.getPage(pA.id);
				if (!pB) {
					cf = this.getPage((pA.copyFrom ? pA.copyFrom : wb_builder.pageId));
					pA.blocks = cf.blocks;
					pA.title = null;
					this.addPage((pB = new Site.Page(pA)));
				} else {
					pB.title = pA.title;
				}
				if (!hasFront && pA.isFront) {
					hasFront = true;
					pB.isFront = true;
				} else {
					pB.isFront = false;
				}
			}
			for (k in this.pages) {
				pA = this.pages[k];
				if (!list.getItemById(pA.id)) {
					this.removePage(pA);
				} else if (!hasFront) {
					hasFront = true;
					pA.isFront = true;
				}
			}
		}
		this.refreshAnchors();
	};
	
	Site.prototype.reloadPagesMiId = function(forceReloadAll) {
		for (var i in this.pages) {
			this.pages[i].reloadMiId(forceReloadAll);
		}
	};

	/**
	 * Get page by id
	 * @param {Number} id page id
	 */
	Site.prototype.getPage = function(id) {
		var _id = parseInt(id, 10);
		return this.pages["#" + _id] ? this.pages["#" + _id] : null;
	};

	/**
	 * Add page to this site
	 * @param {Site.Page} page page of type WB_Site.Page
	 */
	Site.prototype.addPage = function(page) {
		this.pages["#" + parseInt(page.id, 10)] = page;
		page.site = this;
		/* if (this.frontPage) {
			page.isFront = false;
		} else if (page.isFront) {
			this.frontPage = page;
		} */
		if (page.isFront)
			this.frontPage = page;
	};

	/**
	 * Add page to this site
	 * @param {Site.Page} page page of type WB_Site.Page
	 */
	Site.prototype.removePage = function(page) {
		// never allow to remove current page
		if (page && parseInt(page.id, 10) === parseInt(wb_builder.pageId, 10)) {
			if (Object.keys(this.pages).length === 1) page.isSingle = true;
			return;
		}
		this.pages["#" + parseInt(page.id, 10)] = null;
		delete this.pages["#" + parseInt(page.id, 10)];
		page.site = null;
		if (this.frontPage && parseInt(this.frontPage.id, 10) === parseInt(page.id, 10)) {
			this.frontPage = null;
		}
	};

	/**
	 * Get id for new page, that is not alredy taken
	 * @param {Object} more
	 * @return {Number} new id
	 */
	Site.prototype.getFreeId = function(more) {
		for (var i = 1; i < 5000; i++) {
			if (!this.pages["#" + i]) {
				if (!more || !more["#" + i]) return i;
			}
		}
		return 1;
	};
	
	Site.prototype.addAnchor = function(elem) {
		Site.AnchorUtil.addByElem(elem);
	};
	
	Site.prototype.removeAnchor = function(elem) {
		Site.AnchorUtil.removeByElem(elem);
	};
	
	Site.prototype.getAnchors = function(pageId, langCode) {
		return Site.AnchorUtil.getData(pageId, langCode);
	};
	
	Site.prototype.refreshAnchors = function() {
		Site.AnchorUtil.refreshData();
	};

	/**
	 * Update style
	 */
	Site.prototype.updateStyle = function() {
		if (!this.stylesElem) {
			this.stylesElem = $('<style type="text/css" id="wb_site_style_sheet"></style>');
			$("head").append(this.stylesElem);
			if (!window.createPopup) { /* For Safari */
				this.stylesElem.append(document.createTextNode(''));
			}
			this.stylesElem = null;
			for (var si = 1; si < document.styleSheets.length; si++) {
				var sheet = document.styleSheets[si];
				var sid = sheet.id ? sheet.id : (sheet.ownerNode ? sheet.ownerNode.id : null);
				if (sid === "wb_site_style_sheet") {
					this.stylesElem = sheet;
					break;
				}
			}
		}

		if (!this.stylesElem) return;
		var list = this.stylesElem.cssRules ? this.stylesElem.cssRules : this.stylesElem.rules;
		for (var i = (list.length - 1); i >= 0; i--) {
			try { this.stylesElem.deleteRule(i); } catch (ex) {}
		}
		var thisClass = this;
		var fixLocalUrls = function(rule) {
			return (/^(.*)url\(['"](gallery\/.+)['"]\)(.*)$/.test(rule))
					? RegExp.$1 + "url('" + wb_builder.makeLocalUrl(RegExp.$2) + "')" + RegExp.$3
					: rule;
		};
		var addCssRule = function(style) {
			var name = "#site " + style.selector;
			var name2 = "#WB_TextArea_maxCont " + style.selector;
			var name3 = ".wb-wysiwyg-control " + style.selector;
			var name4 = ".wb-element-preview " + style.selector;
			var rule_ = style.rules, rule__, m;
			if (typeof(rule_) === "object") {
				rule__ = $.extend({}, rule_);
				rule_ = [];
				for (var k in rule__) {
					if (style.tag === 'ul' && k === 'padding' && rule__[k]) {
						rule__[k] = rule__[k].replace(/^(\d+px\ \d+px\ \d+px\ )(\d+)(px)$/i, '$10$3');
					}
					rule_.push(k + ": " + thisClass._applyFontScale(k, rule__[k], style) + ";");
				}
				rule_ = rule_.join(" ");
			}
			rule_ = fixLocalUrls(rule_);
			if (thisClass.stylesElem.insertRule) {
				thisClass.stylesElem.insertRule(name + " { " + rule_ + " }", list.length);
				thisClass.stylesElem.insertRule(name2 + " { " + rule_ + " }", list.length);
				thisClass.stylesElem.insertRule(name3 + " { " + rule_ + " }", list.length);
				thisClass.stylesElem.insertRule(name4 + " { " + rule_ + " }", list.length);
			} else {
				thisClass.stylesElem.addRule(name, rule_);
				thisClass.stylesElem.addRule(name2, rule_);
				thisClass.stylesElem.addRule(name3, rule_);
				thisClass.stylesElem.addRule(name4, rule_);
			}
		};

		for (i = 0; i < this.styles.length; i++) {
			addCssRule(this.styles[i]);
			if (this.styles[i].subs) {
				for (var n = 0; n < this.styles[i].subs.length; n++) {
					this.styles[i].subs[n].fontScale = this.styles[i].fontScale;
					addCssRule(this.styles[i].subs[n]);
				}
			}
		}
		this.reloadCkIframeStyles();
	};

	Site.prototype._applyFontScale = function(key, value, style) {
		var valueApply = value, m, val;
		if (style.fontScale > 0 && style.fontScale !== 1/*  && !String(style.selector).match(/\.wb\-stl\-normal(?:\ .+|)/i) */) {
			if (key === 'font-size' || style.tag === 'ul' && key === 'width') {
				m = String(valueApply).match(/^([\-0-9]+)([a-z]+|)$/i);
				if (m) {
					val = Math.max(Math.round(parseInt(m[1], 10) * style.fontScale), 8);
					valueApply = String(val) + m[2];
				}
			} else if (key === 'font') {
				m = String(valueApply).match(/^(.+\ )([\-0-9]+)(px\ .+)$/i);
				if (m) {
					val = Math.max(Math.round(parseInt(m[2], 10) * style.fontScale), 8);
					valueApply = m[1] + String(val) + m[3];
				}
			} else if (key === 'line-height' || style.tag === 'ul' && key === 'height') {
				m = String(valueApply).match(/^([\-0-9]+)([a-z]+|)$/i);
				if (m) {
					val = Math.max(Math.round(parseInt(m[1], 10) * style.fontScale), 8);
					valueApply = String(val) + m[2];
				}
			}
		}
		return valueApply;
	};

	/**
	 * Reload styles in CKEditor iframe (Styles list now o_0)
	 */
	Site.prototype.reloadCkIframeStyles = function() {
		if (!$(".cke_panel_frame").length && !$(".cke_wysiwyg_frame").length)
			return false;
		var addCssRule = (function() {
			var addRule;

			if (typeof document.styleSheets !== "undefined" && document.styleSheets) {
				addRule = function(selector, rule, doc, el) {
					var sheets = doc.styleSheets, sheet;
					if (sheets && sheets.length) {
						sheet = sheets[sheets.length - 1];
						if (sheet.addRule) {
							sheet.addRule(selector, rule);
						} else if (typeof sheet.cssText === "string") {
							sheet.cssText = selector + " {" + rule + "}";
						} else if (sheet.insertRule && sheet.cssRules) {
							sheet.insertRule(selector + " {" + rule + "}", sheet.cssRules.length);
						}
					}
				};
			} else {
				addRule = function(selector, rule, doc, el) {
					el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
				};
			}

			return function(selector, rule, doc) {
				doc = doc || document;

				var head = doc.getElementsByTagName("head")[0];
				if (head && addRule) {
					var styleEl = doc.createElement("style");
					styleEl.type = "text/css";
					styleEl.media = "screen";
					head.appendChild(styleEl);
					addRule(selector, rule, doc, styleEl);
					styleEl = null;
				}
			};
		})();

		var i, dc = frames[frames.length - 1].document;
		for (i = 0; i < wb_builder.site.styles.length; i++) {
			var rule__, rule_ = wb_builder.site.styles[i].rules;
			if (typeof(rule_) === "object") {
				rule__ = $.extend({}, rule_);
				rule_ = [];
				for (var k in rule__) {
					rule_.push(k + ": " + rule__[k] + ";");
				}
				rule_ = rule_.join(" ");
			}
			addCssRule(wb_builder.site.styles[i].selector, rule_, dc);
			/*if (wb_builder.site.styles[i].subs) {
				for (var n = 0; n < wb_builder.site.styles[i].subs.length; n++) {
					addCssRule(wb_builder.site.styles[i].subs[n]);
				}
			}*/
		}
		return true;
	};

	/**
	 * Center popover
	 *
	 * @param el popover trigger element
	 */
	Site.prototype.centerPopover = function(el) {
		var pop = el.next(".popover");
		pop.css("left", el.position().left+el.width()/2-pop.width()/2);
	};

	Site.prototype.changeFavicon = function() {
		var thisClass = this;
		var fields = null;
		if (!this.faviconDlg) {
			this.faviconDlg = new Dialog(__("Change favicon"), null, new Service.UIBuilder({
				type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Favicon')},
					{type: 'ImageSelector', id: 'imageUrl', mode: 'favicon', multyselect: false, mediatabs: false},
					{type: 'CustomContainer', styleClass: 'alert alert-info',
						css: {marginTop: 15, marginBottom: 0},
						content:
							__("Supported image formats are PNG, JPEG, GIF and ICO.") +
							'<br />' +
							__("Internet Explorer browsers only support ICO format.") +
							'<br />' +
							__("When you are using ICO format, to see changes you might need to clear browser cache and even restart browser.")
					}
				]
			}));

			fields = this.faviconDlg.fields;

			this.faviconDlg.addButton(__("Cancel"));
			this.faviconDlg.addButton(__("Apply"), function() {
				thisClass.faviconDlg.hide();

				wb_builder.setPageModified(true);

				thisClass.favicon = fields.imageUrl.getValue();

			}, true);
		}
		fields = this.faviconDlg.fields;

		fields.imageUrl.setValue(this.favicon);

		this.faviconDlg.setVisible(true);
	};

	/**
	 * Show change site width dialog
	 * @param {Object} btn
	 */
	Site.prototype.changeSiteWidth = function(btn) {
		var panel = $('<div></div>');
		panel.css({ textAlign: "center" });

		var fields = {};

		panel.append(fields.width = $('<input type="text" class="span1" />'));
		fields.width.val(wb_builder.bodyInstance.siteWidth);

		panel.append("&nbsp;<span>px (1003 px " + __("Recomended") + ")</span>");

		var buttons = $('<div class="clearfix"></div>');
		panel.append(buttons);

		var btnSave = $('<button class="btn btn-success pull-right"></button>');
		btnSave.html(__("Apply"));
		btnSave.css({ marginLeft: "5px" });
		btnSave.bind("click", function() {
			btn.popover("hide");

			wb_builder.setPageModified(true);

			var val = fields.width.val()*1;
			wb_builder.bodyInstance.siteWidth = Math.round(isNaN(val) ? 1003 : val);
			wb_builder.bodyInstance.updateStyle();
			wb_builder.bodyInstance.fitElements();
			if (wb_builder.showLayout) wb_builder.highlightLayout(wb_builder.showLayout);

			panel.empty();
			btn.popover("destroy");
		});
		buttons.append(btnSave);

		var btnCancel = $('<button class="btn pull-right"></button>');
		btnCancel.html(__("Cancel"));
		btnCancel.bind("click", function() {
			btn.popover("hide");
			panel.empty();
			btn.popover("destroy");
		});
		buttons.append(btnCancel);

		btn.popover({
			html: true,
			title: __("Change site width"),
			content: function() { return panel; },
			trigger: "manual",
			placement: "bottom"
		});
		btn.popover("show");
		btn.next(".popover").width(300);
		this.centerPopover(btn);

	};

	/**
	 * Show change site/page SEO dialog
	 */
	Site.prototype.changeSiteSEO = function() {
		var thisClass = this;
		var fields = null;
		if (!this.siteSEODlg) {
			this.siteSEODlg = new Dialog(__("Search engine optimization"));
			this.siteSEODlg.setSize(684);
			this.siteSEODlg.setContent(new Service.UIBuilder({
				type: 'TabbedPane', tabs: [
					{children: [
						{type: 'HorizontalLayout', columnWeights: [5, 7], css: {marginTop: '20px'}, children: [
							{type: 'List', id: 'list',
								css: {height: 328},
								listHeight: 310,
								itemType: Service.menu.MenuItem,
								editable: false,
								init: function() {
									this.pages = {
										pages: {},
										addPage: function(page) {
											page.mis = {};
											page.addMi = function(mi) {
												this.mis["#" + mi.id] = mi;
											};
											page.getMis = function() {
												var list = [];
												for (var k in this.mis) { list.push(this.mis[k]); }
												return list;
											};
											this.pages["#" + page.id] = page;
										},
										removeAllPages: function() {
											this.pages = {};
										},
										getPage: function(pageId) {
											return this.pages["#" + pageId] ? this.pages["#" + pageId] : null;
										}
									};
									this.setAliasSlashVisible = function(fields, visible) {
										var ml = (wb_builder.site.languages.length > 0);
										var dl = wb_builder.site.getLastDefLang();
										fields.alias.getInputs().each(function() {
											var langCode = $(this).parent().children('span').text().toLowerCase();
											$(this).parent().find('i').text((visible ? (((ml && langCode !== dl) ? '/' + langCode : '') + '/') : ''));
											$(this).css('padding-left', ((ml && langCode !== dl) ? 40 : 20) + 'px');
										});
									};
								},
								select: function(fields, item) {
									var p, selected = fields.list.getLastSelected();
									if (selected && selected.type !== "external") {
										if (fields.list.getLastSelected().type === "default") {
											fields.defaultInf.title = fields.title.getValue();
											fields.defaultInf.keywords = fields.keywords.getValue();
											fields.defaultInf.description = fields.description.getValue();
											fields.defaultInf.image = fields.image.getValue();
										} else {
											p = fields.list.pages.getPage(fields.list.getLastSelected().targetId);
											if (p) {
												p.alias = fields.alias.getValue();
												p.title = fields.title.getValue();
												p.keywords = fields.keywords.getValue();
												p.description = fields.description.getValue();
												p.image = fields.image.getValue();
												p.addMi(item);
											}
										}
									}
									if (item.type === "default") {
										fields.aliasBlock.setVisible(false);
										fields.imageBlock.setVisible(true);
										fields.title.setValue(fields.defaultInf.title);
										fields.keywords.setValue(fields.defaultInf.keywords);
										fields.description.setValue(fields.defaultInf.description);
										fields.image.setValue(fields.defaultInf.image);
										fields.title.setEnabled(true);
										fields.keywords.setEnabled(true);
										fields.description.setEnabled(true);
									} else if (item.type !== "external" && item.type !== "anchor" && item.type !== "empty") {
										p = fields.list.pages.getPage(item.targetId);
										if (p) {
											var menu = item.menuUID ? Service.menu.getMenuByUID(item.menuUID) : null;
											var isHome = p.isFront;
											var aliasAllowed = (menu && menu.landing || !isHome);
											fields.alias.setValue((aliasAllowed ? (p.alias ? p.alias : item.alias) : ''));
											fields.alias.setPlaceholder((!isHome ? __trf(item.name, window.sanitizeAlias) : null), true);
											fields.alias.setEnabled(aliasAllowed);
											this.setAliasSlashVisible(fields, true);
											fields.aliasBlock.setVisible(true);
											fields.imageBlock.setVisible(true);
											fields.title.setValue(p.title);
											fields.title.setPlaceholder(item.name, true);
											fields.keywords.setValue(p.keywords);
											fields.description.setValue(p.description);
											fields.image.setValue(p.image);
											fields.title.setEnabled(true);
											fields.keywords.setEnabled(true);
											fields.description.setEnabled(true);
										}
									} else {
										fields.alias.setValue("");
										fields.alias.setEnabled(false);
										fields.alias.setPlaceholder(null, true);
										this.setAliasSlashVisible(fields, false);
										fields.aliasBlock.setVisible(true);
										fields.imageBlock.setVisible(false);
										fields.title.setValue("");
										fields.keywords.setValue("");
										fields.description.setValue("");
										fields.image.setValue(null);
										fields.title.setEnabled(false);
										fields.keywords.setEnabled(false);
										fields.description.setEnabled(false);
									}
								}
							},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Title'),
									helpText: __("Title is critical to giving users a quick insight into the content of a result and why it's relevant to their query. It's often the primary piece of information used to decide which result to click on.")
								},
								{type: 'MultilangTextField', id: 'title'},
								{type: 'Label', text: __('Description'),
									css: {marginTop: 10},
									helpText: __("The description attribute is a good way to provide a concise, human-readable summary of each page's content. Accurate meta descriptions can help improve your clickthrough.")
								},
								{type: 'MultilangTextField', id: 'description', textArea: true},
								{type: 'Label', text: __('Keywords'),
									css: {marginTop: 10},
									helpText: __("Keywords are words or phrases your target audience would type in the search box when looking for the subject of your web page.")
								},
								{type: 'MultilangTextField', id: 'keywords', textArea: true},
								{type: 'VerticalLayout', id: 'aliasBlock', children: [
									{type: 'Label', text: __('User friendly URL'),
										css: {marginTop: 10},
										// helpText: __("URLs should be constructed in a manner that is most intelligible and friendly to humans (when possible, readable words rather than long ID numbers).")
										helpText: __('This is an alias for the page. For example if you specify value "apple" then this website page will have URL "yourwebsite.com/apple".')
									},
									{type: 'MultilangTextField', id: 'alias', onChange: function(e, value, langCode) {
										if (!value) return;
										value = value.replace(/(?:http|https):\/\//i, '');
										var parts = value.split('/');
										if ((0 in parts) && parts[0].indexOf('.') > -1) {
											parts.shift();
											value = WB_Builder.trim(parts.join('/'), '/');
										}
										fields.alias.setText(value, langCode, true);
										for (var i in fields.list.pages.pages) {
											var page = fields.list.pages.pages[i];
											if (fields.list.getLastSelected().targetId === page.id) continue;
											if (value && __tr(page.alias, langCode) === value) {
												var mi = Service.menu.getMenuItemById(page.miId);
												var miName = mi ? __tr(mi.name, '__DEFAULT__', null, true, true)
														: __tr(page.title, '__DEFAULT__', null, true, true);
												alert(__("The value \"%s\" is already assigned to page \"%s\"")
													.replace('%s', value)
													.replace('%s', miName));
												fields.alias.setText("", langCode);
												return;
											}
										}
									}, onReload: function() {
										this.elem.find('.__alias__').remove();
										this.getInputs().each(function() {
											var prefix = $('<i class="__alias__">').css({
												fontStyle: 'normal', position: 'absolute', left: 12, top: 0, lineHeight: '34px', zIndex: 3, color: '#999'
											});
											$(this).parent().append(prefix);
										});
									}}
								]},
								{type: 'VerticalLayout', id: 'imageBlock', children: [
										{type: 'Label', text: __('Image'), css: {marginTop: 10}, helpText: __('Unique image representing the content of the page. It will be used by social graphs like Facebook Open Graph and Twitter Cards when the page is liked or shared.')},
										{type: 'ImageSelector', id: 'image'}
								]}
							]}
						]}
					]},
					{name: __('Analytics'), children: [
						{type: 'VerticalLayout', css: {marginTop: '20px'}, children: [
							{type: 'Label', text: __('Google Analytics Tracking ID'),
								helpText: __("Create google analytics profile on google analytics page for your website and paste profile ID hare (ex. UA-38401376-1)")
							},
							{type: 'TextField', id: 'analyticsId'},
							{type: 'CheckBox', css: {marginTop: 5}, label: __('Anonymize IP'), id: 'anonymizeIp', helpText: __('Click for more information') + ':' + '<br /><a style="display: inline-block; max-width: 100%; word-break: break-all;" href="https://support.google.com/analytics/answer/2763052" target="_blank">https://support.google.com/analytics/answer/2763052</a>'},
							{type: 'Label', text: __('Google Webmaster Tools Code'),
								css: {marginTop: '15px'},
								helpText: __('In "Webmaster Tools" verification page choose "Alternative methods" > "HTML tag" and copy that tag to this field.')
							},
							{type: 'TextField', id: 'webmasterId'},
							{type: 'Label', text: __('Sitemap URL'),
								css: {marginTop: '15px'},
								helpText: __('You can submit this URL as a sitemap to Google Webmaster Tools.')
							},
							{type: 'CustomContainer', tag: 'pre', id: 'sitemapUrl',
								content: wb_builder.meta.sitemapUrl,
								css: {padding: '4px 6px'},
								init: function() { this.setValue = function(val) { this.getElem().text(val); }; }
							}
						]}
					]}
				]
			}, this.siteSEODlg.fields), true);
			this.siteSEODlg.setMinBodyHeight(444);
			fields = this.siteSEODlg.fields;

			this.siteSEODlg.addButton(__("Cancel"));
			this.siteSEODlg.addButton(__("Apply"), function() {
				thisClass.siteSEODlg.hide();

				wb_builder.setPageModified(true);

				fields.list.selectFirst();
				for (var k in fields.list.pages.pages) {
					var p_ = fields.list.pages.pages[k];
					if (p_.type !== "external") {
						var p = thisClass.getPage(p_.id);
						if (p) {
							p.alias = p_.alias;
							p.title = p_.title;
							p.keywords = p_.keywords;
							p.description = p_.description;
							p.image = p_.image;
							var mis = p_.getMis();
							for (var i = 0; i < mis.length; i++) {
								mis[i].alias = p_.alias;
							}
						}
					}
				}
				wb_builder.meta.title = fields.defaultInf.title;
				wb_builder.meta.keywords = fields.defaultInf.keywords;
				wb_builder.meta.description = fields.defaultInf.description;
				wb_builder.meta.image = fields.defaultInf.image;

				thisClass.analyticsId = fields.analyticsId.getValue();
				thisClass.anonymizeIp = fields.anonymizeIp.getValue();
				thisClass.webmasterId = fields.webmasterId.getValue();
				var m = thisClass.webmasterId.match(/<meta[^>]+content="([^"]+)"[^>]+>/i);
				if (m) {
					thisClass.webmasterId = m[1];
				}
			}, true);
		}
		fields = this.siteSEODlg.fields;

		var p = this.getPage(wb_builder.pageId);
		if (p) {
			fields.alias.setValue(p.alias);
			fields.title.setValue(p.title);
			fields.keywords.setValue(p.keywords);
			fields.description.setValue(p.description);
			fields.image.setValue(p.image);
			//this.siteSEODlg.setTitle(__('SEO for page "%s"').replace("%s", p.title));
		}
		var k, wasSelected = false, wasSelectedItem = null;
		fields.list.removeAllItems();
		fields.list.addItem(fields.defaultInf = {
			id: -1,
			type: "default",
			name: __("Default (for all pages)"),
			title: wb_builder.meta.title,
			keywords: wb_builder.meta.keywords,
			description: wb_builder.meta.description,
			image: wb_builder.meta.image,
			serialize: function() { return this; }
		}, false, 'glyphicon glyphicon-folder-open');
		
		var menuList = MenuList.buildMenuStruct(false, true);
		var first = true;
		for (var i = 0; i < menuList.length; i++) {
			var menu = menuList[i];
			if (first) first = false; else fields.list.addSeparator();
			for (var n = 0; n < menu.items.length; n++) {
				var mi = menu.items[n];
				if (!mi.miElem) continue;
				
				var page = (mi.targetId && (('#' + mi.pageId) in wb_builder.site.pages)) ? wb_builder.site.pages['#' + mi.pageId] : null;
				var icon = (mi.type === "external" || mi.type === "internal" || mi.type === "anchor" || mi.type === "empty")
					? "glyphicon glyphicon-share-alt"
					: ((page && page.isFront) ? "glyphicon glyphicon-home" : "glyphicon glyphicon-folder-open");
				var hmi = fields.list.addItem(mi.miElem, false, icon);
				var marginLeft = 20; 
				var identIdx = mi.lvl; while (identIdx > 0) { identIdx--; marginLeft += 20; }
				hmi.css({ marginLeft: marginLeft + "px" });
				if (!wasSelected && mi.type !== "external" && mi.pageId == wb_builder.pageId) {
					wasSelected = true;
					wasSelectedItem = hmi;
				}
			}
		}
		
		fields.list.pages.removeAllPages();
		for (k in this.pages) { fields.list.pages.addPage(this.pages[k].serialize()); }

		if (!wasSelected) fields.list.selectFirst(); else if (wasSelectedItem) wasSelectedItem.trigger('click');

		fields.analyticsId.setValue(this.analyticsId);
		fields.anonymizeIp.setValue(this.anonymizeIp);
		fields.webmasterId.setValue(this.webmasterId);
		fields.sitemapUrl.setValue(('' + wb_builder.meta.sitemapUrl).replace(/^(?:http|https):\/\//, this.publishWithForcedHttps ? 'https://' : 'http://'));

		this.siteSEODlg.setVisible(true);
	};

	/**
	 * Toggle site landing
	 * @param {Boolean} landing
	 * @param {Boolean} initial
	 */
	Site.prototype.setLanding = function(landing, initial) {
		if (!initial) wb_builder.setPageModified(true);
		this.landing = landing ? true : false;
		var i, len, menuList = Service.menu.getElemList(true);
		for (i in this.pages) { this.pages[i].setLanding(false); }
		for (i in menuList) { menuList[i].setLanding(false); }
		wb_builder.bodyInstance.setLandingLock(false);

		if (this.landing) {
			var homepage = null;
			for (i in this.pages) {
				if (this.pages[i].isFront) { homepage = this.pages[i]; break; }
			}
			if (homepage) {
				var landingMenu, page;
				mainLoop: for (i in menuList) {
					var menuStructList = MenuList.buildMenuStruct(false, false, menuList[i]);
					for (var ii = 0; ii < menuStructList.length; ii++) {
						var menu = menuStructList[ii];
						for (var n = 0; n < menu.items.length; n++) {
							var mi = menu.items[n];
							if (!landingMenu && mi.type === 'page' && mi.pageId === homepage.id) {
								menu.menuElem.setLanding(true);
								landingMenu = menu.menuElem;
								break mainLoop;
							}
						}
					}
				}
				if (landingMenu) {
					var pageIds = [], order = 0;
					var menuStructList = MenuList.buildMenuStruct(false, false, landingMenu);
					for (var ii = 0; ii < menuStructList.length; ii++) {
						var menu = menuStructList[ii];
						for (var n = 0; n < menu.items.length; n++) {
							var mi = menu.items[n];
							if (mi.type === 'page' && mi.pageId) pageIds.push(mi.pageId);
						}
					}
					
					for (i=0, len=pageIds.length; i < len; i++) {
						page = this.getPage(pageIds[i]);
						if (page) {
							page.setLanding(true, (++order));
							if (page.id === wb_builder.pageId && !page.isFront) wb_builder.bodyInstance.setLandingLock(true);
						}
					}
				}
			}
		}
		wb_builder.layoutManager.setPageSwitchesEnabled(this.landing);
		BuilderEvent.GlobalEvents.triggerEvent(
			'pages.changed',
			new BuilderEvent.PagesChangedEvent()
		);
		BuilderEvent.GlobalEvents.triggerEvent(
			"landing.changed",
			new BuilderEvent.LandingChangedBuilderEvent(this.landing)
		);
	};

	/**
	 * Change background of site or page block
	 * @param block
	 * @return Dialog
	 */
	Site.prototype.changeBackground = function(block) {
		var thisClass = this;
		var fields = null;
		var currMode = ModeManager.getMode();
		var page, getRawOrModeHeight = function(block) {
			if ((typeof block !== 'object') || !block) return null;
			if (Service.modeManager.getUseModes()) {
				if (currMode && ('modes' in block) && (typeof block.modes === 'object') && block.modes
						&& (currMode in block.modes) && (typeof block.modes[currMode] === 'object')
						&& block.modes[currMode]
						&& ('height' in block.modes[currMode]) && block.modes[currMode].height) {
					return block.modes[currMode].height;
				}
			}
			return (('height' in block) && block.height) ? block.height : null;
		};
		var blocksData = wb_builder.bodyInstance.blocksData, v;
		//initial data
		var data = {
			defBlock: {
				top: {
					background: (blocksData.wb_header ? blocksData.wb_header.background : null),
					prop: ((v = getRawOrModeHeight(blocksData.wb_header)) ? v : wb_builder.bodyInstance.blocks.wb_header.height),
					fixedPos: this.defFixedHeader,
					noPageBg: this.defNoPageBg,
					useDefault: (blocksData.wb_header ? blocksData.wb_header.useDefault : false)
				},
				middle: {
					background: (blocksData.wb_main ? blocksData.wb_main.background : null),
					prop: (blocksData.wb_main ? blocksData.wb_main.blockPadding : wb_builder.bodyInstance.blocks.wb_main.blockPadding),
					useDefault: (blocksData.wb_main ? blocksData.wb_main.useDefault : false)
				},
				bottom : {
					background: (blocksData.wb_footer ? blocksData.wb_footer.background : null),
					prop: ((v = getRawOrModeHeight(blocksData.wb_footer)) ? v : wb_builder.bodyInstance.blocks.wb_footer.height),
					useDefault: (blocksData.wb_footer ? blocksData.wb_footer.useDefault : false)
				},
				template: {
					background : wb_builder.bodyInstance.bgSite,
					background2 : wb_builder.bodyInstance.bg2Site
				}
			},
			page: null,
			pages: {}
		};
		data.rd = false;
		
		for (var key in this.pages) {
			page = this.pages[key];
			data.pages[page.id] = {
				top : {
					background: (page.blocks.wb_header ? page.blocks.wb_header.background : null),
					prop: getRawOrModeHeight(page.blocks.wb_header),
					fixedPos: page.fixedHeader,
					noPageBg: page.noPageBg
				},
				middle : {
					background: (page.blocks.wb_main ? page.blocks.wb_main.background : null),
					prop: (page.blocks.wb_main ? page.blocks.wb_main.blockPadding : null)
				},
				bottom : {
					background: (page.blocks.wb_footer ? page.blocks.wb_footer.background : null),
					prop: getRawOrModeHeight(page.blocks.wb_footer)
				},
				template : {
					background: page.background,
					background2: page.background2
				}
			};
		}
		/* page = thisClass.getPage(wb_builder.pageId);
		data.pages[wb_builder.pageId] = {
			top : {
				background: wb_builder.bodyInstance.blocks.wb_header.background,
				prop: wb_builder.bodyInstance.blocks.wb_header.elem.height(),
				fixedPos: page.fixedHeader,
				noPageBg: page.noPageBg
			},
			middle : {
				background: wb_builder.bodyInstance.blocks.wb_main.background,
				prop: wb_builder.bodyInstance.blocks.wb_main.blockPadding
			},
			bottom : {
				background: wb_builder.bodyInstance.blocks.wb_footer.background,
				prop: wb_builder.bodyInstance.blocks.wb_footer.elem.height()
			},
			template : {
				background: page.background,
				background2: page.background2
			}
		}; */
		if (!this.changeBgDlg) {
			this.changeBgDlg = new Dialog(__("Properties"));
			this.changeBgDlg.setSize(866, null);
			this.changeBgDlg.setMinBodyHeight(300);
//			this.changeBgDlg.setMaxBodyHeight(490);
			fields = this.changeBgDlg.fields;
			fields.data = data;
			fields.pages = {
				pages: {},
				addPage: function(page) {
					page.mis = {};
					page.addMi = function(mi) {
						this.mis["#" + mi.id] = mi;
					};
					page.getMis = function() {
						var list = [];
						for (var k in this.mis) { list.push(this.mis[k]); }
						return list;
					};
					this.pages["#" + page.id] = page;
				},
				removeAllPages: function() {
					this.pages = {};
				},
				getPage: function(pageId) {
					return this.pages["#" + pageId] ? this.pages["#" + pageId] : null;
				}
			};

			this.changeBgDlg.setContent(new Service.UIBuilder({
				type: 'HorizontalLayout', columnWeights: [4, 8], children: [
					{type: 'List', id: 'list',
						itemType: Service.menu.MenuItem,
						editable: false,
						init: function(def, fields) {
							this._control.setHeight(300);
							this.updateListIcon = function(item, li) {
								var isSet = false;
								var obj = (item.type !== "external" && item.targetId) ? fields.data.pages[item.targetId] : fields.data.defBlock;
								for (var blockId in obj) {
									var block = obj[blockId];
									if (BackgroundControl.isSet(block.background) || BackgroundControl.isSet(block.background2)) {
										isSet = true;
										break;
									}
								}
								fields.list.setItemIcon(li, (item.type === 'internal' || item.type === 'external' || item.type === 'anchor' || item.type === 'empty') ? "glyphicon glyphicon-share-alt"
										: "glyphicon glyphicon-folder" + (isSet ? "-close" : "-open"));
							};
						},
						select: function(fields, item, li) {
							if (fields.list.getLastSelected()) this.updateListIcon(fields.list.getLastSelected(), fields.list.getLastSelectedLi());
							this.updateListIcon(item, li);
							fields.data.page = (item.type !== 'external' && item.targetId) ? item.targetId : null;
							fields.layoutBlocks.onChange();
						},
						add: function(fields, item, li) {
							this.updateListIcon(item, li);
						}
					},
					{type: 'VerticalLayout', children: [
						{type: 'FlowLayout', children: [
							{type: 'LayoutBlocksControl', id: 'layoutBlocks',
								init: function() {
									this.nt = {
										'template' : __("Site Background"),
										'ptemplate' : __("Page Background"),
										'top' : __("Header Background"),
										'middle' : __("Body Background"),
										'bottom' : __("Footer Background")
									};
									this.pt = {
										'template' : __("Template Width"),
										'top' : __("Header Height"),
										'middle' : __("Body Bottom Padding"),
										'bottom' : __("Footer Height")
									};
								},
								change: function(fields) {
									var b = fields.layoutBlocks.getValue();
									var rn = (fields.data.page && b === "template") ? "ptemplate" : b;
									fields.mainTitle.setText(this.nt[rn]);
									var blocks = this.getBlocks(), blockIdx;
									var defaultPropsUsed = (fields.data.page && fields.data.defBlock[b].useDefault);

									var obj = fields.data.page ? fields.data.pages[fields.data.page] : fields.data.defBlock;
									fields.bgPage.setValue(obj[b].background);
									if (b === 'template') {
										fields.bg2Page.setValue(obj[b].background2);
									} else {
										fields.prop.setValue(defaultPropsUsed ? fields.data.defBlock[b].prop : obj[b].prop);
									}
									for (blockIdx in blocks) {
										var block = blocks[blockIdx];
										var val = false;
										if (obj[block]) {
											val = BackgroundControl.isSet(obj[block].background);
											if (!val && block === 'template' && BackgroundControl.isSet(obj[block].background2)) {
												val = true;
											}
										}
										this.setIsSet(val, block);
									}
									
									fields.prop.setEnabled(!defaultPropsUsed);
									fields.fixedPosCb.setEnabled(!defaultPropsUsed);
									fields.noPageBg.setEnabled(!defaultPropsUsed);
									fields.prop.setValue(defaultPropsUsed ? fields.data.defBlock[b].prop : obj[b].prop);
									if (b === 'top') {
										fields.fixedPosCb.setValue(defaultPropsUsed ? fields.data.defBlock[b].fixedPos : obj[b].fixedPos);
										fields.noPageBg.setValue(defaultPropsUsed ? fields.data.defBlock[b].noPageBg : obj[b].noPageBg);
									} else {
										fields.fixedPosCb.setValue(false);
										fields.noPageBg.setValue(false);
									}
									if (defaultPropsUsed) {
										fields.prop.setTooltip(__('Default value is used'), 'top', 'click');
										fields.fixedPosCb.setTooltip(__('Default value is used'), 'top', 'click');
										fields.noPageBg.setTooltip(__('Default value is used'), 'top', 'click');
									} else {
										fields.prop.setTooltip(false);
										fields.fixedPosCb.setTooltip(false);
										fields.noPageBg.setTooltip(false);
									}
									
									if (b === 'top') {
										setTimeout(function() {
											var item = fields.list.getLastSelected();
											var menu = (item && item.menuUID) ? Service.menu.getMenuByUID(item.menuUID) : null;
											var landing = (menu && menu.landing);
											var checked = (landing || (defaultPropsUsed ? fields.data.defBlock && fields.data.defBlock[b].fixedPos : obj && obj[b].fixedPos));
											fields.fixedPosCb.setValue(checked);
											fields.fixedPosCb.setEnabled(!landing && !defaultPropsUsed);
											if (landing) {
												fields.fixedPosCb.setTooltip(__('Always checked if %s mode is turned on').replace('%s', __('Landing')), 'top', 'click');
											} else if (!defaultPropsUsed) {
												fields.fixedPosCb.setTooltip(false);
											}
											fields.noPageBg.setVisible(checked);
										}, 10);
										fields.fixedPosCb.setVisible(true);
									}
									else {
										fields.fixedPosCb.setVisible(false);
										fields.noPageBg.setVisible(false);
									}
									
									if (b === 'template') {
										fields.bgPage.setOption("useAttachment", true);
										fields.bgPage.setOption("useFullWidth", false);
										if (fields.bg2Page.isSet()) {
											fields.moreLine.setVisible(false);
											fields.moreInfo.setVisible(true);
										} else {
											fields.moreLine.setVisible(true);
											fields.moreInfo.setVisible(false);
										}
										fields.propControl.setVisible(false);
										fields.useDefault.setValue(false);
									} else {
										fields.bgPage.setOption("useAttachment", false);
										fields.bgPage.setOption("useFullWidth", true);
										fields.moreLine.setVisible(false);
										fields.moreInfo.setVisible(false);
										fields.propControl.setVisible(true);
										fields.useDefault.setValue(fields.data.defBlock[b].useDefault);
									}
									fields.bgPage.setOption("useFullWidth", (b === 'top' || b === 'middle' || b === 'bottom'));
									fields.propLabel.setText(this.pt[b]);
									fields.useDefault.setVisible((b !== 'template' && !fields.data.page));
								}
							},
							{type: 'VerticalLayout', css: {maxWidth: 360},
								children: [
									{type: 'Label', id: 'mainTitle', text: __('Site Background')},
									//new BackgroundControl(false, {image:0, position:1, repeat:2, color:3}, '<table><tr><td></td><td></td><td></td></tr><tr><td colspan="3" style="padding-top:15px;"></td></tr></table>');
									{type: 'BackgroundSelector', id: 'bgPage', useAttachment: true, useSize: true, useFullWidth: true,
										change: function(fields) {
											if (this.t1) clearTimeout(this.t1);
											this.t1 = setTimeout(function() {
												var obj = fields.data.page ? fields.data.pages[fields.data.page] : fields.data.defBlock;
												var b = fields.layoutBlocks.getValue();
												obj[b].background = fields.bgPage.getValue();
											}, 50);
											Service.HelpSystemPlayer.notify('config-background-prop-bgPage-change', thisClass.changeBgDlg);
										}
									}
								]
							}
						]},
						{type: 'FlowLayout', id: 'propControl',
							verticalAlign: 'middle',
							css: {marginTop: 15},
							children: [
								{type: 'Label', id: 'propLabel', text: __('Template Width')},
								{type: 'SizeSelector', id: 'prop', min: 0,
									css: {marginBottom: 5},
									change: function(fields) {
//										if (this.t3) clearTimeout(this.t3);
//										this.t3 = setTimeout(function() {
											var obj = fields.data.page ? fields.data.pages[fields.data.page] : fields.data.defBlock;
											var b = fields.layoutBlocks.getValue();
											if (b !== 'template') {
												obj[b].prop = fields.prop.getValue();
											}
//										}, 50);
									}
								},
								{type: 'CheckBox', id: 'fixedPosCb',
									label: __("Sticky"),
									helpText: __('If checked header will be fixed on top when scrolling page'),
									css: {marginBottom: 5},
									change: function(fields) {
										var b = fields.layoutBlocks.getValue();
										var checked = fields.fixedPosCb.getValue();
										if (b === 'top') {
											var obj = fields.data.page ? fields.data.pages[fields.data.page] : fields.data.defBlock;
											obj[b].fixedPos = checked;
										}
										if (checked) {
											fields.noPageBg.setVisible(true);
										} else {
											fields.noPageBg.setVisible(false);
										}
									}
								},
								{type: 'CheckBox', id: 'noPageBg',
									label: __("No page background"),
									helpText: __('If checked page background will not be applied to header'),
									css: {marginBottom: 5},
									change: function(fields) {
										var obj = fields.data.page ? fields.data.pages[fields.data.page] : fields.data.defBlock;
										var b = fields.layoutBlocks.getValue();
										if (b === 'top')
											obj[b].noPageBg = fields.noPageBg.getValue();
									}
								}
							]
						},
						{type: 'CheckBox', id: 'useDefault',
							label: __('Apply to all pages'),
							css: {marginBottom: 5},
							change: function(fields) {
								var b = fields.layoutBlocks.getValue();
								if (b !== 'template')
									fields.data.defBlock[b].useDefault = this.getValue();
							}
						},
						{type: 'Button', id: 'moreLine', buttonStyle: UIButton.UIButton.STYLE_LINK,
							styleClass: 'more-line',
							text: __('Add other Background over this?'),
							click: function() {
								this.setVisible(false);
								fields.moreInfo.setVisible(true);
								return false;
							}
						},
						{type: 'VerticalLayout', id: 'moreInfo',
							css: {marginTop: 15},
							children: [
								{type: 'Label', text: __('Secondary background')},
								//new BackgroundControl(false, {image:0, position:1, repeat:2, color:3}, '<table><tr><td></td><td></td><td></td><td style="padding-left:20px;"></td></tr></table>'))
								{type: 'BackgroundSelector', id: 'bg2Page',
									change: function(fields) {
										if (this.t2) clearTimeout(this.t2);
										this.t2 = setTimeout(function() {
											var obj = fields.data.page ? fields.data.pages[fields.data.page] : fields.data.defBlock;
											var b = fields.layoutBlocks.getValue();
											if (b === 'template')
												obj[b].background2 = fields.bg2Page.getValue();
										}, 50);
									}
								}
							]
						}
					]}
				]
			}, fields), true);

			this.changeBgDlg.addButton(__("Cancel"));
			this.changeBgDlg.addButton(__("Apply"), function() {
				thisClass.changeBgDlg.hide();

				wb_builder.bodyInstance.bgSite = fields.data.defBlock.template.background;
				wb_builder.bodyInstance.bg2Site = fields.data.defBlock.template.background2;
//				var val = fields.data.body.width*1;
//				wb_builder.bodyInstance.siteWidth = Math.round(isNaN(val) ? 1003 : val);

				var currMode = ModeManager.getMode();
				var buildModes = function(data) {
					var modes = {};
					modes[currMode] = data;
					return modes;
				};
				var updateModes = function(cont, data) {
					if (!cont.modes) cont.modes = {};
					cont.modes[currMode] = data;
				};
				var buildBlockOriginal = function(cont) {
					if ((typeof cont === 'object') && cont) {
						if (('blocksData' in cont) && (typeof cont.blocksData === 'object') && cont.blocksData)
							return cont.blocksData;
						else if (('blocks' in cont) && (typeof cont.blocks === 'object') && cont.blocks)
							return cont.blocks;
					}
					return {};
				};
				var buildBlocksData = function(data, cont) {
					if ((typeof data === 'object') && data && Service.modeManager.getUseModes()) {
						var k, ori = buildBlockOriginal(cont);
						for (k in data) {
							if ((k in ori) && (typeof ori[k] === 'object') && ori[k] && ('modes' in ori[k])
									&& (typeof ori[k].modes === 'object') && ori[k].modes) {
								if (('modes' in data[k]) && (typeof data[k].modes === 'object') && data[k].modes) {
									data[k].modes = $.extend(true, ori[k].modes, data[k].modes);
								} else {
									data[k].modes = ori[k].modes;
								}
							}
						}
					}
					return data;
				};
				var buildBlockHeight = function(value, block, cont) {
					var ori = buildBlockOriginal(cont);
					if (Service.modeManager.getUseModes()
							&& (block in ori) && (typeof ori[block] === 'object') && ori[block]) {
						if (('height' in ori[block]) && ori[block].height) {
							return ori[block].height;
						} else if (('modes' in ori[block]) && (typeof ori[block].modes === 'object')
								&& ori[block].modes && (currMode in ori[block].modes)
								&& (typeof ori[block].modes[currMode] === 'object') && ori[block].modes[currMode]
								&& ('height' in ori[block].modes[currMode]) && ori[block].modes[currMode].height) {
							return ori[block].modes[currMode].height;
						}
					}
					return value;
				};
				
				if (!wb_builder.bodyInstance.blocksData) 
					wb_builder.bodyInstance.blocksData = {};
				var blocksData = wb_builder.bodyInstance.blocksData;
				var blocks = wb_builder.bodyInstance.blocks;
				
				if (!blocksData.wb_header) blocksData.wb_header = {};
				blocksData.wb_header.background = fields.data.defBlock.top.background;
				blocksData.wb_header.height = buildBlockHeight((fields.data.defBlock.top.prop ? fields.data.defBlock.top.prop : 0), 'wb_header', wb_builder.bodyInstance.blocksData);
				updateModes(blocksData.wb_header, {height: (fields.data.defBlock.top.prop ? fields.data.defBlock.top.prop : 0)});
				blocksData.wb_header.useDefault = fields.data.defBlock.top.useDefault;
				
				if (!blocksData.wb_main) blocksData.wb_main = {};
				blocksData.wb_main.background = fields.data.defBlock.middle.background;
				blocksData.wb_main.blockPadding = (fields.data.defBlock.middle.prop ? fields.data.defBlock.middle.prop : 0);
				blocksData.wb_main.useDefault = fields.data.defBlock.middle.useDefault;
				
				if (!blocksData.wb_footer) blocksData.wb_footer = {};
				blocksData.wb_footer.background = fields.data.defBlock.bottom.background;
				blocksData.wb_footer.height = buildBlockHeight((fields.data.defBlock.bottom.prop ? fields.data.defBlock.bottom.prop : 0), 'wb_footer', wb_builder.bodyInstance.blocksData);
				updateModes(blocksData.wb_footer, {height: (fields.data.defBlock.bottom.prop ? fields.data.defBlock.bottom.prop : 0)});
				blocksData.wb_footer.useDefault = fields.data.defBlock.bottom.useDefault;
				
				thisClass.defFixedHeader = fields.data.defBlock.top.fixedPos;
				thisClass.defNoPageBg = fields.data.defBlock.top.fixedPos;

				$.each(fields.data.pages, function(i, pd) {
					var p = thisClass.getPage(i);
					if (p) {
						p.background = pd.template.background;
						p.background2 = pd.template.background2;
						if (parseInt(i, 10) === wb_builder.pageId) {
							blocks.wb_header.background = pd.top.background;
							blocks.wb_header.setSize(null, (blocksData.wb_header.useDefault ? blocksData.wb_header.height : pd.top.prop));

							blocks.wb_main.background = pd.middle.background;
							blocks.wb_main.blockPadding = pd.middle.prop;

							blocks.wb_footer.background = pd.bottom.background;
							blocks.wb_footer.setSize(null, (blocksData.wb_footer.useDefault ? blocksData.wb_footer.height : pd.bottom.prop));

							for (var blockId in blocks) {
								blocks[blockId].updateStyle();
								blocks[blockId].updateSize();
							}
						}
						
						p.blocks = buildBlocksData({
							wb_header: {
								background: pd.top.background,
								height: buildBlockHeight(pd.top.prop, 'wb_header', p),
								modes: buildModes({height: pd.top.prop})
							},
							wb_main: {
								background: pd.middle.background,
								blockPadding: pd.middle.prop
							},
							wb_footer: {
								background: pd.bottom.background,
								height: buildBlockHeight(pd.bottom.prop, 'wb_footer', p),
								modes: buildModes({height: pd.bottom.prop})
							}
						}, p);
						p.fixedHeader = pd.top.fixedPos;
						p.noPageBg = pd.top.noPageBg;
						
						wb_builder.pageBlocksData['#' + i] = {blocks: buildBlocksData({
							wb_header: {
								content: {
									background: pd.top.background
								},
								height: buildBlockHeight(pd.top.prop, 'wb_header', p),
								modes: buildModes({height: pd.top.prop})
							},
							wb_main: {
								content: {
									background: pd.middle.background,
									blockPadding: pd.middle.prop
								}
							},
							wb_footer: {
								content: {
									background: pd.bottom.background
								},
								height: buildBlockHeight(pd.bottom.prop, 'wb_footer', p),
								modes: buildModes({height: pd.bottom.prop})
							}
						}, p)};
					}
				});

				wb_builder.bodyInstance.updateStyle();
				wb_builder.bodyInstance.fitElements();
				if (wb_builder.showLayout) wb_builder.highlightLayout(wb_builder.showLayout);

				wb_builder.setPageModified(true);
				Service.HelpSystemPlayer.notify('config-background-apply', thisClass.changeBgDlg);
			}, true);
		}
		fields = this.changeBgDlg.fields;
		fields.data = data;

		var k, wasSelected = false, noMenus = true;
		fields.list.removeAllItems();
		fields.list.addItem(fields.defaultInf = {
			id: -1,
			type: "default",
			name: __("Default (for all pages)"),
			serialize: function() { return this; }
		}, false, "glyphicon glyphicon-folder-open");
		
		var menuList = MenuList.buildMenuStruct(false, true);
		
		var first = true;
		for (var i = 0; i < menuList.length; i++) {
			var menu = menuList[i];
			if (first) first = false; else fields.list.addSeparator();
			for (var n = 0; n < menu.items.length; n++) {
				var mi = menu.items[n];
				if (!mi.miElem) continue;
				
				noMenus = false;
				var hmi = fields.list.addItem(mi.miElem, false, ((mi.type === "external" || mi.type === "internal" || mi.type === "anchor" || mi.type === "empty")? "glyphicon glyphicon-share-alt" : null), (mi.type === "external" || mi.type === "anchor" || mi.type === "empty"));

				var marginLeft = 20; 
				var identIdx = mi.lvl; while (identIdx > 0) { identIdx--; marginLeft += 20; }
				hmi.css({ marginLeft: marginLeft + "px" });
				if (!wasSelected && mi.type !== "external" && mi.pageId == wb_builder.pageId) {
					wasSelected = true;
					hmi.trigger("click");
				}
			}
		}
		
		fields.pages.removeAllPages();
		for (k in this.pages) { fields.pages.addPage(this.pages[k].serialize()); }

		if (!block || noMenus || !wasSelected)
			fields.list.selectFirst();
		else
			fields.layoutBlocks.setValue(block);
		
		/*
		var p = this.getPage(wb_builder.pageId);
		if (p) {
			fields.bgPage.setValue(p.background);
			fields.bg2Page.setValue(p.background2);
			//this.changeBgDlg.setTitle(__('Background for page "%s"').replace("%s", p.title));
		}
		*/
		this.changeBgDlg.setVisible(true);
		fields.data.rd = true;
		Service.HelpSystemPlayer.notify('config-background-open', this.changeBgDlg);
		return this.changeBgDlg;
	};

	/**
	 * Show change site background dialog
	 *
	 * @deprecated => routed to site.changeBackground()
	 */
	Site.prototype.changeSiteBackground = function() {
		this.changeBackground();
		return false;
	};

	/**
	 * Show change page background dialog
	 *
	 * @deprecated => routed to site.changeBackground()
	 */
	Site.prototype.changePageBackground = function() {
		this.changeBackground('template');
		return false;
	};
	
	/**
	 * Get style by style name.
	 * @param {String} styleName
	 * @returns {Site.Style}
	 */
	Site.prototype.getStyleByName = function(styleName) {
		for (var i = 0; i < this.styles.length; i++) {
			if (this.styles[i].name === styleName) {
				return this.styles[i];
			}
		}
		return null;
	}

	/**
	 * Show change styles dialog
	 * @param {String} styleSelector style to select on dialog open
	 */
	Site.prototype.changeStyles = function(styleSelector, closedCallback) {
		var thisClass = this;
		var fields = null;
		if (!this.changeStylesDlg) {
			this.changeStylesDlg = new Dialog(__("Styles"), null, new Service.UIBuilder({
				type: 'HorizontalLayout', columnWeightsSmall: [3, 9], columnWeights: [3, 9], children: [
					{type: 'List', id: 'tree',
						css: {marginBottom: 0},
						listHeight: 390,
						itemType: Site.Style,
						editable: false,
						init: function() {
							var _addItem = this.addItem;
							this.addItem = function(item, noStyleUpdate) {
								var li = _addItem.call(this, item, noStyleUpdate, 'no-icon');
								if (item.ident) {
									if (wb_builder.rtl) {
										li.css({marginRight: '20px'});
									} else {
										li.css({marginLeft: '20px'});
									}
								}
								return li;
							};
						},
						select: function(fields, item) {
							var k, style;
							if (fields.tree.getLastSelected()) {
								style = fields.tree.getLastSelected();
								style.sys.text = fields.text.getValue();
								style.sys.text.name = style.name;
								style.sys.linkNormalColor = fields.linkNormalColor.getValue();
								style.sys.linkNormalStyle = fields.linkNormalStyle.getValue();
								style.sys.linkHoverColor = fields.linkHoverColor.getValue();
								style.sys.linkHoverStyle = fields.linkHoverStyle.getValue();
								style.sys.advTextTransform = fields.advTextTransform.getValue();
								style.sys.advSpacing = fields.advSpacing.getValue();
								style.sys.advListBullet = fields.advListBullet.getValue();
								Site.Style.updateStyleSubs(style);
								var currMode = ModeManager.getMode();
								for (k in style.modes) {
									if (ModeManager.getModes().indexOf(k) < 0) continue;
									style.modes[k].fontScale = (fields.fontScale[k].getValue() / 100.0);
									if (currMode === k) style.fontScale = style.modes[k].fontScale;
								}
							}
							style = item;
							fields.text.setValue(style.sys.text);
							fields.text.setPreviewTag(style.tag);
							fields.linkNormalColor.setValue(style.sys.linkNormalColor);
							fields.linkNormalStyle.setValue(style.sys.linkNormalStyle);
							fields.linkHoverColor.setValue(style.sys.linkHoverColor);
							fields.linkHoverStyle.setValue(style.sys.linkHoverStyle);
							fields.advTextTransform.setValue(style.sys.advTextTransform);
							fields.advSpacing.setValue(style.sys.advSpacing);
							fields.advListBullet.setValue(style.sys.advListBullet);
							for (k in style.modes) {
								if (ModeManager.getModes().indexOf(k) < 0) continue;
								fields.fontScale[k].setValue(Math.round(style.modes[k].fontScale * 100.0));
								if (k !== Service.modeManager.MODE_DESKTOP) {
									if (String(style.selector).match(/\.wb\-stl\-normal(?:\ .+|)/i)) {
										// fields.fontScale[k].setValue(100);
										// fields.fontScale[k].setEnabled(false);
									} else {
										fields.fontScale[k].setEnabled(true);
									}
								}
							}
						}
					},
					{type: 'TabbedPane', tabs: [
						{name: __('Standard'), children: [
							{type: 'FontSelector', id: 'text',
								css: {marginTop: '15px'},
								needLineHeight: true,
								ttPlacement: 'left',
								needPreview: true
							}
						]},
						{name: __('Links'), children: [
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Link Text'), css: {marginTop: '15px'}},
								{type: 'FlowLayout', children: [
									{type: 'ColorSelector', id: 'linkNormalColor', noTransparent: true},
									{type: 'FontStyleSelector', id: 'linkNormalStyle'}
								]},
								{type: 'Label', text: __('Link Hover'), css: {marginTop: '15px'}},
								{type: 'FlowLayout', children: [
									{type: 'ColorSelector', id: 'linkHoverColor', noTransparent: true},
									{type: 'FontStyleSelector', id: 'linkHoverStyle'}
								]}
							]}
						]},
						{name: __('Advanced'), children: [
							{type: 'VerticalLayout', children: [
								{type: 'FlowLayout', css: {marginTop: '15px'}, spacing: 20, children: [
									{type: 'VerticalLayout', children: [
										{type: 'Label', text: __('Text Transform')},
										{type: 'FontTransformSelector', id: 'advTextTransform'}
									]},
									{type: 'VerticalLayout', children: [
										{type: 'Label', text: __('Margin / Padding')},
										{type: 'SpacingSelector', id: 'advSpacing'}
									]},
									{type: 'VerticalLayout', children: [
										{type: 'Label', text: __('List Options'), helpText: __('Default bullet image for list items')},
										{type: 'ImageSelector', fontAwesomeTab: true, id: 'advListBullet'}
									]}
								]},
								{type: 'Label', text: __('Font Scale for different devices'), css: {marginTop: '15px'}},
								{type: 'FlowLayout', styleClass: 'font-scale-ctrl',
									spacing: 20,
									children: [
										{type: 'VerticalLayout', children: [
											{type: 'Label', text: Service.modeManager.getModeName(Service.modeManager.MODE_TV)},
											{type: 'SizeSelector',
												units: '%', min: 1, max: 500,
												init: function(def, fields) {
													fields.fontScale[Service.modeManager.MODE_TV] = this;
												}
											},
											{type: 'CustomContainer', tag: 'p',
												styleClass: 'help-text',
												content: __('Recomended') + ' 120%'
											}
										]},
										{type: 'VerticalLayout', enabled: false, children: [
											{type: 'Label', text: Service.modeManager.getModeName(Service.modeManager.MODE_DESKTOP)},
											{type: 'SizeSelector',
												units: '%', min: 1, max: 500,
												init: function(def, fields) {
													fields.fontScale[Service.modeManager.MODE_DESKTOP] = this;
												}
											},
											{type: 'CustomContainer', styleClass: 'cover'}
										]},
										{type: 'VerticalLayout', children: [
											{type: 'Label', text: Service.modeManager.getModeName(Service.modeManager.MODE_TABLET)},
											{type: 'SizeSelector',
												units: '%', min: 1, max: 500,
												init: function(def, fields) {
													fields.fontScale[Service.modeManager.MODE_TABLET] = this;
												}
											},
											{type: 'CustomContainer', tag: 'p',
												styleClass: 'help-text',
												content: __('Recomended') + ' 80%'
											}
										]},
										{type: 'VerticalLayout', children: [
											{type: 'Label', text: Service.modeManager.getModeName(Service.modeManager.MODE_PHONE)},
											{type: 'SizeSelector',
												units: '%', min: 1, max: 500,
												init: function(def, fields) {
													fields.fontScale[Service.modeManager.MODE_PHONE] = this;
												}
											},
											{type: 'CustomContainer', tag: 'p',
												styleClass: 'help-text',
												content: __('Recomended') + ' 60%'
											}
										]}
									],
									init: function(def, fields) {
										fields.fontScale = {};
									}
								}
							]}
						]}
					]}
				]
			}));
			this.changeStylesDlg.setSize(640, null);
			if (typeof(closedCallback) === 'function') {
				this.changeStylesDlg.onClosed = function() {
					if (Dialog.stack.length > 0) return;
					closedCallback();
				};
			}
			fields = this.changeStylesDlg.fields;

			this.changeStylesDlg.addButton(__("Cancel"));
			this.changeStylesDlg.addButton(__("Apply"), function() {
				thisClass.changeStylesDlg.hide();

				wb_builder.setPageModified(true);
				
				fields.tree.selectFirst(); // to apply last changes
				thisClass.styles = fields.tree.getValue();
				var currMode = ModeManager.getMode();
				for (var k in thisClass.styles) {
					thisClass.styles[k].modes[currMode].applyTo(thisClass.styles[k]);
				}

				thisClass.updateStyle();

			}, true);
		}
		fields = this.changeStylesDlg.fields;

		fields.tree.removeAllItems();
		for (var i = 0; i < this.styles.length; i++) {
			fields.tree.addItem(this.styles[i]);
		}
		if (styleSelector) {
			var found = false;
			fields.tree.getItemsLi().each(function() {
				var obj = $(this).wbGetClassInstance();
				if (obj && obj.selector === styleSelector) {
					fields.tree.selectItemLi($(this));
					found = true;
					return false;
				}
			});
			if (!found) fields.tree.selectFirst();
		} else {
			fields.tree.selectFirst();
		}

		this.changeStylesDlg.setVisible(true);
	};

	/**
	 * Show change site and current page properties dialog
	 */
	Site.prototype.changeProperties = function() {
		var thisClass = this;
		var fields = null;
		if (!this.changeDlg) {
			var tabs = [];
			tabs.push(
				{children: [
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'forceHttps',
							label: __('Publish Site with forced HTTPS'),
							helpText: __('This option requires SSL to be enabled on your server.'),
							change: function(fields) { if (fields.forceHttpsPort) fields.forceHttpsPort.setEnabled(this.getValue()); }
						},
						{type: 'FlowLayout', verticalAlign: 'middle', ignore: !wb_builder.enableForcedHttpsPort, children: [
							{type: 'Label', text: __('Forced HTTPS port')},
							{type: 'TextField', id: 'forceHttpsPort', css: {width: 60}, styleClass: 'input-sm', placeholder: '443'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'forceRedirectEnabled', label: __('Publish Site with forced redirection'), helpText: __('After changing an option and publishing site clear browser cache.'), change: function() {
							if (this.getValue()) {
								fields.forceRedirectLine.setEnabled(true);
							} else {
								fields.forceRedirectLine.setEnabled(false);
							}
						}, init: function() { if (wb_builder.isB2C) this.setEnabled(false); }},
						{type: 'VerticalLayout', id: 'forceRedirectLine', css: {marginTop: 10}, enabled: false, children: [
							{type: 'RadioBox', group: 'force_redirect', id: 'forceRedirectNonWww', label: __('Redirect from www to non-www')},
							{type: 'RadioBox', group: 'force_redirect', id: 'forceRedirectWww', label: __('Redirect from non-www to www')}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'forceSlashes',
							label: __('Force trailing slash symbol "/" in each page URL'),
							helpText: __('If checked page URLs will have trailing slash at the end. For example URL "yourwebsite.com/about" will turn to "yourwebsite.com/about/".')
						}
					]}
				]}
			);
			tabs.push(
				{name: __('Meta information'), children: [
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Meta Tags'),
							helpText: __('Meta data HTML tags to be added to sites head.')
						},
						{type: 'TextField', id: 'metaHtml', textArea: true, css: {height: 100},
							placeholder: '<meta name="some name" content="some content"/>'
						}
					]}
				]}
			);
			tabs.push(
				{name: __('Scripts'), children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Before %s').replace("%s", "</head>"), css: {marginTop: 15},
							helpText: __('Scripts are added as plain HTML to every page of the website.')
						},
						{type: 'TextField', id: 'headSnippetsHtml', textArea: true, css: {height: 100},
							placeholder: ''
						},
						{type: 'Label', text: __('Before %s').replace("%s", "</body>"), css: {marginTop: 15},
							helpText: __('Scripts are added as plain HTML to every page of the website.')
						},
						{type: 'TextField', id: 'bodySnippetsHtml', textArea: true, css: {height: 100},
							placeholder: ''
						},
						{type: 'Label', text: __('After %s').replace("%s", "<body>"), css: {marginTop: 15},
							helpText: __('Scripts are added as plain HTML to every page of the website.')
						},
						{type: 'TextField', id: 'bodyStartSnippetsHtml', textArea: true, css: {height: 100},
							placeholder: ''
						}
					]}
				]}
			);
			tabs.push(
				{name: __('robots.txt'), children: [
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'robotsTxtEnable', label: (__('Enable') + ' robots.txt'),
							css: {marginBottom: 10},
							helpText: __('Only enable if you know what you are doing.')
						},
						{type: 'TextField', id: 'robotsTxt', textArea: true, css: {height: 100},
							placeholder: ""
						},
						{type: 'CustomContainer', styleClass: 'help-block help-block-sm',
							content: (
								__('Example') + ': '
								+ '<a href="https://en.wikipedia.org/wiki/Robots_exclusion_standard#Examples"'
								  + ' target="_blank">'
									+ 'Robots exclusion standard'
								+ '</a>'
							)
						}
					]}
				]}
			);
			tabs.push(
				{name: __('Cookie policy'), children: [
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', label: __('Enable cookie policy block'), id: 'cookiePolicyEnabled'},
						{type: 'FlowLayout', css: {marginTop: 11}, children: [
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Font')},
								{type: 'FlowLayout', spacing: -1, children: [
									{type: 'FontFamilySelector', id: 'cookiePolicyFont', css: {width: 140}},
									{type: 'Button', icon: "glyphicon glyphicon-pencil", click: function(e, fields) {
										fields.cookiePolicyFont.getWrappedControl().openEditFontsDialog();
									}}
								]}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Size')},
								{type: 'SizeSelector', id: 'cookiePolicyFontSize', min: 8, max: 72}
							]}
						]},
						{type: 'HorizontalLayout', css: {marginTop: 11}, children: [
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Message')},
								// {type: 'MultilangTextField', id: 'cookiePolicyMessage', textArea: true}
								{type: 'WYSIWYGControl', id: 'cookiePolicyMessage'}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Button Text')},
								{type: 'MultilangTextField', id: 'cookiePolicyButtonText', textArea: false}
							]}
						]},
						{type: 'HorizontalLayout', css: {marginTop: 11}, children: [
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Background')},
								{type: 'ColorSelector', id: 'cookiePolicyBg', noTransparent: false}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Message Color')},
								{type: 'ColorSelector', id: 'cookiePolicyMessageColor', noTransparent: false}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Button Color')},
								{type: 'ColorSelector', id: 'cookiePolicyButtonBg', noTransparent: false}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Button Text Color')},
								{type: 'ColorSelector', id: 'cookiePolicyButtonColor', noTransparent: false}
							]}
						]}
					]}
				]}
			);
			this.changeDlg = new Dialog(__('Site settings'), null, new Service.UIBuilder({type: 'TabbedPane', tabs: tabs}));
			this.changeDlg.setSize(570, null);
			fields = this.changeDlg.fields;

			this.changeDlg.addButton(__("Cancel"));
			this.changeDlg.addButton(__("Apply"), function() {
				thisClass.changeDlg.hide();
				if (fields.forceHttps) thisClass.publishWithForcedHttps = fields.forceHttps.getValue() ? true : false;
				if (fields.forceHttpsPort) {
					thisClass.publishWithForcedHttpsPort = parseInt(fields.forceHttpsPort.getValue(), 10);
				}
				if (fields.forceRedirectEnabled) {
					thisClass.forceRedirectEnabled = fields.forceRedirectEnabled ? fields.forceRedirectEnabled.getValue() : thisClass.forceRedirectEnabled;
					if (fields.forceRedirectWww.getValue()) thisClass.forceRedirectWww = true;
					if (fields.forceRedirectNonWww.getValue()) thisClass.forceRedirectWww = false;
				}
				thisClass.forceSlashes = fields.forceSlashes ? fields.forceSlashes.getValue() : false;
				thisClass.metaHtml = fields.metaHtml.getValue();
				thisClass.headSnippetsHtml = fields.headSnippetsHtml.getValue();
				thisClass.bodySnippetsHtml = fields.bodySnippetsHtml.getValue();
				thisClass.bodyStartSnippetsHtml = fields.bodyStartSnippetsHtml.getValue();
				thisClass.robotsTxtEnable = (fields.robotsTxtEnable.getValue() ? true : false);
				thisClass.robotsTxt = fields.robotsTxt.getValue();
				thisClass.cookiePolicyEnabled = fields.cookiePolicyEnabled.getValue();
				thisClass.cookiePolicyFont = fields.cookiePolicyFont.getValue();
				thisClass.cookiePolicyFontSize = fields.cookiePolicyFontSize.getValue();
				thisClass.cookiePolicyMessage = fields.cookiePolicyMessage.getValue();
				thisClass.cookiePolicyButtonText = fields.cookiePolicyButtonText.getValue();
				thisClass.cookiePolicyBg = fields.cookiePolicyBg.getValue();
				thisClass.cookiePolicyMessageColor = fields.cookiePolicyMessageColor.getValue();
				thisClass.cookiePolicyButtonBg = fields.cookiePolicyButtonBg.getValue();
				thisClass.cookiePolicyButtonColor = fields.cookiePolicyButtonColor.getValue();
				wb_builder.setPageModified(true);
			}, true);
		}
		fields = this.changeDlg.fields;
		if (fields.forceHttps) fields.forceHttps.setValue(this.publishWithForcedHttps);
		if (fields.forceHttpsPort) {
			fields.forceHttpsPort.setValue((this.publishWithForcedHttpsPort ? this.publishWithForcedHttpsPort : ''));
			fields.forceHttpsPort.setEnabled(fields.forceHttps.getValue());
		}
		if (fields.forceRedirectEnabled) {
			fields.forceRedirectEnabled.setValue(thisClass.forceRedirectEnabled);
			fields.forceRedirectEnabled.trigger('change');
		}
		if (thisClass.forceRedirectWww) {
			fields.forceRedirectWww.setValue(true);
			fields.forceRedirectNonWww.setValue(false);
		} else {
			fields.forceRedirectWww.setValue(false);
			fields.forceRedirectNonWww.setValue(true);
		}
		fields.forceSlashes.setValue(this.forceSlashes);
		fields.metaHtml.setValue(this.metaHtml);
		fields.headSnippetsHtml.setValue(this.headSnippetsHtml);
		fields.bodySnippetsHtml.setValue(this.bodySnippetsHtml);
		fields.bodyStartSnippetsHtml.setValue(this.bodyStartSnippetsHtml);
		fields.robotsTxtEnable.setValue(this.robotsTxtEnable);
		fields.robotsTxt.setValue(this.robotsTxt);
		fields.cookiePolicyEnabled.setValue(this.cookiePolicyEnabled);
		fields.cookiePolicyFont.setValue(this.cookiePolicyFont);
		fields.cookiePolicyFontSize.setValue(this.cookiePolicyFontSize);
		fields.cookiePolicyMessage.setValue(this.cookiePolicyMessage);
		fields.cookiePolicyButtonText.setValue(this.cookiePolicyButtonText);
		fields.cookiePolicyBg.setValue(this.cookiePolicyBg);
		fields.cookiePolicyMessageColor.setValue(this.cookiePolicyMessageColor);
		fields.cookiePolicyButtonBg.setValue(this.cookiePolicyButtonBg);
		fields.cookiePolicyButtonColor.setValue(this.cookiePolicyButtonColor);
		this.changeDlg.setVisible(true);
	};

	Site.prototype.onUpdateLanguages = function(initial) {
		var ea = new BuilderEvent.LanguagesUpdateBuilderEvent(initial);
		BuilderEvent.GlobalEvents.triggerEvent("languages.update", ea);
		if( !ea.defaultPrevented ) {
			WB_Languages.reloadAll(initial);
			LangInputControl.reloadAll();
			URLControl.reloadAll();
			var elems = wb_builder.bodyInstance.getContentElements();
			for (var i=0, elem; (elem = elems[i]); i++) {
				if (typeof elem.onUpdateLanguages === 'function') {
					elem.onUpdateLanguages();
				}
			}
		}
	};

	Site.prototype.switchLanguage = function(langCode) {
		var thisClass = this, elems = wb_builder.bodyInstance.getContentElements();
		if (typeof wb_builder.bodyInstance.onBeforeSwitchLanguage === 'function') {
			wb_builder.bodyInstance.onBeforeSwitchLanguage();
		}
		for (var i=0, elem; (elem = elems[i]); i++) {
			if (typeof elem.onBeforeSwitchLanguage === 'function') {
				elem.onBeforeSwitchLanguage();
			}
		}
		setTimeout(function() {
			thisClass.currSelLang = langCode;
			for (var i=0, elem; (elem = elems[i]); i++) {
				if (typeof elem.onSwitchLanguage === 'function') {
					elem.onSwitchLanguage(langCode);
				}
			}
			if (typeof wb_builder.bodyInstance.onSwitchLanguage === 'function') {
				wb_builder.bodyInstance.onSwitchLanguage(langCode);
			}
		}, 10);
	};

	Site.Mode = (function() {
		/**
		 * @param {Site.Mode} mode
		 * @param {Object} data
		 */
		var applyData = function(mode, data) {
			//mode.fontScale = data.fontScale;
		};

		/**
		 * @param {Object} data
		 * @class WB_Site.Mode
		 */
		var self = function(data) { if (data) applyData(this, data); };
		/** @type Number */
		self.prototype.fontScale = 1;
		/** @param {Site.Mode} mode */
		self.prototype.copy = function(mode) {
			applyData(this, mode);
		};
		/** @param {Site} elem */
		self.prototype.store = function(elem) {
			applyData(this, elem);
		};
		/** @param {Site} elem */
		self.prototype.applyTo = function(elem) {
			//elem.fontScale = this.fontScale;
			elem.updateStyle();
		};
		/** @return {Object} */
		self.prototype.serialize = function() {
			return { /*fontScale: this.fontScale*/ };
		};

		return self;
	})();

	Site.Page = (function() {

		/**
		 * Builder site Page class
		 * @param {Object} data
		 * @class Page
		 * @memberOf WB_Site
		 */
		var self = function(data) { if (data) this.__construct(data); };

		self.prototype.site = null;
		self.prototype.id = 0;
		/** @type Boolean */
		self.prototype.isFront = false;
		/** @type Boolean */
		self.prototype.isSingle = false;	//the only page on site w/o menu
		/** @type String */
		self.prototype.title = "";
		/** @type String */
		self.prototype.alias = "";
		/** @type String */
		self.prototype.keywords = "";
		/** @type String */
		self.prototype.description = "";
		/** @type String */
		self.prototype.image = null;
		/** @type String */
		self.prototype.layout = "";
		/** @type String */
		self.prototype.widget = "";
		self.prototype.background = null;
		self.prototype.background2 = null;
		self.prototype.comments = null;
		self.prototype.siteWidth = null;
		self.prototype.siteHeight = null;
		self.prototype.mlSiteHeight = null;
		self.prototype.copyFrom = null;
		self.prototype.copyClearHeader = null;
		self.prototype.copyClearBody = null;
		self.prototype.copyClearFooter = null;
		self.prototype.blocks = null;
		/** @type Object */
		self.prototype.modes = null;
		self.prototype.landing = null;
		self.prototype.landingOrder = null;
		self.prototype.fixedHeader = false;
		self.prototype.noPageBg = false;
		/** @type Boolean */
		self.prototype.saved = false;
		self.prototype.miId = null;
		self.prototype.guides = null;

		/**
		 * Construct builder page
		 * @param data page data object
		 */
		self.prototype.__construct = function(data) {
			this.id = parseInt(data.id, 10);
			this.isFront = data.isFront ? true : false;
			this.isSingle = data.isSingle ? true : false;
			this.title = data.title;
			this.alias = data.alias;
			this.keywords = data.keywords;
			this.description = data.description;
			this.image = data.image ? data.image : null;
			this.layout = data.layout;
			this.widget = data.widget;
			this.siteWidth = data.siteWidth;
			this.siteHeight = data.siteHeight;
			this.mlSiteHeight = data.mlSiteHeight;
			this.copyFrom = data.copyFrom ? data.copyFrom : null;
			this.copyClearHeader = data.copyClearHeader ? data.copyClearHeader : null;
			this.copyClearBody = data.copyClearBody ? data.copyClearBody : null;
			this.copyClearFooter = data.copyClearFooter ? data.copyClearFooter : null;
			this.blocks = data.blocks ? data.blocks : {};
			this.modes = data.modes;
			if ((typeof this.modes !== 'object') || ('length' in this.modes)) this.modes = {};

			this.landing = data.landing ? true : false;
			this.landingOrder = data.landingOrder ? data.landingOrder : 0;
			this.fixedHeader = data.fixedHeader ? data.fixedHeader : false;
			this.noPageBg = data.noPageBg ? data.noPageBg : false;
			this.saved = data.saved ? data.saved : false;
			this.miId = data.miId ? data.miId : null;
			if (!this.miId) this.reloadMiId();

			this.comments = [];

			if (data.comments) {
				for (var i = 0; i < data.comments.length; i++) {
					var comment = new Site.Comment(data.comments[i]);
					this.addComment(comment);
				}
			}

			this.background = data.background ? data.background : {
				color: "transparent",
				image: "none",
				position: "left top",
				repeat: "repeat",
				css: { background: "transparent none repeat scroll left top" }
			};
			this.background2 = data.background2 ? data.background2 : {
				color: "transparent",
				image: "none",
				position: "left top",
				repeat: "repeat",
				css: { background: "transparent none repeat scroll left top" }
			};

			this.guides = ('guides' in data) ? data.guides : null;
		};

		/**
		 * Serialize this instance
		 * @return {Object}
		 */
		self.prototype.serialize = function(onSave) {

			var i, items = [], modes = $.extend({}, this.modes);
			var currMode = ModeManager.getMode();

			for (i = 0; i < this.comments.length; i++) {
				items.push(this.comments[i].serialize());
			}

			if (parseInt(this.id, 10) === wb_builder.pageId) {
				var sz = wb_builder.bodyInstance.getSiteSize();
				this.siteWidth = sz.width;
				this.siteHeight = sz.height;
				this.mlSiteHeight = sz.mlHeight;
				wb_builder.bodyInstance.switchMode(currMode, currMode);
				for (var k in wb_builder.bodyInstance.modes) {
					var mode = wb_builder.bodyInstance.modes[k];
					modes[k] = {siteWidth: mode.siteWidth, siteHeight: mode.siteHeight, mlSiteHeight: mode.mlSiteHeight};
				}
				this.modes = $.extend({}, modes);
				this.guides = Guides.GuideManagerInstance.serialize();
			}
			if (onSave) {
				this.saved = true;
			}
			return {
				"id":			this.id,
				"isFront":		this.isFront ? true : false,
				"isSingle":		this.isSingle ? true : false,
				"title":		this.title,
				"alias":		this.alias,
				"keywords":		this.keywords,
				"description":	this.description,
				"image":		this.image,
				"layout":		this.layout,
				"widget":		this.widget,
				"background":	this.background,
				"background2":	this.background2,
				"comments":		items,
				"siteWidth":	this.siteWidth,
				"siteHeight":	this.siteHeight,
				"mlSiteHeight":	this.mlSiteHeight,
				"copyFrom":		this.copyFrom,
				"copyClearHeader":	this.copyClearHeader,
				"copyClearBody":	this.copyClearBody,
				"copyClearFooter":	this.copyClearFooter,
				modes: modes,
				landing:		this.landing,
				landingOrder:	this.landingOrder,
				fixedHeader:	this.fixedHeader,
				noPageBg:		this.noPageBg,
				saved:			this.saved,
				miId:			this.miId,
				guides:			this.guides
			};
		};
		
		self.prototype.reloadMiId = function(forceReload) {
			if (!this.miId || forceReload) {
				var _getMi = function(pageId, mi) {
					if (!mi || !mi.items) return null;
					var id, item, mmi;
					for (id in mi.items) {
						item = mi.items[id];
						if (item.type === 'page' && item.targetId == pageId) {
							return item;
						}
						if ((mmi = _getMi(pageId, item))) {
							return mmi;
						}
					}
					return null;
				};
				var menuList = Service.menu.getElemList(true), mi;
				for (var menuId in menuList) {
					var menu = menuList[menuId];
					if ((mi = _getMi(this.id, menu))) {
						this.miId = menu.menuUID + '_' + mi.id;
						return;
					}
				}
			}
		};

		/**
		 * Should not be used for enything, this method is only temporary bugfix
		 * @return {Object}
		 */
		self.prototype.serializeBlocksBugFix = function() {
			var data = this.serialize();
			data.blocks = this.blocks;
			return data;
		};

		/**
		 * Add comment to this page
		 * @param {Site.Comment} comment
		 */
		self.prototype.addComment = function(comment) {
			if (comment.page) {
				comment.page.removeComment(comment);
			}
			comment.page = this;
			comment.index = this.comments.length;
			this.comments.push(comment);
		};

		/**
		 * Remove comment from this page
		 * @param comment comment of type WB_Site.Comment
		 */
		self.prototype.removeComment = function(comment) {
			if (comment.page && comment.page !== this) return;
			if (!comment.page) {
				comment.index = -1;
				return;
			}
			comment.page = null;
			if (comment.index >= 0 && comment.index < this.comments.length) {
				this.comments.splice(comment.index, 1);
			}
			comment.index = -1;
		};

		/**
		 * Remove all comments from this page
		 */
		self.prototype.removeAllComments = function() {
			for (var i = 0; i < this.comments.length; i++) {
				this.removeComment(this.comments[i]);
			}
		};

		/**
		 * Toggle page landing
		 * @param {boolean} landing
		 * @param order
		 */
		self.prototype.setLanding = function(landing, order) {
			this.landing = landing ? true : false;
			this.landingOrder = order;
		};
		
		return self;
	})();

	Site.Comment = (function() {

		/**
		 * Builder site Comment class
		 * @param {Object} data
		 * @class Comment
		 * @memberOf WB_Site
		 */
		var self = function(data) { if (data) this.__construct(data); };

		self.prototype.page = null;
		self.prototype.id = 0;
		self.prototype.index = -1;
		self.prototype.date = null;
		self.prototype.time = null;
		self.prototype.user = null;
		self.prototype.text = null;

		/**
		 * Construct comment
		 * @param {Object} data comment data object
		 */
		self.prototype.__construct = function(data) {
			if (!data) data = {};
			var dt = new Date();
			var y = dt.getFullYear();
			var m = dt.getMonth() + 1; if (m < 10) m = "0" + m;
			var d = dt.getDate(); if (d < 10) d = "0" + d;
			var h = dt.getHours(); if (h < 10) h = "0" + h;
			var i = dt.getMinutes(); if (i < 10) i = "0" + i;
			this.id = data.id;
			this.date = data.date ? data.date : y + "-" + m + "-" + d;
			this.time = data.time ? data.time : h + ":" + i;
			this.user = data.user ? data.user : "anonymous";
			this.text = data.text ? data.text : "";
		};

		/**
		 * Serialize this instance
		 * @return {Object}
		 */
		self.prototype.serialize = function() {
			return {
				id:		this.id,
				date:	this.date,
				time:	this.time,
				user:	this.user,
				text:	this.text
			};
		};

		return self;
	})();

	Site.Style = (function() {

		/**
		 * Builder site style class
		 * @param {Object} data
		 * @class WB_Site.Style
		 */
		var self = function(data) { if (data) this.__construct(data); };

		self.defaults = [
			{
				name: "Page Title", // __("Page Title")
				tag: "h4",
				ident: 0,
				selector: ".wb-stl-pagetitle",
				rules: { "font-size": "24px" },
				sys: { text: { size: 24 } }
			},
			{
				name: "Sub Title", // __("Sub Title")
				tag: "h5",
				ident: 1,
				selector: ".wb-stl-subtitle",
				rules: { "font-size": "18px" },
				sys: { text: { size: 18 } }
			},
			{
				name: "Heading 1", // __("Heading 1")
				tag: "h1",
				ident: 0,
				selector: ".wb-stl-heading1",
				rules: { "font-size": "24px" },
				sys: { text: { size: 24 } }
			},
			{
				name: "Heading 2", // __("Heading 2")
				tag: "h2",
				ident: 1,
				selector: ".wb-stl-heading2",
				rules: { "font-size": "20px" },
				sys: { text: { size: 20 } }
			},
			{
				name: "Heading 3", // __("Heading 3")
				tag: "h3",
				ident: 1,
				selector: ".wb-stl-heading3",
				rules: { "font-size": "16px" },
				sys: { text: { size: 16 } }
			},
			{
				name: "Normal", // __("Normal")
				tag: "p",
				ident: 0,
				selector: ".wb-stl-normal",
				rules: { "font-size": "12px" },
				sys: { text: { size: 12 } }
			},
			{
				name: "Highlight", // __("Highlight")
				tag: "span",
				ident: 1,
				selector: ".wb-stl-highlight",
				rules: { "font-size": "12px", "background": "yellow" },
				sys: { text: { size: 12 } }
			},
			{
				name: "Special", // __("Special")
				tag: "span",
				ident: 1,
				selector: ".wb-stl-special",
				rules: { "font-size": "12px", "font-weight": "bold", "text-decoration": "underline" },
				sys: { text: { size: 12, style: { bold: true, underline: true } } }
			},
			{
				name: "Footer", // __("Footer")
				tag: "p",
				ident: 0,
				selector: ".wb-stl-footer",
				rules: { "background": "black", "color": "#ffffff" },
				sys: { text: { color: "#ffffff" } }
			},
			{
				name: "Custom 1",
				tag: "p",
				ident: 0,
				selector: ".wb-stl-custom1",
				rules: { "font-size": "12px", "line-height": "14px", "color": "#000000" },
				sys: { text: { size: 12, lineHeight: 14, color: "#000000" } }
			},
			{
				name: "Custom 2",
				tag: "p",
				ident: 0,
				selector: ".wb-stl-custom2",
				rules: { "font-size": "16px", "line-height": "18px", "color": "#777777" },
				sys: { text: { size: 16, lineHeight: 18, color: "#777777" } }
			},
			{
				name: "Custom 3",
				tag: "p",
				ident: 0,
				selector: ".wb-stl-custom3",
				rules: { "font-size": "20px", "line-height": "24px", "color": "#ffffff" },
				sys: { text: { size: 20, lineHeight: 24, color: "#ffffff" } }
			},
			{
				name: "List 1",
				tag: "ul",
				ident: 0,
				selector: ".wb-stl-list1",
				rules: { "font-size": "12px", "line-height": "14px", "color": "#000000" },
				sys: { text: { size: 12, lineHeight: 14, color: "#000000" } }
			},
			{
				name: "List 2",
				tag: "ul",
				ident: 0,
				selector: ".wb-stl-list2",
				rules: { "font-size": "16px", "line-height": "18px", "color": "#777777" },
				sys: { text: { size: 16, lineHeight: 18, color: "#777777" } }
			},
			{
				name: "List 3",
				tag: "ul",
				ident: 0,
				selector: ".wb-stl-list3",
				rules: { "font-size": "20px", "line-height": "24px", "color": "#ffffff" },
				sys: { text: { size: 20, lineHeight: 24, color: "#ffffff" } }
			}
		];
		self.prototype.selector = null;
		self.prototype.rules = null;
		self.prototype.name = null;
		self.prototype.tag = null;
		self.prototype.ident = 0;
		self.prototype.sys = null;
		self.prototype.subs = null;
		/** @type Number */
		self.prototype.fontScale = 1;
		/** @type Object */
		self.prototype.modes = null;
		
		self.updateStyleSubs = function(style) {
			if (!(style instanceof Site.Style)) return;
			var rules, rulesText, rulesLinkNormal, rulesLinkHover;
			
			style.subs = [];
			
			style.sys.text = TextControl.buildCss(style.sys.text);
			rulesText = $.extend(true, {}, style.sys.text.css);
			
			style.rules = $.extend(true, {}, rulesText);
			if (style.sys.advSpacing && style.sys.advSpacing.css) {
				style.rules = $.extend(true, style.rules, style.sys.advSpacing.css);
			} else {
				style.rules = $.extend(true, style.rules, { margin: 0, padding: 0 });
			}
			if (style.sys.advTextTransform && style.sys.advTextTransform.css) {
				style.rules = $.extend(true, style.rules, style.sys.advTextTransform.css);
			}
			
			rulesLinkNormal = $.extend(true, {}, rulesText);
			if (style.sys.linkNormalColor) rulesLinkNormal['color'] = style.sys.linkNormalColor;
			if (style.sys.linkNormalStyle && style.sys.linkNormalStyle.css) {
				rulesLinkNormal = $.extend(true, {}, rulesLinkNormal, style.sys.linkNormalStyle.css);
			}
			style.subs.push(new Site.Style({
				tag: style.tag,
				isSub: true,
				selector: (style.selector + " a"),
				rules: rulesLinkNormal
			}));
			
			rulesLinkHover = $.extend(true, {}, rulesText);
			if (style.sys.linkHoverColor) rulesLinkHover['color'] = style.sys.linkHoverColor;
			if (style.sys.linkHoverStyle && style.sys.linkHoverStyle.css) {
				rulesLinkHover = $.extend(true, {}, rulesLinkHover, style.sys.linkHoverStyle.css);
			}
			style.subs.push(new Site.Style({
				tag: style.tag,
				isSub: true,
				selector: (style.selector + " a:hover"),
				rules: rulesLinkHover
			}));
			
			if (style.tag === 'ul') {
				var ulPaddingLeft = null;
				if (/^\d+px\ \d+px\ \d+px\ (\d+)px$/i.test(style.rules['padding'])) {
					ulPaddingLeft = RegExp.$1;
				}
				
				var listBulletFontAwesome = style.sys.advListBullet ? (typeof(style.sys.advListBullet) === 'object' && style.sys.advListBullet) : false;
				style.subs.push(new Site.Style({
					tag: style.tag,
					isSub: true,
					selector: ("ul" + style.selector),
					rules: { "list-style": "none" }
				}));
				
				rules = $.extend(true, {}, rulesText);
				style.subs.push(new Site.Style({
					tag: style.tag,
					isSub: true,
					selector: ("ul" + style.selector + " li"),
					rules: rules
				}));
				
				style.subs.push(new Site.Style({
					tag: style.tag,
					isSub: true,
					selector: ("ul" + style.selector + " li > *"),
					rules: {
						"display": "inline-block",
						"vertical-align": "middle"
					}
				}));
				
				style.subs.push(new Site.Style({
					tag: style.tag,
					isSub: true,
					selector: ("ul" + style.selector + " li:before"),
					rules: {
						"content": '"' + (listBulletFontAwesome ? '\\' + style.sys.advListBullet.faCharacter : (style.sys.advListBullet ? '' : '\\2022')) + '"',
						"font-size": rulesText['font-size'],
						"font-family": (listBulletFontAwesome ? '"FontAwesome"' : ''),
						"display": "inline-block",
						"vertical-align": "middle",
						"background-image": (listBulletFontAwesome ? 'none'
								: "url('" + (style.sys.advListBullet ? style.sys.advListBullet.replace(/\'/g, "\\'") : '') + "')"),
						"background-repeat": "no-repeat",
						"background-size": "contain",
						"background-position": "center center",
						"width": rulesText['font-size'],
						"height": rulesText['line-height'],
						"margin-right": (ulPaddingLeft ? ulPaddingLeft + 'px' : 0)
					}
				}));
			}
		};

		/**
		 * Construct style
		 * @param {Object} data style data object
		 */
		self.prototype.__construct = function(data) {
			this.selector = data.selector ? (data.selector + "") : ".dummy-no-name";
			this.rules = (data.rules && typeof(data.rules) === "object") ? data.rules : {};
			this.name = data.name ? (data.name + "") : "no-name";
			this.tag = data.tag ? (data.tag + "") : "span";
			this.ident = (data.ident && !isNaN(parseInt(data.ident, 10))) ? data.ident : 0;
			this.sys = (data.sys && typeof(data.sys) === "object") ? data.sys : {};
			this.subs = [];
			var i, subs = (data.subs && typeof(data.subs) === "object") ? data.subs : [];
			for (i = 0; i < subs.length; i++) {
				this.subs.push(new Site.Style(subs[i]));
			}
			
			if (('fontScale' in data) && data.fontScale) this.fontScale = data.fontScale;

			this.modes = {}; if (data.modes) for (var k in data.modes) { this.modes[k] = new self.Mode(data.modes[k]); }
			var wbModes = Service.modeManager.getModes();
			for (i = 0; i < wbModes.length; i++) this.switchMode(wbModes[i], wbModes[i], true, true);
			if (!data.isSub) { self.updateStyleSubs(this); }
		};

		/**
		 * Switch to mode (one of Service.modeManager.MODE_* constants)
		 * @param {String} fromMode
		 * @param {String} toMode
		 * @param {Boolean} noApply
		 */
		self.prototype.switchMode = function(fromMode, toMode, initial, noApply) {
			if (!toMode || !Service.modeManager.getUseModes()) return;
			if (!noApply) {
				if (!(fromMode in this.modes)) {
					this.modes[fromMode] = new self.Mode();
				}
				if (!initial) {
					this.modes[fromMode].store(this);
				}
			}
			if (!(toMode in this.modes)) {
				this.modes[toMode] = new self.Mode();
				this.modes[toMode].copy(this.modes[fromMode]);
				if (toMode === Service.modeManager.MODE_TV) {
					this.modes[toMode].fontScale = 1.2;
				} else if (toMode === Service.modeManager.MODE_TABLET) {
					this.modes[toMode].fontScale = 0.8;
				} else if (toMode === Service.modeManager.MODE_PHONE) {
					this.modes[toMode].fontScale = 0.6;
				} else {
					this.modes[toMode].fontScale = 1;
				}
			}
			if (!noApply && (initial || fromMode !== toMode)) {
				this.modes[toMode].applyTo(this);
			}
		};

		/**
		 * Serialize this instance
		 * @return {Object}
		 */
		self.prototype.serialize = function() {
			var m;
			if (Service.modeManager.getUseModes()) {
				var mode = ModeManager.getMode();
				this.switchMode(mode, mode);
				m = this.modes[mode].serialize();
			}
			if (!m) m = {fontScale: this.fontScale};
			var modes = {}; for (var k in this.modes) { modes[k] = this.modes[k].serialize(); }
			var subs = [];
			for (var i = 0; i < this.subs.length; i++) {
				subs.push(this.subs[i].serialize());
			}
			return {
				selector: this.selector,
				rules: $.extend(true, {}, this.rules),
				name: this.name,
				tag: this.tag,
				ident: this.ident,
				sys: $.extend(true, {}, this.sys),
				subs: subs,
				fontScale: m.fontScale,
				modes: modes
			};
		};

		self.Mode = (function() {
			/**
			 * @param {Site.Style.Mode} mode
			 * @param {Object} data
			 */
			var applyData = function(mode, data) {
				mode.fontScale = data.fontScale;
			};

			/**
			 * @param {Object} data
			 * @class WB_Site.Style.Mode
			 */
			var self = function(data) { if (data) applyData(this, data); };
			/** @type Number */
			self.prototype.fontScale = 1;
			/** @param {Site.Style.Mode} mode */
			self.prototype.copy = function(mode) {
				applyData(this, mode);
			};
			/** @param {Site.Style} elem */
			self.prototype.store = function(elem) {
				applyData(this, elem);
			};
			/** @param {Site.Style} elem */
			self.prototype.applyTo = function(elem) {
				elem.fontScale = this.fontScale;
			};
			/** @return {Object} */
			self.prototype.serialize = function() {
				return { fontScale: this.fontScale };
			};

			return self;
		})();

		return self;
	})();
	
	Site.AnchorUtil = {
		
		builder: null,
		site: null,
		
		init: function(builder, site) {
			this.builder = builder;
			this.site = site;
		},
		
		addByElem: function(elem) {
			if (!elem.anchor) return;
			this.applyData(this.prepareElemData(elem));
		},
		
		removeByElem: function(elem) {
			if (!elem.anchor) return;
			this.applyData(this.prepareElemData(elem), true);
		},
		
		refreshData: function() {
			var used = [], unused = [], pid, i;
			for (pid in this.site.pages) {
				used.push(''+this.site.pages[pid].id);
			}
			for (pid in this.site.anchors) {
				if (used.indexOf(''+pid) < 0) unused.push(''+pid);
			}
			for (i in unused) {
				delete this.site.anchors[unused[i]];
			}
		},
		
		getData: function(pageId, langCode) {
			if (!pageId) pageId = this.builder.pageId;
			if (!langCode && this.site.currSelLang) langCode = this.site.currSelLang;
			if (!langCode && this.site.lastDefLang) langCode = this.site.lastDefLang;
			
			var list = [];
			if ((''+pageId) in this.site.anchors) {
				for (var anchor in this.site.anchors[''+pageId]) {
					var dataPart = this.site.anchors[''+pageId][anchor];
					if (typeof dataPart === 'object') {
						if (langCode && (langCode in dataPart) && dataPart[langCode]) {
							list.push(anchor);
						}
					} else if (dataPart === true) {
						list.push(anchor);
					}
				}
			}
			return list;
		},
		
		serialize: function() {
			var data = {};
			for (var pid in this.site.anchors) {
				var pageAnchors = this.site.anchors[pid];
				for (var anchor in pageAnchors) {
					var dataPart = pageAnchors[anchor];
					var normDataPart = this.normalizeDataPart(dataPart);
					var include = false;
					if (typeof normDataPart === 'object') {
						for (var langCode in normDataPart) {
							if (normDataPart[langCode]) { include = true; break; }
						}
					} else if (normDataPart) {
						include = true;
					}
					if (include) {
						if (!((''+pid) in data)) data[''+pid] = {};
						data[''+pid][anchor] = normDataPart;
					}
				}
			}
			return data;
		},
		
		prepareElemData: function(elem) {
			var anchor = elem.anchor,
				isCommon = elem.isCommon,
				includePages = elem.includePages,
				includePagesSet = (Object.keys(includePages).length > 0);
			var data = {};
			if (isCommon) {
				if (includePagesSet) {
					for (var pid in includePages) {
						data[''+pid] = {};
						data[''+pid][anchor] = includePages[pid];
					}
				} else {
					for (var pid in this.site.pages) {
						data[''+this.site.pages[pid].id] = {};
						data[''+this.site.pages[pid].id][anchor] = true;
					}
				}
			} else {
				data[''+ this.builder.pageId] = {};
				if (includePagesSet) {
					data[''+ this.builder.pageId][anchor] = includePages;
				} else {
					data[''+ this.builder.pageId][anchor] = true;
				}
			}
			return data;
		},
		
		applyData: function(data, remove) {
			if (remove) {
				for (var pid in this.site.anchors) {
					if ((''+pid) in data) {
						for (var anchor in this.site.anchors[pid]) {
							if (anchor in data[''+pid]) {
								this.site.anchors[pid][anchor] = this.substractDataPart(
										this.site.anchors[pid][anchor],
										data[''+pid][anchor]);
							}
						}
					}
				}
			} else {
				for (var pid in data) {
					if (!(''+pid in this.site.anchors)) this.site.anchors[''+pid] = {};
					var pageData = data[''+pid];
					for (var anchor in pageData) {
						this.site.anchors[''+pid][anchor] = this.mergeDataParts(
								((anchor in this.site.anchors[''+pid]) ? this.site.anchors[''+pid][anchor] : null),
								pageData[anchor]);
					}
				}
			}
		},
		
		normalizeDataPart: function(dataPart) {
			var normDataPart;
			if (this.site.languages.length > 0) {
				normDataPart = {};
				for (var i=0, len=this.site.languages.length; i < len; i++) {
					var langCode = this.site.languages[i].code;
					normDataPart[langCode] = (dataPart && (typeof dataPart === 'object'))
							? ((langCode in dataPart) ? dataPart[langCode] : false) : (dataPart ? true : false);
				}
			} else {
				normDataPart = (dataPart && (typeof dataPart === 'object'))
						? ((this.site.lastDefLang && (this.site.lastDefLang in dataPart)) ? dataPart[this.site.lastDefLang] : false) : (dataPart ? true : false);
			}
			return normDataPart;
		},
		
		mergeDataParts: function(dataPartA, dataPartB) {
			var result;
			var normDataPartA = this.normalizeDataPart(dataPartA);
			var normDataPartB = this.normalizeDataPart(dataPartB);
			if (this.site.languages.length > 0) {
				result = $.extend(true, {}, normDataPartA);
				for (var langCode in normDataPartB) {
					result[langCode] = normDataPartB[langCode];
				}
			} else {
				result = normDataPartB;
			}
			return result;
		},
		
		substractDataPart: function(dataPartA, dataPartB) {
			var result;
			var normDataPartA = this.normalizeDataPart(dataPartA);
			var normDataPartB = this.normalizeDataPart(dataPartB);
			if (this.site.languages.length > 0) {
				result = $.extend(true, {}, normDataPartA);
				for (var langCode in normDataPartB) {
					result[langCode] = !normDataPartB[langCode];
				}
			} else {
				result = !normDataPartB;
			}
			return result;
		},
		
		/**
		 * Fix anchor data for older websites applying new structure
		 * @param {Object} oldData list distributed by pages
		 */
		fixOldData: function(oldData) {
			var newData = {};
			var i, j, len;
			for (var pageId in oldData) {
				for (i=0, len=oldData[''+pageId].length; i < len; i++) {
					if (!(''+pageId in newData)) newData[''+pageId] = {};
					for (j=0; j < oldData[''+pageId].length; j++) {
						newData[''+pageId][oldData[''+pageId][j]] = true;
					}
				}
			}
			return newData;
		}
		
	};

	Service.site = Site;
	window.WB_Site = Site;

	return Site;
});
;

/** WB Body **/
(window.defineModule = (window.defineModule || {})).name = 'WB Body';

define('Body', ['Service', 'ModeManager', 'ElementBox', 'Content', 'ContextMenu', 'PointerTracker', 'BuilderEvent'], function(Service, ModeManager, ElementBox, Content, ContextMenu, PointerTracker, BuilderEvent) {
	'use strict';

	/**
	 * Builder site Body class
	 * @param {Object} data
	 * @param {Object} elem
	 * @class
	 */
	var Body = function(data, elem) { this.__construct(data, elem); };

	Body.prototype.elem = null;
	Body.prototype.site = null;
	Body.prototype.siteRoot = null;
	Body.prototype.siteCover = null;
	Body.prototype.secBg = null;
	/** @type {Content[]} */
	Body.prototype.blocks = null;
	Body.prototype.blocksData = null;
	Body.prototype.menu = null;
	Body.prototype.siteWidth = 1003;
	Body.prototype.mlSiteHeight = null;
	Body.prototype.bgSite = null;
	Body.prototype.bg2Site = null;
	Body.prototype.siteTextFont = null;
	Body.prototype.siteLinkFontNormal = null;
	Body.prototype.siteLinkFontHover = null;
	Body.prototype.cssRuleIndexes = null;
	/** @type Object */
	Body.prototype.modes = null;

	/**
	 * Construct builder site body
	 * @param {Object} data body data object
	 * @param {Object} elem html dom element to create from
	 */
	Body.prototype.__construct = function(data, elem) {
		this.elem = $(elem);
		this.elem.attr({dir: (wb_builder.site.rtl ? 'rtl' : 'ltr')});
		this.site = $("#site", this.elem);
		this.siteRoot = this.site.children('.root').eq(0);
		this.siteCover = $(".site_cover", this.elem);
		this.secBg = $('<div class="wb_sbg"></div>');
		this.siteRoot.append(this.secBg);

		this.cssRuleIndexes = { a: -1, b: -1, c: -1 };

		this.blocks = {};
		var thisClass = this;
		this.siteWidth = data.content.siteWidth ? data.content.siteWidth : this.siteWidth;
		$(".wb_container", this.elem).each(function() {
			if (!this.id) return;
			var bdata = data.content.blocks[this.id] ? data.content.blocks[this.id] : null;

			if (!bdata && $(".wb_container#wb_right", this.elem).length === 0 &&
					this.id === "wb_left") bdata = data.content.blocks.wb_right;
			if (!bdata && $(".wb_container#wb_left", this.elem).length === 0 &&
					this.id === "wb_right") bdata = data.content.blocks.wb_left;
			if (!bdata) bdata = {};

			if (!bdata.content) bdata.content = {};
			thisClass.blocks[this.id] = new Content(bdata, this, thisClass);
			thisClass.blocks[this.id].setWidth(thisClass.siteWidth);
		});
		this.mlSiteHeight = data.content.mlSiteHeight ? data.content.mlSiteHeight : {};
		this.bgSite = data.content.bgSite ? data.content.bgSite : {
			color: "transparent",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "transparent none repeat scroll left top" }
		};
		this.bg2Site = data.content.bg2Site ? data.content.bg2Site : {
			color: "transparent",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "transparent none repeat scroll left top" }
		};

		this.siteTextFont = data.content.siteTextFont ? data.content.siteTextFont : {
			color: "#333333",
			size: 13,
			decoration: "none",
			font: "Arial,sans-serif",
			style: { },
			align: "left",
			lineHeight: 18, 
			css: {
				font: "normal normal 13px Arial,sans-serif",
				color: "#333333",
				"text-align": "left",
				"text-decoration": "none",
				"line-height": "18px"
			}
		};

		this.siteLinkFontNormal = data.content.siteLinkFontNormal ? data.content.siteLinkFontNormal : {	
			color: "#0088cc",
			size: 13,
			decoration: "underline",
			font: "Arial,sans-serif",
			style: { },
			align: "left",
			lineHeight: 18, 
			css: {
				font: "normal normal 13px Arial,sans-serif",
				color: "#0088cc",
				"text-align": "left",
				"text-decoration": "underline",
				"line-height": "18px"
			}
		};

		this.siteLinkFontHover = data.content.siteLinkFontHover ? data.content.siteLinkFontHover : {	
			color: "#005580",
			size: 13,
			decoration: "underline",
			font: "Arial,sans-serif",
			style: { },
			align: "left",
			lineHeight: 18, 
			css: {
				font: "normal normal 13px Arial,sans-serif",
				color: "#005580",
				"text-align": "left",
				"text-decoration": "underline",
				"line-height": "18px"
			}
		};
		
		this.blocksData = data.content.blocksData ? data.content.blocksData : {};

		this.elem.selectable({
			"filter":	".wb_element",
			"cancel":	".wb_element,.layout_border",
			//"delay":	20,
			"distance": 5,
			"start":	function(event, ui) {
				ContextMenu.hideAllMenus();
			},
			"stop":		function(event, ui) {
				Content.selectionRef = thisClass;
				WB_Element.selected = {};
				$(".ui-selected", this).each(function() {
					$(this).trigger("mouseover");
					var o = $(this).wbGetClassInstance();
					if (o) WB_Element.selected[o.id] = o;
				});
			},
			"unselected":function(event, ui) {
				$(ui.unselected).trigger("mouseout");
				var o = $(ui.unselected).wbGetClassInstance();
				if (o) {
					WB_Element.selected[o.id] = null;
					delete WB_Element.selected[o.id];
				}
			}
		});

		this.elem.on("click", function(e) {
			Service.element.unselectAll();
			wb_builder.clearSelections();
			e.stopPropagation();
		});


		this.updateStyle();

		var k;
		this.modes = {}; if (data.modes) for (k in data.modes) { this.modes[k] = new Body.Mode(data.modes[k]); }
		var p = wb_builder.site.getPage(wb_builder.pageId);
		if (p && ('modes' in p)) { for (k in p.modes) { this.modes[k] = new Body.Mode(p.modes[k]); } }
		this.initTouchDragging();
	};
	
	Body.prototype.setLandingLock = function(lock) {
		for (var i in this.blocks) {
			if (this.blocks[i].id === 'wb_header' || this.blocks[i].id === 'wb_footer') {
				this.blocks[i].setLocked(lock);
			}
		}
	};

	Body.prototype.enableDropZones = function(enable) {
		for (var k in this.blocks) {
			this.blocks[k].enableDropZone(enable);
		}
	};
	
	Body.prototype.initTouchDragging = function() {
		var thisSelf = this;
		var helpIsActive = false;
		var helpPlayerIsActive = false;

		BuilderEvent.GlobalEvents.on("help.show help.hide", function(e) { helpIsActive = e.visible; });
		BuilderEvent.GlobalEvents.on("help.playershow help.playerhide", function(e) { helpPlayerIsActive = e.visible; });

		var triggerJQueryUIEvent = function(eventType, callback, element, pointer) {
			var ui = {
				draggable: pointer.data.elem.elem,
				helper: pointer.data.elem.elem,
				position: {
					left: pointer.data.pos.left + pointer.positionDelta.x,
					top: pointer.data.pos.top + pointer.positionDelta.y
				},
				offset: {
					left: pointer.data.offs.left + pointer.positionDelta.x,
					top: pointer.data.offs.top + pointer.positionDelta.y
				}
			};
			if( typeof callback === "function" ) {
				var e = {
					type: eventType,
					target: element,
					clientX: pointer.position.clientX,
					clientY: pointer.position.clientY,
					pageX: pointer.position.pageX,
					pageY: pointer.position.pageY,
					stopPropagation: function() {},
					preventDefault: function() {}
				};
				callback.call(element, e, ui);
			}
			return ui;
		};
		var handleDroppableEvents = function(eventType, pointer) {
			if( pointer.data.droppableBlocks ) {
				var triggerCallback;
				var offsetTop = null;
				for( var i = 0; i < pointer.data.droppableBlocks.length; i++ ) {
					var block = pointer.data.droppableBlocks[i];
					var droppable = block.data("droppable");
					if( droppable ) {
						if( eventType === "activate" ) {
							triggerJQueryUIEvent("dropactivate", droppable.options.activate, block, pointer);
						}
						else if( eventType === "deactivate" ) {
							block.removeClass(droppable.options.hoverClass);
							triggerJQueryUIEvent("dropdeactivate", droppable.options.deactivate, block, pointer);
							if( droppable.isover )
								triggerJQueryUIEvent("drop", droppable.options.drop, block, pointer);
							droppable.isover = 0;
							droppable.isout = 1;
						}
						else {
							var bounds = block.get(0).getBoundingClientRect();

							var isOver = pointer.position.clientX >= bounds.left && pointer.position.clientX <= bounds.right && pointer.position.clientY >= bounds.top && pointer.position.clientY <= bounds.bottom;
							if( !isOver && eventType === "out" ) {
								triggerCallback = droppable.isover;
								droppable.isout = 1;
								droppable.isover = 0;
								block.removeClass(droppable.options.hoverClass);
								if( triggerCallback )
									triggerJQueryUIEvent("dropout", droppable.options.out, block, pointer);
							}
							if( isOver && eventType === "over" ) {
								triggerCallback = !droppable.isover;
								droppable.isout = 0;
								droppable.isover = 1;
								block.addClass(droppable.options.hoverClass);
								if( triggerCallback )
									triggerJQueryUIEvent("dropover", droppable.options.over, block, pointer);
							}
						}
					}
				}
			}
		};

		this.pointerTracker = new PointerTracker.PointerTracker(this.elem, {
			trackMouse: false,
			allowMultiplePointers: false,
			onPointerStart: function(pointer) {
				var i, b, c, elements = null, droppables = null, droppableBlocks = [];
				if( helpIsActive && !helpPlayerIsActive )
					return false;

				if( helpPlayerIsActive ) {
					c = Service.HelpSystemPlayer.getCanvas();
					if( c ) {
						elements = c.getElements();
						droppables = $(".ui-droppable", c.elem);
					}
				}

				if( elements === null ) {
					elements = thisSelf.getContentElements();
					droppables = $(".ui-droppable");
				}

				if( droppables ) {
					droppables.each(function() {
						var $this = $(this);
						var droppable = $this.data("droppable");
						if( droppable && $this.is(":visible") && !$this.droppable("option", "disabled") && (!droppable.options.accept || droppable.options.accept.indexOf(".wb_element") >= 0) )
							droppableBlocks.push($this);
					});
				}

				for (i = 0; i < elements.length; i++) {
					if( elements[i].isHidden() || elements[i].isHidden(true) )
						continue;
					var draggable = elements[i].elem.data("draggable");
					b = elements[i].getBounds();
					if (b.pageLeft < pointer.position.pageX && (b.pageLeft + b.width) > pointer.position.pageX && b.pageTop < pointer.position.pageY && (b.pageTop + b.height) > pointer.position.pageY) {
						if (!pointer.data || pointer.data.elem.zIndex < elements[i].zIndex) {
							pointer.data = {
								droppableBlocks: droppableBlocks,
								draggableOptions: draggable ? draggable.options : null,
								elem: elements[i],
								pos: {left: b.left, top: b.top},
								offs: elements[i].elem.offset()
							};
						}
					}
				}

				if( !pointer.data )
					return false;
				Service.contextMenu.hideAll();
				Service.element.unselectAll();
				pointer.data.elem.setSelected(true);
				pointer.data.elem.setControlsVisible(true);
				return true;
			},
			onDragStart: function(pointer) {
				if( !pointer.data || !pointer.data.draggableOptions )
					return;
				pointer.data.elem.elem.addClass("ui-draggable-dragging");
				if( typeof pointer.data.draggableOptions.start === "function" ) {
					var ui = triggerJQueryUIEvent("dragstart", pointer.data.draggableOptions.start, pointer.data.elem.elem.get(0), pointer);
					pointer.data.elem.setLocation(Math.round(ui.position.left), Math.round(ui.position.top));
				}
				handleDroppableEvents("activate", pointer);
			},
			onDragMove: function(pointer) {
				if( !pointer.data || !pointer.data.draggableOptions )
					return;
				handleDroppableEvents("out", pointer);
				if( typeof pointer.data.draggableOptions.drag === "function" ) {
					var ui = triggerJQueryUIEvent("drag", pointer.data.draggableOptions.drag, pointer.data.elem.elem.get(0), pointer);
					pointer.data.elem.setLocation(Math.round(ui.position.left), Math.round(ui.position.top));
				}
				handleDroppableEvents("over", pointer);
			},
			onDragEnd: function(pointer) {
				if( !pointer.data || !pointer.data.draggableOptions )
					return;
				pointer.data.elem.elem.removeClass("ui-draggable-dragging");
				handleDroppableEvents("deactivate", pointer);
				if( typeof pointer.data.draggableOptions.stop === "function" ) {
					var ui = triggerJQueryUIEvent("dragstop", pointer.data.draggableOptions.stop, pointer.data.elem.elem.get(0), pointer);
					pointer.data.elem.setLocation(Math.round(ui.position.left), Math.round(ui.position.top));
				}
			},
			onClick: function(pointer) {
				if (pointer.data && pointer.data.elem.isSelected())
					pointer.data.elem.menu.show(pointer.position);
			}
		});
	};
	
	/**
	 * Switch to mode (one of ModeManager.MODE_* constants)
	 * @param {string} fromMode
	 * @param {string} toMode
	 * @param {Object} initial
	 */
	Body.prototype.switchMode = function(fromMode, toMode, initial) {
		for (var k in this.blocks) this.blocks[k].switchMode(fromMode, toMode, initial);
		if (!toMode || !Service.modeManager.getUseModes()) return;
		if (!(fromMode in this.modes)) {
			this.modes[fromMode] = new Body.Mode();
		}
		this.modes[fromMode].store(this);
		if (!(toMode in this.modes)) {
			this.modes[toMode] = new Body.Mode();
			this.modes[toMode].copy(this.modes[fromMode]);
		}
		if (initial || fromMode !== toMode) {
			if (!initial) this.storeMlHeight();
			this.modes[toMode].applyTo(this);
		}
		
		var thisSelf = this;
		ElementBox.switchMode(fromMode, toMode, initial);
		ElementBox.removeAllElements();
		/* if (toMode === ModeManager.MODE_PHONE || toMode === ModeManager.MODE_TABLET) { */
			var list = thisSelf.getContentElements();
			for (var i = 0; i < list.length; i++) {
				if (list[i].isHidden(true)) {
					list[i].hide(true);
				}
			}
		/* } */
		this.elementBoxSetVisible(true);
		
		for (var blockId in this.blocksData) {
			if (blockId === 'wb_main') continue;
			var blockData = this.blocksData[blockId];
			if (!blockData.modes) blockData.modes = {};
			if (!(fromMode in blockData.modes)) blockData.modes[fromMode] = {height: (blockData.height ? blockData.height : this.height)};
		}
	};
	
	Body.prototype.getBlockData = function(blockId) {
		return (this.blocksData && this.blocksData[blockId]) ? this.blocksData[blockId] : null;
	};
	
	Body.prototype.useBlockDataByDefault = function(blockId) {
		return (this.blocksData && this.blocksData[blockId] && this.blocksData[blockId].useDefault);
	};

	Body.prototype.elementBoxSetVisible = function(show) {
		var currMode = ModeManager.getMode();
		ElementBox.setVisible(
			show
			&& wb_builder.site.renderMode != Service.site.RENDER_MODE_RESPONSIVE2
			/* && (currMode === ModeManager.MODE_PHONE || currMode === ModeManager.MODE_TABLET) */
			&& $(window).width() > 485
		);
	};
	
	Body.prototype.storeMlHeight = function() {
		if (wb_builder.site.languages.length && wb_builder.site.currSelLang) {
			if (!this.mlSiteHeight) this.mlSiteHeight = {};
			this.mlSiteHeight[wb_builder.site.currSelLang] = this.site.children('.root').eq(0).height();
			wb_builder.setPageModified(true);
		}
	};
	
	Body.prototype.onBeforeSwitchLanguage = function() {
		for (var bid in this.blocks) {
			if (typeof this.blocks[bid].onBeforeSwitchLanguage === 'function') {
				this.blocks[bid].onBeforeSwitchLanguage();
			}
		}
		this.storeMlHeight();
	};
	
	Body.prototype.onSwitchLanguage = function(langCode) {
		for (var bid in this.blocks) {
			if (typeof this.blocks[bid].onSwitchLanguage === 'function') {
				this.blocks[bid].onSwitchLanguage(langCode);
			}
		}
	};

	/**
	 * Destroy this object
	 */
	Body.prototype.__destruct = function() {
		for (var bid in this.blocks) {
			if (typeof(this.blocks[bid].__destruct) === "function") {
				this.blocks[bid].__destruct();
			}
		}
		this.siteCover.detach();
		this.site.empty().append(this.siteCover);
	};

	/**
	 * Serialize this element
	 * @return {Object}
	 */
	Body.prototype.serialize = function() {
		var m;
		this.storeMlHeight();
		if (Service.modeManager.getUseModes()) {
			var mode = ModeManager.getMode();
			this.switchMode(mode, mode);
			m = this.modes[mode].serialize();
		} else {
			m = {siteWidth: this.siteWidth, siteHeight: this.site.children('.root').eq(0).height(), mlSiteHeight: this.mlSiteHeight};
		}
		var modes = {}; for (var k in this.modes) { modes[k] = this.modes[k].serialize(); }
		return {
			"class": "Body",
			content: {
				blocksData: Object.assign({}, this.blocksData),
				siteWidth: m.siteWidth,
				siteHeight: m.siteHeight,
				mlSiteHeight: m.mlSiteHeight,
				bgSite: this.bgSite,
				bg2Site: this.bg2Site,
				siteTextFont: this.siteTextFont,
				siteLinkFontNormal: this.siteLinkFontNormal,
				siteLinkFontHover: this.siteLinkFontHover
			},
			modes: modes
		};
	};

	/**
	 * Add element to body content block
	 * @param blockId block id to add element to
	 * @param elem element to add
	 * @param noZReset no z-index sorting
	 */
	Body.prototype.addElement = function(blockId, elem, noZReset, initial) {
		var _blockId = blockId;
		if (!this.blocks[_blockId] && _blockId === "wb_left") _blockId = "wb_right";
		if (!this.blocks[_blockId] && _blockId === "wb_right") _blockId = "wb_left";
		if (!this.blocks[_blockId]) _blockId = "wb_main";
		if (!this.blocks[_blockId]) _blockId = "wb_content";
		if (!this.blocks[_blockId]) {
			for (var k in this.blocks) {
				_blockId = k;
				break;
			}
		}
		if (this.blocks[_blockId]) {
			this.blocks[_blockId].addElement(elem, noZReset, initial);
		}
	};

	Body.prototype.zReset = function() {
		for (var blockId in this.blocks) { this.blocks[blockId].changeElementLayer(); }
	};

	/**
	 * Get content block by id
	 * @param blockId block id
	 * @return {Content}
	 */
	Body.prototype.getContentBlock = function(blockId) {
		return this.blocks[blockId] ? this.blocks[blockId] : null;
	};

	/**
	 * Get content elements
	 * @return array of elements
	 */
	Body.prototype.getContentElements = function() {
		var list = [];
		for (var k in this.blocks) {
			var slist = this.blocks[k].getElements();
			for (var k1 in slist) {
				list[list.length] = slist[k1];
			}
		}
		return list;
	};

	/**
	 * Fit elements to content blocks in this body
	 * @param {Boolean} force ignores ignoreParentBounds setting
	 */
	Body.prototype.fitElements = function(force) {
		for (var k in this.blocks) {
			this.blocks[k].fitElements(force);
		}
	};

	/**
	 * Update size request from block element
	 * @param block
	 */
	Body.prototype.updateSize = function(block) {
		var parent = block.elem;
		while (parent.attr("id") !== "site" && (parent = parent.parent())) {
			//var pid = "";
			var maxH = 0;
			parent.children(".hbox").css("height", "");
			parent.children().each(function() {
				if ($(this).hasClass("site_cover") || $(this).hasClass("wb-active-zone") || $(this).hasClass("wb_sbg")) return;
				var height = (($(this).css("minHeight") + "").replace("px", "")*1);
				var height2 = $(this).outerHeight(true);
				var h = $(this).position().top + ((height && height > height2) ? height : height2);
				//pid = $(this).attr("id") ? $(this).attr("id") : $(this).attr("class");
				//console.log("Height: " + pid + " = " + h);
				if (h > maxH) maxH = h;
			});
			//pid = parent.attr("id") ? parent.attr("id") : parent.attr("class");
			//console.log("Update size: " + pid + " = " + maxH);
			parent.css("height", maxH + "px");
			parent.children(".hbox").each(function() {
				$(this).css("height", maxH + "px");
			});
		}
		var i, mBlock;
		for (i in this.blocks) {
			mBlock = this.blocks[i];
			if (mBlock.lock) {
				mBlock.setSize(null, mBlock.elem.height());
			}
		}
	};

	/**
	 * Update style from properties to elements and generate generatable styles
	 * call this method after changing .bg* properties to apply those changes
	 * @param {boolean} [updateBlocks=false] if true then will update block style to.
	 */
	Body.prototype.updateStyle = function(updateBlocks) {
		var bg = $.extend({}, this.bgSite);
		var p = wb_builder.site.getPage(wb_builder.pageId);
		if (p && p.background && (
				(p.background.image && p.background.image !== "none") ||
				(p.background.color && p.background.color !== "transparent")
			)) {
			bg = p.background;
		}
		var css = bg.css;
		if (css.background && bg.image && bg.image !== "none") {
			css.background = css.background.replace(/url\([^\)]+\)/i, 'url("' + wb_builder.makeLocalUrl(bg.image, true) + '")');
		}
		var _css = $.extend({}, css), pos, m;
		if (_css.background && bg.attachment === 'fixed' && (m = bg.position.split(' ')) && m.length === 2 && m[1] === 'top') {
			pos = m[0] + ' ' + wb_builder.body.offset().top + 'px';
			_css.background = _css.background.replace(bg.position, pos);
		}
		this.site.css(_css);

		var bg2 = $.extend({}, this.bg2Site);
		if (p && p.background2 && (
				(p.background2.image && p.background2.image !== "none") ||
				(p.background2.color && p.background2.color !== "transparent")
			)) {
			bg2 = p.background2;
		}
		css = bg2.css;
		if (css.background && bg2.image && bg2.image !== "none") {
			css.background = css.background.replace(/url\([^\)]+\)/i, 'url("' + wb_builder.makeLocalUrl(bg2.image, true) + '")');
		}
		_css = $.extend({}, css);
		if (_css.background && bg2.attachment === 'fixed' && (m = bg2.position.split(' ')) && m.length === 2 && m[1] === 'top') {
			pos = m[0] + ' ' + wb_builder.body.offset().top + 'px';
			_css.background = _css.background.replace(bg2.position, pos);
		}
		this.secBg.css(_css);

		this.setWidth(this.siteWidth);
		
		if (updateBlocks) {
			for (var k in this.blocks) this.blocks[k].updateStyle(true);
		}

		/* disable 
		this.cssRuleIndexes.a = wb_builder.addCSSRule("#" + this.site.attr("id") + "," +
			" #" + this.site.attr("id") + " p", this.siteTextFont.css,
			null, this.cssRuleIndexes.a);
		this.cssRuleIndexes.b = wb_builder.addCSSRule("#" + this.site.attr("id") + " a",
			this.siteLinkFontNormal.css, null, this.cssRuleIndexes.b);
		this.cssRuleIndexes.c = wb_builder.addCSSRule("#" + this.site.attr("id") + " a:hover",
			this.siteLinkFontHover.css, null, this.cssRuleIndexes.c);
		*/
	};

	/**
	 * Set site width
	 * @param width
	 */
	Body.prototype.setWidth = function(width) {
		var w = parseInt(width, 10), ws, ws2;
		this.siteWidth = isNaN(w) ? 0 : w;
		ws = this.siteWidth ? (this.siteWidth + 'px') : '';
		// make wider for page guides (layout lines) to fit
		ws2 = this.siteWidth ? ((this.siteWidth + 5) + 'px') : '';
		// this.siteRoot.css('width', ws);
		this.siteRoot.css('width', '100%');
		this.site.css('min-width', ws2);
		for (var k in this.blocks) {
			this.blocks[k].setWidth(this.siteWidth);
		}
	};

	/**
	 * Get size of the site
	 * @return object = { width: ..., height: ... }
	 */
	Body.prototype.getSiteSize = function() {
		return {
			width: this.siteWidth,
			height: this.site.children(".root").height(),
			mlHeight: this.mlSiteHeight
		};
	};

	// unused 

	Body.prototype.fixSize = function() {
		var head = document.getElementById("wb_head");
		if (head) {
			var h = $(window).height() - $(head).outerHeight(true);
			$(this.element).height(h);
		}
	};

	Body.prototype.initContextMenu = function(elem) {
		var thisClass = this;
		this.menu = new ContextMenu("wb_body_contextmenu");

		this.pagesMenu = new ContextMenu();

		this.menu.addItem("comConfig", __("Properties"), function() {
			//thisClass.changeProperties();
			wb_builder.site.changePageBackground();
		}, null, null, null, "glyphicon glyphicon-cog");

		this.menu.bind(elem, true);
		this.menu.onShow = function(ctxmenu, e) {
			//thisClass.updateContextMenu();
			var ea = new BuilderEvent.ContextMenuEvent(ctxmenu, (e ? e.pageX : 0), (e ? e.pageY : 0), thisClass);
			BuilderEvent.GlobalEvents.triggerEvent('contextmenu.show', ea);
		};
	};

	Body.Mode = (function($) {
		/** @namespace Body */

		/**
		 * @param {Body.Mode} mode
		 * @param {Object} data
		 */
		var applyData = function(mode, data) {
			mode.siteWidth = data.siteWidth;
			mode.siteHeight = data.siteHeight;
			mode.mlSiteHeight = data.mlSiteHeight;
		};

		/**
		 * @param {Object} data
		 * @class Body.Mode
		 */
		var self = function(data) { if (data) applyData(this, data); };
		/** @type Number */
		self.prototype.siteWidth = 2014;
		/** @type Number */
		self.prototype.siteHeight = 2014;
		/** @type mixed */
		self.prototype.mlSiteHeight = {};
		/** @param {Body.Mode} mode */
		self.prototype.copy = function(mode) {
			applyData(this, mode);
		};
		/** @param {Body} elem */
		self.prototype.store = function(elem) {
			applyData(this, {
				siteWidth: elem.siteWidth,
				siteHeight: elem.site.children('.root').eq(0).height(),
				mlSiteHeight: elem.mlSiteHeight
			});
		};
		/** @param {Body} elem */
		self.prototype.applyTo = function(elem) {
			elem.siteWidth = this.siteWidth;
			elem.site.children('.root').eq(0).height(this.siteHeight);
			elem.mlSiteHeight = this.mlSiteHeight;
			elem.getContentBlock('wb_main').updateSize();
		};
		/** @return {Object} */
		self.prototype.serialize = function() {
			return { siteWidth: this.siteWidth, siteHeight: this.siteHeight, mlSiteHeight: this.mlSiteHeight };
		};

		return self;
	})($);
	
	return Body;
});
;

/** WB Content **/
(window.defineModule = (window.defineModule || {})).name = 'WB Content';

define('Content', ['ElementRegister', 'Service', 'ModeManager', 'PasteDialog', 'ContextMenu', 'util/MenuList', 'BuilderEvent'], function(ElementRegister, Service, ModeManager, PasteDialog, ContextMenu, MenuList, BuilderEvent) {
	'use strict';
	
	/**
	 * Container class to contain elements
	 * @param {Object} data
	 * @param {Object} elem
	 * @param {Object} bodyInstance
	 */
	var Content = function(data, elem, bodyInstance) { this.__construct(data, elem, bodyInstance); };

	Content.lastIndex = 0;
	Content.selectionRef = null;

	Content.prototype.elem = null;
	Content.prototype.id = null;
	Content.prototype.name = null;
	Content.prototype.container = null;
	Content.prototype.containerWrapper = null;
	Content.prototype.containerForFullWidth = null;
	Content.prototype.minHeight = 50;
	Content.prototype.mlHeight = null;
	Content.prototype.height = null;
	Content.prototype.bodyInstance = null;
	Content.prototype.menu = null;
	Content.prototype.pagesMenu = null;
	Content.prototype.bodyMenu = null;
	Content.prototype.activeZone = null;
	Content.prototype.activeZoneBody = null;
	Content.prototype.grid = null;

	Content.prototype.parentAutoHeight = true;
	Content.prototype.dialog = null;
	Content.prototype.fittinOk = false;
	Content.prototype.noClasses = null;
	Content.prototype.isFlexible = true;
	Content.prototype.isInitFlexible = false;
	Content.prototype.waitingUpdate = false;
	Content.prototype.zLayers = null;
	Content.locTip = null;
	Content.prototype.dialog = null;
	Content.prototype.pasteDialog = null;
	Content.prototype.background = null;
	Content.prototype.blockPadding = 0;
	Content.prototype.size = null;
	/** @type Object */
	Content.prototype.modes = null;
	Content.prototype.lock = null;
	Content.prototype.locked = null;
	Content.prototype._modeNeedsCheckHeight = false;

	/**
	 * Construct container
	 * @param data content data
	 * @param elem DOM element to construct controller from
	 * @param bodyInstance Instance of Body class.
	 */
	Content.prototype.__construct = function(data, elem, bodyInstance) {
		var thisClass = this;
		this.bodyInstance = bodyInstance;
		this.elem = $(elem);
		this.elem.wbSetClassInstance(this);
		this.id = this.elem.attr("id");
		this.elem.css({position: "relative"});
		if (!this.id) this.id = "wb_content_instance" + (Content.lastIndex++);
		this.name = __("Block");
		if (this.id === "wb_header") {
			this.name = __("Header Block");
		} else if (this.id === "wb_footer") {
			this.name = __("Footer Block");
		} else if (this.id === "wb_left") {
			this.name = __("Left Block");
		} else if (this.id === "wb_right") {
			this.name = __("Right Block");
		} else if (this.id === "wb_main") {
			this.name = __("Main Block");
		}
		if (this.id === 'wb_footer') {
			this.isInitFlexible = true;
			this.minHeight = 0;
		}
		this.activeZoneBody = $('<div class="wb-active-zone"></div>');
		this.elem.append(this.activeZoneBody);

		this.containerWrapper = $('<div></div>');
		this.containerWrapper.css({position: "relative", margin: "0 auto", width: "100%", height: "100%"});
		this.elem.append(this.containerWrapper);

		this.container = $('<div></div>');
		this.container.css({width: "100%", height: "100%"});
		this.containerWrapper.append(this.container);

		this.containerForFullWidth = $('<div></div>');
		this.containerForFullWidth.css({position: "absolute", width: "100%", left: 0, top: 0});
		this.elem.append(this.containerForFullWidth);

		this.zLayers = {};

		this.isFlexible = (this.id !== "wb_header" && this.id !== "wb_footer");

		this.grid = $('<div class="wb_grid"></div>');
		this.containerWrapper.append(this.grid);

		this.activeZone = $('<div class="wb-active-zone"></div>');
		this.containerWrapper.append(this.activeZone);

		this.container.droppable({
			tolerance: "pointer",
			hoverClass: "wb-state-highlight",
			accept: ".wb_element,.wb_item",
			drop: function(e, ui) {
				var itm = ui.draggable.wbGetClassInstance();
				var addItm = function(itm) {
					if( itm.snapData && itm.getParent() !== thisClass ) {
						itm.snapData.droppedOnBlock = thisClass;
					}
					else {
						var offset = thisClass.container.offset();
						itm.setLocation(
							wb_builder.autoSnapX(ui.offset.left - offset.left),
							wb_builder.autoSnapY(ui.offset.top - offset.top, thisClass.id)
						);
						thisClass.addElement(itm);
						//			if (wb_builder.showLayout)
						//				wb_builder.highlightLayout(true);
					}
					wb_builder.setPageModified(true);
				};
				if (itm) {
					if (itm.removed || itm.dropAccepted) return false;
					addItm(itm);
				} else {
					var className = ui.draggable.attr('id');
					className = className ? className.split("__")[1] : null;
					if (!className) return;

					var data = {content: {}};
					if (thisClass.id === 'wb_header' || thisClass.id === 'wb_footer') {
						data.isCommon = true; data.includePages = {};
					}

					ElementRegister.createElement(className, function(itm) {
						addItm(itm);
					}, data);
				}
			}
		});
		
		this.height = data.height ? data.height: null;
		this.mlHeight = data.mlHeight ? data.mlHeight : {};
		this.blockPadding = (data.content && data.content.blockPadding && !isNaN(parseInt(data.content.blockPadding, 10)))
			? parseInt(data.content.blockPadding, 10) : this.blockPadding;
		var h;
		if (this.isFlexible) {
			h = this.getHeight();
		} else {
			h = parseInt(data.height, 10);
			if (isNaN(h)) h = this.getHeight();
			if (!h) h = 200;
		}
		this.setSize(null, h + this.resolveBlockPadding());


		this.background = (data.content && data.content.background) ? data.content.background : {
			color: "transparent",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "transparent none repeat scroll left top" }
		};

		/*this.elem.selectable({
			"filter":	".wb_element",
			"cancel":	".wb_element",
			//"delay":	20,
			"distance": 5,
			"start":	function(event, ui) {
				thisClass.menu.hide();
			},
			"stop":		function(event, ui) {
				Content.selectionRef = thisClass;
				WB_Element.selected = {};
				$(".ui-selected", this).each(function() {
					$(this).trigger("mouseover");
					var o = $(this).wbGetClassInstance();
					WB_Element.selected[o.id] = o;
				});
			},
			"unselected":function(event, ui) {
				$(ui.unselected).trigger("mouseout");
				var o = $(ui.unselected).wbGetClassInstance();
				WB_Element.selected[o.id] = null;
				delete WB_Element.selected[o.id];
			}
		});*/

		/*this.elem.bind("click", function() {
			ContextMenu.hideAllMenus();
			WB_Element.unselectAll();
		});*/

		if (!Content.locTip) {
			Content.locTip = $('<div class="wb_loctip"></div>');
			Content.locTip.css("display", "none");
			$(document.body).ready(function() {
				$(document.body).append(Content.locTip);
			});
		}

		this.modes = {}; if (data.modes) for (var k in data.modes) { this.modes[k] = new Content.Mode(data.modes[k]); }

		this.updateStyle();

		this.initContextMenu(this.activeZone);
		if (this.bodyInstance) this.bodyInstance.initContextMenu(this.activeZoneBody);
	};
	
	Content.prototype.setLocked = function(locked) {
		this.locked = locked ? true : false;
		if (this.locked) {
			if (!this.lock) {
				this.lock = $('<div class="wb_block_lock"></div>');
				$('#site').append(this.lock);
			}
			this.setSize(null, this.getHeight());
		} else {
			if (this.lock) {
				this.lock.detach();
				this.lock.remove();
				this.lock = null;
			}
		}
		this.elem.css({ opacity: (this.locked ? 0.2 : 1) });
	};

	Content.prototype.enableDropZone = function(enable) {
		this.container.droppable(enable ? "enable" : "disable");
	};

	/**
	* Switch to mode (one of ModeManager.MODE_* constants)
	* @param {String} fromMode
	* @param {String} toMode
	*/
	Content.prototype.switchMode = function(fromMode, toMode, initial) {
		if (!toMode || !Service.modeManager.getUseModes()) return;
		var defData = (this.bodyInstance.blocksData && this.bodyInstance.blocksData[this.id]) ? this.bodyInstance.blocksData[this.id] : null;
		if (defData && defData.useDefault) return;
		
		if (!(fromMode in this.modes)) {
			this.modes[fromMode] = new Content.Mode();
		}
		if (!initial) {
			this.modes[fromMode].store(this);
		}
		if (!(toMode in this.modes)) {
			this.modes[toMode] = new Content.Mode();
			this.modes[toMode].copy(this.modes[fromMode]);
		}
		if (initial || fromMode !== toMode) {
			if (!initial) this.storeMlHeight();
			this.modes[toMode].applyTo(this);
		}
	};

	/**
	 * Destroy this object
	 */
	Content.prototype.__destruct = function() {
		var list = this.getElements();
		for (var lid in list) {
			this.removeElement(list[lid], true);
			if (typeof(list[lid].__destruct) === "function") {
				list[lid].__destruct();
			}
			list[lid] = null;
		}
		if (this.lock) {
			this.lock.detach();
			this.lock.remove();
			this.lock = null;
		}
	};

	/**
	 * Serialize this container
	 * @return {Object}
	 */
	Content.prototype.serialize = function() {
		var m;
		this.storeMlHeight();
		if (Service.modeManager.getUseModes()) {
			var mode = ModeManager.getMode();
			this.switchMode(mode, mode);
			if (mode in this.modes) {
				m = this.modes[mode].serialize();
			}
		}
		if (!m) m = {height: this.getBounds().height, mlHeight: this.mlHeight};
		var modes = {}; for (var k in this.modes) { modes[k] = this.modes[k].serialize(); }
		return {
			"class": "Content",
			"id": this.id,
			"isCommon": false,
			content: {
				background: this.background,
				blockPadding: this.blockPadding
			},
			height: m.height,
			mlHeight: m.mlHeight,
			modes: modes
		};
	};

	/**
	 * Get element by id
	 * @param id element id
	 * @return element
	 */
	Content.prototype.getElement = function(id) {
		var list = this.getElements();
		for (var i = 0; i < list.length; i++) {
			if (list[i].id == id) return list[i];
		}
		return null;
	};

	/**
	 * Get content elements
	 * @return array of elements
	 */
	Content.prototype.getElements = function() {
		var list = [];
		this.container.children(".wb_element").each(function() {
			var inst = $(this).wbGetClassInstance();
			if (!inst) return;
			list.push(inst);
		});
		this.containerForFullWidth.children(".wb_element").each(function() {
			var inst = $(this).wbGetClassInstance();
			if (!inst) return;
			list.push(inst);
		});
		return list;
	};

	/**
	 * Add element to this container
	 * @param elm element to add
	 * @param noZReset no z-index sorting
	 * @returns true on success else false
	 */
	Content.prototype.addElement = function(elm, noZReset, initial) {
		var elem = null;
		if (elm && elm instanceof WB_Element) {
			elem = elm;
		} else if ($(elm).size() > 0 && (elm = $(elm).wbGetClassInstance()) && (elm instanceof WB_Element)) {
			elem = elm;
		}
		if (!elem) return false;
		var parent = elem.getParent(), newElem = false;
		if (!parent || parent.id != this.id) {
			if (parent) {
				parent.removeElement(elem);
			} else {
				newElem = true;
			}
			this.updateElementContainer(elem);
			elem.setParent(this);
			elem.setZIndex(this.getValidZIndex(elem.getZIndex()));
			this.zLayers["z" + elem.getZIndex()] = true;
		}
		if (!noZReset) this.changeElementLayer();
		
		var oriHeight = this.resolveHeight();
		this.updateSize((initial && this.isInitFlexible), (initial && this.isInitFlexible ? oriHeight : null));
		elem.fitToParent(false, null, true);
		if (newElem) Service.HelpSystemPlayer.notify('add-plugin-' + elem.getClassType(), elem);
		return true;
	};

	Content.prototype.updateElementContainer = function(elem) {
		if( elem.isFullWidth )
			this.containerForFullWidth.append(elem.elem);
		else
			this.container.append(elem.elem);
	};
	
	Content.prototype.resolveBackground = function() {
		var data = this.bodyInstance ? this.bodyInstance.getBlockData(this.id) : null;
		var bg = (data && data.background) ? $.extend({}, data.background) : null;
		var bgOwn = this.background;
		if (!bg || bgOwn && (bgOwn.image && bgOwn.image !== 'none' || bgOwn.color && bgOwn.color !== 'transparent')) {
			bg = bgOwn;
		}
		return bg;
	};
	
	Content.prototype.resolveBlockPadding = function() {
		if (this.bodyInstance) {
			var data = this.bodyInstance.getBlockData(this.id);
			if (this.bodyInstance.useBlockDataByDefault(this.id)) {
				return data.blockPadding ? data.blockPadding : 0;
			}
		}
		return this.blockPadding;
	};
	
	Content.prototype.resolveHeight = function(mode) {
		if (!mode) mode = ModeManager.getMode();
		if (this.bodyInstance) {
			var data = this.bodyInstance.getBlockData(this.id);
			if (this.bodyInstance.useBlockDataByDefault(this.id)) {
				return (mode && data.modes && (mode in data.modes) && data.modes[mode] && ('height' in data.modes[mode]))
						? data.modes[mode].height
						: data.height;
			}
		}
		return (mode && this.modes && (mode in this.modes) && this.modes[mode] && ('height' in this.modes[mode]))
				? this.modes[mode].height
				: this.height;
	};

	/**
	 * Remove element from this container
	 * @param elm element to remove
	 * @param noSizeUpdate if true content size will not be updated
	 * @returns true on success else false
	 */
	Content.prototype.removeElement = function(elm, noSizeUpdate) {
		var elem = null;
		if (elm && elm instanceof WB_Element) {
			elem = elm;
		} else if ($(elm).size() > 0 && (elm = $(elm).wbGetClassInstance()) && (elm instanceof WB_Element)) {
			elem = elm;
		}
		if (!elem) return false;
		elem.elem.detach();
		elem.setParent(null);
		if (!noSizeUpdate) {
			this.changeElementLayer();
			this.updateSize();
		}
		return true;
	};

	/**
	 * Get unused zIndex
	 * @param zIndex try to find index as close as this
	 * @param topMost get zIndex to be on to
	 * @return zIndex
	 */
	Content.prototype.getValidZIndex = function(zIndex, topMost) {
		var i = 0;
		topMost = (topMost || isNaN(parseInt(zIndex, 10)) || parseInt(zIndex, 10) <= 1);
		if (topMost) {
			var maxIdx = 2;
			for (var k in this.zLayers) {
				var idx = parseInt(k.substring(1), 10);
				if (isNaN(idx)) idx = 0;
				if (idx > maxIdx) maxIdx = idx;
			}

			i = maxIdx + 1;
		} else {
			i = zIndex*1 + 2;
			if (i < 2) i = 2;
			while (this.zLayers["z" + i] && i < 10000) i++;
		}
		return i;
	};

	/**
	 * Change element layer (zIndex)
	 * @param elem element as WB_Element instance
	 * @param dir direction to change layer to
	 */
	Content.prototype.changeElementLayer = function(elem, dir) {
		var list = this.getElements(), i, indexes = [], idx;
		list.sort(function(a, b) { return (a.getZIndex() - b.getZIndex()); });
		for (i = 0; i < list.length; i++) {
			indexes.push(list[i].getZIndex());
		}
		if (elem) {
			idx = -1;
			for (i = 0; i < list.length; i++) {
				if (list[i].id == elem.id) {
					idx = i;
					break;
				}
			}
			if (idx < 0) return;
			var elm = list.splice(idx, 1)[0];
			if (dir === "top" && idx < list.length) {
				list.push(elm);
			} else if (dir === "bottom" && idx > 0) {
				list.unshift(elm);
			} else if (dir === "up" && idx < list.length) {
				list.splice(idx + 1, 0, elm);
			} else if (dir === "down" && idx > 0) {
				list.splice(idx - 1, 0, elm);
			}
		}

		this.zLayers = {};
		var off = 0;
		for (i = 0; i < list.length; i++) {
			idx = parseInt(indexes[i], 10);
			if (i === 0 && idx < 2) off = 2 - idx;
			idx += off;
			list[i].setZIndex(idx);
			this.zLayers["z" + idx] = true;
		}
	};

	/**
	 * Set element size
	 * @param width width in pixels
	 * @param height height in pixels
	 */
	Content.prototype.setSize = function(width, height) {
		var oldWidth, newWidth, oldHeight, newHeight;
		oldWidth = newWidth = this.getWidth();
		oldHeight = newHeight = this.getHeight();
		if (width !== undefined && !isNaN(parseInt(width))) {
			newWidth = parseInt(width);
			this.setWidth(width);
		}
		if (height !== undefined && !isNaN(parseInt(height))) {
			newHeight = parseInt(height);
			this.height = newHeight;
			$(this.elem).css({"height": newHeight + "px", "minHeight": newHeight + "px"});
			if (this.lock) {
				this.lock.css({'height': newHeight + 'px', 'top': (this.elem.offset().top - 1) + 'px'});
			}
			//this.container.css("height", (height + 100) + "px");
		}
		if( newWidth !== oldWidth || newHeight !== oldHeight ) {
			var ea = new BuilderEvent.BlocksResizeBuilderEvent(this, newWidth, newHeight);
			BuilderEvent.GlobalEvents.triggerEvent("blocks.resize", ea);
		}
	};

	Content.prototype.setWidth = function(width) {
		this.containerWrapper.css({"width": width + "px", "minWidth": width + "px", "maxWidth": width + "px"});
	};

	/**
	 * Get element width in pixels
	 * @returns width
	 */
	Content.prototype.getWidth = function() {
		return this.container.width();
	};

	/**
	 * Get element height in pixels
	 * @returns height
	 */
	Content.prototype.getHeight = function() {
		return this.elem.height();
	};

	/**
	 * Get element bounds in pixels
	 * @param asArray set to true, to return as array instead of object
	 * @returns object = {}
	 */
	Content.prototype.getBounds = function(asArray) {
		var o = {
			left: this.container.offset().left, top: this.elem.position().top,
			width: this.container.width(), height: this.container.height()
		};
		// var h = this.getCalculatedHeight();
		var b = {
			left: o.left,
			top: o.top,
			width: this.getWidth(),
			// height: h,
			height: this.getHeight(),
			width2: o.width,
			height2: o.height,
			left1: o.left,
			top1: o.top,
			left2: o.left + this.getWidth(),
			// top2: o.top + h
			top2: o.top + this.getHeight()
		};
		if (asArray)
			return [ b.left, b.top, b.left2, b.top2 ];
		return b;
	};

	Content.prototype.getBoundingClientRect = function() {
		return this.container[0].getBoundingClientRect();
	};

	/**
	 * Fit elements to this content block
	 * @param {Boolean} force
	 */
	Content.prototype.fitElements = function(force) {
		var list = this.getElements(), tmpIgnoreParentBounds;
		for (var i = 0; i < list.length; i++) {
			if (force) {
				tmpIgnoreParentBounds = list[i].ignoreParentBounds;
				list[i].ignoreParentBounds = false;
			}
			list[i].fitToParent();
			if (force) {
				list[i].ignoreParentBounds = tmpIgnoreParentBounds;
			}
		}
	};

	/**
	 * Update content size
	 * @param {boolean} forceFlexible if true then will force height calculation by content.
	 * @param {int} forcedMinHeight if set then height will be not less than it.
	 */
	Content.prototype.updateSize = function(forceFlexible, forcedMinHeight) {
		if (this.isFlexible || forceFlexible) {
			var h = this.getCalculatedHeight();
			if( h === true )
				return true;
			
			if (h < this.minHeight) h = this.minHeight; // min height
			if (parseInt(forcedMinHeight)) {
				h = Math.max(forcedMinHeight, h);
			}

			this.setSize(null, h + this.resolveBlockPadding());
			
		}
		if (this.bodyInstance) this.bodyInstance.updateSize(this);

		if (wb_builder.showLayout) {
			wb_builder.highlightLayout(true);
		}
	};
	
	Content.prototype.getCalculatedHeight = function() {
		var h = 0;
		this.container.children().each(function() {
			var elem = $(this).wbGetClassInstance();
			if (!elem || elem.isHidden() || elem.isHidden(true)) return true;
			var b = elem.getBounds();
			h = Math.max(h, b.top2);
		});
		this.containerForFullWidth.children().each(function() {
			var elem = $(this).wbGetClassInstance();
			if (!elem || elem.isHidden() || elem.isHidden(true)) return true;
			var b = elem.getBounds();
			h = Math.max(h, b.top2);
		});
		return h;
	};

	/**
	 * Update style from properties to elements
	 * @param {boolean} fromParent if true then this is called from parents updateStyle.
	 */
	Content.prototype.updateStyle = function(fromParent) {
		var bg = this.resolveBackground();
		var css = $.extend(true, {}, bg.css);
		if (css.background && bg.image && bg.image !== "none") {
			css.background = css.background.replace(/url\([^\)]+\)/i, 'url("' + wb_builder.makeLocalUrl(bg.image) + '")');
		}
		if (bg.fullWidth) {
			this.elem.css(css);
			this.containerWrapper.css({'background': 'none', 'background-size': 'auto'});
		} else {
			this.containerWrapper.css(css);
			this.elem.css({'background': 'none', 'background-size': 'auto'});
		}
		if (this._modeNeedsCheckHeight && fromParent) {
			this.updateSize(true, this.resolveHeight());
		} else if (this.isFlexible) {
			this.container.css({ padding: "0 0 " + this.resolveBlockPadding() + "px 0" });
		} else if (/* !this.isInitFlexible &&  */fromParent) {
			this.setSize(null, this.resolveHeight());
		}
	};
	
	Content.prototype.storeMlHeight = function() {
		if (wb_builder.site.languages.length && wb_builder.site.currSelLang) {
			if (!this.mlHeight) this.mlHeight = {};
			this.mlHeight[wb_builder.site.currSelLang] = this.getHeight();
			wb_builder.setPageModified(true);
		}
	};
	
	Content.prototype.onBeforeSwitchLanguage = function() {
		this.storeMlHeight();
	};
	
	Content.prototype.onSwitchLanguage = function(langCode) {
		if (this.isFlexible) {
			this.updateSize();
		}
	};

	/**
	 * @deprecated => routed to site.changeBackground()
	 */
	Content.prototype.changeProperties = function() {
		var t = {
			wb_header: 'top',
			wb_main: 'middle',
			wb_footer: 'bottom'
		};
		wb_builder.site.changeBackground(t[this.id]);
		return false;
	};

	/**
	 * Add paste to context menu
	 * @param {Object} menu
	 * @param {Object} elem
	 * @param {Boolean} update
	 */
	Content.prototype.addPaste = function(menu, elem, update) {
		if (!update) {
			menu.addItem("paste", __("Paste"), null, null, null, null, "glyphicon glyphicon-download-alt");
		}
		else {
			var thisClass = this;
			var currMode = ModeManager.getMode();
			var item = menu.getItem('paste');
			var objs = wb_builder.getClipboard();
			var subs = menu.hasSubmenu('paste');
			//paste text callback
			var pasteTextCb = function(e) {
				//@FIXME reikia aptvarkyt o_0 ..o siaip veikia
				if (thisClass.pasteDialog) {
					delete thisClass.pasteDialog;
					thisClass.pasteDialog = null;
				}
				thisClass.pasteDialog = new PasteDialog(
					__("Paste")
				);
				thisClass.pasteDialog.addButton(__("Cancel"));
				thisClass.pasteDialog.addButton(__("Paste"), function() {
					var info = thisClass.pasteDialog.getInfo();
					var pos = {left: menu.pageX, top: menu.pageY};
					if (info.text) {
	//						info.text = $(info.text).text();
						info.text = '<p class="wb-stl-normal">' + info.text.replace(/\n/g, '<br />') + '</p>';
						//inside element
						if (info.inside && elem && elem.className === "TextArea") {
							elem.textDiv.html(elem.textDiv.html() + info.text);
							elem.onResize();
	//							elem.fitToParent();
						}
						//paste new element
						else {
							var itm = new WB_TextArea({content: {text:info.text}});
							var offset = thisClass.elem.offset(); 
							itm.setLocation(pos.left - offset.left, pos.top - offset.top);
							thisClass.addElement(itm);
						}
					}


					thisClass.pasteDialog.hide();
				}, true);


				thisClass.pasteDialog.showCheck((elem && elem.className === "TextArea"));

				thisClass.pasteDialog.show();
				return false;
			};

			//add submenu
			if (objs && !subs) {
				var pasteElementCb = function(e) {
					var pos = {left: menu.pageX, top: menu.pageY};
					var objs = wb_builder.getClipboard();
					var offset = thisClass.elem.offset();
					
					var i, mode, itm, copiedItems = [], maxBounds = {};
					for (i = 0; i < objs.length; i++) {
						var obj = objs[i];
						obj.id = null;
						obj._copy = true; // indicate that this is copy
						obj.isCommon = false;
						obj.includePages = null;
						obj.anchor = null;
						var cls = obj["class"] ? ElementRegister.getClassByName(obj["class"]) : null;
						if (!cls) return;
						itm = new cls(obj);
						itm.switchMode(currMode, currMode, true);
						copiedItems.push(itm);
						if (!Object.keys(itm.modes).length) {
							itm.modes[currMode] = itm.modeClass();
						}
						for (mode in itm.modes) {
							if (!(mode in itm.modes)) continue;
							if (!(mode in maxBounds)) {
								maxBounds[mode] = {
									left: itm.modes[mode].x,
									top: itm.modes[mode].y,
									width: itm.modes[mode].width,
									height: itm.modes[mode].height
								};
							} else {
								if (maxBounds[mode].left > itm.modes[mode].x) {
									maxBounds[mode].left = itm.modes[mode].x;
								}
								if (maxBounds[mode].top > itm.modes[mode].y) {
									maxBounds[mode].top = itm.modes[mode].y;
								}
								if ((maxBounds[mode].left + maxBounds[mode].width) < (itm.modes[mode].x + itm.modes[mode].width)) {
									maxBounds[mode].width = (itm.modes[mode].x + itm.modes[mode].width) - maxBounds[mode].left;
								}
								if ((maxBounds[mode].top + maxBounds[mode].height) < (itm.modes[mode].y + itm.modes[mode].height)) {
									maxBounds[mode].height = (itm.modes[mode].y + itm.modes[mode].height) - maxBounds[mode].top;
								}
							}
						}
					}
					for (i = 0; i < copiedItems.length; i++) {
						itm = copiedItems[i];
						var leftDiff = maxBounds[currMode].left - itm.modes[currMode].x;
						var topDiff = maxBounds[currMode].top - itm.modes[currMode].y;
						for (mode in itm.modes) {
							if (!(mode in itm.modes)) continue;
							var halfWidth = maxBounds[mode].width / 2;
							var halfHeight = maxBounds[mode].height / 2;
							if (mode !== ModeManager.MODE_PHONE) {
								if (itm.modes[mode].x > itm.modes[mode].width) {
									itm.modes[mode].x -= halfWidth;
								} else {
									itm.modes[mode].x += halfWidth;
								}
							}
							itm.modes[mode].y += halfHeight;
						}
						itm.setLocation((pos.left - offset.left) - leftDiff, (pos.top - offset.top) - topDiff);
						thisClass.addElement(itm);
						itm.onResize(true);
					}
				};
				$(item).unbind("click");
				menu.setAction('paste', function(e, g) {
					pasteElementCb(e);
				}, true);

				var pasteMi = new ContextMenu();
				pasteMi.addItem("pasteElement", __("Paste Element"), function(e) {
					pasteElementCb(e);
				}, null, null, null, "icon-picture");
				pasteMi.addItem("pasteText", __("Paste Text"), function(e) {
					pasteTextCb(e);
				}, null, null, null, "icon-text-height");

				menu.setSubmenu('paste', pasteMi);
			}
			//no submenu
			else if (!subs && !$(item).data('pre')) {
	//			menu.removeSubmenu('paste');
				menu.setAction('paste', function() {
					pasteTextCb();
				});
				$(item).data('pre', true);
			}


			/*menu.setAction('paste', function() {

			});
			menu.addItem("paste", __("Paste"), function(e) {
				var objs = wb_builder.getClipboard();
				if (!objs) return;
				var pos = {left: e.pageX, right: e.pageY};

				for (var i = 0; i < objs.length; i++) {
					var obj = objs[i];
					obj.id = null;
					var cls = obj["class"] ? ElementRegister.getClassByName(obj["class"]) : null;
					if (!cls) return;
					var itm = new cls(obj);

					var offset = thisClass.elem.offset(); 
					itm.setLocation(pos.left - offset.left, pos.top - offset.top);
					thisClass.addElement(itm);
				}
			}, null, null, null, "icon-download-alt");*/
		}
	};

	Content.prototype.initContextMenu = function(elem) {
		var thisClass = this;
		this.menu = new ContextMenu(this.id + "_contextmenu");

		if (WB_DEBUG_MODE) {
			this.menu.addItem("dbg_clsTitle", "Content", function() {}, true, true);
		}

		this.pagesMenu = new ContextMenu();
		this.menu.addItem('goTo', __("Go to page"), this.pagesMenu,
			null, null, null, "glyphicon glyphicon-folder-open");
		this.pagesMenu.setHeight(320);
		this.menu.addSeparator();

		this.addPaste(this.menu);

		this.menu.addSeparator();

		this.menu.addItem("comConfig", __("Properties"), function() {
			thisClass.changeProperties();
		}, null, null, null, "glyphicon glyphicon-cog");

		this.menu.bind(elem, true);
		this.menu.onShow = function(ctxmenu, e) {
			thisClass.updateContextMenu();
			var ea = new BuilderEvent.ContextMenuEvent(ctxmenu, (e ? e.pageX : 0), (e ? e.pageY : 0), thisClass);
			BuilderEvent.GlobalEvents.triggerEvent('contextmenu.show', ea);
		};
	};

	Content.prototype.updateContextMenu = function() {
		this.addPaste(this.menu, null, true);

		this.pagesMenu.removeAllItems();
		var pagesMenu = this.pagesMenu;
		var menuList = MenuList.buildMenuStruct(false, false, null, true);
		var first = true;
		for (var i = 0; i < menuList.length; i++) {
			var menu = menuList[i];
			if (menu.items.length === 0) continue;
			if (first) first = false; else pagesMenu.addSeparator();
			for (var n = 0; n < menu.items.length; n++) {
				var mi = menu.items[n];
				var ident = '', identIdx = mi.lvl; while (identIdx > 0) { identIdx--; ident += '&nbsp;&nbsp;&nbsp;&nbsp;'; }
				(function(mi, ident) {
					var opt = pagesMenu.addItem('pages_menu_item_' + mi.uId, ident + mi.name,
						function() { mi.navigate(); }, mi.isCurrent(), false, mi);
					opt.find('a').attr('title', mi.fullName);
				})(mi, ident);
			}
		}
	};

	Content.Mode = (function() {
		/**
		 * @param {Content.Mode} mode
		 * @param {Object} data
		 */
		var applyData = function(mode, data) {
			mode.height = data.height;
			mode.mlHeight = data.mlHeight;
		};

		/**
		 * @param {Object} data
		 * @class Content.Mode
		 */
		var self = function(data) { if (data) applyData(this, data); };
		/** @type Boolean */
		self.prototype.wasApplied = false;
		/** @type Number */
		self.prototype.height = 100;
		/** @type mixed */
		self.prototype.mlHeight = {};
		/** @param {Content.Mode} mode */
		self.prototype.copy = function(mode) {
			applyData(this, mode);
		};
		/** @param {Content} elem */
		self.prototype.store = function(elem) {
			var data = {height: elem.getBounds().height2};
			data.mlHeight = elem.mlHeight;
			applyData(this, data);
		};
		/** @param {Content} elem */
		self.prototype.applyTo = function(elem) {
			if (elem.isInitFlexible) {
				elem._modeNeedsCheckHeight = false;
				if (!this.wasApplied) {
					elem._modeNeedsCheckHeight = true;
				}
			}
			if (!elem.isFlexible) elem.height = this.height;
			elem.mlHeight = this.mlHeight;
			this.wasApplied = true;
		};
		/** @return {Object} */
		self.prototype.serialize = function() {
			return { height: this.height, mlHeight: this.mlHeight };
		};

		return self;
	})();
	
	return Content;
});
;

/** WB Element **/
(window.defineModule = (window.defineModule || {})).name = 'WB Element';

define('Element', [
	'ElementRegister',
	'Service',
	'UserInput',
	'Content',
	'ModeManager',
	'ContextMenu',
	'ElementBox',
	'Dialog',
	'PropertyDialog',
	'util/MenuList',
	'Guides',
	'Rulers',
	'BuilderEvent',
	'ElementMeasurementHelpers',
	'PluginApi/UIManager'
], function(ElementRegister, Service, UserInput, Content, ModeManager, ContextMenu, ElementBox, Dialog, PropertyDialog, MenuList, Guides, Rulers,
		BuilderEvent, ElementMeasurementHelpers, UIManager) {
	'use strict';
	
	/**
	 * Base Element class
	 * @param {Object} data
	 * @param {boolean} initial if true then it is created on page load (or some other mass create operation)
	 * @param {boolean} virtual if true will not show options tab in properties dialog and shold not render dom nodes and limit dom event usage
	 * @constructor
	 */
	var Element = function(data, initial, virtual) { if (data) this.__construct(data, initial, virtual); };

	ElementRegister.registerClass("Element", Element);

	Element.httpProtocol = ((location.protocol && location.protocol === 'https:') ? 'https' : 'http');
	Element.lastIndex = 0;
	Element.hotKeysInitiated = false;
	Element.hotKeysDisabled = false;
	Element.hotKeysCallback = function(e) {
		if (Element.hotKeysDisabled) return;
		if ($(e.target).is("input") || $(e.target).is("textarea") || $(e.target).closest(".modal").length) return;
		var id, elem, key = null, parent = null;
		if (e.data.hotKey === "up") {
			key = {left:  0, top: -1};
		} else if (e.data.hotKey === "down") {
			key = {left:  0, top: +1};
		} else if (e.data.hotKey === "left") {
			key = {left: -1, top:  0};
		} else if (e.data.hotKey === "right") {
			key = {left: +1, top:  0};
		} else if (e.data.hotKey === "shift+up") {
			key = {left:  0, top: -10};
		} else if (e.data.hotKey === "shift+down") {
			key = {left:  0, top: +10};
		} else if (e.data.hotKey === "shift+left") {
			key = {left: -10, top:  0};
		} else if (e.data.hotKey === "shift+right") {
			key = {left: +10, top:  0};
		} else if (e.data.hotKey === "del") {
			for (id in Element.selected) {
				elem = Element.selected[id];
				if (!elem.isEditableStrict) continue;
				if (elem.isLocked) {
					elem.isLockedOpts.highlight();
					continue;
				}
				wb_builder.setPageModified(true);
				if (wb_builder.site.languages.length)
					elem.setVisible(wb_builder.site.currSelLang, false);
				else if (elem.isCommon)
					elem.setVisible('all', false, wb_builder.pageId);
				else
					elem.remove();
			}
		}

		if (!key) return;
		for (id in Element.selected) {
			elem = Element.selected[id];
			if (!elem.isEditableStrict) continue;
			if (elem.isLocked) {
				elem.isLockedOpts.highlight();
				continue;
			}
			if (!parent) parent = elem.getParent();
			var loc = elem.getLocation();
			elem.setLocation(loc.left + key.left, loc.top + key.top);
		}
		if (parent) parent.updateSize();
		for (id in Element.selected) {
			if (!elem.isEditableStrict) continue;
			if (elem.isLocked) {
				elem.isLockedOpts.highlight();
				continue;
			}
			elem = Element.selected[id];
			elem.fitToParent();
		}
		e.preventDefault();
		e.stopPropagation();
	};
	Element.locTip = null;
	Element.selected = {};
	Element.unselectAll = function() {
		for (var id in Element.selected) {
			Element.selected[id].setSelected(false);
		}
		Element.selected = {};
	};
	Element.prototype.system = null;
	Element.prototype.elem = null;
	Element.prototype.parent = null;
	Element.prototype.cover = null;
	Element.prototype.id = null;
	Element.prototype.container = null;
	Element.prototype.controls = null;
	Element.prototype.isControlsVisible = true;
	Element.prototype.debug = false;
	Element.prototype.zIndex = 0;
	Element.prototype.oPos = null;
	/** @type {PropertyDialog} */
	Element.prototype.comDialog = null;

	/** @type jQuery */
	Element.prototype.editBtn = null;
	Element.prototype.moveBtn = null;
	Element.prototype.langLabel = null;
	Element.prototype.seResizeBtn = null;

	Element.prototype.mlHeight = null;
	Element.prototype.hidden = false;
	Element.prototype.hiddenResp = false;
	Element.prototype.index = 0;
	Element.prototype.menu = null;
	Element.prototype._menu = null;
	Element.prototype.isCommon = false;
	Element.prototype.hlight = null;
	Element.prototype.hlight2 = null;
	Element.prototype.selection = null;
	Element.prototype.fadeEvnt = null;
	Element.prototype.isResizable = true;
	Element.prototype.isMovable = true;
	Element.prototype.isEditable = true;
	Element.prototype.isEditableStrict = true;
	Element.prototype.isRemovable = true;
	Element.prototype.hideBorder = false;
	Element.prototype.ctrlOpacity = 1;
	Element.prototype.comDlg = null;
	Element.prototype.noPhotoBg = "ico-tb-picture";
	Element.prototype.noPhotoMsg = null;
	Element.prototype.includePages = null;
	Element.prototype.contextMenuFirstIndex = 0;
	Element.prototype.isLocked = false;
	Element.prototype.isLockedOpts = null;
	Element.prototype.isFullWidth = false;
	Element.prototype.translations = null;
	Element.prototype.dropAccepted = true;
	Element.prototype.dragStartPos = null;
	/**
	 * If true will not show options tab in properties dialog
	 * and shold not render dom nodes and limit dom event usage.
	 * @type {boolean}
	 */
	Element.prototype.virtualElement = false;
	/** @type Boolean */
	Element.prototype.isElementPreview = false;
	/** @type Boolean */
	Element.prototype.ignoreParentBounds = false;
	/** @type Object */
	Element.prototype.modes = null;
	/** @type Object */
	Element.prototype.modeContextOk = null;
	/** @type String */
	Element.prototype.anchor = null;
	/** @type String */
	Element.prototype.referenceId = null;
	/** @type boolean */
	Element.prototype.isAdminLocked = false;

	Element.prototype.debugData = null;
	Element.prototype.debugInfo = null;
	Element.prototype.debugDataBtn = null;
	Element.prototype.debugInfoBtn = null;

	Element.prototype.mouseIsOver = false;
	Element.prototype.snapData = null;
	Element.prototype.measurementHelpers = null;
	Element.prototype.removed = false;

	/**
	 * Constructs element from serialized object
	 * @param data serialized object = { class: ..., id: ..., parentId: ..., x: ..., y: ..., width: ..., height: ..., zIndex: ..., content: ... }
	 * @param {boolean} initial if true then it is created on page load (or some other mass create operation)
	 * @param {boolean} virtual if true will not show options tab in properties dialog and shold not render dom nodes and limit dom event usage
	 */
	Element.prototype.__construct = function(data, initial, virtual) {
		this.virtualElement = (virtual ? true : false);
		this.system = wb_builder;
		var thisClass = this;
		var _data = (typeof(data) === "object") ? data : {};
		if (_data.isAdminLocked && !wb_builder.adminMode) this.isEditableStrict = false;
		if( _data.isElementPreview ) this.isElementPreview = true;

		if( wb_builder.devDebugMode ) {
			this.debugData = $.extend(true, {}, _data);
			if( this.debugData.hasOwnProperty("debugInfo") ) {
				this.debugInfo = this.debugData.debugInfo;
				delete this.debugData.debugInfo;
			}
		}

		if (!Element.hotKeysInitiated && !this.isElementPreview) {
			Element.hotKeysInitiated = true;
			UserInput.UserInput.addHotKey("left", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("right", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("up", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("down", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("shift+left", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("shift+right", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("shift+up", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("shift+down", Element.hotKeysCallback);
			UserInput.UserInput.addHotKey("del", Element.hotKeysCallback);
		}
		if (!Element.locTip) {
			Element.locTip = $('<div class="wb_loctip"></div>');
			Element.locTip.css("display", "none");
			$(document.body).ready(function() {
				$(document.body).append(Element.locTip);
			});
		}

		this.includePages = (_data.includePages && typeof(_data.includePages) === "object")
			? _data.includePages : {};

		if (_data.element && typeof(_data.element) === 'object') {
			this.elem = data.element;
		} else {
			this.elem = $('<div></div>');
		}

		this.elem.addClass("wb_element");
		if( this.isElementPreview )
			this.elem.addClass("wb-element-preview");

		this.elem.wbSetClassInstance(this);
		if( '_restoreId' in data ) {
			this.id = data._restoreId;
			this.index = data._restoreIndex;
			delete data._restoreId;
			delete data._restoreIndex;
			delete data.__requestUndoAfterRestore;
		}
		else {
			this.index = Element.lastIndex;
			this.id = "wb_element_instance" + (Element.lastIndex++);
		}

		this.controls = $('<div class="wb_controls"></div>');
		this.editBtn = $('<div class="wb_edit_btn"><span class="glyphicon glyphicon-pencil"></span></div>');
		this.moveBtn = $('<div class="wb_move_btn"><span class="glyphicon glyphicon-move"></span></div>');
		//var seResizeBtn = $('<div class="wb_resize_se_btn"></div>');
		this.controls.append('<div class="wb_elem_outline"></div><div class="wb_selection"></div><div class="wb_selection2"></div>');
		this.cover = $('<div class="wb_cover"></div>');
		this.controls.append(this.cover);
		this.controls.append(this.editBtn);
		this.controls.append(this.moveBtn);
		//this.elem.append(seResizeBtn);
		if( wb_builder.devDebugMode ) {
			this.debugDataBtn = $('<div class="wb_debug_btn"><span class="fa fa-info"></span></div>');
			this.controls.append(this.debugDataBtn);
			this.debugDataBtn.tooltip({
				trigger: "manual",
				placement: "bottom",
				container: "body",
				html: false,
				title: JSON.stringify(this.debugData, null, 2),
				template: '<div class="tooltip debug-tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
			}).on("click touchend", function() {
				$(this).tooltip("toggle");
			});

			if( this.debugInfo !== null ) {
				this.debugInfoBtn = $('<div class="wb_debug_btn"><span class="fa fa-info"></span></div>');
				this.controls.append(this.debugInfoBtn);
				this.debugInfoBtn.tooltip({
					trigger: "manual",
					placement: "bottom",
					container: "body",
					html: false,
					title: JSON.stringify(this.debugInfo, null, 2),
					template: '<div class="tooltip debug-tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
				}).on("click touchend", function() {
					$(this).tooltip("toggle");
				});
			}
		}

		this.elem.append(this.controls);

		this.container = $('<div class="wb_content"></div>');
		this.elem.append(this.container);

		if (!this.isEditable || !this.isEditableStrict) {
			this.editBtn.css("display", "none");
			if (this.langLabel) this.langLabel.css("right", "-1px");
		}

		this.isFullWidth = ("isFullWidth" in _data) && !!_data.isFullWidth;

		if( this.isElementPreview ) {
			this.isResizable = false;
			this.isEditable = false;
			this.isMovable = false;
			this.isLocked = true;
		}
		else {
			this.elem.draggable({
				//containment: $("#site"),
				distance: 3,
				cancel: this.container,
				axis: this.isFullWidth ? "y" : false,
				start: function(e, ui) {
					thisClass.dropAccepted = false;
					if (!thisClass.isSelected()) {
						for (var id in Element.selected) {
							Element.selected[id].setSelected(false);
						}
						Element.selected = {};
						thisClass.setSelected(true);
					}
					ContextMenu.hideAllMenus();
					Element.locTip.css({
						display: "block",
						left: (e.pageX - 90) + "px",
						top: e.pageY + "px"
					});

					// restores last known coordinates from undo buffer and swaps them with coordinates of elements before restoring
					var historyFunc = function(selElems) {
						var elData, element, selElems2 = [];
						for (var i = 0; i < selElems.length; i++) {
							elData = selElems[i];
							element = window.getElementById(elData.index);
							selElems2.push({index: elData.index, loc: element.getLocation()});
							element.setLocation(elData.loc.left, elData.loc.top);
							element.onResize();
						}
						this.data = selElems2; // swap data
					};
					var k, el, selElems = [];
					for (k in Element.selected) {
						el = Element.selected[k];
						el.dragStartPos = $.extend({}, el.getLocation());
						if (el.isLocked) continue;
						selElems.push({index: el.index, loc: el.getLocation()});
					}
					//selElems.push({el: thisClass, loc: thisClass.getLocation()});
					wb_builder.historyAdd('moveElements', selElems, historyFunc, historyFunc);
					thisClass.snapPrepare(e, ui);
				},
				drag: function(e, ui) {
					if( !thisClass.snapData )
						return;
					if( thisClass.snapData.selectionAcrossMultipleBlocks )
						ui.position.top = thisClass.dragStartPos.top;
					if( thisClass.snapData.selectionHasFullWidthElements )
						ui.position.left = thisClass.dragStartPos.left;
					thisClass.snapMove(e, ui);
					Element.locTip.html(Math.round(ui.position.left) + " &times; " + Math.round(ui.position.top));
					Element.locTip.css({ left: (e.pageX - 90) + "px", top: e.pageY + "px" });
				},
				stop: function(e, ui) {
					if( !thisClass.snapData )
						return;
					thisClass.snapDone(e, ui);
					if (!thisClass.isHidden() && !thisClass.isHidden(true))
						thisClass.onDrag();
					//thisClass.updateContainment();
					Element.locTip.css({ display: "none", left: "0px", top: "0px" });
					thisClass.dragStartPos = null;
				}
			});
			var opts; this.initResizable(opts = {
				//autoHide: true,
				//containment: "parent",
				//handles:	"se e s",
				//fixresize: true,
				minWidth:	64,
				minHeight:	64,
				start: function(e, ui) {
					thisClass.onStartResize(ui);
					/*if (wb_builder.snapToGrid) {
						var sz = thisClass.getSize();
						thisClass.setSize(
							ui.originalSize.width = wb_builder.gridSnap(sz.width),
							ui.originalSize.height = wb_builder.gridSnap(sz.height)
						);
					}*/
					Element.locTip.css({
						display: "block",
						left: (e.pageX + 10) + "px",
						top: e.pageY + "px"
					});
					ContextMenu.hideAllMenus();

					// restores last known size from undo buffer and swaps it with size of the element before restoring
					var historyFunc = function(data) {
						var element = window.getElementById(data.index);
						if( !element ) return;
						// swap data
						this.data = {
							index: data.index,
							size: element.getSize()
						};
						// restore
						element.setSize(data.size.width, data.size.height);
						element.onResize();
					};
					wb_builder.historyAdd('resizeElement', {
						index: thisClass.index,
						size: thisClass.getSize()
					}, historyFunc, historyFunc);
					thisClass.snapPrepare(e, ui);
				},
				resize: function(e, ui) {
					if( !thisClass.snapData )
						return;
					thisClass.snapResize(e, ui);
					thisClass.updateContentSize(ui);
					Element.locTip.html(Math.round(ui.size.width) + " &times; " + Math.round(ui.size.height));
					Element.locTip.css({
						left: (e.pageX + 10) + "px",
						top: e.pageY + "px"
					});
					if (ui.size.width < 74 || ui.size.height < 36) {
						if (thisClass.langLabel) thisClass.langLabel.css({ left: "-30px", right: "", top: "-59px" });
						thisClass.editBtn.css({ left: "-30px", right: "" });
						thisClass.moveBtn.css({ left: "-30px", top: "-30px" });
					} else {
						if (thisClass.langLabel) thisClass.langLabel.css({ left: "", right: "24px", top: "0" });
						thisClass.editBtn.css({ left: "", right: "0" });
						thisClass.moveBtn.css({ left: "0", top: "0" });
					}
					thisClass.onLiveResize(ui.size.width, ui.size.height);
				},
				stop: function(e, ui) {
					if( !thisClass.snapData )
						return;
					thisClass.snapDone(e, ui);
					thisClass.onStopResize(ui);
					if (e.skipStopEvent) return; // set in WB_Languages onResize method
					thisClass.onResize();
					Element.locTip.css({display: "none", left: "0px", top: "0px"});
				}
			});
			this.elem.resizable($.extend({}, opts, {
				handles: "n, e, s, w, ne, se, sw, nw"
			}));
			this.elem.resizable("option", "handles", opts.handles);
			this.seResizeBtn = this.elem.children(".ui-resizable-handle");
			this.fixResizableHandles();

			this.elem.hover(function() {
				thisClass.mouseIsOver = true;
				if( !thisClass.snapData )
					thisClass.showMeasurementHelpers(true);
				if (thisClass.elem.hasClass("ui-selected")) {
					thisClass.setControlsVisible(true);
					return;
				}
				thisClass.controls.stop(true, false).animate({opacity: 1}, 300);
				if (thisClass.isControlsVisible) {
					if (thisClass.langLabel) thisClass.langLabel.stop(true, false).animate({opacity: 1}, 300);
					thisClass.editBtn.stop(true, false).animate({opacity: 1}, 300);
					thisClass.moveBtn.stop(true, false).animate({opacity: 1}, 300);
					if( thisClass.debugDataBtn )
						thisClass.debugDataBtn.stop(true, false).animate({opacity: 1}, 300);
					if( thisClass.debugInfoBtn )
						thisClass.debugInfoBtn.stop(true, false).animate({opacity: 1}, 300);
				}
				thisClass.seResizeBtn.stop(true, false).animate({opacity: 1}, 300);
			}, function() {
				thisClass.mouseIsOver = false;
				if( !thisClass.snapData )
					thisClass.showMeasurementHelpers(false);
				if (thisClass.elem.hasClass("ui-selected")) {
					thisClass.setControlsVisible(true);
					return;
				}
				if (!_data.isMenu)
					thisClass.controls.stop(true, false).delay(500).animate({opacity: 0.3}, 300);
				if (thisClass.isControlsVisible) {
					if (thisClass.langLabel) thisClass.langLabel.stop(true, false).delay(500).animate({opacity: 0}, 300);
					thisClass.editBtn.stop(true, false).delay(500).animate({opacity: 0}, 300);
					thisClass.moveBtn.stop(true, false).delay(500).animate({opacity: 0}, 300);
					if( thisClass.debugDataBtn )
						thisClass.debugDataBtn.stop(true, false).delay(500).animate({opacity: 0}, 300);
					if( thisClass.debugInfoBtn )
						thisClass.debugInfoBtn.stop(true, false).delay(500).animate({opacity: 0}, 300);
				}
				thisClass.seResizeBtn.stop(true, false).delay(500).animate({opacity: 0}, 300);
				//thisClass.menu.hide();
			});
			this.elem.bind("click", function(e) {
				thisClass.onClick(e);
				e.stopPropagation();
				return false;
			});
		}
		// deserialize

		this.isCommon = _data.isCommon ? true : false;
		this.isLocked = _data.isLocked ? true : false;
		this.mlHeight = _data.mlHeight ? _data.mlHeight : {};

		var left = _data.x ? (_data.x * 1) : 0;
		var top = _data.y ? (_data.y * 1) : 0;

		this.setLocation(left, top);

		var width = _data.width ? (_data.width * 1) : 200;
		var height = _data.height ? (_data.height * 1) : 200;

		this.setSize(width, __tr(this.mlHeight, null, height));

		this.zIndex = (_data.zIndex ? (_data.zIndex * 1) : 1);
		this.elem.css("zIndex", _data.zIndex ? (_data.zIndex * 1) : 1);

		if( !this.isElementPreview ) {
			this.initContextMenu(this.editBtn);
			if (this.menu) {
				this.updateContextMenuRemove();
				this.menu.pasiveBind(this.controls);
			}
		}

		this.updateContentSize();
		this.elem.trigger("mouseout");
		
		this.noPhotoMsg = $('<div class="wb_caption">').append(
				$('<div>').append($('<i>').addClass(this.noPhotoBg))
					.append($('<span>').text(__("Double click to change properties")))).hide();
		
		this.elem.append(this.noPhotoMsg);

		if (this.isLocked) this.setLocked(this.isLocked, true);

		this.anchor = (data.anchor ? data.anchor : null);
		this.referenceId = (data.referenceId ? data.referenceId : null);
		this.isAdminLocked = (data.isAdminLocked ? data.isAdminLocked : null);
		wb_builder.site.addAnchor(this);
		
		this.onLiveResize(width, height);
		
		if (!this.isEditableStrict) {
			this.isEditableStrict = true;
			this.setDragginEnabled(false);
			this.setResizingEnabled(false, true);
			this.setControlsVisible(false);
			this.setControlsEnabled(false);
			this.isEditableStrict = false;
			this.elem.css({cursor: 'default'}).on('mousedown', function(e) {
				e.stopPropagation();
				return false;
			}).get(0).oncontextmenu = function(e) {
				e.stopPropagation();
				return false;
			};
		}
		
		this.updateShow(true);
		this.modes = {}; if (data.modes) for (var k in data.modes) { this.modes[k] = this.modeClass(data.modes[k]); }
		this.modeContextOk = {comConfig: true, hideElem: true, lock: true, order: true};
	};
	
	/**
	 * Called on resizable initialisation
	 * @param {Object} options resizable options
	 */
	Element.prototype.initResizable = function(options) {
		if (this.isEditableStrict) {
			options.handles = this.isFullWidth ? "s" : "e, s, se";
		} else {
			options.handles = false;
		}
	};

	/**
	 * This method fixes issue with jQuery UI v1.11 ignoring changes in resizable widget handles.
	 * Resizable element must be always initialized with all handles enabled.
	 * This must be called every time after updating "handles" option of resizable widget.
	 */
	Element.prototype.fixResizableHandles = function() {
		if( !this.isResizable )
			return;
		var activeHandles = [];
		this.elem.resizable("option", "handles").split(",").forEach(function(handleName) {
			handleName = handleName.trim();
			if( handleName === "" )
				return;
			activeHandles.push(".ui-resizable-" + handleName);
		});
		// var $handles = this.elem.find(".ui-resizable-handle");
		if( this.seResizeBtn ) {
			this.seResizeBtn.addClass('hidden');
			if( activeHandles.length )
				this.seResizeBtn.filter(activeHandles.join(",")).removeClass("hidden");
		}
	};

	/**
	 * Called when dragging on resizing of element has started.
	 * @param e
	 */
	Element.prototype.snapPrepare = function(e, ui) {
		var i, c, elements;
		var width = this.getWidth();
		var height = this.getHeight();
		this.snapData = {
			selection: [], // {offset:{x:number, y:number}, elem:JQuery}[] // offset is relative to the active element without applying block coordinate offsets
			selectionBox: {minX: null, minY: null, maxX: null, maxY: null}, // coordinates are relative to the active element
			selectionAcrossMultipleBlocks: false,
			selectionHasFullWidthElements: false,
			activeArea: 1200, // distance at which side snap lines are considered in range
			distance: wb_builder.gridSize / 2, // distance at which snapping is made
			horizontal: [], // contains all vertical snap lines used for snapping when moving or resizing horizontally
			vertical: [], // contains all horizontal snap lines used for snapping when moving or resizing vertically
			blockVerticalOffset: 0, // used to shift ruler coordinates
			aspectRatio: (width > 0 && height > 0) ? width / height : 1,
			keepAspectRatio: false,
			hResize: null,
			vResize: null,
			hHelpers: {
				guides: {},
				rulers: [],
				snapLines: []
			},
			vHelpers: {
				guides: {},
				rulers: [],
				snapLines: []
			},
			guides: Guides.GuideManagerInstance.getActiveGuides(),
			droppedOnBlock: null
		};

		var elem, parentId, pos, otherPos, left, top, right, bottom;

		var parentYOffsets;
		var body = wb_builder.bodyInstance;
		var header = body.getContentBlock('wb_header');
		var headerOffset = header.container.offset();
		var headerHeight = header.getHeight();
		var mainHeight = body.getContentBlock('wb_main').getHeight();
		if( this.parent && this.parent.id === "wb_header" ) {
			parentYOffsets = {
				wb_header: 0,
				wb_main: headerHeight,
				wb_footer: headerHeight + mainHeight
			};
		}
		else if( !this.parent || this.parent.id === "wb_main" ) {
			this.snapData.blockVerticalOffset = headerHeight;
			parentYOffsets = {
				wb_header: -headerHeight,
				wb_main: 0,
				wb_footer: mainHeight
			};
		}
		else if( this.parent.id === "wb_footer" ) {
			this.snapData.blockVerticalOffset = headerHeight + mainHeight;
			parentYOffsets = {
				wb_header: -headerHeight - mainHeight,
				wb_main: -mainHeight,
				wb_footer: 0
			};
		}
		else {
			this.snapData.blockVerticalOffset = 0;
			parentYOffsets = {};
			parentYOffsets[this.parent.id] = 0;
		}

		pos = this.getLocation();

		var skipElement, firstElemParentId = null;
		elements = wb_builder.getActiveViewElements();
		for ( i = 0, c = elements.length; i < c; i++) {
			skipElement = (e.type === "dragstart" && !elements[i].isSelected()) || (e.type === "resizestart" && elements[i] !== this);
			if( skipElement || !elements[i].isSelected() || elements[i].isHidden() || elements[i].isHidden(true) )
				continue;
			elem = elements[i];
			otherPos = elem.getLocation();
			parentId = elem.parent ? elem.parent.id : 'wb_main';
			this.snapData.selection.push({
				offset: {x: otherPos.left - pos.left, y: otherPos.top - pos.top},
				elem: elements[i]
			});

			otherPos.top += parentYOffsets[parentId]; // offset position of elements that are in different blocks to calculate correct bounding box of a group
			left = otherPos.left - pos.left - (elem.isFullWidth ? headerOffset.left : 0);
			top = otherPos.top - pos.top;
			right = left + elem.getWidth();
			bottom = top + elem.getHeight();

			if( this.snapData.selectionBox.minX === null || left < this.snapData.selectionBox.minX )
				this.snapData.selectionBox.minX = left;
			if( this.snapData.selectionBox.maxX === null || right > this.snapData.selectionBox.maxX )
				this.snapData.selectionBox.maxX = right;
			if( this.snapData.selectionBox.minY === null || top < this.snapData.selectionBox.minY )
				this.snapData.selectionBox.minY = top;
			if( this.snapData.selectionBox.maxY === null || bottom > this.snapData.selectionBox.maxY )
				this.snapData.selectionBox.maxY = bottom;

			this.snapData.selectionHasFullWidthElements = this.snapData.selectionHasFullWidthElements || elem.isFullWidth;
			if( firstElemParentId === null )
				firstElemParentId = parentId;
			else if( firstElemParentId !== parentId )
				this.snapData.selectionAcrossMultipleBlocks = true;
		}

		if( this.snapData.selectionAcrossMultipleBlocks )
			wb_builder.bodyInstance.enableDropZones(false);

		if( wb_builder.snapToObjects ) {
			var horizontalSnapLines = [], verticalSnapLines = [];
			for ( i = 0, c = elements.length; i < c; i++) {
				skipElement = (e.type === "dragstart" && elements[i].isSelected()) || (e.type === "resizestart" && elements[i] === this);
				if( skipElement || elements[i].isHidden() || elements[i].isHidden(true) )
					continue;
				elem = elements[i];
				pos = elem.getLocation();
				parentId = elem.parent ? elem.parent.id : 'wb_main';
				pos.top += parentYOffsets[parentId];
				var box = {left: pos.left, top: pos.top, right: pos.left + elem.getWidth(), bottom: pos.top + elem.getHeight()};
				if( elem.isFullWidth ) {
					box.left -= headerOffset.left;
					box.right -= headerOffset.left;
				}

				if( !this.snapData.selectionHasFullWidthElements ) {
					if( !elem.isFullWidth ) {
						horizontalSnapLines.push({
							lineClass: "element",
							elem: elem,
							type: "left",
							offset: box.left,
							areaMin: box.top,
							areaMax: box.bottom
						});
					}
					horizontalSnapLines.push({
						lineClass: "element",
						elem: elem,
						type: "middle",
						offset: Math.round((box.left + box.right) / 2),
						areaMin: box.top,
						areaMax: box.bottom
					});
					if( !elem.isFullWidth ) {
						horizontalSnapLines.push({
							lineClass: "element",
							elem: elem,
							type: "right",
							offset: box.right,
							areaMin: box.top,
							areaMax: box.bottom
						});
					}
				}

				if( !this.snapData.selectionAcrossMultipleBlocks ) {
					verticalSnapLines.push({
						lineClass: "element",
						elem: elem,
						type: "top",
						offset: box.top,
						areaMin: box.left,
						areaMax: box.right
					});
					verticalSnapLines.push({
						lineClass: "element",
						elem: elem,
						type: "middle",
						offset: Math.round((box.top + box.bottom) / 2),
						areaMin: box.left,
						areaMax: box.right
					});
					verticalSnapLines.push({
						lineClass: "element",
						elem: elem,
						type: "bottom",
						offset: box.bottom,
						areaMin: box.left,
						areaMax: box.right
					});
				}
			}

			var sortSnapLines = function(a, b) {
				if( a.offset === b.offset ) {
					if( a.areaMin === b.areaMin ) {
						if( a.areaMax === b.areaMax )
							return 0;
						return (a.areaMax < b.areaMax) ? -1 : 1;
					}
					return (a.areaMin < b.areaMin) ? -1 : 1;
				}
				return (a.offset < b.offset) ? -1 : 1;
			};
			horizontalSnapLines.sort(sortSnapLines);
			verticalSnapLines.sort(sortSnapLines);

			var groupLines = function(lines) {
				var groups = [];
				var group = null, line;
				for( var i = 0, il = lines.length; i < il; i++ ) {
					line = lines[i];
					if( !group || group.offset !== line.offset ) {
						group = {
							offset: line.offset,
							lines: []
						};
						groups.push(group);
					}
					group.lines.push(line);
				}
				return groups;
			};
			this.snapData.horizontal = groupLines(horizontalSnapLines);
			this.snapData.vertical = groupLines(verticalSnapLines);
		}

		if( e.type === "resizestart" ) {
			var axis = $(ui.element).data("ui-resizable").axis;
			if( axis === "nw" ) { this.snapData.hResize = "w"; this.snapData.vResize = "n"; }
			else if( axis === "n" ) { this.snapData.vResize = "n"; }
			else if( axis === "ne" ) { this.snapData.hResize = "e"; this.snapData.vResize = "n"; }
			else if( axis === "w" ) { this.snapData.hResize = "w"; }
			else if( axis === "e" ) { this.snapData.hResize = "e"; }
			else if( axis === "sw" ) { this.snapData.hResize = "w"; this.snapData.vResize = "s"; }
			else if( axis === "s" ) { this.snapData.vResize = "s"; }
			else if( axis === "se" ) { this.snapData.hResize = "e"; this.snapData.vResize = "s"; }
			this.snapData.keepAspectRatio = ((this instanceof WB_Picture) && (this.snapData.hResize === "w" || this.snapData.hResize === "e") && this.snapData.vResize === "s");
		}
		else if( e.type === "dragstart" ) {
			Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-move-start', this);
		}

		ElementMeasurementHelpers.ElementMeasurementHelpers.disabled = true;
		this.showMeasurementHelpers(false);
	};

	Element.prototype.snapFindClosestLines = function(offsets, boundsMin, boundsMax, snapLineGroups, guides, guideShift) {
		var areaMin = boundsMin - this.snapData.activeArea;
		var areaMax = boundsMax + this.snapData.activeArea;
		var i, il, j, jl, k, kl, offsetData = [], breakOffset = null, offs, guideOffset, diff, delta, sideDelta, line, lineGroup, guide, offsChanged, targetLineList, foundALine;
		for( i = 0, il = offsets.length; i < il; i++ ) {
			offsetData[i] = {
				index: i,
				offset: offsets[i],
				min: offsets[i] - this.snapData.distance,
				max: offsets[i] + this.snapData.distance,
				elementAreaMin: null,
				elementAreaMax: null,
				diff: null,
				delta: null,
				lines: [],
				snapToOffset: 0,
				snapsToGuide: null,
				rulerOffsetCorrection: false
			};
			breakOffset = (breakOffset === null) ? offsetData[i].max : Math.max(offsetData[i].max, breakOffset);
		}

		if( wb_builder.snapToGrid ) {
			offs = offsetData[0];
			var gridSnap = wb_builder.gridSnap(offs.offset);
			offs.diff = offs.offset - gridSnap;
			offs.delta = Math.abs(offs.diff);
			offs.snapToOffset = gridSnap;
			offs.lines.push({lineClass: "grid", offset: gridSnap});
		}

		for( i = 0, il = guides.length; i < il; i++ ) {
			guide = guides[i];
			guideOffset = guide.getOffset() - guideShift;
			for( j = 0, jl = offsetData.length; j < jl; j++ ) {
				offs = offsetData[j];
				if( guideOffset < offs.min || guideOffset > offs.max )
					continue;
				diff = offs.offset - guideOffset;
				delta = Math.abs(diff);
				if( offs.delta === null || delta < offs.delta ) {
					offs.diff = diff;
					offs.delta = delta;
					offs.snapToOffset = guideOffset;
					offs.snapsToGuide = guide;
					offs.lines = [guide];
				}
				else if( diff === offs.diff ) {
					if( !offs.snapsToGuide )
						offs.snapsToGuide = guide;
					offs.lines.push(guide);
				}
			}
		}

		for( i = 0, il = snapLineGroups.length; i < il; i++ ) {
			lineGroup = snapLineGroups[i];
			if( lineGroup.offset > breakOffset )
				break;
			for( j = 0, jl = offsetData.length; j < jl; j++ ) {
				offs = offsetData[j];
				if( lineGroup.offset < offs.min || lineGroup.offset > offs.max )
					continue;
				diff = offs.offset - lineGroup.offset;
				delta = Math.abs(diff);

				offsChanged = false;
				if( offs.delta === null || delta < offs.delta )
					offsChanged = true;
				else if( offs.diff !== diff ) // this condition will be false only if already snapping to grid or a guide on the same offset
					continue;

				targetLineList = offsChanged ? [] : offs.lines;
				foundALine = false;

				for( k = 0, kl = lineGroup.lines.length; k < kl; k++ ) {
					line = lineGroup.lines[k];
					if( line.areaMin > areaMax || line.areaMax < areaMin )
						continue;
					foundALine = true;
					targetLineList.push(line);
				}

				if( offsChanged && foundALine ) {
					offs.diff = diff;
					offs.delta = delta;
					offs.snapToOffset = line.offset;
					offs.snapsToGuide = null;
					offs.lines = targetLineList;
				}
			}
		}

		offsetData = offsetData.filter(function(offs) {
			return offs.lines.length > 0;
		});

		offsetData.sort(function(a, b) {
			if( a.delta === b.delta ) {
				if( a.diff === b.diff )
					return 0;
				return (a.diff < b.diff) ? -1 : 1;
			}
			return (a.delta < b.delta) ? -1 : 1;
		});

		if( offsetData.length > 1 ) {
			diff = offsetData[0].diff;
			offsetData = offsetData.filter(function(offs) {
				return offs.diff === diff;
			});
		}

		var midOffs = null, midOffsIdx = 0;
		for( i = offsetData.length - 1; i >= 0; i-- ) {
			offs = offsetData[i];
			for( j = offs.lines.length - 1; j >= 0; j-- ) {
				line = offs.lines[j];
				if( line.lineClass !== "element" )
					continue;
				if( offs.elementAreaMin === null || line.areaMin < offs.elementAreaMin )
					offs.elementAreaMin = line.areaMin;
				if( offs.elementAreaMax === null || line.areaMax > offs.elementAreaMax )
					offs.elementAreaMax = line.areaMax;
			}
			if( offs.index === 1 ) {
				midOffs = offs;
				midOffsIdx = i;
			}
		}

		if( midOffs && offsetData.length > 2 && !midOffs.snapsToGuide ) {
			// we don't need more than two lines snapping to same elements so we will remove middle line if it doesn't snap to a guide
			var uselessData = false;
			for( i = offsetData.length - 1; i >= 0; i-- ) {
				if( i === midOffsIdx )
					continue;
				if( !offsetData[i].snapsToGuide && offsetData[i].elementAreaMin === midOffs.elementAreaMin && offsetData[i].elementAreaMax === midOffs.elementAreaMax ) {
					uselessData = true;
					break;
				}
			}
			if( uselessData )
				offsetData.splice(midOffsIdx, 1);
		}

		return offsetData;
	};

	Element.prototype.snapFindBestGuidePosition = function(line, elementOffset, elementSize) {
		var sgLen, sgShift;
		var deltas = [
			[line.areaMin - elementOffset, 0],
			[line.areaMax - elementOffset, 0],
			[line.areaMin - elementOffset, elementSize],
			[line.areaMax - elementOffset, elementSize]
		];
		deltas = deltas.filter(function(a) {
			a[2] = Math.abs(a[0] - a[1]);
			return a[2] > 0;
		});
		if( deltas.length ) {
			deltas.sort(function(a, b) {
				if( a[2] === b[2] )
					return 0;
				return (a[2] < b[2]) ? -1 : 1;
			});
			sgLen = deltas[0][0] - deltas[0][1];
			sgShift = deltas[0][1];
			//if( deltas[0][0] < sgShift )
			//	sgShift -= sgLen;
		}
		else {
			sgLen = line.areaMax - line.areaMin;
			sgShift = line.areaMin - elementOffset;
		}
		return {offset: sgShift + elementOffset, size: sgLen};
	};

	Element.prototype.prepareSnapHelpers = function(helpers) {
		var i;
		for( i in helpers.guides )
			if( helpers.guides.hasOwnProperty(i) )
				helpers.guides[i].action = -1; // marks guide for hiding
	};

	Element.prototype.cleanupUnusedSnapHelpers = function(helpers, usedRulers, usedSnapLines) {
		var i;
		for( i in helpers.guides ) {
			if( !helpers.guides.hasOwnProperty(i) )
				continue;
			if( helpers.guides[i].action === 1 ) {
				helpers.guides[i].guide.render(true, true);
				helpers.guides[i].action = 0;
			}
			else if( helpers.guides[i].action === -1 ) {
				helpers.guides[i].guide.render(wb_builder.showGuides, false);
				delete helpers.guides[i];
			}
		}
		for( i = helpers.rulers.length - 1; i >= usedRulers; i-- )
			helpers.rulers[i].setVisible(false);
		for( i = helpers.snapLines.length - 1; i >= usedSnapLines; i-- )
			helpers.snapLines[i].addClass("hidden");
	};

	Element.prototype.removeSnapHelpers = function(helpers) {
		var i;
		for( i in helpers.guides ) {
			if( !helpers.guides.hasOwnProperty(i) )
				continue;
			helpers.guides[i].guide.render(wb_builder.showGuides, false);
			delete helpers.guides[i];
		}
		for( i = helpers.rulers.length - 1; i >= 0; i-- )
			Rulers.RulerManagerInstance.removeRuler(helpers.rulers[i]);
		for( i = helpers.snapLines.length - 1; i >= 0; i-- )
			helpers.snapLines[i].remove();
		helpers.guides = {};
		helpers.rulers = [];
		helpers.snapLines = [];
	};

	Element.prototype.renderSnapHelpersForSide = function(snapType, helpers, snaps, left, top, width, height) {
		var rulerFrom, rulerTo, i, j, jl, guideId, snap, usedRulers, usedSnapLines, line, delta, areaMin, areaMax;
		var bestDistanceBefore, bestDistanceAfter;
		var parent = this.getParent().container;
		var blockOffset = parent.offset();
		var body = $(document.body);
		var bodyMaxX = body.width() - blockOffset.left;
		var bodyMaxY = body.height() - blockOffset.top;

		// render horizontal snapping helpers
		usedRulers = usedSnapLines = 0;
		this.prepareSnapHelpers(helpers);

		var elemAreaMin = (snapType === "horizontal") ? top : left;
		var elemAreaMax = elemAreaMin + ((snapType === "horizontal") ? height : width);

		if( snaps ) {
			for( i = snaps.length - 1; i >= 0; i-- ) {
				snap = snaps[i];
				if( snap.snapsToGuide ) {
					// render guides (they cover snap lines so they get priority in rendering)
					guideId = "g" + snap.snapToOffset;
					if( helpers.guides.hasOwnProperty(guideId) ) {
						if( helpers.guides[guideId].action === -1 )
							helpers.guides[guideId].action = 0;
					}
					else {
						helpers.guides[guideId] = {
							action: 1,
							guide: snap.snapsToGuide
						};
					}
				}
				else {
					// render element snap lines
					if( snap.elementAreaMin !== null && snap.elementAreaMax !== null ) {
						snap.elementAreaMin = Math.min(snap.elementAreaMin, elemAreaMin);
						snap.elementAreaMax = Math.max(snap.elementAreaMax, elemAreaMax);

						areaMin = snap.elementAreaMin - 10;
						areaMax = snap.elementAreaMax + 10;
						if( snapType === "horizontal" ) {
							areaMax = Math.min(bodyMaxY, areaMax);
							delta = bodyMaxY - areaMin;
						}
						else {
							areaMax = Math.min(bodyMaxX, areaMax);
							delta = bodyMaxX - areaMin;
						}
						if( delta > 0 ) {
							if (usedSnapLines === helpers.snapLines.length) {
								helpers.snapLines[usedSnapLines] = $('<div class="wb-snap-line wb-snap-line-' + snapType + '">');
								parent.append(helpers.snapLines[usedSnapLines]);
							}
							else {
								helpers.snapLines[usedSnapLines].removeClass("hidden");
							}
							if (snapType === "horizontal") {
								helpers.snapLines[usedSnapLines].css({
									left: snap.snapToOffset - ((snap.index === 2) ? 1 : 0),
									top: areaMin,
									height: areaMax - areaMin
								});
							}
							else {
								helpers.snapLines[usedSnapLines].css({
									top: snap.snapToOffset - ((snap.index === 2) ? 1 : 0),
									left: areaMin,
									width: areaMax - areaMin
								});
							}
							usedSnapLines++;
						}
					}
				}

				// render distance from nearest snapped elements
				if( snap.elementAreaMin !== null && snap.elementAreaMax !== null ) {
					bestDistanceBefore = bestDistanceAfter = null;
					for( j = snap.lines.length - 1; j >= 0; j-- ) {
						line = snap.lines[j];
						if( line.lineClass !== "element" )
							continue;
						if( line.areaMax < elemAreaMin ) {
							delta = elemAreaMin - line.areaMax;
							if( bestDistanceBefore === null || bestDistanceBefore > delta )
								bestDistanceBefore = delta;
						}
						if( line.areaMin > elemAreaMax ) {
							delta = line.areaMin - elemAreaMax;
							if( bestDistanceAfter === null || bestDistanceAfter > delta )
								bestDistanceAfter = delta;
						}
					}
					if( bestDistanceBefore !== null ) {
						if( snapType === "horizontal" ) {
							rulerFrom = {x: blockOffset.left + snap.snapToOffset - ((snap.index === 2) ? 1 : 0), y: this.snapData.blockVerticalOffset + elemAreaMin};
							rulerTo = {x: rulerFrom.x, y: rulerFrom.y - bestDistanceBefore};
						}
						else {
							rulerFrom = {x: blockOffset.left + elemAreaMin, y: this.snapData.blockVerticalOffset + snap.snapToOffset - ((snap.index === 2) ? 1 : 0)};
							rulerTo = {x: rulerFrom.x - bestDistanceBefore, y: rulerFrom.y};
						}
						if( usedRulers === helpers.rulers.length ) {
							helpers.rulers[usedRulers] = Rulers.RulerManagerInstance.addRuler(rulerFrom, rulerTo, false);
						}
						else {
							helpers.rulers[usedRulers].set(rulerFrom, rulerTo);
						}
						helpers.rulers[usedRulers].setVisible(true);
						usedRulers++;
					}
					if( bestDistanceAfter !== null ) {
						if( snapType === "horizontal" ) {
							rulerFrom = {x: blockOffset.left + snap.snapToOffset - ((snap.index === 2) ? 1 : 0), y: this.snapData.blockVerticalOffset + elemAreaMax};
							rulerTo = {x: rulerFrom.x, y: rulerFrom.y + bestDistanceAfter};
						}
						else {
							rulerFrom = {x: blockOffset.left + elemAreaMax, y: this.snapData.blockVerticalOffset + snap.snapToOffset - ((snap.index === 2) ? 1 : 0)};
							rulerTo = {x: rulerFrom.x + bestDistanceAfter, y: rulerFrom.y};
						}
						if( usedRulers === helpers.rulers.length ) {
							helpers.rulers[usedRulers] = Rulers.RulerManagerInstance.addRuler(rulerFrom, rulerTo, false);
						}
						else {
							helpers.rulers[usedRulers].set(rulerFrom, rulerTo);
						}
						helpers.rulers[usedRulers].setVisible(true);
						usedRulers++;
					}
				}
			}
		}

		this.cleanupUnusedSnapHelpers(helpers, usedRulers, usedSnapLines);
	};

	Element.prototype.renderSnapHelpers = function(hSnaps, vSnaps, left, top, width, height) {
		this.renderSnapHelpersForSide("horizontal", this.snapData.hHelpers, hSnaps, left, top, width, height);
		this.renderSnapHelpersForSide("vertical", this.snapData.vHelpers, vSnaps, left, top, width, height);
	};

	/**
	 * Called during dragging
	 * @param e
	 * @param ui
	 */
	Element.prototype.snapMove = function(e, ui) {
		if( this.isHidden() || this.isHidden(true) ) {
			ui.position.left = this.dragStartPos.left;
			ui.position.top = this.dragStartPos.top;
		}
		else {
			var left = ui.position.left + this.snapData.selectionBox.minX;
			var top = ui.position.top + this.snapData.selectionBox.minY;
			var width = this.snapData.selectionBox.maxX - this.snapData.selectionBox.minX;
			var height = this.snapData.selectionBox.maxY - this.snapData.selectionBox.minY;
			var right = left + width;
			var bottom = top + height;

			var hSnaps = null, vSnaps = null, hsgOffset = null, vsgOffset = null, sgPos;

			if( !this.snapData.selectionHasFullWidthElements ) {
				hSnaps = this.snapFindClosestLines([left, (right + left) / 2, right], top, bottom, this.snapData.horizontal, this.snapData.guides.vertical, 0);
				if( hSnaps.length ) {
					if( hSnaps[0].index === 0 )
						hsgOffset = this.snapData.selectionBox.minX;
					else if( hSnaps[0].index === 1 )
						hsgOffset = (this.snapData.selectionBox.minX + this.snapData.selectionBox.maxX) / 2;
					else
						hsgOffset = this.snapData.selectionBox.maxX;
					ui.position.left = hSnaps[0].snapToOffset - Math.round(hsgOffset);
				}
			}

			if( !this.snapData.selectionAcrossMultipleBlocks ) {
				vSnaps = this.snapFindClosestLines([top, (bottom + top) / 2, bottom], left, right, this.snapData.vertical, this.snapData.guides.horizontal, this.snapData.blockVerticalOffset);
				if( vSnaps.length > 0 ) {
					if( vSnaps[0].index === 0 )
						vsgOffset = this.snapData.selectionBox.minY;
					else if( vSnaps[0].index === 1 )
						vsgOffset = (this.snapData.selectionBox.minY + this.snapData.selectionBox.maxY) / 2;
					else
						vsgOffset = this.snapData.selectionBox.maxY;
					ui.position.top = vSnaps[0].snapToOffset - Math.round(vsgOffset);
				}
			}

			this.renderSnapHelpers(hSnaps, vSnaps, ui.position.left + this.snapData.selectionBox.minX, ui.position.top + this.snapData.selectionBox.minY, width, height);
		}

		// Move other selected elements along with the active element
		var elemInfo;
		for( var i = this.snapData.selection.length - 1; i >= 0; i-- ) {
			elemInfo = this.snapData.selection[i];
			elemInfo.elem.setLocation(ui.position.left + elemInfo.offset.x, ui.position.top + elemInfo.offset.y);
		}
	};

	/**
	 * Called during resizing
	 * @param e
	 * @param ui
	 */
	Element.prototype.snapResize = function(e, ui) {
		if( this.snapData.hResize === null && this.snapData.vResize === null )
			return;

		var size = this.getSize();
		var left = ui.position.left;
		var right = left + size.width;
		var top = ui.position.top;
		var bottom = top + size.height;

		// hSnaps and vSnaps arrays will always have either 0 or 1 element
		var hSnaps, vSnaps, delta;
		var hsgOffset = null, vsgOffset = null;

		if( this.snapData.keepAspectRatio )
			ui.size.height = ui.size.width / this.snapData.aspectRatio;

		if( this.snapData.hResize && !this.snapData.selectionHasFullWidthElements ) {
			hSnaps = this.snapFindClosestLines([ui.position.left + ((this.snapData.hResize === "e") ? ui.size.width : 0)], top, bottom, this.snapData.horizontal, this.snapData.guides.vertical, 0);
			if( hSnaps.length && this.snapData.hResize === "e" )
				hSnaps[0].index = 2; // force index to right side of the element (used for snap helper position correction)
		}
		if( this.snapData.vResize && !this.snapData.selectionAcrossMultipleBlocks ) {
			vSnaps = this.snapFindClosestLines([ui.position.top + ((this.snapData.vResize === "s") ? ui.size.height : 0)], left, right, this.snapData.vertical, this.snapData.guides.horizontal, this.snapData.blockVerticalOffset);
			if( vSnaps.length && this.snapData.hResize === "s" )
				vSnaps[0].index = 2; // force index to right side of the element (used for snap helper position correction)
		}

		if( this.snapData.keepAspectRatio && hSnaps && vSnaps && hSnaps.length && vSnaps.length ) {
			// since we need to keep aspect ratio we may use only one snapping guide so we have to choose which
			// one to use
			if( hSnaps[0].delta < vSnaps[0].delta * this.snapData.aspectRatio )
				vSnaps = [];
			else
				hSnaps = [];
		}

		if( hSnaps && hSnaps.length ) {
			delta =  hSnaps[0].snapToOffset - ui.position.left;
			if( this.snapData.hResize === "e" ) {
				// resize right
				ui.size.width = delta;
			}
			else {
				// resize left
				ui.position.left += delta;
				ui.size.width -= delta;
			}
			if( this.snapData.keepAspectRatio ) {
				ui.size.height = ui.size.width / this.snapData.aspectRatio;
			}
		}

		if( vSnaps && vSnaps.length ) {
			delta =  vSnaps[0].snapToOffset - ui.position.top;
			if( this.snapData.vResize === "s" ) {
				// resize down
				ui.size.height = delta;
			}
			else {
				// resize up
				ui.position.top += delta;
				ui.size.height -= delta;
			}
			if( this.snapData.keepAspectRatio ) {
				ui.size.width = ui.size.height * this.snapData.aspectRatio;
			}
		}

		this.renderSnapHelpers(hSnaps, vSnaps, ui.position.left, ui.position.top, ui.size.width, ui.size.height);

		this.setLocation(ui.position.left, ui.position.top);
		this.setSize(ui.size.width, ui.size.height);
	};

	/**
	 * Called when dragging or resizing has stopped
	 */
	Element.prototype.snapDone = function(e, ui) {
		if( !this.snapData )
			return;

		Rulers.RulerManagerInstance.clear();
		Guides.GuideManagerInstance.invalidate();

		if( e ) {
			if( e.type === "dragstop" ) {
				this.snapMove(e, ui);
				if( this.snapData.droppedOnBlock ) {
					var oldBlockPos = this.getParent().getBounds();
					var newBlockPos = this.snapData.droppedOnBlock.getBounds();
					ui.position.top += oldBlockPos.top - newBlockPos.top;
					for( var i = 0; i < this.snapData.selection.length; i++ )
						this.snapData.droppedOnBlock.addElement(this.snapData.selection[i].elem);
				}
			}
			else if( e.type === "resizestop" )
				this.snapResize(e, ui);

			this.setLocation(ui.position.left, ui.position.top); // move element to snapped position since jQuery UI doesn't do it on drop event.

			if( e.type === "dragstop" ) {
				Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-move-end', this);
			}
			else if( e.type === "resizestop" ) {
				this.setSize(ui.size.width, ui.size.height);
			}

			ElementMeasurementHelpers.ElementMeasurementHelpers.disabled = false;
			if( this.mouseIsOver )
				this.showMeasurementHelpers(true);
		}

		wb_builder.updateDropZones();
		this.removeSnapHelpers(this.snapData.hHelpers);
		this.removeSnapHelpers(this.snapData.vHelpers);
		this.snapData = null;
	};

	/**
	 * @param {Object} data
	 * @return {Element.Mode}
	 */
	Element.prototype.modeClass = function(data) {
		return new Element.Mode(data);
	};

	/**
	 * Switch to mode (one of ModeManager.MODE_* constants)
	 * @param {String} fromMode
	 * @param {String} toMode
	 * @param {Boolean} initial
	 * @param {Boolean} manual if true then it means that "switchMode" was called
	 * exactly by user clicking one of mode buttons
	 */
	Element.prototype.switchMode = function(fromMode, toMode, initial, manual) {
		if (!toMode || !Service.modeManager.getUseModes()) return;
		var isNew = false;
		if (!(fromMode in this.modes)) {
			isNew = true;
			this.modes[fromMode] = this.modeClass();
		}
		if ((!initial || isNew) && !this.isHidden()) {
			this.modes[fromMode].store(this);
		}
		if (!(toMode in this.modes)) {
			this.modes[toMode] = this.modeClass();
			this.modes[toMode].copy(this.modes[fromMode]);
		}
		if (initial || fromMode !== toMode) {
			if (!initial) this.storeMlHeight();
			this.modes[toMode].applyTo(this);
		}
	};
	
	Element.prototype.boxItemOptions = function() {
		return {
			title: ElementRegister.getPluginNameById(this.getClassType()),
			text: ('#' + this.id),
			thumb: null
		};
	};
	
	/**
	 * Retrieves properties of serialized object
	 * which describe image sources.
	 * @returns String[]
	 */
	Element.prototype.getUsedMediaGalleryItems = function() {
		return [];
	};
	
	/**
	 * Serialize this element
	 * @returns {Object} object = { class: ..., id: ..., parentId: ..., x: ..., y: ..., width: ..., height: ..., zIndex: ..., content: ... }
	 */
	Element.prototype.serialize = function() {
		var m;
		this.storeMlHeight();
		if (Service.modeManager.getUseModes()) {
			var mode = Service.modeManager.getMode();
			this.switchMode(mode, mode);
			m = this.modes[mode].serialize();
		}
		if (!m) {
			var b = this.getBounds();
			m = {x: b.left, y: b.top, width: b.width, height: b.height, mlHeight: this.mlHeight};
		}
		var modes = {}; for (var k in this.modes) { modes[k] = this.modes[k].serialize(); }
		return {
			"class": this.getClassType(), id: this.id,
			parentId: (this.parent ? this.parent.id : null),
			//x: Math.round(b.left), y: Math.round(b.top), width: Math.round(b.width), height: Math.round(b.height),
			x: m.x, y: m.y, width: m.width, height: m.height, mlHeight: m.mlHeight,
			anchor: this.anchor,
			referenceId: this.referenceId,
			isAdminLocked: this.isAdminLocked,
			zIndex: this.getZIndex(), content: null,
			isCommon: (this.isCommon ? true : false),
			includePages: this.includePages,
			isLocked: this.isLocked,
			isFullWidth: this.isFullWidth,
			modes: modes
		};
	};

	/**
	 * Get element class type
	 * @returns class type
	 */
	Element.prototype.getClassType = function() {
		return this.className;
	};

	/**
	 * Get class name of this element
	 * @return class name
	 */
	Element.prototype.getClassName = function() {
		return "WB_" + this.className;
	};

	/**
	 * Callback called on click event on the element
	 * @param e event object
	 */
	Element.prototype.onClick = function(e) {
		Dialog.hideEditors = true;
		Service.textArea.hideEditors();
		ContextMenu.hideAllMenus();
		UIManager.getManager().closeAll();
		if (this.isEditableStrict) {
			if (!UserInput.UserInput.hotKeysMod.ctrl) {
				Element.unselectAll();
				this.setSelected(true);
			} else {
				this.setSelected(!this.isSelected());
			}
			if (wb_builder.isTouchDevice && this.menu) this.menu.show(e);
		}
		wb_builder.clearSelections();
	};

	/**
	 * Callback called on element drag.
	 * This method should also be called to notify element about manual move/drag.
	 * This method can be overrided to do actions on element drag, but you shuld call it from overriden method.
	 * @param onConstruct if true means it's called from constructor
	 */
	Element.prototype.onDrag = function(onConstruct) {
		this.fitToParent();
		var parent = this.getParent();
		if (parent) parent.updateSize();
		if (!onConstruct) {
			wb_builder.setPageModified(true);
		}
	};

	Element.prototype.onStartResize = function(ui) {
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-resize-start', this);
	};
	
	Element.prototype.onStopResize = function(ui) {
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-resize-end', this);
	};
	
	/**
	 * Callback called on each iteration of resizing.
	 * @param {Number} width
	 * @param {Number} height
	 */
	Element.prototype.onLiveResize = function(width, height) {
		if (width === undefined || height === undefined) {
			var b = this.getBounds();
			width = width || b.width;
			height = height || b.height;
		}
		this.noPhotoMsg.find('i').css('display', ((width * height >= 22500 && width >= 140 && height >= 100) ? 'block' : 'none'));
	};

	/**
	 * Callback called on element resize.
	 * This method should also be called to notify element about manual resize.
	 * This method can be overrided to do actions on element resize, but you shuld call it from overriden method.
	 * @param onConstruct if true means it's called from constructor
	 */
	Element.prototype.onResize = function(onConstruct) {
		if (this.isHidden()) return;
		var parent = this.getParent();
		if (parent) parent.updateSize();
		this.fitToParent();
		if (!onConstruct) {
			wb_builder.setPageModified(true);
		}
		this.elem.trigger("elementresize", [this]);
	};
	
	Element.prototype.updateStyle = function(initial, langCode) {
		
	};

	Element.prototype.setLocked = function(lock, initial) {
		if (!this.isEditableStrict) return;
		var thisClass = this;
		if (lock) {
			this.isLocked = true;
			this.elem.draggable("disable");
			if (this.isResizable) this.elem.resizable("disable");
			this.moveBtn.children(".glyphicon").removeClass("glyphicon-move");
			this.moveBtn.children(".glyphicon").addClass("glyphicon-lock");
			this.elem.css("opacity", 1);
			this.moveBtn.css({cursor: "pointer"});
			this.moveBtn.attr("data-html", true);
			this.moveBtn.attr("data-placement", "right");
			this.moveBtn.attr("data-trigger", "hover");
			this.moveBtn.attr("title", __("Unlock this element to move\n(click icon to unlock)").replace(/\n/g, '<br />'));
			this.moveBtn.tooltip({ trigger: "hover", placement: "right", html: true });
			this.isLockedOpts = {};
			this.isLockedOpts.highlight = function() {
				if (thisClass.isLockedOpts.tooltipShown) return;
				thisClass.moveBtn.tooltip("show");
				if (thisClass.isLockedOpts.timeout) clearTimeout(thisClass.isLockedOpts.timeout);
				thisClass.isLockedOpts.timeout = setTimeout(function() {
					thisClass.moveBtn.tooltip("hide");
					thisClass.isLockedOpts.tooltipShown = false;
				}, 3000);
			};
			this.moveBtn.on("mousedown", this.isLockedOpts.canceler = function(e) {
				thisClass.isLockedOpts.isDown = true;
				e.stopPropagation();
				e.preventDefault();
				return false;
			});
			this.moveBtn.on("click", this.isLockedOpts.unlocker = function() {
				thisClass.setLocked(false);
				return false;
			});
			this.editBtn.on("mousedown", this.isLockedOpts.canceler);
			this.cover.on("mousedown", this.isLockedOpts.canceler);
			this.cover.on("mouseup", this.isLockedOpts.upper = function() {
				thisClass.isLockedOpts.isDown = false;
			});
			this.cover.on("mousemove", this.isLockedOpts.mover = function() {
				if (thisClass.isLockedOpts.isDown) {
					thisClass.setSelected(true);
					thisClass.setControlsVisible(true);
					thisClass.isLockedOpts.highlight();
					thisClass.isLockedOpts.tooltipShown = true;
				}
			});
		} else {
			this.isLocked = false;
			this.elem.draggable("enable");
			if (this.isResizable) this.elem.resizable("enable");
			this.moveBtn.children(".glyphicon").removeClass("glyphicon-lock");
			this.moveBtn.children(".glyphicon").addClass("glyphicon-move");
			this.elem.css("opacity", "");
			this.moveBtn.off({
				"mousedown": this.isLockedOpts.canceler,
				"click": this.isLockedOpts.unlocker
			});
			this.editBtn.off({"mousedown": this.isLockedOpts.canceler});
			this.cover.off({
				"mousedown": this.isLockedOpts.canceler,
				"mouseup": this.isLockedOpts.upper,
				"mousemove": this.isLockedOpts.mover
			});
			this.moveBtn.css({cursor: ""});
			this.moveBtn.removeAttr("title");
			this.moveBtn.tooltip("destroy");
		}
	};

	/**
	 * @param {Boolean} isFullWidth
	 */
	Element.prototype.setFullWidth = function(isFullWidth) {
		if( this.isFullWidth === isFullWidth )
			return;
		this.isFullWidth = isFullWidth;
		if( isFullWidth ) {
			if (typeof(this.modes) === 'object' && this.modes) {
				for (var i in this.modes) {
					if ('x' in this.modes[i]) this.modes[i]._xFullWidthBackup = this.modes[i].x;
					if ('width' in this.modes[i]) this.modes[i]._widthFullWidthBackup = this.modes[i].width;
				}
			}
			var b = this.getBounds();
			this._xFullWidthBackup = b.left;
			this._widthFullWidthBackup = b.width;
			this.elem.draggable("option", "axis", "y");
			this.setLocation(0, null);
			this.setSize("100%", null);
			if( this.parent )
				this.parent.updateElementContainer(this);
		}
		else {
			var currMode = ModeManager.getMode();
			var currModeX, currModeWidth;
			if (typeof(this.modes) === 'object' && this.modes) {
				for (var i in this.modes) {
					if ('_xFullWidthBackup' in this.modes[i]) this.modes[i].x = this.modes[i]._xFullWidthBackup;
					if ('_widthFullWidthBackup' in this.modes[i]) this.modes[i].width = this.modes[i]._widthFullWidthBackup;
					delete this.modes[i]._xFullWidthBackup;
					delete this.modes[i]._widthFullWidthBackup;
				}
				if (currMode in this.modes) {
					currModeX = this.modes[currMode].x;
					currModeWidth = this.modes[currMode].width;
				}
			}
			if ((!currModeX || !currModeWidth) && this._xFullWidthBackup !== null && this._widthFullWidthBackup !== null) {
				currModeX = this._xFullWidthBackup;
				currModeWidth = this._widthFullWidthBackup;
				delete this._xFullWidthBackup;
				delete this._widthFullWidthBackup;
			}
			this.elem.draggable("option", "axis", false);
			this.setLocation((currModeX ? currModeX : 0), null);
			if( this.parent ) {
				this.parent.updateElementContainer(this);
				this.setSize((currModeWidth ? currModeWidth : this.parent.getWidth()), null);
			}
			else
				this.setSize((currModeWidth ? currModeWidth : 1200), null);
		}
		var opts = {};
		this.initResizable(opts);
		this.elem.resizable("option", "handles", opts.handles);
		this.fixResizableHandles();
		this.onFullWidthChanged();
	};

	/**
	 * This event handler method is called only if isFullWidth property changes the value.
	 * @param {Boolean} isFullWidth
	 */
	Element.prototype.onFullWidthChanged = function(isFullWidth) {
		this.updateContentSize();
		this.onResize();
	};

	Element.prototype.updateContentSize = function() {
	};

	/**
	 * Update containment restrictions for element
	 */
	Element.prototype.updateContainment = function() {
		var site = $("#site");
		var cont = site.offset();
		cont.right = cont.left + site.width();
		cont.bottom = cont.top + site.height();
		//this.elem.draggable("option", "containment", [cont.left, cont.top, cont.right, cont.bottom]);
		this.elem.draggable("option", "containment", $("#site"));
	};

	/**
	 * Set text to display when element is empty (when empty message is displayed)
	 * @param text message text to display
	 */
	Element.prototype.setEmtyMessageText = function(text) {
		this.noPhotoMsg.find('span').html(text);
	};

	/**
	 * Set image to display when element is empty (when empty message is displayed)
	 * Note: image url must me relative to builder module folder (ex. img/ico_tb_picture.png)
	 * @param image message image to display
	 */
	Element.prototype.setEmtyMessageImage = function(image) {
		this.noPhotoBg = image;
		this.noPhotoMsg.find('i').attr('class', image);
	};

	/**
	 * Display message to inform user how to change picture
	 * @param display if true message will be displayed else hidden
	 * @param noText (optional) (default false) set true to hide text
	 */
	Element.prototype.displayEmtyMessage = function(display, noText) {
		if (display) {
			this.noPhotoMsg.css("display", noText ? "none" : "block");
		} else {
			this.noPhotoMsg.css("display", "none");
		}
	};

	Element.prototype.onContextMenu = function() {
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-context-menu', this);
		this.menu.setVisible('paste', wb_builder.getClipboard());
	};

	Element.prototype.setResizingEnabled = function(enabled, destroy) {
		if (!this.isEditableStrict) return;
		if (enabled) {
			this.elem.resizable("enable");
		} else {
			this.elem.resizable("disable").css('opacity', 1);
			if (destroy) {
				this.isResizable = false;
				this.elem.resizable("destroy");
			}
		}
	};

	Element.prototype.setDragginEnabled = function(enabled) {
		if (!this.isEditableStrict) return;
		if (this.isLocked) return;
		if (enabled) {
			this.elem.draggable("enable");
		} else {
			this.elem.draggable("disable").css('opacity', 1);
		}
	};

	/**
	 * Enable/Disable controls.
	 * When controls are disabled, they are invisible.
	 * @param {Boolean} enabled
	 */
	Element.prototype.setControlsEnabled = function(enabled) {
		if (!this.isEditableStrict) return;
		if (enabled) {
			this.controls.stop(true, true).show();
		} else {
			this.controls.stop(true, true).hide();
		}
	};

	/**
	 * Set controls visibility
	 * @param visible visibility
	 */
	Element.prototype.setControlsVisible = function(visible) {
		if (!this.isEditableStrict) return;
		if (visible && !this.isElementPreview) {
			this.isControlsVisible = true;
			if (this.langLabel) this.langLabel.stop(true, true).css("opacity", 1);
			this.editBtn.stop(true, true).css("opacity", 1);
			this.moveBtn.stop(true, true).css("opacity", 1);
			if( this.seResizeBtn )
				this.seResizeBtn.stop(true, true).css("opacity", 1);
			this.controls.stop(true, true).css("opacity", 1);
			//this.controls.stop(true, true).css("display", "block");
			this.controls.stop(true, true).css("zIndex", 10);
			this.container.stop(true, true).css("zIndex", 1);
		} else {
			this.isControlsVisible = false;
			if (this.langLabel) this.langLabel.stop(true, true).css("opacity", 0);
			this.editBtn.stop(true, true).css("opacity", 0);
			this.moveBtn.stop(true, true).css("opacity", 0);
			if( this.seResizeBtn )
				this.seResizeBtn.stop(true, true).css("opacity", 0);
			this.controls.stop(true, true).css("opacity", 0.3);
			//this.controls.stop(true, true).css("display", "none");
			this.controls.stop(true, true).css("zIndex", 1);
			this.container.stop(true, true).css("zIndex", 10);
		}
	};

	/**
	 * @return {boolean}
	 */
	Element.prototype.supportsFullWidth = function() {
		return false;
	};

	/**
	 * Common element properties dialog call method
	 * Note: to add element specific properties to this dialog you can override this method
	 * @param {Object} uiDef property dialog UI definition object
	 */
	Element.prototype.comProperties = function(uiDef) {
		if (!this.isEditableStrict) return;
		var thisClass = this;
		var fields = null;
		if (!this.comDialog) {
			var applyFunc, cancelFunc;
			var chkFunc, baseUiDef = {
				size: {/*sizeClass: 'modal-md', width: 580, height: 520, maxBodyHeight: 460, */minBodyHeight: (this.isResizable ? 330 : 220)},
				noScroll: true,
				tabs: [
					{name: __('Options'), options: true, priority: 100, children: [
						{type: 'HorizontalLayout', children: [
							{type: 'VerticalLayout', children: [
								{type: 'FlowLayout', verticalAlign: 'middle', ignore: !this.supportsFullWidth(), children: [
									{type: 'CheckBox', id: 'fullWidth', label: __('Full screen width'),
										change: function() {
											thisClass.updateComPropertiesInterface.call(thisClass);
											Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fullWidth-change', thisClass);
										}
									}
								], css: {marginBottom: 5}},
								{type: 'VerticalLayout', id: 'sizeBlock', visible: (this.isResizable), children: [
									{type: 'Label', text: __('Size')},
									{type: 'FlowLayout', verticalAlign: 'middle', id: "sizeWCont", visible: !this.isFullWidth, children: [
										{type: 'Label', text: __('Width'), css: {marginBottom: '0px', fontWeight: 'normal'}},
										{type: 'TextField', id: 'sizeW', css: {width: 60}, styleClass: 'input-sm',
											change: function() {
												Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-sizeW-change', thisClass);
											}
										},
										{type: 'Label', text: ' px', css: {marginBottom: '0px', fontWeight: 'normal'}}
									], css: (wb_builder.rtl ? {marginLeft: '30px', textAlign: 'left'} : {marginRight: '30px', textAlign: 'right'})},
									{type: 'FlowLayout', verticalAlign: 'middle', children: [
										{type: 'Label', text: __('Height'), css: {marginBottom: '0px', fontWeight: 'normal'}},
										{type: 'TextField', id: 'sizeH', css: {width: 60}, styleClass: 'input-sm',
											init: function() {
												if (thisClass.elem.hasClass('ui-resizable') && !thisClass.elem.resizable('option', 'disabled')) {
													var handles = thisClass.elem.resizable('option', 'handles');
													var handlesArr = handles.split(/,\ ?/);
													var heightDisabled = true;
													for (var i in handlesArr) {
														var h = handlesArr[i];
														if (h === 's' || h === 'se' || h === 'sw' || h === 'n' || h === 'ne' || h === 'nw') heightDisabled = false;
													}
													if (heightDisabled) this.setEnabled(false);
												}
											},
											change: function() {
												Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-sizeH-change', thisClass);
											}
										},
										{type: 'Label', text: ' px', css: {marginBottom: '0px', fontWeight: 'normal'}}
									], css: (wb_builder.rtl ? {marginLeft: '30px', marginTop: 7, textAlign: 'left'} : {marginRight: '30px', marginTop: 7, textAlign: 'right'})}
								]},
								{type: 'VerticalLayout', id: 'positionBlock', css: {marginTop: (this.isResizable ? 15 : 0)}, children: [
									{type: 'Label', text: __('Position')},
									{type: 'FlowLayout', verticalAlign: 'middle', id: "locXCont", visible: !this.isFullWidth, children: [
										{type: 'Label', text: __('From Left'), css: {marginBottom: '0px', fontWeight: 'normal'}},
										{type: 'TextField', id: 'locX', css: {width: 60}, styleClass: 'input-sm',
											change: function() {
												Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-locX-change', thisClass);
											}
										},
										{type: 'Label', text: ' px', css: {marginBottom: '0px', fontWeight: 'normal'}}
									], css: (wb_builder.rtl ? {marginLeft: '30px', textAlign: 'left'} : {marginRight: '30px', textAlign: 'right'})},
									{type: 'FlowLayout', verticalAlign: 'middle', children: [
										{type: 'Label', text: __('From Top'), css: {marginBottom: '0px', fontWeight: 'normal'}},
										{type: 'TextField', id: 'locY', css: {width: 60}, styleClass: 'input-sm',
											change: function() {
												Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-locY-change', thisClass);
											}
										},
										{type: 'Label', text: ' px', css: {marginBottom: '0px', fontWeight: 'normal'}}
									], css: (wb_builder.rtl ? {marginLeft: '30px', marginTop: 7, textAlign: 'left'} : {marginRight: '30px', marginTop: 7, textAlign: 'right'})}
								]},
								{type: 'VerticalLayout', id: 'anchorBlock', css: {marginTop: 15}, children: [
									{type: 'Label', text: __('Anchor name')},
									{type: 'TextField', id: 'anchorName', change: function() {
										var value = this.getValue();
										value = value.replace(/^\s*(.+?)\s*$/i, '$1');
										this.setValue(value);
									}}
								]},
								{type: 'VerticalLayout', id: 'referenceIdBlock', ignore: !wb_builder.adminMode, css: {marginTop: 15}, children: [
									{type: 'Label', text: __('Reference ID'),
										helpText: __('Element ID for use with website creation %sAPIs%s')
											.replace('%s', '<a href="https://site.pro/docs/api/#websites/create" target="_blank" style="text-decoration: underline;">')
											.replace('%s', '</a>')
									},
									{type: 'TextField', id: 'referenceId', change: function() {
										var value = this.getValue();
										value = value.replace(/^\s*(.+?)\s*$/i, '$1');
										this.setValue(value);
									}}
								]},
								{type: 'FlowLayout', id: 'isAdminLockedBlock', ignore: !wb_builder.adminMode, css: {marginTop: 15}, children: [
									{type: 'CheckBox', id: 'isAdminLocked', label: __('Locked by admin')}
								]}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Show object')},
								{type: 'RadioBox', id: 'isNotCommon',  label: __('Show in current page only'), group: 'isCommon',
									click: (chkFunc = function() {
										if (fields.isSpecCommon.getValue()) {
											fields.isCommonValues.setVisible(true);
											fields.isNotCommonValues.setVisible(false);
										} else if (fields.isNotCommon.getValue()) {
											fields.isCommonValues.setVisible(false);
											if (fields.isNotCommonValues.getElem().is('.multilang')) {
												fields.isNotCommonValues.setVisible(true);
											}
										} else {
											fields.isCommonValues.setVisible(false);
											fields.isNotCommonValues.setVisible(false);
										}
									})
								},
								{type: 'CustomContainer', id: 'isNotCommonValues', styleClass: 'well wb-comproperty-show', visible: false},
								{type: 'RadioBox', id: 'isCommon',     label: __('Show in all pages'),         group: 'isCommon',
									click: chkFunc
								},
								{type: 'RadioBox', id: 'isSpecCommon', label: __('Show in a specific pages'),  group: 'isCommon',
									click: chkFunc
								},
								{type: 'CustomContainer', id: 'isCommonValues',    styleClass: 'well wb-comproperty-show', visible: false}
							]}
						]}
					]}
				],
				buttons: [
					{name: __('Cancel'), click: cancelFunc = function() {
						if ('cancelFunc' in baseUiDef && typeof(baseUiDef.cancelFunc) === 'function') {
							baseUiDef.cancelFunc.call(this, fields);
						}
						thisClass.comDialog.hide();
					}},
					{name: __('Apply'), primary: true, click: applyFunc = function() {
						wb_builder.setPageModified(true);
				
						wb_builder.site.removeAnchor(thisClass);
						
						thisClass.anchor = fields.anchorName.getValue();
						if (fields.referenceId) {
							thisClass.referenceId = fields.referenceId.getValue();
						}
						if (fields.isAdminLocked) {
							thisClass.isAdminLocked = fields.isAdminLocked.getValue();
						}
						
						var oldIsCommon = thisClass.isCommon;
						thisClass.isCommon = (fields.isCommon.getValue() || fields.isSpecCommon.getValue());

						thisClass.includePages = {};
						
						var multilang = (wb_builder.site.languages.length > 0);
						if (multilang) {
							if (fields.isNotCommon.getValue()) {
								$.each(wb_builder.site.languages, function() {
									thisClass.includePages[this.code] = false;
								});
								$('input:checked', fields.isNotCommonValues.getElem()).each(function() {
									thisClass.includePages[$(this).val()] = true;
								});
							} else if (fields.isSpecCommon.getValue()) {
								var checked = $('input:checked', fields.isCommonValues.getElem());
								if (checked.size() === wb_builder.site.languages.length * Object.keys(wb_builder.site.pages).length) {
									// if all checked
									thisClass.isCommon = true;
									thisClass.includePages = {};
								} else {
									var defLangs = {};
									$.each(wb_builder.site.languages, function() {
										defLangs[this.code] = false;
									});
									checked.each(function() {
										var val = $(this).val().split('_');
										var pid = val[0], lang = val[1];
										if (pid && lang) {
											if (typeof thisClass.includePages[''+pid] !== 'object') {
												thisClass.includePages[''+pid] = $.extend({}, defLangs);
											}
											thisClass.includePages[''+pid][lang] = true;
										}
									});
								}
							}
						} else {
							if (fields.isSpecCommon.getValue()) {
								$('input:checked', fields.isCommonValues.getElem()).each(function() {
									thisClass.includePages[''+$(this).val()] = true;
								});
							}
						}
						
						if (thisClass.isCommon && Object.keys(thisClass.includePages).length === 1
								&& Object.keys(thisClass.includePages)[0] == wb_builder.pageId) {
							if (multilang) {
								thisClass.includePages = thisClass.includePages[Object.keys(thisClass.includePages)[0]];
							} else {
								thisClass.includePages = {};
							}
							thisClass.isCommon = false;
						}
						
						if (thisClass.isCommon && $('input:not(:checked)', fields.isCommonValues.getElem()).length === 0) {
							thisClass.includePages = {};
						}
						
						wb_builder.site.addAnchor(thisClass);

						thisClass.setLocation(fields.locX.getValue(), fields.locY.getValue());
						if (thisClass.isResizable) {
							thisClass.setSize(fields.sizeW.getValue(), fields.sizeH.getValue());
						}
						thisClass.onResize();

						if ('callbackFunc' in baseUiDef && typeof(baseUiDef.callbackFunc) === 'function') {
							baseUiDef.callbackFunc.call(this, fields);
						}

						if( thisClass.supportsFullWidth() )
							thisClass.setFullWidth(fields.fullWidth.getValue());

						thisClass.updateShow();
						thisClass.comDialog.hide();
						if (thisClass.isCommon !== oldIsCommon) thisClass.updateContextMenuRemove();
						
						thisClass.onLiveResize();
						
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-apply', thisClass);
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-close', thisClass);
					}}
				]
			};
			// TODO: do semething if needed when extending element then call parents callbackFunc if (typeof(cfb) === "function") cfb.call(this);
			var initFunc = null;
			if ((typeof uiDef === 'object') && uiDef && ('init' in uiDef) && (typeof uiDef.init === 'function')) {
				initFunc = uiDef.init;
				uiDef.init = null;
			}
			var closeFunc = null;
			if ((typeof uiDef === 'object') && uiDef && ('close' in uiDef) && (typeof uiDef.close === 'function')) {
				closeFunc = uiDef.close;
				uiDef.close = null;
			}
			this.comDialog = new PropertyDialog(__('Properties'), Service.UIBuilder.extendDefinition(baseUiDef, uiDef));
			if (initFunc) initFunc.call(this, this.comDialog.fields);
			this.comDialog.onClose = function() {
				if (closeFunc) closeFunc.call(thisClass.comDialog, thisClass.comDialog.fields);
				Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-end', thisClass);
				Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-close', thisClass);
			};
			this.comDialog._cancelFunc = cancelFunc;
			this.comDialog._applyFunc = applyFunc;
			this.comDialog.tabbedPane.onChange = function(a, b, tabDef) {
				if (tabDef && tabDef.type) {
					Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tab-' + tabDef.type, thisClass);
				}
			};
		}
		fields = this.comDialog.fields;
		
		fields.anchorName.setText(this.anchor);
		if (fields.referenceId) {
			fields.referenceId.setText(this.referenceId);
		}
		if (fields.isAdminLocked) {
			fields.isAdminLocked.setValue(this.isAdminLocked);
		}
		
		var has = (Object.keys(this.includePages).length > 0);
		if (has && this.isCommon) {
			fields.isNotCommon.setValue(false);
			fields.isCommon.setValue(false);
			fields.isSpecCommon.setValue(true);
			fields.isCommonValues.setVisible(true);
			fields.isNotCommonValues.setVisible(false);
		} else if (this.isCommon) {
			fields.isNotCommon.setValue(false);
			fields.isCommon.setValue(true);
			fields.isSpecCommon.setValue(false);
			fields.isCommonValues.setVisible(false);
			fields.isNotCommonValues.setVisible(false);
		} else {
			fields.isNotCommon.setValue(true);
			fields.isCommon.setValue(false);
			fields.isSpecCommon.setValue(false);
			fields.isCommonValues.setVisible(false);
			fields.isNotCommonValues.setVisible((wb_builder.site.languages.length > 0));
		}

		fields.isNotCommonValues.getElem().empty();
		fields.isCommonValues.getElem().empty();
		
		var i, lang, langs = wb_builder.site.languages, pid, p, td, tr, name;
		var itemNames = {};
		var menuList = MenuList.buildMenuStruct(false);
		for (i = 0; i < menuList.length; i++) {
			var menu = menuList[i];
			for (var n = 0; n < menu.items.length; n++) {
				var mi = menu.items[n];
				if (!mi.uID) continue;
				if (mi.type === 'page' && mi.pageId) {
					itemNames['#' + mi.pageId] = __tr(mi.fullName, wb_builder.site.getLastDefLang());
				}
			}
		}
		if (langs.length) {
			var table = $('<table></table>');
			fields.isNotCommonValues.getElem().addClass('multilang').append(table);
			p = wb_builder.site.pages['#' + wb_builder.pageId];
			tr = $('<tr><td></td></tr>');
			for (i = 0; (lang = langs[i]); i++) {
				td = $('<td>' + lang.code + '</td>');
				tr.append(td);
			}
			table.append(tr);
			name = (('#' + p.id) in itemNames) ? itemNames['#' + p.id] : null;
			if (!name) name = __tr(p.title, null, __tr(p.title, wb_builder.site.getLastDefLang(), ('[' + __('no name') + ']')));
			tr = $('<tr><td><a href="javascript:void(0)">' + name + '</a></td></tr>');
			for (i = 0; (lang = langs[i]); i++) {
				td = $('<td>' +
						'<input type="checkbox" name="isNotCommonPage" />' +
					'</td>');
				td.children('input').val(lang.code);
				if (this.isVisible(lang.code)) {
					td.children('input').get(0).checked = true;
				}
				tr.append(td);
			}
			table.append(tr);

			var table2 = $('<table></table>');
			fields.isCommonValues.getElem().append(table2);
			tr = $('<tr><td></td></tr>');
			for (i = 0; (lang = langs[i]); i++) {
				td = $('<td><a href="javascript:void(0)">' + lang.code + '</a></td>');
				tr.append(td);
			}
			table2.append(tr);
			for (pid in wb_builder.site.pages) {
				p = wb_builder.site.pages[pid];
				name = (('#' + p.id) in itemNames) ? itemNames['#' + p.id] : null;
				if (!name) name = __tr(p.title, null, __tr(p.title, wb_builder.site.getLastDefLang(), ('[' + __('no name') + ']')));
				tr = $('<tr><td><a href="javascript:void(0)">' + name + '</a></td></tr>');
				for (i = 0; (lang = langs[i]); i++) {
					td = $('<td>' +
							'<input type="checkbox" name="isNotCommonPage" />' +
						'</td>');
					td.children('input').val(p.id + '_' + lang.code);
					if (this.isVisible(lang.code, p.id)) {
						td.children('input').get(0).checked = true;
					}
					tr.append(td);
				}
				table2.append(tr);
			}
			var checkboxClick = function(tbl) {
				tbl.find('tr:first').find('a').bind('click', function() {
					var thisA = $(this);
					var checkboxes = tbl.find('input[value$="_' + thisA.html() + '"]');
					var checkedLen = tbl.find('input[value$="_' + thisA.html() + '"]:checked').length;
					if (checkboxes.length > checkedLen) {
						checkboxes.each(function() { this.checked = true; });
					} else {
						checkboxes.each(function() { this.checked = false; });
					}
				});
				tbl.find('tr td:first-child a').bind('click', function() {
					var thisA = $(this);
					var tr = thisA.parent().parent();
					var checkboxes = tr.find('input');
					var checkedLen = tr.find('input:checked').length;
					if (checkboxes.length > checkedLen) {
						checkboxes.each(function() {
							this.checked = true;
						});
					} else {
						checkboxes.each(function() {
							this.checked = false;
						});
					}
				});
			};
			checkboxClick(table);
			checkboxClick(table2);
		} else {
			fields.isNotCommonValues.getElem().removeClass('multilang');
			for (pid in wb_builder.site.pages) {
				p = wb_builder.site.pages[pid];
				name = (('#' + p.id) in itemNames) ? itemNames['#' + p.id] : null;
				if (!name) name = __tr(p.title, null, __tr(p.title, wb_builder.site.getLastDefLang(), ('[' + __('no name') + ']')));
				var li = $('<div class="checkbox"><label>' +
						'<input type="checkbox" name="isCommonPage" /> ' + name +
					'</label></div>');
				li.find("input").val(p.id);
				if (this.isVisible(null, p.id)) {
					li.find("input").get(0).checked = true;
				}
				fields.isCommonValues.getElem().append(li);
			}
		}

		if( thisClass.supportsFullWidth() )
			fields.fullWidth.setValue(this.isFullWidth);

		var loc = this.getLocation();
		fields.locX.setValue(Math.round(loc.left));
		fields.locY.setValue(Math.round(loc.top));
		if (this.isResizable) {
			var size = this.getSize();
			fields.sizeW.setValue(Math.round(size.width));
			fields.sizeH.setValue(Math.round(size.height));
		}

		this.comDialog.tabbedPane.setLocked(false);
		this.comDialog.tabbedPane.setNavVisible(true);
		if (this.virtualElement && this.comDialog.optionsTab) {
			this.comDialog.tabbedPane.setTabVisible(this.comDialog.optionsTab, false);
		}
		
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-edit-start', this);
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-prop-open', this);
		this.comDialog.show();
		return fields;
	};

	/**
	 * This method should be called when there were changes in the properties dialog that may affect the interface of
	 * that dialog.
	 */
	Element.prototype.updateComPropertiesInterface = function() {
		if( !this.comDialog )
			return;
		var isFullWidth = this.comDialog.fields.fullWidth.getValue();
		this.comDialog.fields.sizeWCont.setVisible(!isFullWidth);
		this.comDialog.fields.locXCont.setVisible(!isFullWidth);
	};

	/**
	 * Get dialogs property field.
	 * Note: This is used by help system scenario player.
	 * @param {string} field field identifier in this dialog.
	 * @returns {UIComponent|null}
	 */
	Element.prototype.comPropertiesField = function(field) {
		if (!this.comDialog) return null;
		return this.comDialog.propertyDialogField(field);
	};
	
	Element.prototype.closeComProperties = function() {
		if (!this.comDialog) return;
		this.comDialog.propertyDialogClose();
	};
	
	/**
	 * Apply changes in oproperty dialog and close it (same as clicking dialogs apply button).
	 * Note: This is used by help system scenario player.
	 * @param {string=} type property dialogs type.
	 */
	Element.prototype.applyComProperties = function(type) {
		if (!this.comDialog) return;
		this.comDialog.propertyDialogApply();
	};

	/**
	 * Initialize elements context menu
	 * @param elem element (button) add context menu to
	 */
	Element.prototype.initContextMenu = function(elem) {
		if (!this.isEditableStrict) return;
		var thisClass = this;
		var menu = new ContextMenu("wb_element_contextmenu" + this.index);

		if (WB_DEBUG_MODE) {
			menu.addItem("dbg_clsTitle", this.getClassType(), function() {}, true, true);
			this.contextMenuFirstIndex++;
		}

		menu.addItem("copy", __("Copy"), function() {
			var obj;
			if (thisClass.isSelected()) {
				obj = [];
				thisClass.elem.parent().children(".ui-selected").each(function() {
					var elem = $(this).wbGetClassInstance();
					if (elem) obj.push(elem.serialize());
				});
				wb_builder.setClipboard(obj);
			} else {
				obj = thisClass.serialize();
				wb_builder.setClipboard([obj]);
			}
		}, null, null, null, "glyphicon glyphicon-list-alt", true);

		//paste submenu
		menu.addItem("paste", __("Paste"), null, null, null, null, "glyphicon glyphicon-download-alt");

		menu.addSeparator();

		menu.addItem("lock", __("Lock"), function() {
			wb_builder.setPageModified(true);
			var lock = !thisClass.isLocked;
			if (thisClass.isSelected()) {
				for (var k in Element.selected) {
					var elem = Element.selected[k];
					if (elem) elem.setLocked(lock);
				}
			} else {
				thisClass.setLocked(lock);
			}
		}, null, null, null, "glyphicon glyphicon-lock", true);

		var saveHistoryState = function() {
			var historyFunc = function(selElems) {
				var elData, element, selElems2 = [];
				for (var i = 0; i < selElems.length; i++) {
					elData = selElems[i];
					element = window.getElementById(elData.index);
					selElems2.push({index: elData.index, loc: element.getLocation()});
					element.setLocation(elData.loc.left, elData.loc.top);
					element.onResize();
				}
				this.data = selElems2; // swap data
			};
			var k, el, selElems = [];
			for (k in Element.selected) {
				el = Element.selected[k];
				if (el.isLocked) continue;
				selElems.push({index: el.index, loc: el.getLocation()});
			}
			//selElems.push({el: thisClass, loc: thisClass.getLocation()});
			wb_builder.historyAdd('moveElements', selElems, historyFunc, historyFunc);
		};

		var alignSubmenu = new ContextMenu();
		alignSubmenu.addItem("alignLeft", __("Left"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var commonValue = null;
			Service.element.eachSelected(function() {
				var x = this.getLocation().left;
				commonValue = (commonValue === null) ? x : Math.min(x, commonValue);
			}).eachSelected(function() {
				if( !this.isLocked ) {
					this.setLocation(commonValue, null);
					this.onResize();
				}
			});
		}, null, null, null, "glyphicon glyphicon-object-align-left");
		alignSubmenu.addItem("alignVertical", __("Middle (vertical)"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var commonValue = 0;
			var bestWidth = null;
			Service.element.eachSelected(function() {
				var w = this.getWidth();
				if( bestWidth === null || bestWidth < w ) {
					bestWidth = w;
					commonValue = this.getLocation().left + w / 2;
				}
			}).eachSelected(function() {
				if( !this.isLocked ) {
					this.setLocation(Math.floor(commonValue - this.getWidth() / 2), null);
					this.onResize();
				}
			});
		}, null, null, null, "glyphicon glyphicon-object-align-vertical");
		alignSubmenu.addItem("alignRight", __("Right"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var commonValue = null;
			Service.element.eachSelected(function() {
				var x = this.getLocation().left + this.getWidth();
				commonValue = (commonValue === null) ? x : Math.max(x, commonValue);
			}).eachSelected(function() {
				if( !this.isLocked ) {
					this.setLocation(commonValue - this.getWidth(), null);
					this.onResize();
				}
			});
		}, null, null, null, "glyphicon glyphicon-object-align-right");
		alignSubmenu.addItem("alignTop", __("Top"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var commonValue = null;
			Service.element.eachSelected(function() {
				var y = this.getLocation().top;
				commonValue = (commonValue === null) ? y : Math.min(y, commonValue);
			}).eachSelected(function() {
				if( !this.isLocked ) {
					this.setLocation(null, commonValue);
					this.onResize();
				}
			});
		}, null, null, null, "glyphicon glyphicon-object-align-top");
		alignSubmenu.addItem("alignHorizontal", __("Middle (horizontal)"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var commonValue = 0;
			var bestHeight = null;
			Service.element.eachSelected(function() {
				var h = this.getHeight();
				if( bestHeight === null || bestHeight < h ) {
					bestHeight = h;
					commonValue = this.getLocation().top + h / 2;
				}
			}).eachSelected(function() {
				if( !this.isLocked ) {
					this.setLocation(null, Math.floor(commonValue - this.getHeight() / 2));
					this.onResize();
				}
			});
		}, null, null, null, "glyphicon glyphicon-object-align-horizontal");
		alignSubmenu.addItem("alignBottom", __("Bottom"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var commonValue = null;
			Service.element.eachSelected(function() {
				var y = this.getLocation().top + this.getHeight();
				commonValue = (commonValue === null) ? y : Math.max(y, commonValue);
			}).eachSelected(function() {
				if( !this.isLocked ) {
					this.setLocation(null, commonValue - this.getHeight());
					this.onResize();
				}
			});
		}, null, null, null, "glyphicon glyphicon-object-align-bottom");
		menu.addItem("align", __("Align"), alignSubmenu, null, null, null, "glyphicon glyphicon-object-align-left", "only");

		var distributeSubmenu = new ContextMenu();
		distributeSubmenu.addItem("distributeHorizontal", __("Horizontally"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var min = null, max = null, total = 0;
			var elementArr = [];
			Service.element.eachSelected(function() {
				if( this.isLocked )
					return;
				var pos = this.getLocation();
				var w = this.getWidth();
				total += w;
				min = (min === null) ? pos.left : Math.min(pos.left, min);
				max = (max === null) ? (pos.left + w) : Math.max((pos.left + w), max);
				elementArr.push({elem: this, pos: pos});
			});
			if( elementArr.length > 2 ) {
				var separation = Math.floor((max - min - total) / (elementArr.length - 1));
				elementArr.sort(function(a, b) {
					if( a.pos.left === b.pos.left ) {
						if( a.pos.top === b.pos.top )
							return 0;
						return (a.pos.top < b.pos.top) ? -1 : 1;
					}
					return (a.pos.left < b.pos.left) ? -1 : 1;
				});
				var prevValue = null, value;
				for( var i = 0; i < elementArr.length; i++ ) {
					if( i > 0 ) {
						value = prevValue + separation;
						elementArr[i].elem.setLocation(value, null);
					}
					else
						value = elementArr[i].pos.left;
					prevValue = value + elementArr[i].elem.getWidth();
				}
			}
		}, null, null, null, "glyphicon glyphicon-option-horizontal");
		distributeSubmenu.addItem("distributeVertival", __("Vertically"), function() {
			wb_builder.setPageModified(true);
			saveHistoryState();
			var min = null, max = null, total = 0;
			var elementArr = [];
			Service.element.eachSelected(function() {
				if( this.isLocked )
					return;
				var pos = this.getLocation();
				var h = this.getHeight();
				total += h;
				min = (min === null) ? pos.top : Math.min(pos.top, min);
				max = (max === null) ? (pos.top + h) : Math.max((pos.top + h), max);
				elementArr.push({elem: this, pos: pos});
			});
			if( elementArr.length > 2 ) {
				var separation = Math.floor((max - min - total) / (elementArr.length - 1));
				elementArr.sort(function(a, b) {
					if( a.pos.top === b.pos.top ) {
						if( a.pos.left === b.pos.left )
							return 0;
						return (a.pos.left < b.pos.left) ? -1 : 1;
					}
					return (a.pos.top < b.pos.top) ? -1 : 1;
				});
				var prevValue = null, value;
				for( var i = 0; i < elementArr.length; i++ ) {
					if( i > 0 ) {
						value = prevValue + separation;
						elementArr[i].elem.setLocation(null, value);
					}
					else
						value = elementArr[i].pos.top;
					prevValue = value + elementArr[i].elem.getHeight();
				}
			}
		}, null, null, null, "glyphicon glyphicon-option-vertical");
		menu.addItem("distribute", __("Distribute"), distributeSubmenu, null, null, null, "glyphicon glyphicon-option-horizontal", "only");

		if (this.isMovable) {
			var orderMi = new ContextMenu();
			orderMi.addItem("indexMax", __("Bring to front"), function() {
				wb_builder.setPageModified(true);
				thisClass.parent.changeElementLayer(thisClass, "top");
			}, null, null, null, "glyphicon glyphicon-arrow-up");
			orderMi.addItem("indexMin", __("Send to back"), function() {
				wb_builder.setPageModified(true);
				thisClass.parent.changeElementLayer(thisClass, "bottom");
			}, null, null, null, "glyphicon glyphicon-arrow-down");
			orderMi.addItem("indexUp", __("Bring forward"), function() {
				wb_builder.setPageModified(true);
				thisClass.parent.changeElementLayer(thisClass, "up");
			}, null, null, null, "glyphicon glyphicon-arrow-up");
			orderMi.addItem("indexDown", __("Send backwards"), function() {
				wb_builder.setPageModified(true);
				thisClass.parent.changeElementLayer(thisClass, "down");
			}, null, null, null, "glyphicon glyphicon-arrow-down");
			menu.addItem("order", __("Order"), orderMi, null, null, null, "glyphicon glyphicon-list");
		}


		menu.addItem("remove", __("Remove"), null, null, null, null, "glyphicon glyphicon-remove", true);

		menu.addSeparator();

		menu.addItem("comConfig", __("Properties"), function() {
			thisClass.comProperties();
		}, null, null, null, "glyphicon glyphicon-cog");

		this.menu = menu;
		menu.bind(elem);
		menu.onShow = function(ctxmenu, e) {
			if (!thisClass.isSelected()) {
				Element.unselectAll();
				Service.textArea.hideEditors();
				thisClass.setSelected(true);
			}
			thisClass.updateContextMenu();
			
			var ea = new BuilderEvent.ContextMenuEvent(ctxmenu, (e ? e.pageX : 0), (e ? e.pageY : 0), thisClass);
			BuilderEvent.GlobalEvents.triggerEvent('contextmenu.show', ea);
		};
	};

	Element.prototype.updateContextMenuRemove = function() {
		if (!this.menu) return;
		var submenu = null, submenu2 = null, thisClass = this;
		this.menu.removeItem('remove');
		var singlePageDelete = function(elem) {
			if (elem.isCommon) {
				elem.setVisible('all', false, wb_builder.pageId);
			} else {
				elem.remove();
			}
		};
		var clb = function(ev, single) {
			wb_builder.setPageModified(true);
			if (thisClass.isSelected()) {
				for (var k in Element.selected) {
					var elem = Element.selected[k];
					if (!elem) continue;
					if (elem.isLocked) {
						elem.isLockedOpts.highlight();
						continue;
					}
					(single) ? singlePageDelete(elem) : elem.remove();
				}
			} else {
				(single) ? singlePageDelete(thisClass) : thisClass.remove();
			}
		};
		var clbSingle = function(ev) { clb(ev, true); };
		
		if (wb_builder.site.languages.length > 0) {
			submenu = new ContextMenu();
			submenu.menu.addClass('wb-multi-mi-remove');
			submenu.addItem("lang_all", __("From all languages"), clbSingle);
			if (this.isCommon) {
				submenu2 = new ContextMenu();
				submenu2.addItem("page_single_lang_all", __("From this page"), clbSingle);
				submenu2.addItem("page_all_lang_all", __("From all pages"), clb);
				submenu.setSubmenu("lang_all", submenu2);
			}
			for (var i=0, lang; (lang = wb_builder.site.languages[i]); i++) {
				var lnClb = function(ev, lang, single) {
					wb_builder.setPageModified(true);
					if (thisClass.isSelected()) {
						for (var k in Element.selected) {
							var elem = Element.selected[k];
							if (elem.isLocked) {
								elem.isLockedOpts.highlight();
								continue;
							}
							elem.setVisible(lang.code, false, (single ? wb_builder.pageId : null));
						}
					} else {
						// elem cia neegzistuoja
						// elem.setVisible(lang.code, false);
					}
				};
				var lnClbSingle = function(ev, lang) { lnClb(ev, lang, true); };
				
				submenu.addItem("lang_" + lang.code, '<i class="flag-icon-' + wb_builder.getCountryCode(lang.code) + '"></i>' + lang.name, lnClb, false, false, lang);
				if (this.isCommon) {
					submenu2 = new ContextMenu();
					submenu2.addItem("page_single_lang_" + lang.code, __("From this page"), lnClbSingle, false, false, lang);
					submenu2.addItem("page_all_lang_" + lang.code, __("From all pages"), lnClb, false, false, lang);
					submenu.setSubmenu("lang_" + lang.code, submenu2);
				}
			}
		} else {
			if (this.isCommon) {
				submenu = new ContextMenu();
				submenu.addItem("page_signle", __("From this page"), clbSingle);
				submenu.addItem("page_all", __("From all pages"), clb);
			}
		}
		this.menu.insertItemAt(this.menu.getIndexById('order') + 2, "remove", __("Remove"), clbSingle, null, null, null, "glyphicon glyphicon-remove", true);
		if (submenu) this.menu.setSubmenu('remove', submenu);
	};

	/**
	 * Update context menu, this method called just before menu is shown
	 */
	Element.prototype.updateContextMenu = function() {
		this.menu.setName("lock", (this.isLocked ? __("Unlock") : __("Lock")));

		if (this.parent) {
			this.parent.addPaste(this.menu, this, true);
		}

		var cc = 0;
		for (var id in Element.selected) {
			cc++;
			if (cc >= 2) break;
		}
		if (cc >= 2) {
			this.menu.setMultiMode(true);
		} else {
			this.menu.setMultiMode(false);
		}
		var mode = ModeManager.getMode();
		/* if (mode === ModeManager.MODE_PHONE || mode === ModeManager.MODE_TABLET) { */
			if (!this.hideElemCi) {
				var thisSelf = this;
				this.hideElemCi = this.menu.insertItemAt(this.menu.getIndexById('remove') + 2, 'hideElem', __('Hide'), function() { thisSelf.hide(true, true); }, null, null, null, 'glyphicon glyphicon-eye-open', true);
			} else {
				this.menu.setVisible('hideElem', true);
			}
		/* } else {
			if (this.hideElemCi) this.menu.setVisible('hideElem', false);
		} */
	};

	/**
	 * Set element selected/unselected
	 * @param selected
	 */
	Element.prototype.setSelected = function(selected) {
		if (selected) {
			this.elem.addClass("ui-selected");
			Element.selected[this.id] = this;
		} else {
			this.elem.removeClass("ui-selected");
			this.elem.trigger("mouseout");
			Element.selected[this.id] = null;
			delete Element.selected[this.id];
		}
	};

	/**
	 * Tests if element is selected
	 * @return selection status
	 */
	Element.prototype.isSelected = function() {
		return this.elem.hasClass("ui-selected") ? true : false;
	};

	/**
	 * Make this element fit to parent
	 * @param {Boolean} preserveAspectRatio
	 * @param {Object} oriBounds
	 */
	Element.prototype.fitToParent = function(preserveAspectRatio, oriBounds, initial) {
		if (!this.parent || this.isHidden() || this.ignoreParentBounds) return;
		if (!oriBounds || (typeof oriBounds !== "object")) oriBounds = this.getBounds();
		var px, py, b = this.getBounds();
		this.setLocation(Math.max(b.left, 0), Math.max(b.top, 0));
		b = this.getBounds();
		// modify size if it's to big to fit in content element
		var pb = {
			"width": this.parent.getWidth(),
			"height": this.parent.getHeight()
		};
		if (b.left2 > pb.width || b.top2 > pb.height) {
			var xk = (b.left2 - pb.width) / b.width;
			var yk = (b.top2 - pb.height) / b.height;
			if (xk > 0 && xk <= 0.44) {
//				this.setSize(wb_builder.gridSnap(b.width * (1.0 - xk), true), b.height);
				this.setSize(b.width * (1.0 - xk), b.height);
			} else if (xk > 0) {
				px = Math.max(0, b.left - (b.left2 - pb.width));
//				this.setLocation(wb_builder.gridSnap(px, true), b.top);
				this.setLocation(px, b.top);
				if (b.width > pb.width)
//					this.setSize(wb_builder.gridSnap(pb.width, true), b.height);
					this.setSize(pb.width, b.height);
			}
			b = this.getBounds(); // update bounds
			if (yk > 0 && yk <= 0.44) {
//				this.setSize(b.width, wb_builder.gridSnap(b.height * (1.0 - yk), true));
				this.setSize(b.width, b.height * (1.0 - yk));
			} else if (yk > 0) {
				py = Math.max(0, b.top - (b.top2 - pb.height));
//				this.setLocation(b.left, wb_builder.gridSnap(py, true));
				this.setLocation(b.left, py);
				if (b.height > pb.height) {
//					this.setSize(b.width, wb_builder.gridSnap(pb.height, true));
					this.setSize(b.width, pb.height);
				}
			}
		}
		if (preserveAspectRatio) {
			b = this.getBounds(); // update bounds
			//oriSize
			var pw = b.width;
			var ph = b.width * oriBounds.height / oriBounds.width;
			if (ph > b.height) {
				pw = b.height * oriBounds.width / oriBounds.height;
				ph = b.height;
			}
//			this.setSize(wb_builder.gridSnap(pw, true), wb_builder.gridSnap(ph, true));
			this.setSize(pw, ph);
			var l2 = oriBounds.left + pw;
			var t2 = oriBounds.top + ph;
			px = (l2 > pb.width) ? Math.max(0, oriBounds.left - (l2 - pb.width)) : oriBounds.left;
			py = (t2 > pb.height) ? Math.max(0, oriBounds.top - (t2 - pb.height)) : oriBounds.top;
			if (px < 0) px = 0;
			if (py < 0) py = 0;
//			this.setLocation(wb_builder.gridSnap(px, true), wb_builder.gridSnap(py, true));
			this.setLocation(px, py);
		}
	};

	/**
	 * Set minimum size of element
	 * @param {Number} width
	 * @param {Number} height
	 */
	Element.prototype.setMinSize = function(width, height) {
		if (!this.isResizable && !this.isElementPreview) return;
		if (width) {
			$(this.elem).css("min-width", width + "px");
			if( this.isResizable )
				$(this.elem).resizable("option", "minWidth", width);
		}
		if (height) {
			$(this.elem).css("min-height", height + "px");
			if( this.isResizable )
				$(this.elem).resizable("option", "minHeight", height);
		}
		this.updateContentSize();
	};

	/**
	 * Exclude this element
	 * @param {Boolean} noRemove if true element wont be removed (until page reload), only added to exclude list
	 * @param {Boolean} onConstruct
	 */
	Element.prototype.exclude = function(noRemove, onConstruct) {
		if (onConstruct) {
			this.dontAdd = true;
		} else {
			var data = this.serialize();
			wb_builder.excludedElements.push(data);
			this.excluded = true;
			if (!noRemove) this.remove();
		}
	};

	/**
	 * Shows element
	 * @param {Boolean} responsive if false then shows element in current language (if website is multilang); if true then shows element in tablet/phone mode
	 * @param {Boolean} updateParentSize if true then content height will be updated
	 */
	Element.prototype.show = function(responsive, updateParentSize) {
		if (responsive) {
			this.hiddenResp = false;
		} else {
			this.hidden = false;
		}
		if (!this.hiddenResp && !this.hidden) {
			this.elem.show();
			if (responsive && updateParentSize) this.parent.updateSize();
		}
	};

	/**
	 * Hides element
	 * @param {Boolean} responsive if false then hides element from current language (if website is multilang); if true then hides element in tablet/phone mode in recycle bin
	 * @param {Boolean} updateParentSize if true then content height will be updated
	 */
	Element.prototype.hide = function(responsive, updateParentSize) {
		if (responsive) {
			this.hiddenResp = true;
			var thisSelf = this;
			ElementBox.addElement(thisSelf, function() {
				ElementBox.removeElement(thisSelf);
				thisSelf.show(true, true);
			}, thisSelf.boxItemOptions());
		} else {
			this.hidden = true;
		}
		if (this.hiddenResp || this.hidden) {
			this.elem.hide();
			if (responsive && updateParentSize) this.parent.updateSize();
		}
	};
	
	/**
	 * Check if element is hidden
	 * @param {Boolean} responsive 
	 */
	Element.prototype.isHidden = function(responsive) {
		if (responsive) {
			if (this.hiddenResp) return true;
			else return false;
		} else {
			if (this.hidden) return true;
			else return false;
		}
	};
	
	Element.prototype.updateShow = function(onConstruct, returnState, isCommon, includePages) {
		var multilang = (wb_builder.site.languages.length > 0);
		var exclude = true;
		if (multilang) {
			for (var i=0, lang; (lang = wb_builder.site.languages[i]); i++) {
				if (this.isVisible(lang.code, wb_builder.pageId, isCommon, includePages)) {
					exclude = false;
					break;
				}
			}
		} else {
			exclude = !this.isVisible(wb_builder.site.getLastDefLang(), wb_builder.pageId, isCommon, includePages);
		}
		var hide = (multilang && !this.isVisible(wb_builder.site.currSelLang, wb_builder.pageId, isCommon, includePages));
		
		if (hide && !this.isHidden() && !returnState) {
			this.hide();
			if (!onConstruct) this.parent.updateSize();
		} else if (!hide && this.isHidden() && !returnState) {
			this.show();
			if (!onConstruct) this.parent.updateSize();
		}

		if (exclude && !returnState) this.exclude(false, onConstruct);
		
		if (returnState) {
			if (exclude) return 1;
			return 0;
		}
	};
	
	/**
	 * Remove this element
	 * @param noHistory if true deletion will not be recorded to history
	 */
	Element.prototype.remove = function(noHistory) {
		if (!this.isEditableStrict) return;
		if (this.parent) {
			this.snapDone();
			this.showMeasurementHelpers(false);
			if (!noHistory) {
				wb_builder.historyAdd('removeElement', {
					id: this.id,
					index: this.index,
					parent: this.parent,
					data: this.serialize(),
					excluded: this.excluded,
					requireUndo: (this.__requestUndoAfterRestore ? this.__requestUndoAfterRestore : false)
				}, function(data) { // undo callback
					var cls = data.data["class"] ? ElementRegister.getClassByName(data.data["class"]) : null;
					if (!cls) return;
					data.data._restoreId = data.id;
					data.data._restoreIndex = data.index;
					var element = new cls(data.data);
					data.parent.addElement(element);
					if (data.requireUndo) { wb_builder.historyUndo(); }
					if (data.excluded) { wb_builder.removeFromExcluded(element.id); }
				}, function(data) { // redo callback
					var element = window.getElementById(data.index);
					if (element) element.remove(true);
				});
			}
			if (!this.excluded)
				wb_builder.site.removeAnchor(this);
			if (Element.selected[this.id]) {
				Element.selected[this.id] = null;
				delete Element.selected[this.id];
			}
			ContextMenu.hideAllMenus();
			this.parent.removeElement(this);
			Element.locTip.css({ display: "none", left: "0px", top: "0px" });
			this.removed = true;
		}
	};

	/**
	 * Remove/restore element for specified language
	 * @param {String} langCode language code (TRUE = all languages)
	 * @param {Boolean} visible true to display and false to remove
	 * @param {Number} pageId page ID for which to apply changes
	 */
	Element.prototype.setVisible = function(langCode, visible, pageId) {
		var isCommon = this.isCommon,
			includePages = $.extend({}, true, this.includePages),
			includePagesLen = (Object.keys(includePages).length > 0);
		var isCommonBackup = this.isCommon,
			includePagesBackup = $.extend({}, true, this.includePages);
		
		var i, p;
		if (wb_builder.site.languages.length > 0) {
			var allLangsApply = (langCode === 'all');
			var allLangsFalse = {}, allLangsTrue = {};
			$.each(wb_builder.site.languages, function() {
				allLangsFalse[this.code] = false;
				allLangsTrue[this.code] = true;
			});
			if (visible) {
				if (isCommon && includePagesLen) {
					for (i in wb_builder.site.pages) {
						p = wb_builder.site.pages[i];
						if (pageId && pageId != p.id) continue;
						if (!includePages[''+p.id]) {
							includePages[''+p.id] = $.extend({}, allLangsFalse);
						}
						if (allLangsApply) {
							includePages[''+p.id] = $.extend({}, allLangsTrue);
						} else {
							includePages[''+p.id][langCode] = true;
						}
					}
				} else if (!isCommon) {
					if (includePagesLen) {
						if (pageId && pageId != wb_builder.pageId) {
							isCommon = true;
							var includePagesTmp = $.extend({}, includePages);
							includePages = {}; includePages[''+wb_builder.pageId] = includePagesTmp;
							includePages[''+pageId] = $.extend({}, allLangsFalse);
							if (allLangsApply) {
								includePages[''+pageId] = $.extend({}, allLangsTrue);
							} else {
								includePages[''+pageId][langCode] = true;
							}
						} else {
							if (allLangsApply) {
								includePages = $.extend({}, allLangsTrue);
							} else {
								includePages[langCode] = true;
							}
						}
					}
				}
			} else {
				if (isCommon && includePagesLen) {
					for (var pid in includePages) {
						if (pageId && pageId != pid) continue;
						if (typeof includePages[''+pid] === 'object') {
							if (allLangsApply) {
								includePages[''+pid] = $.extend({}, allLangsFalse);
							} else {
								includePages[''+pid][langCode] = false;
							}
							if (Object.wbCompare(includePages[''+pid], allLangsFalse)) {
								delete includePages[''+pid];
							}
						} else {
							includePages[''+pid] = $.extend({}, allLangsTrue);
							if (allLangsApply) {
								includePages[''+pid] = $.extend({}, allLangsFalse);
							} else {
								includePages[''+pid][langCode] = false;
							}
						}
					}
				} else if (isCommon) {
					for (i in wb_builder.site.pages) {
						p = wb_builder.site.pages[i];
						includePages[''+p.id] = $.extend({}, allLangsTrue);
						if (pageId && pageId != p.id) continue;
						if (allLangsApply) {
							delete includePages[''+p.id];
						} else {
							includePages[''+p.id][langCode] = false;
							var hasTrue = false;
							for (var lc in includePages[''+p.id]) {
								if (includePages[''+p.id][lc]) { hasTrue = true; break; }
							}
							if (!hasTrue) delete includePages[''+p.id];
						}
					}
				} else {
					if (!pageId || pageId == wb_builder.pageId) {
						if (!includePagesLen) {
							includePages = $.extend({}, allLangsTrue);
						}
						if (allLangsApply) {
							includePages = $.extend({}, allLangsFalse);
						} else {
							includePages[langCode] = false;
						}
					}
				}
			}
		} else {
			if (!pageId) pageId = wb_builder.pageId;
			if (visible) {
				if (isCommon) {
					includePages[''+pageId] = true;
				} else {
					isCommon = true;
					includePages[''+pageId] = true;
				}
			} else {
				if (isCommon && includePagesLen) {
					delete includePages[''+pageId];
					if (Object.wbCompare(includePages, {})) {
						this.remove(); return;
					}
				} else if (isCommon) {
					for (i in wb_builder.site.pages) {
						p = wb_builder.site.pages[i];
						includePages[''+p.id] = true;
					}
					delete includePages[''+pageId];
				} else {
					if (pageId == wb_builder.pageId) {
						this.remove(); return;
					}
				}
			}
		}
		
		var excluded = (this.updateShow(false, true, isCommon, includePages) === 1);
		
		// restores last known state from undo buffer and swaps it with state before restoring
		var historyFunc = function(data, type) {
			var element = window.getElementById(data.index);
			if (!element) return;
			// swap data
			this.data = {
				index: data.index,
				isCommon: element.isCommon,
				includePages: element.includePages,
				excluded: data.excluded
			};
			// restore
			if (type === 'redo' && data.excluded) {
				element.__requestUndoAfterRestore = true;
			}
			element.isCommon = data.isCommon;
			element.includePages = data.includePages;
			element.updateShow();
		};
		wb_builder.historyAdd('hideElementInLang', {
			index: this.index,
			isCommon: isCommonBackup,
			includePages: includePagesBackup,
			excluded: excluded
		}, function(data) {
			historyFunc.call(this, data, 'undo');
		}, function(data) {
			historyFunc.call(this, data, 'redo');
		});
		
		this.isCommon = isCommon;
		this.includePages = includePages;
		if (isCommon !== this.isCommon) this.updateContextMenuRemove();
		if (excluded) {
			this.__requestUndoAfterRestore = true;
		}
		this.updateShow();
	};

	/**
	 * If element should be displayed by isCommon and includePages parameters
	 * @param {String} langCode language code
	 * @param {Number} pageId page ID
	 */
	Element.prototype.isVisible = function(langCode, pageId, isCommon, includePages) {
		isCommon = (isCommon !== undefined) ? isCommon : this.isCommon;
		includePages = (includePages !== undefined) ? includePages : this.includePages;
		langCode = langCode ? langCode : wb_builder.site.currSelLang; // site multilang
		langCode = langCode ? langCode : defLang; // site not multilang but was earlier
		pageId = pageId ? pageId : wb_builder.pageId;
		var includePagesLen = Object.keys(includePages).length,
			defLang = wb_builder.site.getLastDefLang();
		
		if (langCode) {
			if (isCommon && includePagesLen) {
				if (typeof includePages[''+pageId] === 'object') {
					if (includePages[''+pageId][langCode]) return true;
					if (!(langCode in includePages[''+pageId]) && includePages[''+pageId][defLang]) return true;
				} else if (includePages[''+pageId]) {
					return true;
				}
			} else if (isCommon) {
				return true;
			} else {
				if (includePagesLen) {
					if (includePages[langCode]) return true;
					if (!(langCode in includePages) && includePages[defLang]) return true;
				} else {
					if (pageId == wb_builder.pageId) return true;
				}
			}
		} else { // site not multilang and never was
			if (isCommon && includePagesLen) {
				if (includePages[''+pageId]) return true;
			} else if (isCommon) {
				return true;
			} else {
				if (pageId == wb_builder.pageId) return true;
			}
		}
		return false;
	};

	/**
	 * Set parent of this element
	 * @param parent element parent to set
	 */
	Element.prototype.setParent = function(parent) {
		if (!parent) {
			this.parent = null;
		} else if (parent instanceof Content) {
			this.parent = parent;
		} else {
			throw new new TypeError("parent must be of type Content");
		}
	};

	/**
	 * Set parent of this element
	 * @return parent element parent to set
	 */
	Element.prototype.getParent = function() {
		return this.parent;
	};

	/**
	 * Set element size
	 * @param width width in pixels
	 * @param height height in pixels
	 */
	Element.prototype.setSize = function(width, height) {
		if( this.isFullWidth ) {
			this.elem.css({width: "", right: 0});
		}
		else if (width) {
			this.elem.css({width: width + "px", right: ""});
		}
		if (height) {
			this.elem.css("height", height + "px");
		}
		this.updateContentSize();
	};

	/**
	 * Set element location
	 * @param left relative to parent left offset in pixels
	 * @param top relative to parent top offset in pixels
	 */
	Element.prototype.setLocation = function(left, top) {
		if( this.isFullWidth ) {
			this.elem.css("left", 0);
		}
		else if (left !== false && typeof(left) !== "undefined" && left !== null) {
			this.elem.css("left", left + "px");
		}
		if (top !== false && typeof(top) !== "undefined" && top !== null) {
			this.elem.css("top", top + "px");
		}
		if( this.measurementHelpers )
			this.measurementHelpers.update();
	};

	/**
	 * Get element location in pixels
	 * @returns object = { left: ..., top: ... }
	 */
	Element.prototype.getLocation = function() {
		return { left: this.elem.position().left, top: this.elem.position().top };
	};

	/**
	 * Get element size in pixels
	 * @returns object = { width: ..., height: ... }
	 */
	Element.prototype.getSize = function() {
		return { width: this.getWidth(), height: this.getHeight() };
	};

	/**
	 * Get element width in pixels
	 * @returns width
	 */
	Element.prototype.getWidth = function() {
		return this.elem.width();
	};

	/**
	 * Get element height in pixels
	 * @returns height
	 */
	Element.prototype.getHeight = function() {
		return this.elem.height();
	};

	/**
	 * Get element bounds in pixels
	 * @param asArray set to true, to return as array instead of object
	 * @returns object = {}
	 */
	Element.prototype.getBounds = function(asArray) {
		var wasHidden = (this.isHidden() || this.isHidden(true));
		this.elem.show();
		var o = this.elem.position();
		var o2 = this.elem.offset();
		var b = {
			left: o.left,
			top: o.top,
			width: this.getWidth(),
			height: this.getHeight(),
			left1: o.left,
			top1: o.top,
			left2: o.left + this.getWidth(),
			top2: o.top + this.getHeight(),
			pageLeft: o2.left,
			pageTop: o2.top
		};
		if (wasHidden) this.elem.hide();
		if (asArray)
			return [ b.left, b.top, b.left2, b.top2 ];
		return b;
	};

	/**
	 * Get zIndex of this element
	 * @return zIndex
	 */
	Element.prototype.getZIndex = function() {
		var idx = this.elem.css("zIndex");
		idx = idx ? (idx * 1) : 1;
		return idx;
	};

	/**
	 * Set zIndex of this element
	 * @param {Number} index z index to set
	 */
	Element.prototype.setZIndex = function(index) {
		var idx = index ? (index * 1) : 1;
		this.zIndex = idx;
		this.elem.css("zIndex", idx);
	};

	/**
	 * Make local system URL
	 * 
	 * @param url url to make into local URL
	 * @return local system URL
	 */
	Element.prototype.makeLocalUrl = function(url) {
		return wb_builder.makeLocalUrl(url);
	};

	/**
	 * Make relative URL
	 * 
	 * @param url url to make into relative URL
	 * @return relative url
	 */
	Element.prototype.makeRelUrl = function(url) {
		return wb_builder.makeRelUrl(url);
	};

	/**
	 * Truncate a string
	 * 
	 * @param string 
	 * @param length max length
	 * @param end append string if truncated   
	 * 
	 * @return truncated string
	 */
	Element.truncate = function(string, length, end) {
		if (typeof(string) === "object")
			string = __tr(string);
		if (typeof(length) === "undefined")
			length = 20;
		if (typeof(end) === "undefined")
			end = '...';
		var res = string.substring(0, length);
		if (res !== string)
			res += end;
		return res;
	};
	
	Element.prototype.storeMlHeight = function() {
		if (wb_builder.site.languages.length && wb_builder.site.currSelLang) {
			if (!this.mlHeight) this.mlHeight = {};
			this.mlHeight[wb_builder.site.currSelLang] = this.getHeight();
			wb_builder.setPageModified(true);
		}
	};
	
	Element.prototype.onBeforeSwitchLanguage = function() {
		this.storeMlHeight();
	};

	Element.prototype.onSwitchLanguage = function(langCode) {
		this.updateShow();
		this.updateLangLabel();
	};

	Element.prototype.onUpdateLanguages = function() {
		this.updateContextMenuRemove();
		this.updateLangLabel();
	};

	Element.prototype.addLangLabel = function() {
		if (!this.langLabel) {
			this.langLabel = $('<div class="wb_lang_label" style="opacity: 0;"></div>');
			this.controls.append(this.langLabel);
		}
		this.updateLangLabel();
	};

	Element.prototype.updateLangLabel = function() {
		if (this.langLabel) {
			if (wb_builder.site.languages.length) {
				this.langLabel.show();
			} else {
				this.langLabel.hide();
			}
			if (wb_builder.site.currSelLang) {
				this.langLabel.html(wb_builder.site.currSelLang);
			}
		}
	};

	Element.prototype.showMeasurementHelpers = function(show) {
		if (!this.isEditableStrict) return;
		if (!wb_builder.showMeasurementHelpers) return;
		if( show ) {
			if( !this.measurementHelpers )
				this.measurementHelpers = new ElementMeasurementHelpers.ElementMeasurementHelpers(this);
			this.measurementHelpers.show();
		}
		else if( this.measurementHelpers ) {
			this.measurementHelpers.hide();
			this.measurementHelpers = null;
		}
	};

	/** @class */
	Element.Mode = (function() {
		/**
		 * @param {Element.Mode} mode
		 * @param {Object} data
		 */
		var applyData = function(mode, data) {
			mode.x = data.x;
			mode.y = data.y;
			mode.width = data.width;
			mode.height = data.height;
			mode.mlHeight = data.mlHeight;
			mode.hidden = data.hidden;
		};

		/**
		 * @param {Object} data
		 * @class
		 */
		var self = function(data) { if (data) applyData(this, data); };
		/** @type Number */
		self.prototype.x = 0;
		/** @type Number */
		self.prototype.y = 0;
		/** @type Number */
		self.prototype.width = 200;
		/** @type Number */
		self.prototype.height = 200;
		/** @type mixed */
		self.prototype.mlHeight = {};
		/** @type Boolean */
		self.prototype.hidden = false;
		/** @param {Element.Mode} mode */
		self.prototype.copy = function(mode) {
			applyData(this, mode);
		};
		/** @param {Element} elem */
		self.prototype.store = function(elem) {
			var b = elem.getBounds();
			b.x = b.left;
			b.y = b.top;
			b.hidden = elem.isHidden(true);
			b.mlHeight = elem.mlHeight;
			applyData(this, b);
		};
		/** @param {Element} elem */
		self.prototype.applyTo = function(elem) {
			elem.mlHeight = this.mlHeight;
			elem.setLocation(this.x, this.y);
			elem.setSize(this.width, this.height);
			if (this.hidden) elem.hide(true); else elem.show(true);
		};
		/** @return {Object} */
		self.prototype.serialize = function() {
			return { x: Math.round(this.x), y: Math.round(this.y), width: Math.round(this.width), height: Math.round(this.height), mlHeight: this.mlHeight, hidden: this.hidden };
		};

		return self;
	})();
	
	Service.element = {
		unselectAll: Element.unselectAll,
		truncate: Element.truncate,
		getSelected: function() {
			return Element.selected;
		},
		getSelectedCount: function() {
			var count = 0;
			for( var i in Element.selected )
				if( Element.selected.hasOwnProperty(i) )
					count++;
			return count;
		},
		eachSelected: function(callback) {
			for( var i in Element.selected )
				if( Element.selected.hasOwnProperty(i) )
					callback.call(Element.selected[i]);
			return Service.element;
		},
		getUsedMediaGalleryItems: function(elements) {
			if (!elements) elements = wb_builder.bodyInstance.getContentElements();
			var index = {}, items, i, j, c;
			for (i=0, c = elements.length; i < c; i++) {
				items = elements[i].getUsedMediaGalleryItems();
				for (j=0; j < items.length; j++) {
					if (items[j]) index[items[j]] = true;
				}
			}
			return Object.keys(index);
		},
		resetIdentifierIndex: function() {
			Element.lastIndex = 0;
		}
	};
	
	window.WB_Element = Element;
	
	return Element;
});
;

/** WB TextArea **/
(window.defineModule = (window.defineModule || {})).name = 'WB TextArea';

define('TextArea', ['ElementRegister', 'Element', 'Dialog', 'Service'], function(ElementRegister, Element, Dialog, Service) {
	'use strict';
	
	/**
	 * Text Area class
	 * @param {Object} data
	 */
	var TextArea = function(data) {this.__construct(data);};

	TextArea.prototype = new Element();
	TextArea.prototype.constructor = TextArea;
	ElementRegister.registerClass("TextArea", TextArea);

	TextArea.rtl = false;
	TextArea.mousedowned = false; // true if mousedown is currently triggered on text area
	TextArea.allowHideEditors = false;
	TextArea.areaActive = null;
	TextArea.editorDefaultText = '<p class="wb-stl-normal">' + __("Enter your text here") + '</p>';
	TextArea.editorInitialized = false;
	TextArea.tinyEditor = false; // limited editor
	TextArea.editorInit = function() {
		if (TextArea.editorInitialized) return;
		TextArea.editorInitialized = true;
		
		TextArea.tinyEditor = false; //wb_builder.isTouchDevice;
		
		if (!TextArea.tinyEditor) {
			$(function() {
				wb_builder.body.on('click', function(e){
					if (TextArea.mousedowned && !$.browser.mozilla) {
						TextArea.mousedowned = false;
						return;
					}
					Dialog.hideEditors = true;
					TextArea.hideEditors();
				});
			});
		}
	};
	TextArea.hideEditors = function() {
		if (TextArea.editorActive) {
			TextArea.editorActive.hideEditor();
		}
	};
	TextArea.editorActive = null;
	TextArea.execCommandCallback = function(editor_id, elm, command, user_interface, value) {
		switch (command) {
			case "ForeColor":
				var elem = $(elm);
				if (elem.is("a")) {
					if (TextArea.rgb2hex(elem.css("color")) !== value.toLowerCase()) {
						elem.css("color", value);
					} else {
						elem.css("color", "");
					}
					return true;
				} else if (elem.parent().is("a")) {
					if (TextArea.rgb2hex(elem.parent().css("color")) !== value.toLowerCase()) {
						elem.parent().css("color", value);
					} else {
						elem.parent().css("color", "");
					}
					return true;
				}
			break;
		}
		return false;
	};
	TextArea.rgb2hex = function(rgb) {
		var _rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
		if (!_rgb) return rgb;
		function hex(x) {
			return ("0" + parseInt(x).toString(16)).slice(-2);
		}
		return ("#" + hex(_rgb[1]) + hex(_rgb[2]) + hex(_rgb[3])).toLowerCase();
	};
	TextArea.getActiveTextArea = function() {
		var elems = wb_builder.bodyInstance.getContentElements();
		for (var i=0, elem; (elem = elems[i]); i++) {
			if (elem instanceof TextArea && elem.editor) {
				return elem;
			}
		}
	};


	TextArea.prototype.cover = false;
	TextArea.prototype.editor = null;
	TextArea.prototype.editorAttached = false;
	TextArea.prototype.lastContent = "";

	TextArea.prototype.textId = "";
	TextArea.prototype.editorId = "";
	TextArea.prototype.toolbarWidth = 350;
	TextArea.prototype.toolbarHeight = 29;
	TextArea.prototype.editor = null;
	TextArea.prototype.editorToolbar = null;
	TextArea.prototype.editorVisible = false;
	TextArea.prototype.editorChosenLanguage = null;
	TextArea.prototype.textDiv = null;
	TextArea.prototype.textDivValue = null;
	TextArea.prototype.textArea = null;
	TextArea.prototype.toolbarMover = null;

	TextArea.prototype.cssRuleIndexes = null;

	TextArea.prototype.wflRefreshCounter = 120;
	TextArea.prototype.wflInitialSize = 0;

	/**
	 * Construct text area element
	 * @param data text area data object
	 */
	TextArea.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);
		this.elem.addClass('wb_text_element');
		this.addLangLabel();

		this.cssRuleIndexes = { a: -1, b: -1, c: -1 };

		CKEDITOR.timestamp = Math.random();
		TextArea.editorInit();
	//	TextArea.elemList[TextArea.elemList.length] = this;

		var thisClass = this;

		this.textId = this.id + '_text';
		this.editorId = this.id + '_editor';

		TextArea.rtl = (wb_builder.locale === 'ar_AE' || wb_builder.locale === 'he_IL' || wb_builder.locale === 'fa_IR');

		this.textDiv = $('<div id="' + this.textId + '"' + (TextArea.rtl ? ' class="rtl"' : '') + '></div>');
		this.textDiv.css({
			position: "absolute", left: "0px", top: "0px", width: "100%"
		});
		this.textDiv.on('mousedown', function() {
			TextArea.mousedowned = true;
		});
		this.textDiv.on('mouseup', function() {
			if (!$.browser.msie) TextArea.mousedowned = false;
		});
		this.container.append(this.textDiv);
		this.container.css("line-height", "normal");

		$(this.container).bind("resize", function() {
			$(thisClass.textDiv).css("width", $(thisClass.container).width());
		});

		this.controls.tooltip({ trigger: "manual", placement: "top", html: true, title: __("This element can be edited only in Desktop mode") });
		if (this.isEditableStrict) {
			this.controls.bind("dblclick", function(e) {
				if (thisClass.debug) console.log("DoubleClick");
				thisClass.showEditor(e.pageX, e.pageY);
			});
		}

		this.setMinSize(24, 24);

		if (data && data.content && data.content.text !== null && data.content.text !== undefined) {
			this.textDivValue = data.content.text;
		} else {
			this.textDivValue = TextArea.editorDefaultText;
		}
		if (!data.content.__noInitCleanupWbTrOk) this.cleanupWbTrOk();
		this.setHtml(__tr(this.textDivValue, null, TextArea.editorDefaultText, true));

		this.elem.bind("resize", function() {
			thisClass.wflRefreshCounter = 0;
			thisClass.onResize();
		});
		if (!data.id && !this.isElementPreview && !data._fromTablePlugin) {
			setTimeout(function() {
				var func;
				thisClass.showEditor();
				setTimeout(func = function() {
					var node = thisClass.textDiv.get(0);
					if (document.body.createTextRange) {
						var range = document.body.createTextRange();
						range.moveToElementText(node);
						range.select();
					} else if (window.getSelection) {
						var selection = window.getSelection();
						var range = document.createRange();
						range.selectNodeContents(node);
						selection.removeAllRanges();
						selection.addRange(range);
					}
				}, 250);
				setTimeout(func, 500);
			}, 0);
		}
		this.onUpdateLanguages();
		this.wflInitialSize = this.height;
		this.waitFontLoaded();
	};
	
	TextArea.prototype.cleanupWbTrOk = function(updateElement, _html) {
		if (_html) {
			var tmpElem = $('<div>').html(_html);
			tmpElem.find('.wb_tr_ok').contents().unwrap();
			var res = tmpElem.html();
			tmpElem = null;
			return res;
		} else {
			if (typeof(this.textDivValue) === 'object') {
				for (var i in this.textDivValue) {
					if (this.textDivValue[i]) this.textDivValue[i] = this.cleanupWbTrOk(false, this.textDivValue[i]);
				}
			} else {
				if (this.textDivValue) this.textDivValue = this.cleanupWbTrOk(false, this.textDivValue);
			}
		}
		if (updateElement) {
			this.setHtml(__tr(this.textDivValue));
		}
	};
	
	TextArea.prototype.waitFontLoaded = function() {
		if( --this.wflRefreshCounter < 0 || this.editorVisible )
			return;
		this.onResize(true);
		if( this.wflRefreshCounter > 0 && this.height === this.wflInitialSize )
			setTimeout(this.waitFontLoaded.bind(this), 250);
	};
	
	TextArea.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = 'e, w';
	};

	TextArea.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this), txt = String(__tr(this.textDivValue)).replace(/<[^>]+>/g, '');
		opts.text = txt.substring(0, 100);
		if (opts.text.length < txt.length) opts.text += '...';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	TextArea.prototype.serialize = function() {
		var cleanup = function(value) {
			return value ? value.replace(/<(\/*(?:script|iframe|object|embed|audio|video|source|canvas)[^>]*\/*)>/g, '&lt;$1&gt;') : value;
		};
		if (typeof this.textDivValue === 'object') {
			for (var i in this.textDivValue) {
				this.textDivValue[i] = cleanup(this.textDivValue[i]);
			}
		} else {
			this.textDivValue = cleanup(this.textDivValue);
		}
		var data = Element.prototype.serialize.call(this);
		data.content = {
			text:				this.textDivValue,
			rtl:				TextArea.rtl
		};
		return data;
	};
	
	TextArea.prototype.setHtml = function(html) {
		html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*(?:<\/script>|$)/gi, '');
		this.textDiv.html(html);
	};

	TextArea.prototype.getHtml = function() {
		return this.textDiv.html();
	};

	TextArea.prototype.onClick = function(e) {
		if (!this.editorVisible) {
			Element.prototype.onClick.call(this, e);
		}
	};

	TextArea.prototype.fitToParent = function(preserveAspectRatio, oriBounds, initial) {
		Element.prototype.fitToParent.call(this, preserveAspectRatio, oriBounds, initial);
		if (!initial) this.onResize(initial);
	};

	TextArea.prototype.setParent = function(parent) {
		//var oldParent = this.parent;
		Element.prototype.setParent.call(this, parent);
	};
	
	/** Select all text in open editor. */
	TextArea.prototype.selectAll = function() {
		if (!this.editor) return;
		this.editor.focus();
		var range = this.editor.createRange();
		if (range) {
			range.selectNodeContents(range.root);
			range.select();
			this.editor.getSelection().selectRanges([range]);
		}
	};
	
	/**
	 * Insert text at cursor/selection in editor.
	 * @param {string} text
	 * @param {boolean=false} isHtml
	 */
	TextArea.prototype.insertText = function(text, isHtml) {
		if (!this.editor) return;
		this.editor.focus();
		if (isHtml) {
			this.editor.insertHtml(text);
		} else {
			this.editor.insertText(text);
		}
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-edit-text', this);
	};
	
	/**
	 * Execute command in open editor.
	 * @param {string} command command to execute.
	 * @return {boolean} if success then true else false.
	 */
	TextArea.prototype.execCommand = function(command) {
		if (!this.editor) return;
		this.editor.focus();
		return command ? this.editor.execCommand(command) : false;
	};
	
	/**
	 * Get toolbar element of open editor.
	 * @param {string=} button if set then buttons element is returned else toolbar element is returned.
	 * @returns {JQuery}
	 */
	TextArea.prototype.getToolbarElem = function(button) {
		if (!this.editor) return;
		var toolbar = $('#cke_' + this.textId);
		if (button) {
			return toolbar.find('.cke_button__' + button);
		} else {
			return toolbar;
		}
	};
	
	TextArea.prototype.showEditor = function(x, y) {
		if( this.isElementPreview )
			return;
		if (this.isLocked) {
			this.moveBtn.tooltip('show');
			return;
		}
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-edit-start', this);
		if (this.debug) console.log("ShowEditor");
		var thisClass = this;

		if (this.editor) 
			return;

		TextArea.hideEditors();
		if( this.menu )
			this.menu.hide();

		var styles = CKEDITOR.stylesSet.get("wb_site_styles");
		if (!styles) {
			styles = CKEDITOR.stylesSet.add("wb_site_styles", []);
		}
		styles.splice(0, styles.length); // empty array by keeping instance thesame
		for (var i = 0; i < this.system.site.styles.length; i++) {
			var s = this.system.site.styles[i];
			var selector = /^\.([^\ ]+)(?:\ |$)/i.exec(s.selector);
			if (!selector) continue;
			styles.push({
				name: s.name, element: (s.tag ? s.tag : "span"), attributes: { "class": selector[1] }
			});
		}


		//border o_0
		this.textDiv.addClass('outline1');

		if (!TextArea.tinyEditor) {
			this.textDiv.attr("contenteditable", "true");
		}
		this.setDragginEnabled(false);
		this.setControlsEnabled(false);
		//this.elem.draggable( 'disable' ).fadeTo(0, 1).find(".wb_controls").hide();
		Element.hotKeysDisabled = true;

		var config = {
	//		uiColor: '#9AB8F3',
			title: '', // remove annoying tooltip
			stylesSet: 'wb_site_styles',
			on: {
				selectionChange: function(e) {
					if (e.data.selection && e.data.selection.getSelectedText()) {
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-select', thisClass);
					}
				},
				afterCommandExec: function(e) {
					Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-cmd-' + e.data.name, thisClass);
				}
				/* focus: function() {
					// hack to prevent creation of empty <p/> tag at the beginning
					setTimeout(function() {
						thisClass.textDiv.caret(0);
					}, 500);
				} */
			}
		};
		this.textDiv.focus();
		if (TextArea.tinyEditor) {
			document.removeEventListener("touchstart", wb_builder.touchHandler, true);
			document.removeEventListener("touchmove", wb_builder.touchHandler, true);
			document.removeEventListener("touchend", wb_builder.touchHandler, true);
			document.removeEventListener("touchcancel", wb_builder.touchHandler, true);
			$(".wb-scroll-bar").hide();
			if (!TextArea.maxCont) {
				TextArea.maxCont = $('<div id="WB_TextArea_maxCont"><div class="inner3" contenteditable="true"></div></div>');
				var inner = TextArea.maxCont.find('.inner3');
				TextArea.maxCont.css({
					border: 0,
					left: 0,
					top: 0,
					width: '100%',
					height: $(window).height(),
					overflow: 'auto',
					position: "fixed",
					background: "#ffffff",
					zIndex: 1001
				});
				inner.on('paste', function(e) {
					e.stopPropagation();
					e.preventDefault();
					var clipboardData = e.originalEvent.clipboardData || window.clipboardData;
					if (clipboardData && clipboardData.getData) {
						var pastedData = clipboardData.getData('Text');
						pastedData = pastedData.replace(/\n/gi, '<br />');
						$(this).html(pastedData);
					}
				});
				inner.css({
					margin: '60px 10px 10px'
				});
				var maxContBtnWrp = $('<div class="form-actions input-block-level"><span class="wb-ed-small-msg">'+ __("Full featured text editor is currently not available on touch devices") +'</span><button id="WB_TextArea_maxContBtn" class="btn btn-success pull-right">'+ __("Apply") +'</button></div>');
				var maxContBtn = maxContBtnWrp.find("button");
				maxContBtnWrp.css({
					top: 0,
					right: 0,
					marginTop: 0,
					padding: 10,
					borderBottom: '1px solid #E5E5E5',
					position: "absolute",
					zIndex: 9001
				});
				$(TextArea.maxCont).append(maxContBtnWrp);
				$(document.body).append(TextArea.maxCont);
				maxContBtn.on('click', function() {
					TextArea.hideEditors();
				});
				TextArea.maxCont.on('click', function() {
					TextArea.maxCont.find('.inner3').focus();
				});
				TextArea.maxCont.click();
			}
			var cColor = thisClass.getContentColor(true);
			TextArea.maxCont.css({background: (cColor ? cColor : '#ffffff')});
			var innerElem = TextArea.maxCont.find('.inner3');
			innerElem.html(this.textDiv.html());
			$(document.body).append(TextArea.maxCont);
			var tbHeight = TextArea.maxCont.children('.form-actions').eq(0).outerHeight(true);
			innerElem.css({marginTop: (tbHeight + 'px')});
			this.editor = true;
		} else {
			if ($.browser.msie) {
				var html = this.textDiv.html();
				//console.log(html);
				html = html.replace(/(<p[^>]*>)&nbsp;(<\/p>)/ig, '$1\xad$2');
				//console.log(html);
				this.textDiv.html(html);
			}
			this.editor = CKEDITOR.inline(this.textId, config);
			for (var ts=1000; ts <= 2000; ts+=1000) {
				setTimeout(function() {
					var el = $("#cke_" + thisClass.textId);
					el.css({"z-index": 2000});
					// el.draggable({cancel: '.cke_toolgroup, .cke_toolgroup *, .cke_combo_button, .cke_combo_button *'});
				}, ts);
			}
		}
		if (!TextArea.tinyEditor) {
			this.textDiv.on("click", function(e) {
				e.stopPropagation();
			});
			if (jQuery.browser.chrome) {
				this.textDiv.blur();
				setTimeout(function() {
					thisClass.textDiv.focus();
				}, 100);
			}
		}
		this._onStylesComboboxCreate();
		this.lastContent = this.textDiv.html();
		this.editorVisible = true;
		TextArea.editorActive = this;
		Dialog.hideEditors = false;

		this.editor.wbTextAreaInstance = this;
	};
	
	TextArea.prototype._onStylesComboboxCreate = function() {
		var thisClass = this;
		var callback = function(combo) {
			var doc = combo.children('iframe')[0].contentDocument;
			var s = doc.createElement('scr' + 'ipt');
			s.type = 'text/javascript';
			s.src = CKEDITOR.basePath + 'stylescombo.js?ts=' + (new Date()).getTime();
			doc.getElementsByTagName('head')[0].appendChild(s);
		};
		this._stylesComboboxIntervalId = setInterval(function() {
			var combo = null;
			if ((combo = $('#cke_' + thisClass.textId + ' .cke_combopanel:not(.dropdown_languages)')).length) {
				clearInterval(thisClass._stylesComboboxIntervalId);
				callback(combo);
			}
		}, 100);
	};

	TextArea.prototype.hideEditor = function() {
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-edit-end', this);
		if (!this.editor) return;
	//	CKEDITOR.remove(this.editor);
		if (this.editor !== true) {
			this.editor.focus();	//to close all combobox iframes (throws errors otherwise)
			this.editor.destroy();
		}

		// var editorLang = this.editor.wbCurrEditLang;
		this.editor = null;

		if (TextArea.tinyEditor) {
			if (TextArea.maxCont) {
				this.setHtml(TextArea.maxCont.find('.inner3').html());
				TextArea.maxCont.find('.inner3').empty();
				TextArea.maxCont.remove();
				TextArea.maxCont = null;
				document.addEventListener("touchstart", wb_builder.touchHandler, true);
				document.addEventListener("touchmove", wb_builder.touchHandler, true);
				document.addEventListener("touchend", wb_builder.touchHandler, true);
				document.addEventListener("touchcancel", wb_builder.touchHandler, true);
				$(".wb-scroll-bar").show();
			}
		} else {
			this.textDiv.removeAttr("contenteditable");
			var html = this.textDiv.html();
			html = html.replace(/[\r\t]/g, '');
			if ($.browser.msie) {
				html = html.replace(/(<p[^>]*>)(?:&shy;|&shy;&shy;|&shy;&shy;&shy;)(<\/p>)/ig, '$1&nbsp;$2');
			}
			this.textDiv.html(html);
		}

		this.textDiv.off("click").removeClass('outline1');

		this.setDragginEnabled(true);
		this.setControlsEnabled(true);
		//this.elem.draggable( 'enable' ).find(".wb_controls").show();
		Element.hotKeysDisabled = false;
		
		var cont = this.textDiv.html();
		if (this.lastContent !== cont) this.system.setPageModified(true);
		this.lastContent = "";
		this.editorVisible = false;
		TextArea.editorActive = null;
		this.setValue(cont, this.editorChosenLanguage);
		this.onSwitchLanguage(this.system.site.currSelLang, true);
		
		this.onResize();
		if (this.getParent()) {
			this.getParent().updateSize();
			this.fitToParent();
		}
		
		clearInterval(this._stylesComboboxIntervalId);
	};
	
	/**
	 * Get text color of content
	 * @param {boolean} contrast return contrasted color
	 * @param {Node=} elem element to get color from (internal do not use)
	 * @param {string=} parentColor color of parent element (internal do not use)
	 * @param {number=} lvl element structure level (internal do not use)
	 * @returns {string}
	 */
	TextArea.prototype.getContentColor = function(contrast, elem, parentColor, lvl) {
		if (!elem) elem = this.container.get(0);
		if (elem.nodeType === 3 && parentColor) return parentColor;
		if (!lvl) lvl = 0;
		var ident = '', identCount = lvl;
		while (identCount > 0) { ident += ' '; identCount--; }
		var style = (elem.nodeType < 3 && 'getComputedStyle' in window) ? window.getComputedStyle(elem) : null;
		var pc, color = null, colorStr = (style ? style.color : null);
		if (colorStr && (pc = colorStr.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i))) {
			color = {r: parseInt(pc[1]), g: parseInt(pc[2]), b: parseInt(pc[3])};
		} else if (colorStr && (colorStr.length === 4 || colorStr.length === 7) && (pc = colorStr.match(/^#([0-f]+)$/i))) {
			if (pc[0].length === 3) {
				color = {r: parseInt(pc[0].substring(0, 1), 16), g: parseInt(pc[0].substring(1, 2), 16), b: parseInt(pc[0].substring(2, 3), 16)};
			} else {
				color = {r: parseInt(pc[0].substring(0, 2), 16), g: parseInt(pc[0].substring(2, 4), 16), b: parseInt(pc[0].substring(4, 6), 16)};
			}
		}
		if (color && contrast) {
			var cb = (299 * color.r + 587 * color.g + 114 * color.b) / 1000;
			if (255 - cb > cb) {
				color.r = color.g = color.b = 255;
			} else {
				color.r = color.g = color.b = 0;
			}
		}
		colorStr = color ? ('#' + ('0' + parseInt(color.r).toString(16)).slice(-2) + ('0' + parseInt(color.g).toString(16)).slice(-2) + ('0' + parseInt(color.b).toString(16)).slice(-2)) : null;
		//console.log(ident + elem.nodeName + ' (' + elem.nodeType + '): ' + (color ? ('Color: ' + colorStr) : ''));
		for (var i = 0; i < elem.childNodes.length; i++) {
			var r = this.getContentColor(contrast, elem.childNodes[i], colorStr, lvl + 1);
			if (r) return r;
		}
		return null;
	};
	
	TextArea.prototype.setValue = function(html, langCode) {
		var i, lang, newValue;
		langCode = langCode || this.system.site.currSelLang;
		if (typeof this.textDivValue === 'string') {
			if (this.system.site.languages.length) {
				newValue = {};
				for (i = 0; (lang = this.system.site.languages[i]); i++) {
					if (lang.code === langCode)
						newValue[lang.code] = html;
					else if (lang.code === this.system.site.getLastDefLang())
						newValue[lang.code] = this.textDivValue;
					else {}
						// newValue[lang.code] = '';
				}
				this.textDivValue = newValue;
			} else {
				this.textDivValue = html;
			}
		} else if (typeof this.textDivValue === 'object') {
			newValue = {};
			for (i = 0; (lang = this.system.site.languages[i]); i++) {
				if (lang.code in this.textDivValue) newValue[lang.code] = this.textDivValue[lang.code];
			}
			newValue[langCode] = html;
			this.textDivValue = newValue;
		}
	};

	/**
	 * Fit element to window horizontaly
	 * @param left horizontal element coordinate (left coordinate)
	 * @param width element width
	 * @return ajusted horizontal (left) coordinate
	 */
	TextArea.prototype.fitToWindow = function(left, width) {
		var vw = $(window).width();

		var px = left;

		if ((px + width) > vw) {
			px = left - ((px + width) - vw + 10);
		}
		return px;
	};

	TextArea.prototype.onResize = function(onConstruct) {
		if (!onConstruct) this.system.setPageModified(true);
		var w = this.getWidth();
		var h = this.textDiv.outerHeight(false);
		if (this.editorVisible && false) {
			var body = $(this.editor.getBody());
			var html = body.parent();

			$("#" + this.editorId + "_tbl").css("width", (w-0) + "px");
			$("#" + this.editorId + "_ifr").css("width", (w-0) + "px");
			body.css({width: (w-0) + "px", margin: "0", padding: "0", overflow: "hidden"});
			html.css({width: (w-0) + "px"});

			h = body.outerHeight(true);

			$("#" + this.editorId + "_tbl").css("height", h + "px");
			$("#" + this.editorId + "_ifr").css("height", h + "px");
		} else {
			var mh = $("p", this.textDiv).last();
			if (mh.size() > 0) {
				h -= mh.outerHeight(true) - mh.outerHeight(false);
			}
		}
		if (h < 10) h = 10;
		//console.log("Height: " + h);
		this.setSize(w, h);
		this.elem.trigger("elementresize", [this]);
	};
	
	TextArea.prototype.onStopResize = function(ui) {
		Element.prototype.onStopResize.call(this, ui);
		var parent = this.getParent();
		if (parent) parent.updateSize();
	};
		
	/**
	 * @param {Object} elem
	 */
	TextArea.prototype.initContextMenu = function(elem) {
		var thisClass = this;
		Element.prototype.initContextMenu.call(this, elem);
		if (!this.menu) return;

		var idx = this.contextMenuFirstIndex;

		this.menu.insertItemAt(idx++, 'editText', __("Edit text"), function() {
			var pos = thisClass.menu.menu.offset();
			thisClass.showEditor(pos.left, pos.top);
		}, null, null, null, "glyphicon glyphicon-pencil");

		this.menu.addSeparator(idx++);
	};

	TextArea.prototype.onSwitchLanguage = function(langCode, fromEditor) {
		if (!fromEditor) {
			Element.prototype.onSwitchLanguage.call(this, langCode);
			this.hideEditor();
		}
		this.setHtml(__tr(this.textDivValue, langCode, __tr(this.textDivValue, '__DEFAULT__', TextArea.editorDefaultText, true)));
		this.onResize();
	};
	
	Service.textArea = {
		hideEditors: function() { TextArea.hideEditors(); },
		isMousedowned: function() { return TextArea.mousedowned; },
		getActiveEditor: function() { return TextArea.editorActive; }
	};
	
	return TextArea;
});
;

/** WB Picture **/
(window.defineModule = (window.defineModule || {})).name = 'WB Picture';

define('Picture', [
	'ElementRegister',
	'Element',
	'Service',
	'ModeManager',
	'Rectangle',
	'UIButton'
], function(ElementRegister, Element, Service, ModeManager, Rectangle, UIButton) {
	'use strict';
	
	/**
	 * Picture class
	 * @param {Object} data
	 * @param {boolean} initial
	 */
	var Picture = function(data, initial) { if (data) this.__construct(data, initial); };

	Picture.prototype = new Element();
	Picture.prototype.constructor = Picture;
	ElementRegister.registerClass("Picture", Picture);

	Picture.prototype.noPhotoBg = 'ico-tb-picture';
	Picture.prototype.image = null;
	Picture.prototype.imageW = null;
	Picture.prototype.dialog = null;
	Picture.prototype.uploader = null;
	Picture.prototype.originalSize = null;
	Picture.prototype.noReset = false;
	Picture.prototype.runtimeNoReset = false;
	Picture.prototype.imageAlt = null;
	Picture.prototype.imageUrl = null;
	Picture.prototype.imageLink = null;
	Picture.prototype.color = "#000000";
	Picture.prototype.linkDialog = null;
	Picture.prototype.myEmtyMessageText = null;
	Picture.prototype.keepAspectRatio = true;
	Picture.prototype.autoHeight = false;
	Picture.prototype.imageLinkType = 'url';
	Picture.prototype.customLock = false;
	/** @type {Rectangle} */
	Picture.prototype.crop = null;
	Picture.prototype.fullWidthBackground = null;

	/**
	 * Construct picture element
	 * @param data picture data object
	 * @param {boolean} initial
	 */
	Picture.prototype.__construct = function(data, initial) {
		this.customLock = data.customLock ? data.customLock : false;
		if (this.customLock) this.isEditable = false;
		this.ignoreParentBounds = true;

		Element.prototype.__construct.call(this, data, initial);

		var thisClass = this;

		this.setEmtyMessageText(this.myEmtyMessageText = __("Double click to change picture"));
		this.displayEmtyMessage(true);	

		//this.setMinSize(48, 24);
		this.setMinSize(24, 14);

		// if (data.width)
			// this.elem.css("width", Math.max(data.width, 24) + "px");
		this.container.css("overflow", "hidden");

		this.imageUrl = data.content.src ? data.content.src : null;
		this.imageAlt = data.content.alt ? data.content.alt : null;
		this.color = data.content.color ? data.content.color : "#000000";
		this.border = data.content.border ? data.content.border : {
			color: '#000000',
			style: 'none',
			weight: 1,
			css: { border: '1px none #000000' }
		};
		this.corners = data.content.corners ? data.content.corners : {
			lt: 0, rt: 0, rb: 0, lb: 0,
			css: {
				"border-radius"			: "0",
				"-webkit-border-radius"	: "0",
				"-moz-border-radius"	: "0"
			}
		};
		if (this.imageUrl && typeof this.imageUrl === "string" && this.imageUrl.indexOf("user_images/") === 0) {
			this.imageUrl = this.imageUrl.replace("user_images/", "gallery/");
		}
		this.autoHeight = (data.content.autoHeight ? true : false);
		this.crop = ('crop' in data.content) ? Rectangle.fromObject(data.content.crop) : new Rectangle();

		if (data.content.link && (typeof data.content.link === 'object')) {
			this.imageLink = data.content.link;
		} else {
			this.imageLink = {
				url: (data.content.link ? data.content.link : null),
				type: (data.content.linkType ? data.content.linkType : null),
				title: (data.content.linkTitle ? data.content.linkTitle : null),
				target: (data.content.linkTarget ? data.content.linkTarget : null),
				noFollow: (data.content.linkNoFollow ? data.content.linkNoFollow : null)
			};
		}

		this.imageLinkType = (data.content.imageLinkType) ? data.content.imageLinkType : 'url';

		this.fullWidthBackground = $.extend(true, {
			position: "center top",
			size: "cover",
			repeat: "repeat",
			css: {
				"background": "repeat center top",
				"background-size": "cover"
			}
		}, (("fullWidthBackground" in data.content) ? data.content.fullWidthBackground : {}));

		if (data.id || data._copy || this.isElementPreview) {
			this.loadImage(this.getSrc());
		} else if (!initial) {
			thisClass.changePicture(function() {
				thisClass.resetImageSize();
			});
		}
		if( this.customLock || this.isAdminLocked ) {
			this.updateImageSize();
			this.setResizingEnabled(false, true);
		}
		else {
			this.controls.tooltip({ trigger: "manual", placement: "top", html: true, title: __("This element can be edited only in Desktop mode") });
			this.controls.bind("dblclick", function(e) {
				if (thisClass.debug) console.log("DoubleClick");
				thisClass.changePicture();
			});
		}
		this.modeContextOk.resetSize = true;
	};
	
	Picture.prototype.supportsFullWidth = function() {
		return true;
	};

	Picture.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = this.isFullWidth ? 'n, s' : 'n, e, s, w, ne, se, sw, nw';
		options.fixresize = true;
	};
	
	Picture.prototype.updateContentSize = function(resizer) {
		Element.prototype.updateContentSize.call(this, resizer);
		if (!this.imageW) return;
		var dw, dh;
		if (resizer && !resizer.originalElement.isCorner && this.crop) {
			var eWidth = this.elem.width(), eHeight = this.elem.height();
			if (this.crop.imageSize) {
				this.crop.width = this.crop.imageSize.width;
				this.crop.height = this.crop.imageSize.height;
			}
			if (this.crop.oriMainSize && this.crop.originalPosition) {
				if ((resizer.originalPosition.left - resizer.position.left) !== 0) {
					this.crop.x = Math.min(this.crop.originalPosition.x + (eWidth - this.crop.oriMainSize.width), 0);
				}
				if ((resizer.originalPosition.top - resizer.position.top) !== 0) {
					this.crop.y = Math.min(this.crop.originalPosition.y + (eHeight - this.crop.oriMainSize.height), 0);
				}
			}
			var borderWeight = this.getBorderTotalWeight();
			dw = this.crop.width + this.crop.x + borderWeight.horizontal;
			dh = this.crop.height + this.crop.y + borderWeight.vertical;
			if (dw < eWidth) {
				dh = dh * eWidth / dw;
				dw = eWidth;
			}
			if (dh < eHeight) {
				dw = dw * eHeight / dh;
				dh = eHeight;
			}
			this.crop.width = dw - this.crop.x;
			this.crop.height = dh - this.crop.y;
		} else if (resizer && this.crop) {
			if (this.crop.koefSize && this.crop.originalPosition) {
				var eWidth = this.elem.width(), eHeight = this.elem.height();
				this.crop.x = Math.min(eWidth * this.crop.koefPosition.x, 0);
				this.crop.y = Math.min(eHeight * this.crop.koefPosition.y, 0);
				this.crop.width = eWidth * this.crop.koefSize.width;
				this.crop.height = eHeight * this.crop.koefSize.height;
			}
		}
		this.updateImageSize();
	};
	
	/**
	 * @param {Object} data
	 * @return {Picture.Mode}
	 */
	Picture.prototype.modeClass = function(data) {
		return new Picture.Mode(data);
	};
	
	/** @return {String} */
	Picture.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this), txt = String((this.imageAlt === null) ? '' : this.imageAlt).replace(/<[^>]+>/g, '');
		opts.text = txt.substring(0, 100);
		if (opts.text.length < txt.length) opts.text += '...';
		if (this.imageUrl) {
			if (typeof this.imageUrl === 'object' && ('faIcon' in this.imageUrl)) {
				opts.thumb = $('<i>').addClass('fa fa-' + this.imageUrl.faIcon)
						.css({
							"text-align": "center",
							position: "absolute",
							width: "100%",
							"font-size": "20px",
							"line-height": "28px",
							color: this.color
						});
			} else {
				opts.thumb = this.makeLocalUrl(this.imageUrl);
			}
		}
		return opts;
	};
	
	Picture.prototype.getUsedMediaGalleryItems = function() {
		var items = Element.prototype.getUsedMediaGalleryItems.call(this);
		return items.concat([this.imageUrl]);
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	Picture.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);
		var m;
		if (Service.modeManager.getUseModes()) {
			m = this.modes[ModeManager.getMode()].serialize();
		} else {
			m = {crop: (this.crop ? this.crop.serialize() : null)};
		}
		data.customLock = this.customLock;
		data.content = {
			src: this.imageUrl,
			color: this.color,
			border: this.border,
			corners: this.corners,
			alt: this.imageAlt,
			link: this.imageLink,
			imageLinkType: this.imageLinkType,
			crop: m.crop,
			fullWidthBackground: this.fullWidthBackground
		};

		return data;
	};
	
	Picture.prototype.onStartResize = function(ui) {
		Element.prototype.onStartResize.call(this, ui);
		if (this.crop && this.imageW) {
			var size = this.imageW.css('background-size').split(/\s+/).map($.trim).map(window.parseFloat);
			this.crop.imageSize = {width: size[0], height: size[1]};
			this.crop.originalPosition = {x: this.crop.x, y: this.crop.y};
			this.crop.koefPosition = {x: this.crop.x / this.elem.width(), y: this.crop.y / this.elem.height()};
			this.crop.koefSize = {width: this.crop.width / this.elem.width(), height: this.crop.height / this.elem.height()};
			this.crop.oriMainSize = {width: this.elem.width(), height: this.elem.height()};
		}
	};
	
	Picture.prototype.onStopResize = function(ui) {
		Element.prototype.onStopResize.call(this, ui);
		if (this.crop) {
			this.crop.imageSize = null;
			delete this.crop.imageSize;
			this.crop.originalPosiotion = null;
			delete this.crop.originalPosition;
			this.crop.koefPosition = null;
			delete this.crop.koefPosition;
			this.crop.koefSize = null;
			delete this.crop.koefSize;
			this.crop.oriMainSize = null;
			delete this.crop.oriMainSize;
		}
	};
	
	Picture.prototype.onResize = function(onConstruct) {
		Element.prototype.onResize.call(this, onConstruct);
		this.updateImageSize();
		this.elem.trigger("elementresize", [this]);
	};

	Picture.prototype.fitToParent = function(preserveAspectRatio, oriBounds, initial) {
		var oriSize = this.getSize();
		Element.prototype.fitToParent.call(this, true, oriBounds, initial);
		var newSize = this.getSize();
		if ((oriSize.width !== newSize.width || oriSize.height !== newSize.height)
				&& (!this.crop || (this.crop.width === oriSize.width && this.crop.height === oriSize.height))) {
			if (!this.crop || typeof this.crop !== 'object') this.crop = {};
			this.crop.width = newSize.width;
			this.crop.height = newSize.height;
		}
		this.updateImageSize();
	};

	/**
	 * Set image url
	 * @param url image url
	 * @param onChange on change callback
	 */
	Picture.prototype.setSrc = function(url, onChange) {
		if (!url) return;
		if( url && typeof url === "object" ) {
			this.imageUrl = $.extend({}, url);
			this.loadImage(this.imageUrl, onChange);
		}
		else {
			this.imageUrl = this.makeRelUrl(url);
			this.loadImage(this.makeLocalUrl(url), onChange);
		}
	};

	/**
	 * Get image url (local url)
	 */
	Picture.prototype.getSrc = function() {
		return this.imageUrl ? ((typeof this.imageUrl === "string") ? this.makeLocalUrl(this.imageUrl) : $.extend({}, this.imageUrl)) : null;
	};

	/**
	 * Get image url (relative url)
	 */
	Picture.prototype.getRelSrc = function() {
		return this.imageUrl ? ((typeof this.imageUrl === "string") ? this.makeRelUrl(this.imageUrl) : $.extend({}, this.imageUrl)) : null;
	};

	Picture.prototype.getColor = function() {
		return this.color;
	};

	Picture.prototype.setColor = function(value) {
		this.color = value;
		this.updateImageSize();
	};

	Picture.prototype.updateImageSize = function() {
		if (!this.imageW) return;
		var w, h;
		if( this.imageUrl && typeof this.imageUrl === "object" && "faIcon" in this.imageUrl ) {
			h = this.elem.height();
			this.imageW.css({
				"font-size": h + "px",
				"color": this.color
			});
		}
		else if( !this.isFullWidth ) {
			if (this.crop && this.crop.width && this.crop.height) {
				var borderWeight = this.getBorderTotalWeight();
				w = this.crop.width - borderWeight.horizontal;
				h = this.crop.height - borderWeight.vertical;
				this.imageW.css({
					'background-position': this.crop.x + 'px ' + this.crop.y + 'px',
					'background-size': w + 'px ' + h + 'px'
				});
			} else {
				var borderWeight = this.getBorderTotalWeight();
				w = this.elem.width() - borderWeight.horizontal;
				h = this.elem.height() - borderWeight.vertical;
				this.imageW.css({
					'background-position': '0 0',
					'background-size': w + 'px ' + h + 'px'
				});
			}
		}
	};
	
	Picture.prototype.getBorderTotalWeight = function() {
		var vert = 0, horiz = 0;
		var src = this.getSrc();
		if ((!src || typeof(src) === 'string') && this.border && this.border.weight) {
			if (typeof this.border.weight === 'object') {
				if (this.border.differ) {
					horiz = (this.border.style[1] === 'none' ? 0 : this.border.weight[1])
							+ (this.border.style[3] === 'none' ? 0 : this.border.weight[3]);
					vert = (this.border.style[0] === 'none' ? 0 : this.border.weight[0])
							+ (this.border.style[2] === 'none' ? 0 : this.border.weight[2]);
				} else {
					horiz = (this.border.style[0] === 'none' ? 0 : this.border.weight[0]) * 2;
					vert = (this.border.style[0] === 'none' ? 0 : this.border.weight[0]) * 2;
				}
			} else {
				horiz = (this.border.style === 'none' ? 0 : this.border.weight) * 2;
				vert = (this.border.style === 'none' ? 0 : this.border.weight) * 2;
			}
		}
		return {horizontal: horiz, vertical: vert};
	};

	Picture.prototype.resetImageSize = function(getSize) {
		if (this.isLocked) {
			this.moveBtn.tooltip('show');
			return;
		}
		if (this.originalSize) {
			var w = this.originalSize.width;
			var h = this.originalSize.height;
			if (getSize) {
				return { width: w, height: h };
				// return { width: this.system.gridSnap(w, true), height: this.system.gridSnap(h, true) };
			}
	//		/var b = this.getBounds();
			this.setSize(w, h);
			this.crop.width = w;
			this.crop.height = h;
			this.crop.x = 0;
			this.crop.y = 0;
			// this.setSize(this.system.gridSnap(w, true), this.system.gridSnap(h, true));
			this.parent.updateSize();
			this.fitToParent();
			this.updateImageSize();
		} else {
			if (getSize) {
				return { width: 0, height: 0 };
			}
		}
	};

	/**
	 * @inheritDoc
	 */
	Picture.prototype.updateComPropertiesInterface = function() {
		Element.prototype.updateComPropertiesInterface.call(this);
		if( !this.comDialog )
			return;
		var isFullWidth = this.comDialog.fields.fullWidth.getValue();
		var src = this.comDialog.fields.imageUrl.getValue();
		if( src && typeof src === "object" ) {
			this.comDialog.fields.linkTypeUrl.setValue(true);
			this.comDialog.fields.linkTypeEnlarge.setVisible(false);
			this.comDialog.fields.colorLabel.setVisible(true);
			this.comDialog.fields.color.setVisible(true);
			this.comDialog.fields.fullWidthBackground.setVisible(false);
			this.comDialog.fields.borderBlock.setVisible(false);
			this.comDialog.fields.cornersBlock.setVisible(false);
		}
		else {
			this.comDialog.fields.linkTypeEnlarge.setVisible(true);
			this.comDialog.fields.colorLabel.setVisible(false);
			this.comDialog.fields.color.setVisible(false);
			this.comDialog.fields.fullWidthBackground.setVisible(isFullWidth);
			this.comDialog.fields.borderBlock.setVisible(true);
			this.comDialog.fields.cornersBlock.setVisible(true);
		}
	};

	Picture.prototype.onFullWidthChanged = function() {
		Element.prototype.onFullWidthChanged.call(this);

		var sz = this.getSize();
		this.crop.x = 0;
		this.crop.y = 0;
		this.crop.width = sz.width;
		this.crop.height = sz.height * sz.width / sz.height;
		this.onResize();

		this.loadImage(this.getSrc());
	};

	Picture.prototype.getFullWidthBackgroundCSS = function(src) {
		return $.extend(true, {}, this.fullWidthBackground.css, {
			position: "absolute",
			width: "100%",
			height: "100%",
			"background-image": "url('" + src + "')"
		});
	};

	Picture.prototype.loadImage = function(src, onChange) {
		var thisClass = this;
		var thisOnChange = onChange;
		if (this.image) {
			if (this.image.parentNode) {
				this.image.parentNode.removeChild(this.image);
			}
			delete this.image;
			this.imageW = null;
		}
		if( src && typeof src === "object" ) {
			if( "faIcon" in src ) {
				this.imageW = $('<i>')
					.addClass("fa fa-" + src.faIcon)
					.css({
						"text-align": "center",
						position: "absolute",
						width: "100%",
						height: "100%"
					});
				thisClass.setEmtyMessageText(thisClass.myEmtyMessageText);
				thisClass.originalSize = { width: thisClass.getWidth(), height: thisClass.getHeight() };
				thisClass.autoHeight = false;
				$(thisClass.container).append(thisClass.imageW);
				this.image = this.imageW.get(0);
				thisClass.updateImageSize();
				thisClass.displayEmtyMessage(false);
				if (typeof thisOnChange === "function") thisOnChange.call(thisClass);
				Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-loaded', thisClass);
			}
		}
		else {
			if (src) this.setEmtyMessageText(__("loading..."));
			var img = new Image();
			this.imageW = $('<span></span>').css($.extend(true,
				{'background-repeat': 'no-repeat'},
				(this.isFullWidth ? this.fullWidthBackground.css : {}),
				{
					position: "absolute",
					width: "100%",
					height: "100%",
					"background-image": "url('" + src + "')"
				}
			));
			this.image = this.imageW.get(0);
			// DO NOT USE VISIBILITY HIDDEN OR DISPLAY NONE IE BUG
			//this.image.style.visibility = "hidden";
			img.onload = function() {
				thisClass.setEmtyMessageText(thisClass.myEmtyMessageText);
				thisClass.originalSize = { width: this.width, height: this.height };
				if (thisClass.autoHeight) {
					var w = Math.min(thisClass.originalSize.width, thisClass.getWidth());
					var h = w * thisClass.originalSize.height / thisClass.originalSize.width;
					thisClass.setSize(w, h);
					thisClass.autoHeight = false;
				}
				thisClass.imageW.css({maxWidth: 'inherit', position: 'absolute'});
				$(thisClass.container).append(thisClass.imageW);
				thisClass.updateImageSize();
				//$(thisClass.image).css("visibility", "visible");
				thisClass.displayEmtyMessage(false);
				if (typeof thisOnChange === "function") thisOnChange.call(thisClass);
				Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-loaded', thisClass);
			};
			img.onerror = function() {
				thisClass.setEmtyMessageText(thisClass.myEmtyMessageText);
				//thisClass.image.style.visibility = "hidden";
				thisClass.displayEmtyMessage(true);

				thisClass.imageUrl = "";
				Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-loaded', thisClass);
			};
			img.src = src ? src : "";
			this.imageW.css("visibility", src ? "visible" : "hidden");
			this.imageW.css(thisClass.border.css);
			this.imageW.css(thisClass.corners.css);
		}
	};

	/**
	 * Call change picture dialog
	 * @param {Function} onChange on change callback
	 */
	Picture.prototype.changePicture = function(onChange) {
		if (this.isLocked) {
			this.moveBtn.tooltip('show');
			return;
		}
		var thisClass = this;
		var thisOnChange = onChange;
		
		Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-start', thisClass);
		this.dialog = Service.mediaLibrary.open(__("Change picture"), null, 'image', true, true);
		this.dialog.addButton(__("Cancel"));
		this.dialog.addButton(__("Select"), function() {
			var list = thisClass.dialog.getSelectedFiles();
			thisClass.system.setPageModified(true);
			thisClass.setSrc(((list.length > 0) ? list[0] : null), thisOnChange);
			thisClass.dialog.hide();
		}, true);
		this.dialog.onClose = function() {
			Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-end', thisClass);
		};

		var url = this.getRelSrc();
		if (url) {
			this.dialog.setSelectedFiles([url]);
		} else {
			this.dialog.clearFileSelection();
		}
		this.dialog.setVisible(true);
	};

	/**
	 * Extend element properties dialog
	 */
	Picture.prototype.comProperties = function() {
		var isCustom = (this.imageUrl && typeof this.imageUrl === "object");

		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 350},
			tabs: [
				{name: __('General'), children: [
					{type: 'HorizontalLayout', columnWeights: [5, 7], children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Picture')},
							{type: 'ImageSelector', id: 'imageUrl', thumbSize: 140, fontAwesomeTab: true, select: this.updateComPropertiesInterface.bind(this)},
							{type: 'Label', id: 'colorLabel', text: __('Color'), css: {marginTop: 15}},
							{type: 'ColorSelector', id: 'color',
								label: __('Color'),
								noTransparent: false
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Alternative Text'),
								helpText: __('Information for an image if a user for some reason cannot view it')
							},
							{type: 'MultilangTextField', id: 'alt', onChange: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-alt-change', thisClass);
							}},
							{type: 'RadioBox', id: 'linkTypeUrl',
								css: {marginTop: 15},
								label: __('Link to another place'),
								group: 'link_type',
								value: true
							},
							{type: 'LinkSelector', id: 'urlLink',
								multilang: true,
								css: {marginLeft: '20px'},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-urlLink-change', thisClass);
								},
								click: function() { fields.linkTypeUrl.setValue(true); }
							},
							{type: 'RadioBox', id: 'linkTypeEnlarge',
								label: __('Enlarge picture on click'),
								group: 'link_type',
								css: {marginTop: '10px'},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-linkTypeEnlarge-change', thisClass);
								}
							}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: "BackgroundSelector", id: "fullWidthBackground", visible: this.isFullWidth && !isCustom, useColor: false, useImage: false, useSize: true}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, id: 'borderBlock', visible: !isCustom, children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'border'}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, id: 'cornersBlock', visible: !isCustom, children: [
						{type: 'Label', text: __('Rounded corners')},
						{type: 'RoundCornersSelector', id: 'corners'}
					]}
				]}
			],
			init: function(fields) {
				//aspect ratio
				var aspectDiv = $('<div class="aspect-div"></div>');
				var aspectBox = $('<div class="aspect-box ico-aspect-ratio"></div>');
				aspectBox.on('click', function() {
					if ($(this).hasClass('ico-aspect-ratio')) {
						$(this).removeClass('ico-aspect-ratio');
						$(this).addClass('ico-aspect-ratio-off');
						thisClass.keepAspectRatio = false;
					}
					else {
						$(this).addClass('ico-aspect-ratio');
						$(this).removeClass('ico-aspect-ratio-off');
						thisClass.keepAspectRatio = true;
					}
				});
				aspectDiv.append(aspectBox);
				fields.sizeW.getElem().parent().css('position', 'relative').append(aspectDiv);
				//input trigger for aspect
				var aspectInputTrigger = function(w) {
					if (thisClass.keepAspectRatio) {
						var r = (thisClass.originalSize.width / thisClass.originalSize.height),
							val = parseInt((w ? fields.sizeW.getValue() : fields.sizeH.getValue()), 10);
						if (w) {
							fields.sizeH.setValue(parseInt(val / r, 10));
						} else {
							fields.sizeW.setValue(parseInt(val * r, 10));
						}
					}
				};
				fields.sizeW.on('change', function() { aspectInputTrigger(true); });
				fields.sizeH.on('change', function() { aspectInputTrigger(false); });

				var resetBtn = new UIButton.UIButton(__('Reset size'), UIButton.UIButton.STYLE_DEFAULT, 'glyphicon glyphicon-fullscreen');
				resetBtn.addClass('btn-xs');
				resetBtn.on('click', function() {
					var size = thisClass.resetImageSize(true);
					if (size && size.width && size.height) {
						fields.sizeW.setValue(size.width);
						fields.sizeH.setValue(size.height);
						fields.wasReset = true;
					}
				});
				fields.sizeBlock.addChild(resetBtn);
				fields.sizeBlock.applyLayoutCellCss(3, (wb_builder.rtl ? {textAlign: 'left', paddingLeft: '38px', marginTop: 4} : {textAlign: 'right', paddingRight: '38px', marginTop: 4}));
			},
			callbackFunc: function(fields) {
				thisClass.imageAlt = fields.alt.getValue();
				thisClass.imageLink = fields.urlLink.getValue();
				thisClass.imageLinkType = fields.linkTypeUrl.getValue() ? 'url' : 'enlarge';
				if (fields.wasReset) {
					var size = thisClass.resetImageSize(true);
					thisClass.crop.width = size.width;
					thisClass.crop.height = size.height;
					thisClass.crop.x = 0;
					thisClass.crop.y = 0;
				} else {
					var ratio = {
						width: parseInt(fields.sizeW.getValue()) / fields.oldSize.width,
						height: parseInt(fields.sizeH.getValue()) / fields.oldSize.height
					};
					thisClass.crop.width = parseInt(thisClass.crop.width * ratio.width);
					thisClass.crop.height = parseInt(thisClass.crop.height * ratio.height);
					thisClass.crop.x = parseInt(thisClass.crop.x * ratio.width);
					thisClass.crop.y = parseInt(thisClass.crop.y * ratio.height);
				}
				thisClass.fullWidthBackground = fields.fullWidthBackground.getValue(); // must be before calling setSrc()
				thisClass.color = fields.color.getValue(); // do not use setColor() method here!
				thisClass.border = fields.border.getValue();
				thisClass.corners = fields.corners.getValue();
				thisClass.setSrc(fields.imageUrl.getValue()); // this also updates the background properties for full-width elements
			}
		});

		fields.wasReset = false;
		fields.oldSize = this.getSize();
		fields.imageUrl.setValue(this.imageUrl);
		fields.alt.setValue(this.imageAlt);
		fields.urlLink.setValue(this.imageLink);
		fields.linkTypeUrl.setValue((this.imageLinkType === 'url'));
		fields.linkTypeEnlarge.setValue((this.imageLinkType === 'enlarge'));
		fields.color.setValue(this.getColor());
		fields.border.setValue(this.border);
		fields.corners.setValue(this.corners);
		fields.fullWidthBackground.setValue(this.fullWidthBackground);
		this.updateComPropertiesInterface();
	};

	/**
	 * Extend element context menu
	 * @param {Object} elem
	 */
	Picture.prototype.initContextMenu = function(elem) {
		var thisClass = this;
		if( this.customLock )
			return;
		Element.prototype.initContextMenu.call(this, elem);
		if (!this.menu) return;
		var idx = this.contextMenuFirstIndex;
		this.menu.insertItemAt(idx++, 'changePicture', __("Change picture"), function() {
			thisClass.changePicture();
		}, null, null, null, "glyphicon glyphicon-picture");
		if (this.isResizable) {
			this.menu.insertItemAt(idx++, 'resetSize', __("Reset to original size"), function() {
				thisClass.system.setPageModified(true);
				thisClass.resetImageSize();
			}, null, null, null, "glyphicon glyphicon-fullscreen");
		}

		this.menu.addSeparator(idx++);
	};

	Picture.prototype.remove = function(noHistory) {
		if( this.customLock )
			return;
		Element.prototype.remove.apply(this, arguments);
	};
	
	Picture.Mode = (function() {
		/**
		 * @param {Picture.Mode} mode
		 * @param {Object} data
		 */
		var applyData = function(mode, data) {
			mode.crop = Rectangle.fromObject(data.crop);
		};

		/**
		 * @param {Object} data
		 * @class WB_Picture.Mode
		 */
		var self = function(data) { Element.Mode.prototype.constructor.call(this, data); if (data) applyData(this, data); };
		self.prototype = Object.create(Element.Mode.prototype);
		/** @type Rectangle */
		self.prototype.crop = null;
		/** @param {WB_Form.Mode} mode */
		self.prototype.copy = function(mode) {
			Element.Mode.prototype.copy.call(this, mode);
			applyData(this, mode);
		};
		/** @param {WB_Form} elem */
		self.prototype.store = function(elem) {
			Element.Mode.prototype.store.call(this, elem);
			applyData(this, {
				crop: elem.crop
			});
		};
		/** @param {Picture} elem */
		self.prototype.applyTo = function(elem) {
			Element.Mode.prototype.applyTo.call(this, elem);
			elem.crop = Rectangle.fromObject(this.crop);
		};
		/** @return {Object} */
		self.prototype.serialize = function() {
			var obj = Element.Mode.prototype.serialize.call(this);
			obj.crop = (this.crop) ? this.crop.serialize() : null;
			return obj;
		};

		return self;
	})();
	
	window.WB_Picture = Picture;
	
	return Picture;
});
;

/** WB Table **/
(window.defineModule = (window.defineModule || {})).name = 'WB Table';

define('Table', [
	'ElementRegister',
	'Element',
	'ContextMenu',
	'Service',
	'ModeManager'
], function(ElementRegister, Element, ContextMenu, Service, ModeManager) {
	'use strict';

	/**
	 * Table class
	 * @param {Object} data
	 */
	function Table(data) { if (data) this.__construct(data); }
	
	Table.prototype = new Element();
	ElementRegister.registerClass("Table", Table);
	
	Table.editor = null;
	
	Table.prototype.table = null;
	Table.prototype.tableBody = null;
	Table.prototype.cols = 0;
	Table.prototype.rows = 0;
	Table.prototype.cells = null;
	Table.prototype.resizeCells = null;
	Table.prototype.selectedCells = null;
	Table.prototype.border = null;
	Table.prototype.padding = null;
	Table.prototype.bgColor = null;
	Table.prototype.editingCell = null;
	Table.prototype._selectableConfig = null;
	Table.prototype._selectableDisabled = false;
	Table.prototype._eventsDisabled = true;
	
	Table.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);
		var thisClass = this;
		this.setMinSize(10, 10);
		
		this.cols = data.content.cols ? (data.content.cols*1) : 2;
		this.rows = data.content.rows ? (data.content.rows*1) : 2;
		
		this.border = data.content.border ? data.content.border : {
			color: "#c0c0c0",
			style: "solid",
			weight: 1,
			css: {
				border: "1px solid #c0c0c0"
			}
		};
		this.padding = (data.content.padding || data.content.padding === 0) ? data.content.padding : 2;
		this.bgColor = data.content.bgColor ? data.content.bgColor : 'transparent';
		
		this.table = $('<table>').attr({cellspacing: 0, cellpadding: 0}).append('<tbody>');
		this.table.addClass("wb_table");
		this.table.css({"border-collapse": "collapse"});
		this.tableBody = this.table.children("tbody");
		
		this.container.append(this.table);
		
		this.selectedCells = [];
		
		if (!Table.editor) {
			Table.editor = new WB_TextArea({content: {}, _fromTablePlugin: true});
			Table._showEditor = Table.editor.showEditor;
			Table.editor.showEditor = function(cell) {
				Table.editor.hideEditor();
				this.textId = cell.textId;
				this.editorId = cell.textId + '_editor';
				this.textDiv = cell.container;
				this.textDivValue = cell.text;
				Table._showEditor.call(this);
				this.textDiv.removeClass('outline1').addClass('outline2');
				this.thisTable = cell.table;
				this.thisTable.editingCell = cell;
				this.thisTable.setEventsEnabled(false);
				this.thisTable.setControlsEnabled(false);
			};
			Table._hideEditor = Table.editor.hideEditor;
			Table.editor.hideEditor = function() {
				Table._hideEditor.call(this);
				if (!this.thisTable) return;
				this.thisTable.editingCell.text = this.textDivValue;
				this.textDiv.removeClass('outline2');
				this.thisTable.setControlsEnabled(true);
				this.thisTable.editingCell = null;
				this.thisTable.setEventsEnabled(true);
				this.thisTable.updateElemSize();

				this.thisTable.table.removeAttr('data-cke-table-faked-selection-table');
				this.thisTable.table.find('td').removeClass('cke_table-faked-selection');
				this.thisTable.table.find('td > div').removeClass('cke_table-faked-selection-editor');
				this.thisTable = null;
			};
		}
		
		this.cells = {};
		var cells = data.content.cells ? data.content.cells : [];

		var r = 0, c = 0, tr, cellData, cell;
		for (r = 0; r < this.rows; r++) {
			tr = $('<tr>');
			for (c = 0; c < this.cols; c++) {
				cellData = this.getCell(r, c, cells);
				if (data._copy) cellData.id = null;
				cell = new Table.TableCell(cellData);
				cell.row = r;
				cell.col = c;
				cell.table = this;
				tr.append(cell.elem);
				this.cells['#' + cell.id] = cell;
			}
			this.tableBody.append(tr);
		}
		this.setBorder(this.border);
		this.setPadding(this.padding);
		this.setBgColor(this.bgColor);
		this.updateElemSize(true);
		
		this.elem.draggable("option", "handle", this.moveBtn);
		this.moveBtn.bind('mousedown', function(e) {
			thisClass.elem.unbind('mousemove', thisClass._mousemoveFunc);
		});
		this.moveBtn.bind('mouseup', function(e) {
			thisClass.elem.bind('mousemove', thisClass._mousemoveFunc);
		});
		this.setResizingEnabled(false, true);
		
		this._mousemoveFunc = function(e) {
			var thisClass = $(this).wbGetClassInstance();
			if (thisClass.isMouseDown) {
				thisClass._onMouseDrag(e);
				e.stopPropagation();
				return false;
			} else {
				thisClass._onMouseMove(e);
			}
		};
		this._mousedownFunc = function(e) {
			var thisClass = $(this).wbGetClassInstance();
			if (e.button === 2) {
				thisClass._selectCellByEvent(e);
			} else {
				thisClass.isMouseDown = {x: e.offsetX, y: e.offsetY};
				thisClass.container.css({'box-sizing': 'content-box', padding: '0 100px 100px 0'});
				if (thisClass.resizeCells) {
					var _resizeCells = thisClass.resizeCells;
					thisClass.resizeCells = [];
					for (var id in thisClass.cells) {
						if (thisClass.cells[id].col === _resizeCells.col) {
							thisClass.resizeCells.push(thisClass.cells[id]);
						}
					}
				}
			}
		};
		this._mouseupFunc = function(e) {
			var thisClass = $(this).wbGetClassInstance();
			thisClass.isMouseDown = null;
			thisClass.container.css({'box-sizing': '', padding: ''});
		};
		this._dblclickFunc = function(e) {
			thisClass._selectCellByEvent(e);
			thisClass.editCell();
			e.stopPropagation();
		};

		if (this.isLocked) this.setLocked(this.isLocked);
		
		this.setEventsEnabled(true);
	};

	Table.prototype._selectCellByEvent = function(e) {
		var cell, cx, cy, cw, ch, co, x = e.pageX, y = e.pageY;
		for (var i in this.cells) {
			cell = this.cells[i];
			co = cell.elem.offset();
			cx = co.left; cy = co.top;
			cw = cell.elem.outerWidth();
			ch = cell.elem.outerHeight();
			
			if (x >= cx && x <= cx + cw && y >= cy && y <= cy + ch) {
				if (('#' + cell.id) in this.selectedCells) break;
				for (var j in this.cells) {
					this.cells[j].elem.removeClass('ui-selected');
				}
				cell.elem.addClass('ui-selected');
				this.selectedCells = {};
				this.selectedCells['#' + cell.id] = cell;
				break;
			}
		}
	};
	
	Table.prototype.setEventsEnabled = function(enabled) {
		if (enabled && this._eventsDisabled) {
			this.elem.wbSetClassInstance(this);
			this.elem.bind('mousedown', this._mousedownFunc);
			this.elem.bind('mousemove', this._mousemoveFunc);
			this.elem.bind('mouseup', this._mouseupFunc);
			this.elem.bind('dblclick', this._dblclickFunc);
			this._eventsDisabled = false;
		} else if (!enabled && !this._eventsDisabled) {
			this.elem.unbind('mousedown', this._mousedownFunc);
			this.elem.unbind('mousemove', this._mousemoveFunc);
			this.elem.unbind('mouseup', this._mouseupFunc);
			this.elem.unbind('dblclick', this._dblclickFunc);
			this._eventsDisabled = true;
		}
	};
	
	Table.prototype._selectableSetEnabled = function(enabled) {
		if (this.elem.hasClass('ui-selectable')) {
			if (enabled && this._selectableDisabled && !this.editingCell) {
				this.elem.selectable('enable');
				this._selectableDisabled = false;
			} else if (!enabled && !this._selectableDisabled) {
				this.elem.selectable('disable');
				this.elem.removeClass('ui-state-disabled');
				this._selectableDisabled = true;
			}
		}
	};
	
	Table.prototype._getModOffset = function(e) {
		var eo = this.elem.offset();
		return {x: e.pageX - eo.left, y: e.pageY - eo.top};
	};
	
	Table.prototype._onMouseDrag = function(e) {
		if (this.resizeCells && this.resizeCells.length) {
			var offset = this._getModOffset(e);
			var diffX = offset.x - this.isMouseDown.x, diffY = offset.y - this.isMouseDown.y;
			var setSize = 0;
			for (var i in this.resizeCells) {
				if (!setSize) setSize = this.resizeCells[i].width + diffX;
				this.resizeCells[i].setSize(setSize);
			}
			this.isMouseDown.x = offset.x; this.isMouseDown.y = offset.y;
			this.updateElemSize();
		}
	};
	
	Table.prototype._onMouseMove = function(e) {
		var minP = 10, x = e.offsetX, brd = this.getHorizBorderWeight();
		var pad = (Math.max(brd, minP) - brd) / 2, x1 = 0, x2 = brd;
		var condition = false, condPart = null;
		var row0 = this.getRow(0), i, len, cell;
		row0.sort(function(a, b) { return (a.col > b.col) ? 1 : -1; });
		for (i=0, len=row0.length; i < len; i++) {
			cell = row0[i];
			x1 += cell.width + brd;
			x2 += cell.width + brd;
			condPart = (x >= x1 - pad && x <= x2 + pad);
			if (condPart) {
				this.resizeCells = cell;
			}
			condition = condition || condPart;
		}
		if (condition) {
			this.elem.css('cursor', 'w-resize');
		} else {
			this.elem.css('cursor', '');
			this.resizeCells = null;
		}
	};
	
	Table.prototype.getFirstSelectedCell = function(fromEnd) {
		fromEnd = fromEnd ? true : false;
		if (Object.keys(this.selectedCells).length) {
			var rCell = null;
			if (fromEnd) {
				for (var id in this.selectedCells) {
					var cell = this.selectedCells[id];
					if (!rCell || cell.col > rCell.col || cell.row > rCell.row) {
						rCell = cell;
					}
				}
			} else {
				for (var id in this.selectedCells) {
					var cell = this.selectedCells[id];
					if (!rCell || cell.row < rCell.row || cell.col < rCell.col) {
						rCell = cell;
					}
				}
			}
			return rCell;
		}
		return null;
	};
	
	Table.prototype.getCell = function(row, col, cellsArr) {
		cellsArr = cellsArr ? cellsArr : this.cells;
		for (var i in cellsArr) {
			var cell = cellsArr[i];
			if (cell.row === row && cell.col === col) {
				return cell;
			}
		}
		return null;
	};
	
	Table.prototype.getLastCell = function() {
		return this.getCell(this.rows-1, this.cols-1);
	};
	
	Table.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);
		
		var cells = [];
		for (var id in this.cells) {
			cells.push(this.cells[id].serialize());
		}
		
		data.content = {
			'cols': this.cols,
			'rows': this.rows,
			'border': this.border,
			'padding': this.padding,
			'bgColor': this.bgColor,
			'cells': cells
		};
		return data;
	};
	
	Table.prototype.setSize = function(width, height, adjustCells, useParentMethod) {
		if (useParentMethod) {
			Element.prototype.setSize.call(this, width, height);
		}
		if (adjustCells) {
			if (width) {
				if (!this.border || !this.cols || !this.cells) return;
				var bw = this.getHorizBorderWeight();
				var currWidth = this.getWidth() - (this.cols + 1) * bw;
				var newWidth = width - (this.cols + 1) * bw;
				var ratio = newWidth / currWidth, totalWidth = 0;
				var lastCellsInRows = {};
				for (var id in this.cells) {
					var cell = this.cells[id];
					var cellWidth = Math.round(cell.width * ratio);
					cell.setSize(cellWidth);
					if (cell.row === 0) totalWidth += cellWidth;
					if (!(cell.row in lastCellsInRows) || lastCellsInRows[cell.row].col < cell.col) {
						lastCellsInRows[cell.row] = cell;
					}
				}
				var diffWidth = newWidth - totalWidth;
				for (var row in lastCellsInRows) {
					var cell = lastCellsInRows[row];
					cell.setSize(cell.width + diffWidth);
				}
				Element.prototype.setSize.call(this, width, height);
			}
			if (height) {}
		}
	};
	
	Table.prototype.setLocked = function(lock, initial) {
		if (lock) {
			for (var i in this.cells) {
				this.cells[i].elem.removeClass('ui-selected');
			}
		}
		Element.prototype.setLocked.call(this, lock);
	};
	
	Table.prototype.calcTotalWidth = function() {
		var w = 0, i, len, isFirst, isLast;
		var row0 = this.getRow(0);
		for (i=0, len=row0.length; i < len; i++) {
			isFirst = (i === 0);
			isLast = (i === len-1);
			w += Math.ceil(row0[i].width);
			if (this.border && this.border.weight) {
				if (typeof(this.border.weight) === 'object' && this.border.weight) {
					if (this.border.differ) {
						if (isFirst) {
							w += this.border.weight[3];
						} else if (isLast) {
							w += this.border.weight[1];
						} else {
							w += Math.max(this.border.weight[1], this.border.weight[3]);
						}
					} else {
						w += this.border.weight[0];
					}
				} else if (this.border.weight) {
					w += this.border.weight;
				}
			}
		}
		return w;
	};
	
	Table.prototype.updateElemSize = function(onConstruct) {
		var w = this.calcTotalWidth();
		this.setSize(w, null, false, true);
		var h = this.table.outerHeight();
		this.setSize(null, h, false, true);
		this.onResize(onConstruct);
		
		var row0 = this.getRow(0), i, len, id, cell;
		var rowIndex = {};
		for (i=0, len=row0.length; i < len; i++) {
			rowIndex['c' + row0[i].col] = row0[i];
		}
		for (id in this.cells) {
			cell = this.cells[id];
			if (cell.row === 0) continue;
			if (('c' + cell.col) in rowIndex) {
				cell.setSize(rowIndex['c' + cell.col].width);
			}
		}
	};
	
	Table.prototype.getRow = function(r) {
		var row = [];
		for (var id in this.cells) {
			if (this.cells[id].row === r) {
				row.push(this.cells[id]);
			}
		}
		return row;
	};
	
	Table.prototype.getCol = function(c) {
		var col = [];
		for (var id in this.cells) {
			if (this.cells[id].col === c) {
				col.push(this.cells[id]);
			}
		}
		return col;
	};
	
	Table.prototype.refreshCellsPosition = function() {
		var thisClass = this;
		this.tableBody.children('tr').each(function(row) {
			$(this).children('td').each(function(col) {
				var idx = '#' + $(this).attr('data-id');
				if (idx in thisClass.cells) {
					var c = thisClass.cells[idx];
					thisClass.cells[idx].row = row;
					thisClass.cells[idx].col = col;
				}
			});
		});
	};
	
	Table.prototype.insertRow = function(above) {
		var sCell = this.getFirstSelectedCell(!above);
		if (!sCell) {
			var cellCount = Object.keys(this.cells).length;
			if (cellCount) {
				sCell = this.cells[Object.keys(this.cells)[(above ? 0 : cellCount-1)]];
			}
		}
		if (!sCell) return;
		var tr = $('<tr></tr>');
		for (var i=0; i < this.cols; i++) {
			var cell = new Table.TableCell();
			cell.row = -1;
			cell.col = i;
			cell.table = this;
			cell.setSize(this.getCell(sCell.row, i).width);
			this.cells['#' + cell.id] = cell;
			tr.append(cell.elem);
		}
		if (above) {
			sCell.elem.parent().before(tr);
		} else {
			sCell.elem.parent().after(tr);
		}
		this.rows++;
		this.refreshCellsPosition();
		this.setBorder();
		this.setPadding();
		this.updateElemSize();
	};
	
	Table.prototype.insertColumn = function(toLeft) {
		var sCell = this.getFirstSelectedCell(!toLeft);
		if (!sCell) {
			var cellCount = Object.keys(this.cells).length;
			if (cellCount) {
				sCell = this.cells[Object.keys(this.cells)[(toLeft ? 0 : cellCount-1)]];
			}
		}
		if (!sCell) return;
		for (var i=0; i < this.rows; i++) {
			var adjCell = this.getCell(i, sCell.col);
			var cell = new Table.TableCell();
			cell.row = i;
			cell.col = -1;
			cell.table = this;
			this.cells['#' + cell.id] = cell;
			if (toLeft) {
				adjCell.elem.before(cell.elem);
			} else {
				adjCell.elem.after(cell.elem);
			}
		}
		this.cols++;
		this.refreshCellsPosition();
		this.setBorder();
		this.setPadding();
		this.updateElemSize();
	};
	
	Table.prototype.removeRows = function() {
		var rowIndex = {};
		for (var id in this.selectedCells) {
			var cell = this.selectedCells[id];
			if (!rowIndex[cell.row]) {
				this._removeRow(cell.row);
				rowIndex[cell.row] = true;
				this.rows--;
			}
		}
		this.refreshCellsPosition();
		this.updateElemSize();
	};
	
	Table.prototype._removeRow = function(row) {
		var tr = null;
		for (var id in this.cells) {
			var cell = this.cells[id];
			if (cell.row === row) {
				if (!tr) tr = cell.elem.parent();
				cell.remove();
			}
		}
		if (tr) {
			tr.detach();
			tr = null;
		}
	};
	
	Table.prototype.removeColumns = function() {
		var colIndex = {};
		for (var id in this.selectedCells) {
			var cell = this.selectedCells[id];
			if (!colIndex[cell.col]) {
				this._removeColumn(cell.col);
				colIndex[cell.col] = true;
				this.cols--;
			}
		}
		this.refreshCellsPosition();
		this.updateElemSize();
	};
	
	Table.prototype._removeColumn = function(col) {
		for (var id in this.cells) {
			var cell = this.cells[id];
			if (cell.col === col) {
				cell.remove();
			}
		}
	};
	
	Table.prototype.mergeCells = function() {
		
	};
	
	Table.prototype.splitCells = function() {
		
	};
	
	Table.prototype.editCell = function() {
		var thisClass = this;
		var cell = null;
		for (var id in this.selectedCells) { cell = this.selectedCells[id]; break; }
		if (!cell) return;
		cell.elem.removeClass('ui-selected');
		delete this.selectedCells['#' + cell.id];
		this.menu.hide();
		Table.editor.showEditor(cell);
	};
	
	Table.prototype.clearCells = function() {
		for (var id in this.selectedCells) {
			var cell = this.selectedCells[id];
			cell.setText("&nbsp;");
			delete this.selectedCells[id];
		}
		this.updateElemSize();
	};
	
	Table.prototype.getHorizBorderWeight = function() {
		var b = 0;
		if (this.border) {
			if (typeof this.border.weight !== 'object') {
				b = this.border.weight;
			} else if ('length' in this.border.weight) {
				b = Math.max(this.border.weight[1], this.border.weight[3]);
			}
		}
		return b;
	};
	
	Table.prototype.setBorder = function(border) {
		if (border !== undefined) this.border = border;
		for (var i in this.border.css) {
			this.table.find('td').css(i, this.border.css[i]);
		}
	};
	
	Table.prototype.setPadding = function(padding) {
		if (padding !== undefined) this.padding = padding;
		this.table.find('td > div').css('padding', this.padding + 'px');
	};
	
	Table.prototype.setBgColor = function(bgColor) {
		if (bgColor !== undefined) this.bgColor = bgColor;
		this.table.css('background-color', bgColor);
	};
	
	Table.prototype.initContextMenu = function(elem) {
		Element.prototype.initContextMenu.call(this, elem);
		if (!this.menu) return;
		var thisClass = this;
		
		var idx = this.contextMenuFirstIndex;
		
		var submenu = new ContextMenu(this.id + "_insert_sub");
		submenu.addItem('insertRowAbove', __("Row above"), function() {
			thisClass.insertRow(true);
		});
		submenu.addItem('insertRowBelow', __("Row below"), function() {
			thisClass.insertRow();
		});
		submenu.addSeparator();
		submenu.addItem('insertColumnLeft', __("Column to the left"), function() {
			thisClass.insertColumn(true);
		});
		submenu.addItem('insertColumnRight', __("Column to the right"), function() {
			thisClass.insertColumn();
		});
		this.menu.insertItemAt(idx++, 'insert', __('Insert'), submenu, null, null, null, 'glyphicon glyphicon-plus');

		submenu = new ContextMenu(this.id + "_remove_sub");
		submenu.addItem('removeRows', __("Row(s)"), function() {
			thisClass.removeRows();
		});
		submenu.addItem('removeColumns', __("Column(s)"), function() {
			thisClass.removeColumns();
		});
		submenu.addItem("removeTable", __("Table"), function() {
			thisClass.remove();
		});
		this.menu.insertItemAt(idx++, 'remove2', __('Remove'), submenu, null, null, null, 'glyphicon glyphicon-remove');
		this.submenu_remove = submenu;
		// this.menu.addItem('mergeCells', __("Merge cells"), function() {
			// thisClass.mergeCells();
		// });
		// this.menu.addItem('splitCells', __("Split cell(s)"), function() {
			// thisClass.splitCells();
		// });
		this.menu.insertItemAt(idx++, 'editCellText', __("Edit cell text"), function() {
			thisClass.editCell();
		}, null, null, null, 'glyphicon glyphicon-pencil');
		this.menu.insertItemAt(idx++, 'clearCells', __("Clear cell(s)"), function() {
			thisClass.clearCells();
		}, null, null, null, 'glyphicon glyphicon-erase');
		this.menu.addSeparator(idx++);
	};
	
	Table.prototype.updateContextMenu = function() {
		Element.prototype.updateContextMenu.call(this);
		var len = Object.keys(this.selectedCells).length;
		this.menu.setDisabled('mergeCells', (len === 1));
		this.menu.setDisabled('editCellText', (len > 1));
		this.submenu_remove.setDisabled('removeRows', (this.rows === 1));
		this.submenu_remove.setDisabled('removeColumns', (this.cols === 1));
	};
	
	Table.prototype.onSwitchLanguage = function(langCode) {
		Element.prototype.onSwitchLanguage.call(this, langCode);
		for (var id in this.cells) {
			var cell = this.cells[id];
			cell.setText();
		}
	};
	
	Table.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			tabs: [
				{children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, columnWeights: [4, 4, 4], children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background color')},
							{type: 'ColorSelector', id: 'bgColor', big: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Cell padding')},
							{type: 'SizeSelector', id: 'padding', min: 0}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.setBorder(fields.border.getValue());
				thisClass.setPadding(fields.padding.getValue());
				thisClass.setBgColor(fields.bgColor.getValue());
				thisClass.setSize(fields.sizeW.getValue(), fields.sizeH.getValue(), true);
				thisClass.updateElemSize();
			}
		});
		fields.border.setValue(thisClass.border);
		fields.padding.setValue(thisClass.padding);
		fields.bgColor.setValue(thisClass.bgColor);
	};
	
	Table.prototype.modeClass = function(data) {
		return new Table.Mode(data);
	};
	
	Table.prototype.switchMode = function(fromMode, toMode, initial, manual) {
		var thisClass = this;
		Element.prototype.switchMode.call(this, fromMode, toMode, initial, manual);
		if (!toMode || !Service.modeManager.getUseModes()) return;
		for (var id in this.cells) {
			this.cells[id].switchMode(fromMode, toMode, initial);
		}
		setTimeout(function() {
			thisClass.updateElemSize(initial);
		}, 1);
	};
	
	/** @class */
	Table.Mode = (function() {
		/**
		 * @param {Table.Mode} mode
		 * @param {Object} data
		 */
		var applyData = function(mode, data) {
			mode.x = data.x;
			mode.y = data.y;
			mode.hidden = data.hidden;
		};

		/**
		 * @param {Object} data
		 * @class
		 */
		var self = function(data) { if (data) applyData(this, data); };
		/** @type Number */
		self.prototype.x = 0;
		/** @type Number */
		self.prototype.y = 0;
		/** @type Boolean */
		self.prototype.hidden = false;
		/** @param {Element.Mode} mode */
		self.prototype.copy = function(mode) {
			applyData(this, mode);
		};
		/** @param {Element} elem */
		self.prototype.store = function(elem) {
			var b = elem.getBounds();
			b.x = b.left;
			b.y = b.top;
			b.hidden = elem.isHidden(true);
			applyData(this, b);
		};
		/** @param {Element} elem */
		self.prototype.applyTo = function(elem) {
			elem.setLocation(this.x, this.y);
			if (this.hidden) elem.hide(true); else elem.show(true);
		};
		/** @return {Object} */
		self.prototype.serialize = function() {
			return { x: Math.round(this.x), y: Math.round(this.y), hidden: this.hidden };
		};

		return self;
	})();
	
	(function(proto) {
		
		var TableCell = function(data) { this.__construct(data); };
		proto.TableCell = TableCell;
		
		TableCell.defaultWidth = 160;
		TableCell.defaultHeight = 30;
		TableCell.idReg = {};
		TableCell.prototype.id = null;
		TableCell.prototype.textId = null;
		TableCell.prototype.elem = null;
		TableCell.prototype.container = null;
		TableCell.prototype.table = null;
		TableCell.prototype.row = 0;
		TableCell.prototype.col = 0;
		TableCell.prototype.colspan = 1;
		TableCell.prototype.rowspan = 1;
		TableCell.prototype.width = 0;
		// TableCell.prototype.height = 0;
		TableCell.prototype.text = '<p class="wb-stl-normal" style="text-align: center;">' + __("Enter your text here") + '</p>';
		TableCell.prototype.modes = null;
		
		TableCell.prototype.__construct = function(data) {
			if (data === undefined || data === null) data = {};
			this.id = (data.id && !(('#' + data.id) in TableCell.idReg)) ? data.id : this.getFreeId();
			this.textId = 'wb_celltext_' + this.id;
			TableCell.idReg['#' + this.id] = true;
			this.row = data.row ? (data.row*1) : this.row;
			this.col = data.col ? (data.col*1) : this.col;
			this.width = data.width ? (data.width*1) : 0;
			if (!this.width || this.width <= 0) this.width = TableCell.defaultWidth;
			// this.height = data.height ? (data.height*1) : 0;
			// if (!this.height || this.height <= 0) this.height = TableCell.defaultHeight;
			this.text = (data.text !== undefined) ? data.text : this.text;
			this.elem = $('<td>').append('<div>');
			this.elem.attr('data-id', this.id);
			this.container = this.elem.children('div');
			this.container.attr('id', this.textId);
			// this.setSize(this.width, this.height);
			this.setSize(this.width);
			this.setText(this.text);
			this.setColspan(data.colspan ? (data.colspan*1) : this.colspan);
			this.setRowspan(data.rowspan ? (data.rowspan*1) : this.rowspan);
			this.modes = {}; if (data.modes) for (var k in data.modes) { this.modes[k] = this.modeClass(data.modes[k]); }
		};
		
		TableCell.prototype.setText = function(text) {
			this.text = (text === undefined) ? this.text : text;
			this.container.html(__tr(this.text, null, "&nbsp;"));
		};
		
		TableCell.prototype.serialize = function() {
			var m;
			if (Service.modeManager.getUseModes()) {
				var mode = ModeManager.getMode();
				this.switchMode(mode, mode);
				m = this.modes[mode].serialize();
			} else {
				m = {width: this.width};
			}
			var modes = {}; for (var k in this.modes) { modes[k] = this.modes[k].serialize(); }
			return {
				'id': this.id,
				'row': this.row,
				'col': this.col,
				'width': m.width,
				'height': this.height,
				'colspan': this.colspan,
				'rowspan': this.rowspan,
				'text': this.text,
				'modes': modes
			};
		};
		
		TableCell.prototype.remove = function() {
			this.elem.detach();
			this.elem = null;
			this.table.cells['#' + this.id] = null;
			delete this.table.cells['#' + this.id];
		};
		
		TableCell.prototype.setColspan = function(colspan) {
			this.colspan = parseInt(colspan);
			this.elem.attr('colspan', ((this.colspan && this.colspan > 1) ? this.colspan : ''));
		};
		
		TableCell.prototype.setRowspan = function(rowspan) {
			this.rowspan = parseInt(rowspan);
			this.elem.attr('rowspan', ((this.rowspan && this.rowspan > 1) ? this.rowspan : ''));
		};
		
		TableCell.prototype.setSize = function(width, height) {
			var css = {};
			if (width !== undefined) {
				width *= 1;
				width = Math.max(width, 0);
				if (width) this.width = width;
				css.width = (width) ? width + 'px' : '';
			}
			// if (height !== undefined) {
				// height *= 1;
				// if (height) this.height = height;
				// css.height = (height) ? height + 'px' : '';
			// }
			this.container.css(css);
			// this.elem.css(css);
		};
		
		TableCell.prototype.getFreeId = function() {
			for (var i=1; i < 5000; i++) {
				if (!TableCell.idReg['#' + i]) return i;
			}
		};
		
		TableCell.prototype.modeClass = function(data) {
			return new TableCell.Mode(data);
		};
		
		TableCell.prototype.switchMode = function(fromMode, toMode, initial) {
			if (!toMode || !Service.modeManager.getUseModes()) return;
			var isNew = false;
			if (!(fromMode in this.modes)) {
				isNew = true;
				this.modes[fromMode] = this.modeClass();
			}
			if ((!initial || isNew)) {
				this.modes[fromMode].store(this);
			}
			if (!(toMode in this.modes)) {
				this.modes[toMode] = this.modeClass();
				this.modes[toMode].copy(this.modes[fromMode]);
			}
			if (initial || fromMode !== toMode) {
				this.modes[toMode].applyTo(this);
			}
		};
		
		TableCell.Mode = (function() {
			'use strict';
			
			/**
			 * @param {TableCell.Mode} mode
			 * @param {Object} data
			 */
			var applyData = function(mode, data) {
				mode.width = data.width;
			};
			
			/**
			 * @param {Object} data
			 * @class TableCell.Mode
			 */
			var self = function(data) { if (data) applyData(this, data); };
			
			/** @type Number */
			self.prototype.width = 0;
			
			/** @param {TableCell.Mode} mode */
			self.prototype.copy = function(mode) {
				applyData(this, mode);
			};
			
			/** @param {TableCell} elem */
			self.prototype.store = function(elem) {
				applyData(this, {
					width: elem.width
				});
			};
			/** @param {TableCell} elem */
			self.prototype.applyTo = function(elem) {
				elem.setSize(this.width);
			};
			/** @return {Object} */
			self.prototype.serialize = function() {
				var obj = { width: this.width };
				return obj;
			};
			
			return self;
			
		})();
		
	})(Table);
	
	return Table;
});
;

/** WB Menu **/
(window.defineModule = (window.defineModule || {})).name = 'WB Menu';

define('Menu', [
	'ElementRegister',
	'Element',
	'Site',
	'ContextMenu',
	'ModeManager',
	'EditMenuItemsDialog',
	'Service',
	'MenuConfirmDialog',
	'TextControl',
	'TreeListControl',
	'SizeSelector',
	'BuilderEvent',
	'util/MenuList'
], function(ElementRegister, Element, Site, ContextMenu, ModeManager, EditMenuItemsDialog,
			Service, MenuConfirmDialog, TextControl, TreeListControl, SizeSelector, BuilderEvent, MenuList) {
	'use strict';
	
	var wb_builder = window.wb_builder;
	
	/**
	 * Menu class
	 * @param {Object} data
	 */
	var Menu = function(data) { if (data) this.__construct(data); };

	Menu.prototype = new Element();
	Menu.prototype.constructor = Menu;
	ElementRegister.registerClass("Menu", Menu);

	Menu.lastIndex = 0;
	Menu.lastPageId = 0;
	Menu.elemList = {};
	Menu.strangeElemList = {};
	/**
	 * Get menu by menuUID
	 * @param {String} menuUID
	 * @returns {Menu}
	 */
	Menu.getMenuByUID = function(menuUID, includeStrange) {
		var list = Menu.getElemList(includeStrange);
		for (var k in list) {
			if (list[k].menuUID === menuUID) {
				return list[k];
			}
		}
		return null;
	};
	/**
	 * Get menu item.
	 * @param {String} miId can be either item ID or combined menu UID and item ID
	 * @param {String} menuUID optional
	 * @returns {Menu.MenuItem}
	 */
	Menu.getMenuItemById = function(miId, menuUID) {
		var parts = miId.split('_');
		if (parts.length > 1) {
			miId = parts[1];
		}
		if (!menuUID) {
			if (parts.length > 1) {
				menuUID = parts[0];
			}
		}
		var searchItem = function(mi, id) {
			var item, i;
			for (i in mi.items) {
				if (mi.items[i].id == id) {
					item = mi.items[i];
				}
				if (!item) {
					item = searchItem(mi.items[i], id);
				}
				if (item) break;
			}
			return item;
		};
		var menu = Menu.getMenuByUID(menuUID, true);
		return (menu ? searchItem(menu, miId) : null);
	};
	Menu.hasPage = function(pageId, menu, extended) {
		var list = [], k, i, subList;
		if (!menu) {
			for (var k0 in Menu.elemList) {
				var m = Menu.elemList[k0];
				for (k in m.items) {
					if (!m.items[k].type || m.items[k].type === "internal" || m.items[k].type === "page") {
						if (m.items[k].targetId == pageId) {
							if (extended) {
								list.push({menuUID: m.menuUID, menuItemId: m.items[k].id});
							} else {
								list.push(m.items[k].id);
							}
						}
					}
					subList = Menu.hasPage(pageId, m.items[k], extended);
					for (i = 0; i < subList.length; i++) list.push(subList[i]);
				}
				if (m.itemsTmp && m.itemsTmp.items) {
					for (k in m.itemsTmp.items) {
						if (!m.itemsTmp.items[k].type || m.itemsTmp.items[k].type === "internal" || m.itemsTmp.items[k].type === "page") {
							if (m.itemsTmp.items[k].targetId == pageId) {
								if (extended) {
									list.push({menuUID: m.menuUID, menuItemId: m.itemsTmp.items[k].id});
								} else {
									list.push(m.itemsTmp.items[k].id);
								}
							}
						}
						subList = Menu.hasPage(pageId, m.itemsTmp.items[k], extended);
						for (i = 0; i < subList.length; i++) list.push(subList[i]);
					}
				}
			}
		} else {
			for (k in menu.items) {
				if (!menu.items[k].type || menu.items[k].type === "internal" || menu.items[k].type === "page") {
					if (menu.items[k].targetId == pageId) {
						if (extended) {
							list.push({menuUID: menu.menuUID, menuItemId: menu.items[k].id});
						} else {
							list.push(menu.items[k].id);
						}
					}
				}
				subList = Menu.hasPage(pageId, menu.items[k], extended);
				for (i = 0; i < subList.length; i++) list.push(subList[i]);
			}
		}
		return (extended ? list : WB_Builder.arrayUnique(list));
	};
	Menu.editMenu = function() {
		for (var k in Menu.elemList) {
			var m = Menu.elemList[k];
			if (m.menuElem.children("li").size() > 0) {
				m.openEditMenuItems(false);
			} else {
				m.openEditMenuItems(true);
			}
			break;
		}
	};
	Menu.getTotalPages = function(excludeMe) {
		var total = 0;
		for (var k in Menu.elemList) {
			if (Menu.elemList[k] === excludeMe) continue;
			total += Menu.elemList[k].getItemsCount();
		}
		return total;
	};
	Menu.getLandingMenu = function() {
		var elemList = Menu.getElemList(true);
		for (var k in elemList) {
			if (elemList[k].landing) return elemList[k];
		}
		return null;
	};
	Menu.updateEmptyLinks = function() {
		var elemList = Service.menu.getElemList(true);
		var updateItems = function(m) {
			if (!m.items) return;
			for (var id in m.items) {
				var mi = m.items[id];
				if (mi.type === 'internal' && mi.targetId && !(('#' + mi.targetId) in wb_builder.site.pages)) {
					mi.type = 'empty';
				}
				updateItems(mi);
			}
		};
		for (var k in elemList) {
			updateItems(elemList[k]);
		}
	};
	Menu.getElemList = function(includeStrange) {
		if (includeStrange) {
			var list = {}, uidIdx = {}, i, elem;
			for (i in Menu.elemList) {
				elem = Menu.elemList[i];
				if (elem.menuUID) uidIdx['#' + elem.menuUID] = true;
				list[i] = Menu.elemList[i];
			}
			for (i in Menu.strangeElemList) {
				elem = Menu.strangeElemList[i];
				if ((elem.menuUID && !(('#' + elem.menuUID) in uidIdx)) || !elem.menuUID) {
					if (elem.menuUID) uidIdx['#' + elem.menuUID] = true;
					list[i] = elem;
				}
			}
			return list;
		} else {
			return Menu.elemList;
		}
	};
	Menu.constructStrangeMenu = function(data) {
		var m = new Menu();
		m.menuType = 'strange';
		m.menuUID = data.content.menuUID ? data.content.menuUID : null;
		m.menuIndex = (Menu.lastIndex++);
		m.menuId = m.menuType + "_" + m.menuIndex;
		m.pageId = data.pageId ? data.pageId : null;
		m.isCommon = data.isCommon ? true : false;
		m.includePages = (data.includePages && (typeof data.includePages === 'object'))
				? data.includePages : {};
		m.items = {};
		(function() {
			var tree = [], map = {}, item, i;
			for (i = 0; i < data.content.tree.length; i++) {
				map[data.content.tree[i].id] = i;
				data.content.tree[i]._items = [];
			}
			for (i = 0; i < data.content.tree.length; i++) {
				item = data.content.tree[i];
				if (item.idp !== 0) {
					data.content.tree[map[item.idp]]._items.push(item);
				} else {
					tree.push(item);
				}
			}
			data.content.tree = tree;
		})();
		var addItems = function(m, tree) {
			for (var i in tree) {
				(function(data) {
					var mi = new Menu.MenuItem();
					mi.id = (data._ignoreId ? null : data.id);
					if (!mi.id) mi.id = mi.getFreeId();
					Menu.MenuItem.idReg['#' + mi.id] = true;
					mi.idp = data.idp ? data.idp : 0;
					mi.name = __tr(data.name, wb_builder.site.getLastDefLang()) ? data.name : __("New Item");
					mi.type = data.type ? data.type : 'page';
					mi.url = data.url;
					mi.targetId = data.targetId ? data.targetId : data.target_id;
					mi.type = mi.type ? mi.type : (mi.url ? 'external' : 'internal');
					mi.items = {};
					if (data._items) {
						addItems(mi, data._items);
					}
					m.items['#' + mi.id] = mi;
				})(tree[i]);
			}
		};
		addItems(m, data.content.tree);
		return m;
	};
	Menu.storeStrangeMenu = function(data) {
		var menu = Menu.constructStrangeMenu(data);
		Menu.strangeElemList[menu.menuId] = menu;
	};
	Menu.removeStrangeMenu = function(menu, tryUID) {
		if (!menu) return;
		if (menu.menuId && (menu.menuId in Menu.strangeElemList)) {
			delete Menu.strangeElemList[menu.menuId];
		} else if (tryUID && menu.menuUID) {
			for (var k in Menu.strangeElemList) {
				if (Menu.strangeElemList[k].menuUID === menu.menuUID) {
					delete Menu.strangeElemList[k];
				}
			}
		}
	};
	Menu.firstMenuLoadedCallback = null;
	Menu._editDialog = null;

	Menu.prototype.noPhotoBg = 'ico-tb-menu';
	/** @type {String} */
	Menu.prototype.menuUID = 0;
	Menu.prototype.menuIndex = 0;
	Menu.prototype.menuElem = null;
	Menu.prototype.menuTmp = null;
	Menu.prototype.pagesMenu = null;
	Menu.prototype.menuId = "";
	Menu.prototype.items = null;
	Menu.prototype.itemsTmp = {};
	Menu.prototype.menuType = "hmenu";
	Menu.prototype.noCollapse = false;
	Menu.prototype.menuItemTextTransform = null;
	Menu.prototype.menuItemPadding = 2;
	Menu.prototype.menuItemSpacing = 10;
	Menu.prototype.menuItemAlign = "left";
	Menu.prototype.txtNormal = null;
	Menu.prototype.txtHover = null;
	Menu.prototype.txtActive = null;
	Menu.prototype.bgMenu = null;
	Menu.prototype.bgSubMenu = null;
	Menu.prototype.bgMobMenu = null;
	Menu.prototype.bgItemNormal = null;
	Menu.prototype.bgItemHover = null;
	Menu.prototype.bgItemActive = null;
	Menu.prototype.brdMenu = null;
	Menu.prototype.brdNormal = null;
	Menu.prototype.brdHover = null;
	Menu.prototype.brdActive = null;
	Menu.prototype.landing = null;
	Menu.prototype.editDialog = null;
	Menu.prototype.editDialogMode = null;
	Menu.prototype.origType = null;
	Menu.prototype._elemCollapseBtn = null;

	/**
	 * Construct menu element
	 * @param data menu data object
	 */
	Menu.prototype.__construct = function(data) {
		data.isCommon = ("isCommon" in data) ? (data.isCommon ? true : false) : true;
		data.isMenu = true;

		if (!data.width) {
			data.width = 200;
			data.height = 200;
		}
		Element.prototype.__construct.call(this, data);
		var thisClass = this;

		//clone first menu style data if empty
		if ($.isEmptyObject(data.content) && !$.isEmptyObject(Menu.elemList)) {
			//get 1st menu
			$.each(Menu.elemList, function(i, menu) {
				//params we take from menu
				var params = ['brdActive', 'brdHover', 'brdNormal', 'brdMenu', 'bgSubMenu', 'bgMobMenu', 'bgMenu', 'bgItemActive', 'bgItemHover', 'bgItemNormal', 'txtActive', 'txtHover', 'txtNormal', 'menuItemAlign', 'menuType', 'menuItemPadding', 'menuItemSpacing'];
				/*
				if (menu.elem) {
					data.height = menu.elem.height();
				}
				*/
				$.each(params, function(i, param) {
					if (menu[param])
						data.content[param] = menu[param];
				});

				return false;
			});
		}

		this.setEmtyMessageText(__("Double click to add menu items"));
		this.displayEmtyMessage(true);

		this.menuType = (data.content.menuType === "vmenu") ? "vmenu" : "hmenu";
		this.noCollapse = data.content.noCollapse ? true : false;
		this.menuUID = data.content.menuUID ? data.content.menuUID : null;
		if (!this.menuUID || data._copy) this.menuUID = HasherUtil.crc32Hex('' + (new Date()).getTime());
		this.menuIndex = (Menu.lastIndex++);
		this.menuId = this.menuType + "_" + this.menuIndex;
		this.items = {};
		if (data.isStrange) {
			Menu.strangeElemList['strange_' + this.menuId] = this;
		} else {
			Menu.elemList[this.menuId] = this;
		}

		this.menuElem = $('<ul></ul>');
		this.menuElem.addClass(this.menuType);
		this.menuElem.attr("id", this.menuId);

		//var div = $('<div class="subnav"></div>');
		/* var div = $('<div class="navbar"><div class="navbar-inner"><div class="container"></div></div></div>');
		div.css({width: "100%", height: "100%", margin: "0px", padding: "0px"});
		div.children().first().css({height: "100%"});
		div.children().first().children().first().css({height: "100%"});
		$(".container", div).append(this.menuElem);
		this.container.append(div); */
		this.container.append(this.menuElem);
		//this.controls.append(this.menuElem);
		this.container.css({ overflow: "hidden" });

		//this.cover.css("display", "none");
		this.cover.on("click mousemove", function(e) {
			var px = e.pageX, py = e.pageY, isHover = false;
			for (var k in thisClass.items) {
				var mio = thisClass.items[k].elem.offset();
				var mis = {width: thisClass.items[k].elem.width(), height: thisClass.items[k].elem.height()};
				if (px >= mio.left && px <= (mio.left + mis.width) && py >= mio.top && py <= (mio.top + mis.height)) {
					if (e.type === "click") {
						thisClass.items[k].elem.find("a").eq(0).trigger("click");
					}
					isHover = true;
					break;
				}
			}
			if (e.type === "mousemove") {
				thisClass.cover.css("cursor", (isHover ? "pointer" : "default"));
			}
		});
		// deserialize

		var menu = data.content.tree ? data.content.tree : [];
		var miList = {}, i;

		for (i = 0; i < menu.length; i++) {
			var mi = new Menu.MenuItem(menu[i]);
			miList["#" + mi.id] = mi;
		}

		for (i in miList) {
			if (miList[i].idp && parseInt(miList[i].idp, 10) !== parseInt(miList[i].id, 10) && miList["#" + miList[i].idp]) {
				miList["#" + miList[i].idp].addItem(miList[i]);
			} else {
				miList[i].idp = 0;
				this.addItem(miList[i]);
			}
		}

		this.menuType = data.content.menuType ? data.content.menuType : this.menuType;
		this.menuItemTextTransform = data.content.menuItemTextTransform ? data.content.menuItemTextTransform : null;
		this.menuItemPadding = data.content.menuItemPadding ? data.content.menuItemPadding : this.menuItemPadding;
		this.menuItemSpacing = data.content.menuItemSpacing ? data.content.menuItemSpacing : this.menuItemSpacing;
		this.menuItemAlign = data.content.menuItemAlign ? data.content.menuItemAlign : this.menuItemAlign;

		this.txtNormal = data.content.txtNormal ? data.content.txtNormal : {
			color: "#2c2c2c",
			size: 22,
			decoration: "none",
			font: "Arial,sans-serif",
			style: { },
			align: this.menuItemAlign,
			css: {
				font: "normal normal 22px Arial,sans-serif",
				color: "#2c2c2c",
				"text-decoration": "none"
			}
		};
		this.txtHover = data.content.txtHover ? data.content.txtHover : {
			color: "#43852d",
			size: 22,
			decoration: "none",
			font: "Arial,sans-serif",
			style: { },
			align: this.menuItemAlign,
			css: {
				font: "normal normal 22px Arial,sans-serif",
				color: "#43852d",
				"text-decoration": "none"
			}
		};
		this.txtActive = data.content.txtActive ? data.content.txtActive : {
			color: "#43852d",
			size: 22,
			decoration: "none",
			font: "Arial,sans-serif",
			style: { },
			align: this.menuItemAlign,
			css: {
				font: "normal normal 22px Arial,sans-serif",
				color: "#43852d",
				"text-decoration": "none"
			}
		};
		delete this.txtNormal.css["text-align"];
		delete this.txtHover.css["text-align"];
		delete this.txtActive.css["text-align"];
		this.bgItemNormal = data.content.bgItemNormal ? data.content.bgItemNormal : {
			color: "transparent",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "transparent none repeat scroll left top" }
		};
		this.bgItemHover = data.content.bgItemHover ? data.content.bgItemHover : {
			color: "transparent",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "transparent none repeat scroll left top" }
		};
		this.bgItemActive = data.content.bgItemActive ? data.content.bgItemActive : {
			color: "transparent",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "transparent none repeat scroll left top" }
		};
		this.bgMenu = data.content.bgMenu ? data.content.bgMenu : {
			color: "transparent",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "transparent none repeat scroll left top" }
		};
		this.bgSubMenu = data.content.bgSubMenu ? data.content.bgSubMenu : {
			color: "#2e2e2e",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "#2e2e2e none repeat scroll left top" }
		};
		this.bgMobMenu = data.content.bgMobMenu ? data.content.bgMobMenu : {
			color: "#bcbcbc",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "#bcbcbc none repeat scroll left top" }
		};
		this.brdMenu = data.content.brdMenu ? data.content.brdMenu : {
			color: "#000000",
			style: "none",
			weight: 0,
			css: { border: "none" }
		};
		this.brdNormal = data.content.brdNormal ? data.content.brdNormal : {
			color: "#000000",
			style: "none",
			weight: 0,
			css: { border: "none" }
		};
		this.brdHover = data.content.brdHover ? data.content.brdHover : {
			color: "#000000",
			style: "none",
			weight: 0,
			css: { border: "none" }
		};
		this.brdActive = data.content.brdActive ? data.content.brdActive : {
			color: "#000000",
			style: "none",
			weight: 0,
			css: { border: "none" }
		};
		this.landing = data.content.landing ? true : false;
		this.setMinSize(null, 24);

		if (!data.id && !data._copy) {
			this.openEditMenuItems(true);
		}
		/*
		// generate menu items for new menu
		if (!data.id && !data._copy) {
			var page = null, copyFrom = null;
			//find non-front page to copy from (or front if no other pages present)
			for (var pid in this.system.site.pages) {
				if (!copyFrom) copyFrom = this.system.site.pages[pid];
				if (this.system.site.pages[pid].isFront) continue;
				copyFrom = this.system.site.pages[pid];
				break;
			}
			//check if we have a page w/o menu as a single-page site
			var singlePage = null;
			$.each(this.system.site.pages, function(num, page) {
				if (page.isSingle) {
					singlePage = page;
				}
				//should have one and only (if exists)
				return false;
			});

			if (singlePage) {
				this.addItem(new Menu.MenuItem({
					name: (singlePage.title),
					targetId: singlePage.id,
					type: 'page'
				}));
			}
			else {
				var d = (copyFrom) ? copyFrom.serialize() : {};
				d.saved = false;
				this.system.site.addPage((page = new Site.Page($.extend(true, d, {
					id: this.system.site.getFreeId(),
					title: (__("New Item") + " 1"),
					isFront: false,
					copyFrom: (copyFrom ? copyFrom.id : null)
				}))));
				this.addItem(new Menu.MenuItem({
					name: (__("New Item") + " 1"),
					targetId: page.id,
					type: 'page'
				}));
			}

			var d = (copyFrom) ? copyFrom.serialize() : {};
			d.saved = false;
			this.system.site.addPage((page = new Site.Page($.extend(true, d, {
				id: this.system.site.getFreeId(),
				title: (__("New Item") + " 2"),
				isFront: false,
				copyFrom: (copyFrom ? copyFrom.id : null)
			}))));
			this.addItem(new Menu.MenuItem({
				name: (__("New Item") + " 2"),
				targetId: page.id,
				type: 'page'
			}));
		} */
		
		if (data._copy) {
			// convert menu item type "page" to "internal"
			this.convertItemsFromPageToInternal();
		}

		this._elemCollapseBtn = $('<a>').addClass('btn btn-default btn-collapser').appendTo(this.container);
		this._elemCollapseBtn.append('<span class="icon-bar"></span>');
		this._elemCollapseBtn.append('<span class="icon-bar"></span>');
		this._elemCollapseBtn.append('<span class="icon-bar"></span>');

		this.updateStyle(true);

		this.elem.bind("resize", function() {
			thisClass.onResize();
		});

		setTimeout(function() {
			thisClass.updateStyle(true);
		}, 1000);

		$(this.controls).bind("dblclick", function(e) {
			if (thisClass.menuElem.children("li").size() > 0) {
				thisClass.comProperties();
				thisClass.comDialog.tabbedPane.selectTab(0);
			} else {
				thisClass.openEditMenuItems(true);
			}
		});

		BuilderEvent.GlobalEvents.triggerEvent('pages.changed', new BuilderEvent.PagesChangedBuilderEvent());
		this.modeContextOk.goTo = true;
	};
	
	Menu.prototype.convertItemsFromPageToInternal = function() {
		for (var i in this.items) {
			if (this.items[i].type === 'page') {
				this.items[i].type = 'internal';
			}
			this.convertItemsFromPageToInternal.call(this.items[i]);
		}
	};

	Menu.prototype.supportsFullWidth = function() {
		return true;
	};

	Menu.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = this.isFullWidth ? '' : 'e, w';
	};

	Menu.prototype.onResize = function(onConstruct, onlySelf) {
		if (!onlySelf) Element.prototype.onResize.call(this, onConstruct);

		if (this.menuType === 'hmenu') {
			this.updateElemHeight();
		}
		this.elem.trigger("elementresize", [this]);
	};
	
	Menu.prototype.fitToParent = function(preserveAspectRatio, oriBounds, initial) {
		Element.prototype.fitToParent.call(this, preserveAspectRatio, oriBounds, initial);
		this.onResize(false, true);
	};

	/** @param {String} mode */
	Menu.prototype.switchMode = function(fromMode, toMode, initial, manual) {
		Element.prototype.switchMode.call(this, fromMode, toMode, initial, manual);
		if (!Service.modeManager.getUseModes()) return;
		if (toMode === ModeManager.MODE_PHONE && !this.noCollapse) {
			this.container.addClass('collapsed');
		} else {
			this.container.removeClass('collapsed');
		}
	};
	
	/** @return {Object} */
	Menu.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this), txt = '';
		for (var k in this.items) { txt += (txt.length ? ' | ' : '') + __tr(this.items[k].name); }
		opts.text = txt.substring(0, 100);
		if (opts.text.length < txt.length) opts.text += '...';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	Menu.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);
		
		data.content = {
			menuUID: this.menuUID,
			tree: this.serializeItems(),
			menuType: this.menuType,
			noCollapse: this.noCollapse,
			menuItemTextTransform: this.menuItemTextTransform,
			menuItemPadding: this.menuItemPadding,
			menuItemSpacing: this.menuItemSpacing,
			menuItemAlign: this.menuItemAlign,
			txtNormal: this.txtNormal,
			txtHover: this.txtHover,
			txtActive: this.txtActive,
			bgItemNormal: this.bgItemNormal,
			bgItemHover: this.bgItemHover,
			bgItemActive: this.bgItemActive,
			bgMenu: this.bgMenu,
			bgSubMenu: this.bgSubMenu,
			bgMobMenu: this.bgMobMenu,
			brdMenu: this.brdMenu,
			brdNormal: this.brdNormal,
			brdHover: this.brdHover,
			brdActive: this.brdActive,
			landing: this.landing,
			// landingContentOffset: this.landingContentOffset
		};

		return data;
	};

	/**
	 * Serialize all items in this menu
	 * @param {Array} src
	 * @param {Array} dest
	 * @return object
	 */
	Menu.prototype.serializeItems = function(src, dest) {
		if (!dest) dest = [];
		if (!src) src = this.items;
		for (var i in src) {
			dest.push(src[i].serialize());
			this.serializeItems(src[i].items, dest);
		}
		return dest;
	};

	/**
	 * Add menu item
	 * @param {Menu.MenuItem} mi menu item as WB_Menu.MenuItem
	 * @param {Number} idx index to add menu item at
	 * @param {Boolean} tmp
	 */
	Menu.prototype.addItem = function(mi, idx, tmp) {
		tmp = (typeof(tmp) === "undefined") ? false : tmp; 
		if (idx === null || typeof(idx) === "undefined") idx = -1;
		if (mi.parent) {
			mi.parent.removeItem(mi, tmp);
		} else if (!tmp && mi.menu) {
			mi.menu.removeItem(mi, tmp);
		}

		var items = (tmp ? this.itemsTmp : this.items), sortedItems;

		items["#" + mi.id] = mi;
		if (!tmp) {
			if (idx >= 0 && idx < this.menuElem.children().size()) {
				$(this.menuElem.children().get(idx)).before(mi.elem);
				sortedItems = {};
				this.menuElem.children().each(function() {
					var mi = $(this).wbGetClassInstance();
					sortedItems["#" + mi.id] = mi;
				});
				items = sortedItems;
			} else {
				this.menuElem.append(mi.elem);
			}
		}
		else {
			sortedItems = {};
			var ct = 0;
			$.each(items, function(id, el){
				if (ct === idx) {
					sortedItems["#" + mi.id] = mi;
				}
				if (el.id != mi.id) {
					sortedItems["#" + el.id] = el;
				}
				ct++;
			});

			this.itemsTmp = sortedItems;
		}


		mi.idp = 0;
		mi.setMenu(this);
		mi.parent = null;
	};

	/**
	 * Copy and add all items from provided menu item
	 * @param {Menu.MenuItem} mi menu item
	 * @param {Menu.MenuItem} subMi menu item to add to
	 */
	Menu.prototype.addAllItems = function(mi, subMi) {
		if (subMi && subMi.menu && subMi.menu !== this) return;
		var i, k, item, target = (subMi ? subMi : this);
		if (mi instanceof TreeListControl.Item) {
			for (i = 0; i < mi.getItemCount(); i++) {
				item = new Menu.MenuItem(mi.getItem(i).getOriginal());
				target.addItem(item);
				this.addAllItems(mi.getItem(i), item);
			}
		} else {
			for (k in mi.items) {
				item = new Menu.MenuItem(mi.items[k].serialize());
				target.addItem(item);
				this.addAllItems(mi.items[k], item);
			}
		}
	};

	/**
	 * Remove menu item
	 * @param {Menu.MenuItem} mi menu item
	 * @param tmp something tmp
	 */
	Menu.prototype.removeItem = function(mi, tmp) {
		var items = tmp ? this.itemsTmp : this.items;
		items["#" + mi.id] = null;		
		delete items["#" + mi.id];

		if (!tmp && mi.elem) {
			mi.setMenu(null);
			mi.parent = null;
			mi.elem.detach();
		}
	};

	/**
	 * Remove (and dispose of) all items from menu
	 */
	Menu.prototype.removeAllItems = function() {
		for (var k in this.items) {
			var mi = this.items[k];
			this.removeItem(mi);
			mi.dispose();
		}
		// IE remembers object property positions,
		// so without this sorting do not work on IE
		this.items = {};
	};
	
	Menu.prototype.getItemsCount = function() {
		if (Object.keys) {
			return Object.keys(this.items).length;
		} else {
			var count = 0;
			for (var i in this.items) {
				count++;
			}
			return count;
		}
	};

	/**
	 * Update style
	 * @param {String} langCode
	 */
	Menu.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var thisClass = this;

		if (this.menuElem.children().size() === 0) {
			this.displayEmtyMessage(true);
			this.menuElem.hide();
		} else {
			this.displayEmtyMessage(false);
			this.menuElem.show();
		}

		var css = {};

		this.menuElem.removeClass("vmenu");
		this.menuElem.removeClass("hmenu");
		this.menuElem.addClass(this.menuType);

		var allItemsHidden = true;
		for (var i in this.items) {
			var item = this.items[i];
			if (!item.noMenu) {
				allItemsHidden = false;
				break;
			}
		}
		if (allItemsHidden) {
			this.elem.addClass('wb-menu-hidden');
		} else {
			this.elem.removeClass('wb-menu-hidden');
		}
		this.menuElem.children("li").each(function() {
			$("a", this).css($.extend(
					{padding: SizeSelector.toCSS(thisClass.menuItemPadding)},
					((thisClass.menuItemTextTransform && typeof(thisClass.menuItemTextTransform) === "object") ? thisClass.menuItemTextTransform.css : {})
				));
			if ($(this).hasClass("active")) {
				css = $.extend({}, thisClass.txtActive.css);
				css = $.extend(css, thisClass.bgItemActive.css);
			} else {
				css = $.extend({}, thisClass.txtNormal.css);
				css = $.extend(css, thisClass.bgItemNormal.css);
			}
			css.background = css.background.replace("url('", "url('" + wb_builder.userBaseUrl);
			delete css["text-align"];
			$(this).children("a").css(css);
		});
		/*for (var mk in this.items) {
			var mi = this.item[mk];
			if ((!mi.type || mi.type === "internal" || mi.type === "page") && mi.targetId) {
				mi.elem.find("a").on("click", function() {
					wb_builder.goToPage(mi.targetId);
				});
			}
		}*/
		this.menuElem.children("li").css({ margin: SizeSelector.toCSS(this.menuItemSpacing) });
		this.menuElem.children("li").css(this.brdNormal.css);
		var ww = 0;
		this.menuElem.children("li").each(function() {
			if ($(this).is(':not(:visible)')) { return true; }
			ww += $(this).outerWidth(true);
		});
		//if (ww < this.getWidth()) ww = this.getWidth();
		if (this.menuType === "vmenu") {
			this.menuElem.css({ minWidth: "auto" });
		} else {
			// this.menuElem.css({ minWidth: ww + "px" });
		}
		this.menuElem.css(this.brdMenu.css);
		css = $.extend({}, this.bgMenu.css);
		css.background = css.background.replace("url('", "url('" + wb_builder.userBaseUrl);
		this.menuElem.css(css);
		if (this.menuItemAlign === 'justify') {
			this.menuElem.css({display: 'flex', 'justify-content': 'space-between'});
			this.elem.css("text-align", '');
		} else {
			this.menuElem.css({display: '', 'justify-content': '', 'text-align': this.menuItemAlign});
			this.elem.css("text-align", this.menuItemAlign);
		}

		if (typeof Menu.firstMenuLoadedCallback === 'function' && Object.keys(Menu.elemList).length === 1)
			Menu.firstMenuLoadedCallback();
		
		if (ModeManager.getMode() === ModeManager.MODE_PHONE && !this.noCollapse) {
			this.container.addClass('collapsed');
		} else {
			this.container.removeClass('collapsed');
		}
		
		setTimeout(function() {
			thisClass.resizeMenuBox();
		}, 5);
	};

	Menu.prototype.openEditMenuItems = function(isNewItem) {
		var thisClass = this;
		if (!Menu._editDialog) {
			Menu._editDialog = new EditMenuItemsDialog();
			Menu._editDialog.onClose = function() {
				Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-end', thisClass);
			};
			if (wb_builder.maxMenuItems > 0) {
				Menu._editDialog.setLiteVersionMessage('<div class="wb-tiny-btn">' + (true && wb_builder.premiumButtonType === 'expired'
					? '<span style="color: #fff;">' + __('Ask administrator to enable this feature') + '</span>'
					: __('%sGo Premium%s to manage more than %d pages')
						.replace('%s', '<a' + (wb_builder.upgradeUrl ? ' href="' + wb_builder.upgradeUrl + '"' : '') + ' target="_blank">')
						.replace('%s', '</a>')
						.replace('%d', wb_builder.maxMenuItems))
				+ '</div>');
			}
		}
		if (isNewItem || !this.getItemsCount()) {
			Menu._editDialog.getNewDialog().setMenu(this, wb_builder.site.pages);
			Menu._editDialog.getNewDialog().setOnCancel(function() {
				if (!Object.keys(thisClass.items).length) thisClass.remove(true, true);
			});
			var canAdd = (wb_builder.maxMenuItems <= 0 || Menu.getTotalPages() < wb_builder.maxMenuItems);
			Menu._editDialog.getNewDialog().setDisabled(!canAdd);
			Menu._editDialog.getNewDialog().setVisible(true);
		} else {
			Menu._editDialog.setMenu(this, wb_builder.site.pages);
			Menu._editDialog.setVisible(true);
		}
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-menu-' + (isNewItem ? 'new' : 'edit'), this);
		Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-edit-start', this);
	};
	
	Menu.prototype.setLanding = function(landing) {
		this.landing = landing ? true : false;
	};

	/**
	 * Extend element properties dialog
	 */
	Menu.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 524, maxBodyHeight: 524}, // 420
			tabs: [
				{name: __('Menu Style'), children: [
					{type: 'FlowLayout', spacing: 20, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Align')},
							{type: 'HAlignSelector', id: 'menuItemAlign', justify: true, change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-menuItemAlign-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'brdMenu', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-brdMenu-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Type')},
							{type: 'VerticalLayout', id: 'menuType',
								children: [
									{type: 'RadioBox', label: __('Horizontal'), id: 'hmenu', group: ('wb_menu_' + this.id + '_menuType')},
									{type: 'RadioBox', label: __('Vertical'), id: 'vmenu', group: ('wb_menu_' + this.id + '_menuType')}
								],
								init: function() {
									this.getValue = function() {
										var val = 'hmenu';
										if (fields.hmenu.getValue()) {
											val = 'hmenu';
										} else if (fields.vmenu.getValue()) {
											val = 'vmenu';
										}
										return val;
									};
									this.setValue = function(val) {
										fields.hmenu.setValue((val === 'hmenu'));
										fields.vmenu.setValue((val === 'vmenu'));
									};
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Collapse on mobile')},
							{type: 'CheckBox', label: __('Do not collapse'), id: 'noCollapse'}
						]}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'BackgroundSelector', id: 'bgMenu', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-bgMenu-change', thisClass);
						}},
						{type: 'Label', text: __('Submenu background'), css: {marginTop: '10px'}},
						{type: 'BackgroundSelector', id: 'bgSubMenu', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-bgSubMenu-change', thisClass);
						}},
						{type: 'Label', text: __('Mobile menu background'), css: {marginTop: '10px'}},
						{type: 'BackgroundSelector', id: 'bgMobMenu', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-bgMobMenu-change', thisClass);
						}}
					], styleClass: 'modal-body-inscroll', css: {height: 365, overflowY: 'auto', marginTop: '10px'}}
				]},
				{name: __('Menu Item Style'), type: 'menuItemStyles', children: [
					{type: 'FlowLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Font')},
							{type: 'FlowLayout', spacing: -1, children: [
								{type: 'FontFamilySelector', id: 'txtFont', css: {width: 140}, change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-txtFont-change', thisClass);
								}},
								{type: 'Button', icon: "glyphicon glyphicon-pencil", click: function(e, fields) {
									fields.txtFont.getWrappedControl().openEditFontsDialog();
								}}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'txtSize', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-txtSize-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Letter spacing')},
							{type: 'SizeSelector', id: 'txtLetterSpacing', min: -100, precision: 2, step: 0.01, value: 0}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Text Transform')},
							{type: 'FontTransformSelector', id: 'menuItemTextTransform'}
						]}
					]},
					{type: 'FlowLayout', children: [
						{type: 'VerticalLayout', css: {margin: "10px 0"}, children: [
							{type: 'Label', text: __('Spacing')},
							{type: 'SpacingSelector', id: 'menuItemSpacing'}
						]}
					]},
					{type: 'TabbedPane', fixedHeight: 180, noScroll: true, tabs: [
						{name: __('Item'), children: [
							{type: 'FlowLayout', css: {marginTop: 10}, children: [
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Style')},
									{type: 'FontStyleSelector', id: 'textNormalStyle', change: function() {
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-textNormalStyle-change', thisClass);
									}}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Color')},
									{type: 'ColorSelector', id: 'textNormalColor', noTransparent: true, change: function() {
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-textNormalColor-change', thisClass);
									}}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Border')},
									{type: 'BorderSelector', id: 'brdNormal', change: function() {
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-brdNormal-change', thisClass);
									}}
								]}
							]},
							{type: 'Label', text: __('Background'), css: {marginTop: 10}},
							{type: 'BackgroundSelector', id: 'bgNormal', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-bgNormal-change', thisClass);
							}}
						]},
						{name: __('Item: Hover'), children: [
							{type: 'FlowLayout', css: {marginTop: 10}, children: [
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Style')},
									{type: 'FontStyleSelector', id: 'textHoverStyle'}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Color')},
									{type: 'ColorSelector', id: 'textHoverColor', noTransparent: true}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Border')},
									{type: 'BorderSelector', id: 'brdHover'}
								]}
							]},
							{type: 'Label', text: __('Background'), css: {marginTop: 10}},
							{type: 'BackgroundSelector', id: 'bgHover'}
						]},
						{name: __('Item: Active'), children: [
							{type: 'FlowLayout', css: {marginTop: 10}, children: [
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Style')},
									{type: 'FontStyleSelector', id: 'textActiveStyle'}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Color')},
									{type: 'ColorSelector', id: 'textActiveColor', noTransparent: true}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Border')},
									{type: 'BorderSelector', id: 'brdActive'}
								]}
							]},
							{type: 'Label', text: __('Background'), css: {marginTop: 10}},
							{type: 'BackgroundSelector', id: 'bgActive'}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.menuItemAlign = fields.menuItemAlign.getValue();
				thisClass.brdMenu = fields.brdMenu.getValue();
				thisClass.menuType = fields.menuType.getValue();
				thisClass.noCollapse = fields.noCollapse.getValue();
				thisClass.bgMenu = fields.bgMenu.getValue();
				thisClass.bgSubMenu = fields.bgSubMenu.getValue();
				thisClass.bgMobMenu = fields.bgMobMenu.getValue();
				thisClass.brdNormal = fields.brdNormal.getValue();
				thisClass.brdHover = fields.brdHover.getValue();
				thisClass.brdActive = fields.brdActive.getValue();

				thisClass.menuItemTextTransform = fields.menuItemTextTransform.getValue();

				// backward compatibility to old format
				var spc = fields.menuItemSpacing.getValue();
				thisClass.menuItemPadding = [ spc.paddingTop, spc.paddingRight, spc.paddingBottom, spc.paddingLeft ];
				thisClass.menuItemSpacing = [ spc.marginTop, spc.marginRight, spc.marginBottom, spc.marginLeft ];

				thisClass.txtNormal = TextControl.combine(
					fields.txtFont,
					fields.txtSize,
					fields.textNormalColor,
					fields.textNormalStyle,
					null,
					fields.txtLetterSpacing
				);
				delete thisClass.txtNormal.css["text-align"];

				thisClass.txtHover = TextControl.combine(
					fields.txtFont,
					fields.txtSize,
					fields.textHoverColor,
					fields.textHoverStyle,
					null,
					fields.txtLetterSpacing
				);
				delete thisClass.txtHover.css["text-align"];

				thisClass.txtActive = TextControl.combine(
					fields.txtFont,
					fields.txtSize,
					fields.textActiveColor,
					fields.textActiveStyle,
					null,
					fields.txtLetterSpacing
				);
				delete thisClass.txtActive.css["text-align"];

				thisClass.bgItemNormal = fields.bgNormal.getValue();
				thisClass.bgItemHover = fields.bgHover.getValue();
				thisClass.bgItemActive = fields.bgActive.getValue();
				
				// thisClass.setLanding(fields.landing.getValue());
				// thisClass.system.site.landingContentOffset = fields.landingContentOffset.getValue();

				thisClass.updateStyle();
//				thisClass.resizeMenuBox();
			}
		});

		fields.menuItemAlign.setValue(this.menuItemAlign);
		fields.brdMenu.setValue(this.brdMenu);
		fields.menuType.setValue(this.menuType);
		fields.noCollapse.setValue(this.noCollapse);
		fields.bgMenu.setValue(this.bgMenu);
		fields.bgSubMenu.setValue(this.bgSubMenu);
		fields.bgMobMenu.setValue(this.bgMobMenu);
		fields.brdNormal.setValue(this.brdNormal);
		fields.brdHover.setValue(this.brdHover);
		fields.brdActive.setValue(this.brdActive);
		// fields.landing.setValue(this.landing);
		// fields.landingContentOffset.setValue(this.system.site.landingContentOffset);
		/* if (!Menu.elemLanding || Menu.elemLanding === this) {
			fields.landingContent1._elem.show();
			fields.landingContent2._elem.hide();
		} else {
			fields.landingContent1._elem.hide();
			fields.landingContent2._elem.show();
		} */

		fields.menuItemTextTransform.setValue(this.menuItemTextTransform);

		// backward compatibility to old format
		var val;
		if (!this.menuItemPadding.length) {
			val = isNaN(parseInt(this.menuItemPadding, 10)) ? 0 : parseInt(this.menuItemPadding, 10);
			this.menuItemPadding = [val, val, val, val];
		} else if (this.menuItemPadding.length === 2) {
			this.menuItemPadding[2] = this.menuItemPadding[0];
			this.menuItemPadding[3] = this.menuItemPadding[1];
		} else if (this.menuItemPadding.length !== 4) {
			this.menuItemPadding = [0, 0, 0, 0];
		}
		if (!this.menuItemSpacing.length) {
			val = isNaN(parseInt(this.menuItemSpacing, 10)) ? 0 : parseInt(this.menuItemSpacing, 10);
			this.menuItemSpacing = [val, val, val, val];
		} else if (this.menuItemSpacing.length === 2) {
			this.menuItemSpacing[2] = this.menuItemSpacing[0];
			this.menuItemSpacing[3] = this.menuItemSpacing[1];
		} else if (this.menuItemSpacing.length !== 4) {
			this.menuItemSpacing = [0, 0, 0, 0];
		}
		fields.menuItemSpacing.setValue({
			paddingTop: this.menuItemPadding[0],
			paddingRight: this.menuItemPadding[1],
			paddingBottom: this.menuItemPadding[2],
			paddingLeft: this.menuItemPadding[3],
			marginTop: this.menuItemSpacing[0],
			marginRight: this.menuItemSpacing[1],
			marginBottom: this.menuItemSpacing[2],
			marginLeft: this.menuItemSpacing[3]
		});

		fields.txtFont.setValue(this.txtNormal.font);
		fields.txtSize.setValue(this.txtNormal.size);
		fields.txtLetterSpacing.setValue(("letterSpacing" in this.txtNormal) ? this.txtNormal.letterSpacing : 0);

		fields.textNormalColor.setValue(this.txtNormal.color);
		fields.textNormalStyle.setValue(this.txtNormal.style);
		fields.textHoverColor.setValue(this.txtHover.color);
		fields.textHoverStyle.setValue(this.txtHover.style);
		fields.textActiveColor.setValue(this.txtActive.color);
		fields.textActiveStyle.setValue(this.txtActive.style);

		fields.bgNormal.setValue(this.bgItemNormal);
		fields.bgHover.setValue(this.bgItemHover);
		fields.bgActive.setValue(this.bgItemActive);
	};

	Menu.prototype.comPropertiesField = function(field) {
		var m, dialog;
		if (field && (m = field.match(/^menu\-(.+)$/))) {
			if (!Menu._editDialog) return null;
			m = m[1].split('-');
			
			if (m[0] === 'new') {
				dialog = Menu._editDialog.getNewDialog();
			} else if (m[0] === 'edit') {
				dialog = Menu._editDialog;
			}
			
			if (m[1] === 'apply') {
				return dialog.primaryButton ? {
					_elem: dialog.primaryButton,
					getElem: function() { return this._elem; }
				} : null;
			} else if (m[1].match(/^select\:[0-9]+$/i)) {
				var item = dialog.getTreeRootItem(m[1].split(':')[1] * 1);
				return item ? {
					_elem: item._elem,
					getElem: function() { return this._elem; }
				} : null;
			} else if ((m[1] in dialog.fields) && dialog.fields[m[1]]) {
				return dialog.fields[m[1]];
			}
			return null;
		}
		return Element.prototype.comPropertiesField.call(this, field);
	};
	
	Menu.prototype.applyComProperties = function(type) {
		var m, dialog;
		if (type && (m = type.match(/^menu\-(.+)$/))) {
			if (!Menu._editDialog) return;
			m = m[1].split('-');

			if (m[0] === 'new') {
				dialog = Menu._editDialog.getNewDialog();
			} else if (m[0] === 'edit') {
				dialog = Menu._editDialog;
			}

			if (m[1] === 'apply') {
				dialog._applyAction();
			} else if (m[1].match(/^select\:[0-9]+$/i)) {
				var idx = m[1].split(':')[1] * 1;
				dialog.selectTreeRootItem(idx);
				Service.HelpSystemPlayer.notify('item-plugin-' + this.getClassType() + '-menu-edit-select:' + idx, this);
			}
			return;
		}
		Element.prototype.applyComProperties.call(this, type);
	};

	Menu.prototype.toggleDialogMode = function(type, fields) {
		if (this.editDialogMode === type) return;
		if (type === "add") {
			this.reloadTree(fields.miList);
			fields.miId.val(null).removeData();
			if (this.editDialog)
				this.editDialog.buttons.children("[iid='" + __("Save") + "']").html(__("Add"));
			//uncheck radios
			fields.miType.input.find("input").removeAttr("checked");
			fields.miType.input.find("input:first").attr("checked", "checked");
			fields.miType.input.find("input").change();
			//show blank radio
			fields.miType.input.find("input[value='blank']").parent().show();
			//empty fields
			fields.miName.setValue("");
			fields.miTypePages.setValue("");
			fields.miTypeUrl.setValue('http://');
			fields.miTarget.setValue("");
			if (fields.miNoMenu) { fields.miNoMenu.setValue(false); }
		}
		else {
			if (this.editDialog) {
				this.editDialog.buttons.children("[iid='" + __("Save") + "']").html(__("Save"));
				// this.editDialog.buttons.children("[iid='" + __("Save") + "']").removeClass("hide2");
			}
			//remove blank radio
			fields.miType.input.find("input[value='blank']").parent().hide();
		}
		//focus
		// fields.miName.input.focus();

		this.editDialogMode = type;
	};

	Menu.prototype.reloadTree = function(tree, noRefresh) {
		if (!noRefresh) tree.jstree("refresh", -1);
		tree.find("li").unbind("mouseenter").unbind("mouseleave").each(function() {
			var thisLi = $(this);
			var btn = thisLi.children("button.btn");
			if (btn.size() === 0) {
				btn = $('<button class="btn btn-mini btn-link jstree-x-btn"><i class="icon-remove"></i></button>').bind("click", function() {
					tree.jstree("remove", thisLi);
				});
				thisLi.append(btn);
			}
		}).mouseenter(function(e) {
			e.stopPropagation();
			var th = this;
			tree.find("button").hide();
			if ($(this).parents("li").length) {
				setTimeout(function(){
					tree.find("button").hide();
					$(th).children("button").show();
				}, 1);
			}
			else 
				$(this).children("button").show();
		}).mouseleave(function() {
			$(this).children("button").hide();
			$(this).parents("li").mouseenter();
		});
	};

	Menu.prototype.pagesPre = {};

	/**
	 * Reloads menu from a given list object
	 * @param {Array} items
	 * @param {Number} lvl
	 * @param {Object} parent
	 */
	Menu.prototype.reloadMenu = function(items, lvl, parent) {
		var thisClass = this;
		if (!lvl) {
			lvl = 0;
			//remove old items, Why not using this.removeAllItems() ?
			if (typeof this.items === 'object' && this.items !== null) {
				$.each(this.items, function(i, item){
					thisClass.removeItem(item);
				});
			}
		}
		lvl++;
		$.each(items, function(i, item) {
			item.id = String(item.id);
			item.targetId = String(item.targetId);
			item.idp = String(item.idp);
			var id = item.id.substr(0, 1) === 'p' ? item.id.substr(1) : item.id;
			var target = item.targetId.substr(0, 1) === 'p' ? item.targetId.substr(1) : item.targetId;
			var idp = item.idp.substr(0, 1) === 'p' ? item.idp.substr(1) : item.idp;
			item.idp = idp;
			var page;
			//need new page
			if (item.type && (item.type === 'internal' || item.type === 'page')) {
				if (item.id === item.targetId) {
					//page created?
					if (thisClass.pagesPre[id])
						item.targetId = thisClass.pagesPre[id];
					//create page
					else {
						page = new Site.Page({});
						page.title = item.name;
						page.id = thisClass.system.site.getFreeId();
						thisClass.system.site.addPage(page);
						item.targetId = page.id;
						thisClass.pagesPre[id] = page.id;
					}
				}
				else if (item.targetId.substr(0, 1) === 'p') {
					//page created?
					if (thisClass.pagesPre[target])
						item.targetId = thisClass.pagesPre[target];
					//create page
					else {
						page = new Site.Page({});
						page.title = item.name;
						page.id = thisClass.system.site.getFreeId();
						thisClass.system.site.addPage(page);
						item.targetId = page.id;
						thisClass.pagesPre[target] = page.id;
					}
				}
				else 
					thisClass.pagesPre[id] = target;
			}
			else if(!item.type && target && item.targetId.substr(0, 1) !== 'p') {
				thisClass.pagesPre[id] = target;
			}
			item.id = id;

			var mi = new Menu.MenuItem(item);
			if (item.items) {
				thisClass.reloadMenu(item.items, lvl, mi);
			}

			if (lvl === 1) {
				thisClass.addItem(mi);
			}
			else if (parent) {
				parent.addItem(mi, null, false);	
			}
		});
		if (lvl === 1) {
			//deleting unused pages 
			//WB_Menu.deleteUnusedPages(); // commented because it works very wrong
		}
	};

	Menu.getUsedPages = function(menu) {
		var pages = {};
		if (!$.isEmptyObject(menu.items)) {
			$.each(menu.items, function(i, item) {
				if(item.targetId && ((typeof(item.type) === "undefined" && !item.url) || (item.type === 'internal' || item.type === 'page'))) {
					pages[item.targetId] = item.id;
				}
				if (!$.isEmptyObject(item.items)) {
					pages = $.extend(pages, Menu.getUsedPages(item));
				}
			});
		}
		return pages;
	};

	Menu.getAllUsedPages = function() {
		var pages = {};

		$.each(Menu.elemList, function(num, menu) {
			pages = $.extend(pages, Menu.getUsedPages(menu));
		});

		return pages;
	};

	/**
	 * Delete unused pages
	 * @FIXME need alert to say that pages will be deleted?
	 */
	Menu.deleteUnusedPages = function() {
		//used pages id's
		var pages = Menu.getAllUsedPages();
		var pgs = {};
		$.each(pages, function(i, v) {
			pgs['#' + i] = 1; 
		});
		//if all menu items deleted - keep current page
		var keepPage = $.isEmptyObject(pgs) ? '#' + wb_builder.pageId : null;
		for (var pid in wb_builder.site.pages) {
			if (!pgs[pid] && pid != keepPage) {
				wb_builder.site.removePage(wb_builder.site.pages[pid]);
			}
			else {
				wb_builder.site.pages[pid].isSingle = true;
			}
		}
	};

	Menu.prototype.updateElemHeight = function() {
		if (ModeManager.getMode() === ModeManager.MODE_PHONE && !this.noCollapse) {
			if (this._elemCollapseBtn) {
				this.elem.css("height", this._elemCollapseBtn.outerHeight(true) + "px");
				this.parent.updateSize();
			}
		} else {
			if (this.menuElem && this.menuElem.children('li').length > 0) {
				this.elem.css("height", this.menuElem.outerHeight(true) + "px");
				this.parent.updateSize();
			}
		}
	};
	
	Menu.prototype.setSize = function(width, height) {
		if( this.isFullWidth )
			this.elem.css({width: "", right: 0});
		else if (width)
			this.elem.css({width: width + "px", right: ""});
		if (height) {
			$(this.elem).css("height", height + "px");
		} else {
			this.updateElemHeight();
		}
	};

	/**
	 * Resize menu parent box
	 */
	Menu.prototype.resizeMenuBox = function() {
		if (ModeManager.getMode() === ModeManager.MODE_PHONE && !this.noCollapse)
			return;
		if (this.menuType === "hmenu") {
			var items = this.menuElem.children("li");
			if (items.length > 0) {
				var ih = this.menuElem.children('li:first').outerHeight(true);
				if (this.elem.height() === ih) {
					var w = 0;
					items.each(function(){
						if ($(this).css("display") === "none") return;
						var ew = $(this).outerWidth() + parseInt($(this).css("margin-left"), 10) + parseInt($(this).css("margin-right"), 10);
						w = w + ew;
					});
					if (w > this.elem.width()) {
						this.setSize(w + 2);
					}
				} else {
					this.updateElemHeight();
				}
			}
		}
		else {
			this.updateElemHeight();
		}
		this.fitToParent();
	};

	/**
	 * Clone o_0
	 * @param {Object} obj object to clone
	 */
	Menu.prototype.cloneItems = function(obj) {
		var CloneObj = {};
		// CloneObj.clear();
		//items list iteration
		var thisClass = this;
		jQuery.each(obj, function(i, val) {
			var newObject = jQuery.extend(true, {}, val);
			//menu item params
			jQuery.each(newObject, function(i, val) {
				if (i === 'items') {
					var its = {};
					jQuery.each(val, function(it, mi) {
						var nm = new Menu.MenuItem(mi);	
						nm.parent = newObject;
						its[it] = nm;
					});
					newObject[i] = its;
				}
			});

			CloneObj[i] = newObject;
		});
		return CloneObj;
	};

	Menu.prototype.initContextMenu = function(elem) {
		Element.prototype.initContextMenu.call(this, elem);
		if (!this.menu) return;

		var idx = this.contextMenuFirstIndex;	
		var thisClass = this;

		this.menu.insertItemAt(idx++, 'newMenu', __("New Menu Item"), function() {
			thisClass.openEditMenuItems(true);
		}, null, null, null, "glyphicon glyphicon-plus");
		this.menu.insertItemAt(idx++, 'editManu', __("Edit Menu"), function() {
			thisClass.openEditMenuItems(false);
		}, null, null, null, "glyphicon glyphicon-pencil");

		this.pagesMenu = new ContextMenu();

		this.menu.insertItemAt(idx++, "goTo", __("Go to page"), this.pagesMenu,
			null, null, null, "glyphicon glyphicon-folder-open");
		this.pagesMenu.setHeight(200);

		this.menu.addSeparator(idx++);
	};

	Menu.prototype.updateContextMenu = function() {
		Element.prototype.updateContextMenu.call(this);
		this.pagesMenu.removeAllItems();

		var thisClass = this;
		var pd = '&nbsp;&nbsp;&nbsp;&nbsp;';
		var menuList = MenuList.buildMenuStruct(false, false, this);
		
		for (var i = 0; i < menuList.length; i++) {
			var menu = menuList[i];
			if (menu.items.length === 0) continue;
			for (var n = 0; n < menu.items.length; n++) {
				var mi = menu.items[n];
				var ident = '', identIdx = mi.lvl; while (identIdx > 0) { identIdx--; ident += pd; }
				(function(mi) {
					thisClass.pagesMenu.addItem("pages_menu_item_" + mi.uID, ident + mi.name,
						function() { mi.navigate(); }, mi.isCurrent(), false, mi);
				})(mi);
			}
		}
		
		if (this.parent) {
			this.parent.addPaste(this.menu, this, true);
		}
	};

	Menu.prototype.exclude = function(noRemove, onConstruct) {
		if (onConstruct) {
			Element.prototype.exclude.call(this, noRemove, onConstruct);
		} else {
			Element.prototype.exclude.call(this, true);
			this.remove(false, true);
		}
	};
	
	Menu.prototype.deletePagesByItems = function(items) {
		if (items && (typeof items === 'object')) {
			var page;
			for (var i in items) {
				if (items[i].type === 'page' && parseInt(items[i].targetId)
						&& (page = wb_builder.site.getPage(parseInt(items[i].targetId)))) {
					wb_builder.site.removePage(page);
					this.deletePagesByItems(items[i].items);
				}
			}
		}
	};
	
	Menu.prototype.remove = function(noHistory, noConfirm, deletePages) {
		var thisClass = this;
		if (!noConfirm) {
			var thisNoHistory = noHistory;
			MenuConfirmDialog.confirmDelete(function() { thisClass.remove(thisNoHistory, true, true); });
			return;
		}
		Menu.elemList[this.menuId] = null;
		delete Menu.elemList[this.menuId];
		Service.menu.removeStrangeMenu(this, true);
		if (deletePages) {
			this.deletePagesByItems(this.items);
		} else {
			Menu.storeStrangeMenu(this.serialize());
		}
		Element.prototype.remove.call(this, noHistory);
		BuilderEvent.GlobalEvents.triggerEvent('pages.changed', new BuilderEvent.PagesChangedBuilderEvent());
	};

	Menu.prototype.onSwitchLanguage = function(langCode) {
		Element.prototype.onSwitchLanguage.call(this, langCode);
		this.updateStyle(false, langCode);

		for (var i in this.items) {
			this.items[i].onSwitchLanguage(langCode);
		}
	};

	(function(proto) {

		/**
		 * Menu Item class
		 * @param {Object} data
		 */
		var MenuItem = function(data) { if (data) this.__construct(data); };
		proto.MenuItem = MenuItem;

		MenuItem.idReg = {};
		MenuItem.prototype.elem = null;
		MenuItem.prototype.virtual = false;
		MenuItem.prototype.menu = null;
		MenuItem.prototype.menuUID = null;
		MenuItem.prototype.menuElem = null;
		MenuItem.prototype.parent = null;
		/** @type {Site.MenuItem} */
		MenuItem.prototype.items = null;
		MenuItem.prototype.itemCount = 0;
		MenuItem.prototype.id = 0;
		MenuItem.prototype.idp = 0;
		MenuItem.prototype.targetId = 0;
		MenuItem.prototype.anchor = 0;
		MenuItem.prototype.name = "";
		MenuItem.prototype.alias = "";
		MenuItem.prototype.url = "";
		MenuItem.prototype.type = "internal";
		MenuItem.prototype.target = "_self";
		MenuItem.prototype.copyFrom = null;
		MenuItem.prototype.isNew = false;
		MenuItem.prototype.noMenu = false;
		MenuItem.prototype._clickIsSet = false;
		/**
		 * Construct menu item element
		 * @param data menu item data object
		 */
		MenuItem.prototype.__construct = function(data) {
			this.virtual = (data && data.virtual) ? true : false;
			if (!this.virtual) {
				this.elem = $('<li><a href="javascript:void(0)"></a></li>');
				if ((!data.type || data.type === "internal" || data.type === "page") && data.targetId) {
					this.elem.find("a").on("click", function() {
						wb_builder.goToPage(data.targetId);
					});
					this._clickIsSet = true;
				}
				this.elem.wbSetClassInstance(this);
			} else {
				this.isNew = data.isNew ? true : false;
			}
			this.id = (data._ignoreId ? null : data.id);
			this.type = data.type;
			if (!this.id) this.id = this.getFreeId();
			MenuItem.idReg["#" + this.id] = true;
			this.idp = data.idp ? data.idp : 0;
			this.targetId = data.targetId ? data.targetId : data.target_id;
			this.anchor = data.anchor ? data.anchor : null;
			this.setName(data.name);
			this.alias = data.alias;
			this.url = data.url;
			this.target = data.target;
			this.menuUID = data.menuUID;
			if (this.target !== "_blank") this.target = "_self";
			this.setNoMenu(data.noMenu ? true : false);
			this.type = this.type ? this.type : (this.url ? 'external' : 'internal');
//			this.fixItemType();

			this.items = {};

			//console.log(this.name + " :: " + wb_builder.pageId + " :: " + this.targetId + " :: " + ((wb_builder.pageId == this.targetId) ? "Y" : "N"));

			if (!this.virtual) {
				if (wb_builder.pageId == this.targetId && ((!this.type && !this.url) || (this.type && (this.type === 'internal' || this.type === 'page')))) {
					this.elem.addClass("active");
				}

				this.elem.children("a").hover(
					function() {
						if ($(this).hasClass("dropdown")) {
							$(this).addClass("open");
						}
					}, function() {
						$(this).removeClass("open");
					}
				);
			}
		};
		
		MenuItem.prototype.convertItemsFromPageToInternal = function() {
			Menu.prototype.convertItemsFromPageToInternal.call(this);
		};
		
		MenuItem.prototype.fixItemType = function() {
			var pages = wb_builder.site.pages;
			if (!this.type || this.type === 'internal' && this.targetId) {
				var p = (('#' + this.targetId) in pages) ? pages['#' + this.targetId] : null;
				if (p && p.title && __tr(p.title) && __tr(p.title) === __tr(this.name)) {
					this.type = 'page';
				}
			}
		};

		MenuItem.prototype.updateConstruct = function() {
			var thisClass = this;
			if (!this.virtual && !this._clickIsSet) {
				if ((!this.type || this.type === "internal" || this.type === "page") && this.targetId) {
					this.elem.find("a").on("click", function() {
						wb_builder.goToPage(thisClass.targetId);
					});
					this._clickIsSet = true;
				}
			}
		};

		/**
		 * Get id for new menu item, that is not alredy taken
		 * @return new id
		 */
		MenuItem.prototype.getFreeId = function() {
			for (var i = 100; i < 5000; i++) {
				if (!MenuItem.idReg["#" + i]) 
					return i;

			}
			return 1;
		};

		/**
		 * Serialize this element
		 * @return object
		 */
		MenuItem.prototype.serialize = function() {
			var obj = {
				id:			this.id,
				idp:		((!this.idp && this.parent) ? this.parent.id : this.idp),
				type:		this.type,
				targetId:	this.targetId,
				anchor:		((this.anchor && (typeof this.anchor === 'object')) ? {name: this.anchor.name, pageId: this.anchor.pageId} : null),
				name:		this.name,
				alias:		this.alias,
				url:		this.url,
				target:		this.target,
				noMenu:		this.noMenu,
				copyFrom:	this.copyFrom,
				menuUID:	((this.menu && this.menu.menuUID) ? this.menu.menuUID : null)
			};
			if (this.virtual) {
				obj.isNew = this.isNew ? true : false;
			}
			return obj;
		};

		/**
		 * Add submenu item
		 * @param {Menu.MenuItem} mi menu item as WB_Menu.MenuItem
		 * @param {Number} idx index to insert menu item at
		 * @param {Number} r unused
		 */
		MenuItem.prototype.addItem = function(mi, idx, tmp, r) {
			if (idx === null || typeof(idx) === "undefined") idx = -1;
			if (mi.parent) {
				mi.parent.removeItem(mi, tmp);
			} else if (mi.menu) {
				mi.menu.removeItem(mi, tmp);
			}
			if (this.virtual) {
				mi.virtual = true;
			}
			var sortedItems;
			if (!tmp) {
				if (!this.virtual) {
					if (!this.menuElem) {
						this.menuElem = $('<ul class="dropdown-menu pull-right"></ul>');
					}
					if (this.menuElem.children().length === 0) {
						this.elem.append(this.menuElem);
						this.elem.addClass("dropdown");
						this.elem.children("a").addClass("dropdown-toggle");
						this.elem.children("a").attr("data-toggle", "dropdown");
					}
				}
				if (idx >= 0 && idx < this.getItemCount()) {
					if (!this.virtual) {
						$(this.menuElem.children().get(idx)).before(mi.elem);
					}
					sortedItems = [];
					for (var k in this.items) { sortedItems.push(this.items[k]); }
					sortedItems.splice(idx, 0, mi);
					this.items = {};
					for (var i = 0; i < sortedItems.length; i++) {
						this.items["#" + sortedItems[i].id] = sortedItems[i];
					}
				} else if (!this.virtual) {
					this.menuElem.append(mi.elem);
					this.items["#" + mi.id] = mi;
				}
			}
			else {
				sortedItems = {};
				var ct = 0;
				$.each(this.items, function(id, el){
					if (ct === idx) {
						sortedItems["#" + mi.id] = mi;
					}
					if (el.id != mi.id) {
						sortedItems["#" + el.id] = el;
					}
					ct++;
				});
				this.items = sortedItems;
			}
			this.items["#" + mi.id] = mi;

			mi.setMenu(this.menu);
			mi.parent = this;
			mi.idp = this.id;
		};
		
		MenuItem.prototype.setMenu = function(menu) {
			this.menu = menu;
			this.menuUID = (menu ? menu.menuUID : null);
		};

		/**
		 * Get item by ID
		 * @param {Number} id menu item id
		 * @return {Menu.MenuItem} menu item as WB_Menu.MenuItem
		 */
		MenuItem.prototype.getItem = function(id) {
			return this.items["#" + id];
		};
		
		/**
		 * Remove submenu item
		 * @param {Menu.MenuItem} mi menu item as WB_Menu.MenuItem
		 * @param {Boolean} tmp
		 */
		MenuItem.prototype.removeItem = function(mi, tmp) {
			tmp = (typeof(tmp) === "undefined") ? false : tmp;
			this.items["#" + mi.id] = null;
			delete this.items["#" + mi.id];

			if (!tmp) {
				mi.setMenu(null);
				mi.parent = null;
				mi.idp = null;
				if (!this.virtual) {
					if (mi.elem) mi.elem.detach();
					if (this.menuElem && this.menuElem.children().length === 0) {
						this.menuElem.detach();
						if (this.elem) {
							this.elem.removeClass("dropdown");
							this.elem.children("a").removeClass("dropdown-toggle");
							this.elem.children("a").removeAttr("data-toggle");
						}
					}
				}
			}
		};

		/**
		 * Dispose of item (remove from memory)
		 */
		MenuItem.prototype.dispose = function() {
			if (this.parent) {
				this.parent.removeItem(this);
			} else if (this.menu) {
				this.menu.removeItem(this);
			}
			for (var k in this.items) {
				this.items[k].dispose();
			}
			if (!this.virtual && this.elem) {
				this.elem.remove();
				this.elem.empty();
				delete this.elem;
			}
		};

		/**
		 * Get item count
		 * @return {Number} item count
		 */
		MenuItem.prototype.getItemCount = function() {
			var count = 0;
			for (var k in this.items) { count++; }
			return count;
		};

		/**
		 * Get parent of this item
		 * @return parent or null
		 */
		MenuItem.prototype.getParent = function() {
			return this.parent;
		};

		/**
		 * Set menu item name
		 * @param {String} name name to set
		 * @param {String} langCode
		 */
		MenuItem.prototype.setName = function(name, langCode) {
			this.name = name;
			if (!this.virtual) {
				var trName = __tr(this.name, langCode, __tr(this.name, wb_builder.site.getLastDefLang()), true, true);
				if (!trName) trName = __('New Item');
				this.elem.children("a").html(trName);
			}
		};

		MenuItem.prototype.setNoMenu = function(noMenu) {
			this.noMenu = noMenu;
			if (!this.virtual) {
				if (this.noMenu) {
					this.elem.css({display: "none"});
				} else {
					this.elem.css({display: ""});
				}
			}
		};

		MenuItem.prototype.onSwitchLanguage = function(langCode) {
			this.setName(this.name, langCode);
		};

	})(Menu);
	
	Service.menu = {
		MenuItem: Menu.MenuItem,
		getElemList: Menu.getElemList,
		getFirstMenuLoadedCallback: function() { return Menu.firstMenuLoadedCallback; },
		setFirstMenuLoadedCallback: function(func) { Menu.firstMenuLoadedCallback = func; },
		getLandingMenu: Menu.getLandingMenu,
		editMenu: Menu.editMenu,
		getMenuByUID: Menu.getMenuByUID,
		storeStrangeMenu: function(data) { Menu.storeStrangeMenu(data); },
		removeStrangeMenu: function(menu, tryUID) { Menu.removeStrangeMenu(menu, tryUID); },
		updateEmptyLinks: function() { Menu.updateEmptyLinks(); },
		getMenuItemById: function(miId, menuUID) { return Menu.getMenuItemById(miId, menuUID); }
	};
	
	return Menu;
});
;

/** WB Gallery **/
(window.defineModule = (window.defineModule || {})).name = 'WB Gallery';

define('Gallery', ['ElementRegister', 'Element', 'Service', 'ContextMenu', 'ColorPicker', 'GalleryPictureManager', 'BorderControl', 'TextControl', 'BuilderEvent'], function(ElementRegister, Element, Service, ContextMenu, ColorPicker, GalleryPictureManager, BorderControl, TextControl, BuilderEvent) {

	/**
	 * Gallery element class
	 * @param {Object} data
	 * @param {boolean} initial
	 */
	var Gallery = function(data, initial) { if (data) this.__construct(data, initial); };

	Gallery.prototype = new Element();
	Gallery.prototype.constructor = Gallery;
	ElementRegister.registerClass("Gallery", Gallery);

	Gallery.config = {
		thumbWidth: 290,
		thumbHeight: 290,
		minWidth: 320,
		minHeight: 240
	};
	Gallery.selectDialog = null;
	Gallery.editDialog = null;
	Gallery.prototype.noPhotoBg = 'ico-tb-gallery';
	Gallery.prototype.gallery_name = false;
	Gallery.prototype.type = "thumbs";
	Gallery.prototype.slideshowInterval = 5;
	Gallery.prototype.slideshowSpeed = 400;
	Gallery.prototype.images = null;
	Gallery.prototype.galleryElem = null;
	Gallery.prototype.imageIndex = 0;
	Gallery.prototype.typeSubmenu = null;
	Gallery.prototype.slideshowTimer = null;
	Gallery.prototype.displayedImage = null;
	Gallery.prototype.loadingImage = null;
	Gallery.prototype.listImgCont = null;
	Gallery.prototype.thumbImgCont = null;
	Gallery.prototype.fullThumbWidth = 0;
	Gallery.prototype.fullThumbHeight = 0;
	Gallery.prototype.bgColor = "#000000";
	Gallery.prototype.backupBgColor = null;
	Gallery.prototype.border = null;
	Gallery.prototype.padding = null;
	Gallery.prototype.imageCover = false;
	Gallery.prototype.thumbWidth = Gallery.config.thumbWidth;
	Gallery.prototype.thumbHeight = Gallery.config.thumbHeight;
	Gallery.prototype.thumbAlign = "left";
	Gallery.prototype.showPictureCaption = "always";
	Gallery.prototype.metaChangeHandler = null;
	Gallery.prototype.captionBackground = "rgba(0,0,0,0.66)";
	Gallery.prototype.captionTitleStyle = null;
	Gallery.prototype.captionDescriptionStyle = null;

	/**
	 * Construct gallery element
	 * @param data gallery data object
	 * @param {boolean} initial
	 */
	Gallery.prototype.__construct = function(data, initial) {
		if (!data.width) {
			data.width = 910;
			data.height = 600;
		}
		Element.prototype.__construct.call(this, data, initial);
		var thisClass = this;

		this.setEmtyMessageText(__("Double click to add pictures"));

		this.container.append((this.galleryElem = $('<div class="wb_gallery"></div>')));

		this.displayEmtyMessage(true);

		this.images = [];

		this.border = data.content.border ? data.content.border : {
			color: '#FFFFFF',
			style: 'none',
			weight: 5,
			css: { border: '5px none #FFFFFF' }
		};

		this.thumbWidth = data.content.hasOwnProperty("thumbWidth") ? data.content.thumbWidth : (data.content.hasOwnProperty("thumbSize") ? data.content.thumbSize : null);
		if( !this.thumbWidth ) this.thumbWidth = Gallery.config.thumbWidth;
		this.thumbHeight = data.content.hasOwnProperty("thumbHeight") ? data.content.thumbHeight : (data.content.hasOwnProperty("thumbSize") ? data.content.thumbSize : null);
		if( !this.thumbHeight ) this.thumbHeight = Gallery.config.thumbHeight;
		this.thumbAlign = data.content.thumbAlign ? data.content.thumbAlign : this.thumbAlign;
		this.padding = (data.content.padding || data.content.padding === 0) ? data.content.padding : 0;
		this.type = data.content.type ? data.content.type : this.type;
		this.slideshowInterval = WB_Builder.isset(data.content.interval) ? data.content.interval : 10;
		this.imageCover =  WB_Builder.isset(data.content.imageCover) ? data.content.imageCover : this.imageCover;
		this.slideshowSpeed = WB_Builder.isset(data.content.speed) ? data.content.speed : 400;
		this.setBgColor(data.content.bgColor ? data.content.bgColor : "#000000");
		this.images = (data.content.images && data.content.images.length)
			? data.content.images : [];
		this.showPictureCaption = WB_Builder.isset(data.content.showPictureCaption) ? data.content.showPictureCaption : this.showPictureCaption;
		this.setCaptionBackground(data.content.captionBackground ? data.content.captionBackground : "rgba(0, 0, 0, 0.66)");
		this.setCaptionTitleStyle(data.content.captionTitleStyle ? data.content.captionTitleStyle : {
			color: "#FFFFFF",
			size: 20,
			align: 'center',
			letterSpacing: 0
		});
		this.setCaptionDescriptionStyle(data.content.captionDescriptionStyle ? data.content.captionDescriptionStyle : {
			color: "#FFFFFF",
			size: 16,
			align: 'center',
			letterSpacing: 0
		});

		this.render();

		this.metaChangeHandler = (function(e) {
			if( this.images.indexOf(e.path) >= 0 )
				this.render();
		}).bind(this);
		BuilderEvent.GlobalEvents.on("media.meta.changed", this.metaChangeHandler);

		this.updateMinSize(true);

		if (!this.images.length && !initial)
			thisClass.changePictures();

		this.elem.bind("resize", function() { thisClass.onContinuousResize(); });
		this.elem.bind("resizestop", function() { thisClass.onResize(); });

		this.controls.bind("dblclick", function(e) {
			thisClass.changePictures();
		});
	};

	Gallery.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = this.isFullWidth ? 'n, s' : 'n, e, s, w, ne, se, sw, nw';
	};

	Gallery.prototype.supportsFullWidth = function() {
		return true;
	};

	/** @return {String} */
	Gallery.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = this.type;
		if (this.images.length) opts.thumb = wb_builder.makeLocalUrl(this.images[0]);
		return opts;
	};

	Gallery.prototype.getUsedMediaGalleryItems = function() {
		var items = Element.prototype.getUsedMediaGalleryItems.call(this);
		return items.concat(this.images);
	};

	/**
	 * Serialize this element
	 * @return object
	 */
	Gallery.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			"type":		this.type,
			"interval":	this.slideshowInterval,
			"speed":	this.slideshowSpeed,
			"bgColor":	this.bgColor,
			"images":	this.images,
			"border":	this.border,
			"padding":	this.padding,
			"thumbWidth": this.thumbWidth,
			"thumbHeight": this.thumbHeight,
			"thumbAlign": this.thumbAlign,
			"imageCover": this.imageCover,
			"showPictureCaption": this.showPictureCaption,
			"captionBackground": this.captionBackground,
			"captionTitleStyle": this.captionTitleStyle,
			"captionDescriptionStyle": this.captionDescriptionStyle
		};

		return data;
	};

	/**
	 * Display message to inform user how to change picture
	 * @param display if true message will be displayed else hidden
	 */
	Gallery.prototype.displayEmtyMessage = function(display) {
		if (display) {
			this.elem.css("background", this.noPhotoBg);
			this.noPhotoMsg.css("display", "block");
			if (this.galleryElem)
				this.galleryElem.css("display", "none");
		} else {
			this.elem.css("background", "");
			this.noPhotoMsg.css("display", "none");
			if (this.galleryElem)
				this.galleryElem.css("display", "block");
		}
	};

	Gallery.prototype.changePictures = function() {
		var thisClass = this;
		if( !this.images.length ) {
			this.dialog = Service.mediaLibrary.open(__("Add pictures"), true, "image", true);

			this.dialog.addButton(__("Close"));
			this.dialog.addButton(__("Apply"), function() {
				thisClass.images = thisClass.dialog.getSelectedFiles();
				thisClass.dialog.hide();
				thisClass.render();
				if( thisClass.images.length )
					thisClass.changePictures();
			}, true);
			this.dialog.onClose = function() {
				Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-end', thisClass);
			};

			if (this.images.length > 0) {
				this.dialog.setSelectedFiles(this.images);
			} else {
				this.dialog.clearFileSelection();
			}
			this.dialog.setVisible(true);
		}
		else {
			Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-edit-start', thisClass);
			Service.GalleryPictureManager.setMediaLibraryOptions({
				showMediaTabs: true,
				customContentCallback: null
			});
			Service.GalleryPictureManager.setValue(this.images);
			Service.GalleryPictureManager.setApplyCallback(function () {
				thisClass.images = Service.GalleryPictureManager.getValue();
				Service.GalleryPictureManager.setVisible(false);
				thisClass.render();
			});
			Service.GalleryPictureManager.setVisible(true);
		}
	};

	Gallery.prototype.render = function() {
		if (this.slideshowTimer) clearInterval(this.slideshowTimer);
		this.slideshowTimer = null;

		this.galleryElem.empty();
		if (this.images.length > 0) {
			this.displayEmtyMessage(false);
			switch (this.type) {
				case "slideshow": this.renderSlideshow(); break;
				case "list": this.renderList(); break;
				case "masonry": this.renderMasonry(); break;
				default: this.renderThumbs(); break;
			}
		} else {
			this.displayEmtyMessage(true);
		}
	};

	Gallery.prototype.renderThumbs = function() {
		this.displayedImage = null;
		this.loadingImage = null;
		this.galleryElem.html('<div class="wb-thumbs-only" style="width: 100%; height: 100%; overflow: auto;"></div>');
		this.galleryElem.css("text-align", this.thumbAlign);
		var elem = this.galleryElem.children().first();
		for (var i = 0; i < this.images.length; i++) {
			this.addImage(elem, this.images[i], false);
		}
	};

	Gallery.prototype.renderSlideshow = function() {
		var thisClass = this;
		this.displayedImage = null;
		this.loadingImage = null;
		this.galleryElem.html(
			'<div class="gallery-slideshow">'+
				'<div class="gallery-slide-image" style="overflow: hidden;"></div>'+
				'<div class="gallery-slide-left"><i class="fa fa-chevron-left"></i></div>'+
				'<div class="gallery-slide-right"><i class="fa fa-chevron-right"></i></div>'+
			'</div>'
		);
		var cont = this.galleryElem.children().first();
		var larr = cont.children(".gallery-slide-left");
		var rarr = cont.children(".gallery-slide-right");
		this.listImgCont = cont.children(".gallery-slide-image");

		larr.click(function() {
			thisClass.slideshowPrev();
		});

		rarr.click(function() {
			thisClass.slideshowNext();
		});

		if( this.slideshowInterval ) {
			this.slideshowTimer = setInterval(function(){
				thisClass.slideshowNext();
			}, this.slideshowInterval * 1000);
		}
		else
			this.slideshowTimer = null;
		this.imageIndex = -1;
		this.slideshowNext();
	};

	Gallery.prototype.renderList = function() {
		var thisClass = this;
		this.displayedImage = null;
		this.loadingImage = null;

		var w = this.getWidth();
		var h = this.getHeight();
		var tw = this.getThumbWidth();
		var th = this.getThumbHeight();

		var thumbcont = $("<div></div>");
		var callback = function() {
			var img = thisClass.imageElems[thisClass.imageIndex];
			$(img.parentNode.parentNode.parentNode).children(".tmb-selected").removeClass("tmb-selected");
			$(img.parentNode.parentNode).addClass("tmb-selected");
		};
		this.imageElems = {};
		
		//var images = [];
		for (var i = 0; i < this.images.length; i++) {
			var image = this.images[i];
			/*var img_title = "";
			var img_file = this.system.makeLocalUrl(image);
			var img_thumb = this.system.makeLocalUrl(image);*/
			var img = this.addImage(thumbcont, image, false, true);
			img.idx = i;
			img.css({cursor: "pointer"});
			this.imageElems[img.idx] = img.get(0);
			img.click(function() {
				// TODO: change image
				thisClass.imageIndex = parseInt(this.idx, 10);
				thisClass.displayImage(thisClass.listImgCont, callback);
			});

			var par = img.parent().parent();
			if (i === this.imageIndex) {
				par.addClass("tmb-selected");
				tw = this.getThumbWidth() + 8;
				th = this.getThumbHeight() + 8;
			}
		}

		this.fullThumbWidth = tw;
		this.fullThumbHeight = th;

		thumbcont.css({position: "absolute", left: "0", top: "5px", width: (tw * this.images.length) + "px", height: th + "px"});

		var galcont = document.createElement("DIV");
		$(galcont).css({position: "relative", width: w + "px", height: h + "px"});
		galcont.className = "gallery-list";

		var imgcont = document.createElement("DIV");
		$(imgcont).css({position: "relative", width: w + "px", height: (h - th - 10) + "px", overflow: "hidden"});
		imgcont.className = "gallery-list-image";

		var icon;

		var thumbdiv_in1 = document.createElement("DIV");
		$(thumbdiv_in1).css({position: "relative", "float": "left", width: "16px", height: (th + 10) + "px", cursor: "pointer"});
		thumbdiv_in1.className = "gallery-list-left";
		$(thumbdiv_in1).click(function() {
			thisClass.slideBy(-thisClass.fullThumbWidth * 3);
		});
		icon = document.createElement("I");
		icon.setAttribute("class", "fa fa-chevron-left");
		thumbdiv_in1.appendChild(icon);

		var thumbdiv_in2 = document.createElement("DIV");
		$(thumbdiv_in2).css({position: "relative", "float": "left", width: (w-32) + "px", height: (th + 10) + "px", overflow: "hidden"});
		thumbdiv_in2.className = "gallery-list-thumbs";

		var thumbdiv_in3 = document.createElement("DIV");
		$(thumbdiv_in3).css({position: "relative", "float": "left", width: "16px", height: (th + 10) + "px", cursor: "pointer"});
		thumbdiv_in3.className = "gallery-list-right";
		$(thumbdiv_in3).click(function() {
			thisClass.slideBy(thisClass.fullThumbWidth * 3);
		});
		icon = document.createElement("I");
		icon.setAttribute("class", "fa fa-chevron-right");
		thumbdiv_in3.appendChild(icon);

		var thumbdiv = document.createElement("DIV");
		$(thumbdiv).css({position: "relative", width: w + "px", height: (th + 10) + "px", overflow: "hidden"});

		$(thumbdiv_in2).append(thumbcont);

		thumbdiv.appendChild(thumbdiv_in1);
		thumbdiv.appendChild(thumbdiv_in2);
		thumbdiv.appendChild(thumbdiv_in3);

		galcont.appendChild(imgcont);
		galcont.appendChild(thumbdiv);

		this.listImgCont = $(imgcont);
		this.thumbImgCont = thumbdiv_in2;
		this.galleryElem.append(galcont);
		// this.displayImage(this.listImgCont);

		if( this.slideshowInterval ) {
			this.slideshowTimer = setInterval(function(){
				thisClass.slideshowNext(callback);
			}, this.slideshowInterval * 1000);
		}
		else
			this.slideshowTimer = null;
		this.imageIndex = -1;
		this.slideshowNext(callback);
	};

	Gallery.prototype.renderMasonry = function() {
		this.displayedImage = null;
		this.loadingImage = null;
		var elem = $('<div class="wb-masonry-items"/>');
		var cont = $('<div class="wb-masonry" style="width: 100%; height: 100%; overflow: auto;"/>');
		cont.append(elem);
		this.galleryElem.append(cont);
		if( this.thumbAlign === "left" )
			elem.css("float", "left");
		else if( this.thumbAlign === "right" )
			elem.css("float", "right");
		else
			elem.css("margin", "0 auto");
		for (var i = 0; i < this.images.length; i++) {
			this.addImage(elem, this.images[i], false);
		}
		var brd = this.getBorder();
		elem.masonry({
			itemSelector: ".wb_thumb",
			columnWidth: this.getThumbWidth() + (brd ? BorderControl.getBorderWidth(brd, 1) + BorderControl.getBorderWidth(brd, 3) : 0) + 6, // +6 because each .wb_thumb has 3px padding on sides
			fitWidth: true,
			transitionDuration: 0
		});
	};

	Gallery.prototype.slideBy = function(delta) {
	   var cont = $(this.thumbImgCont);
	   var div = $(this.thumbImgCont.firstChild);
	   var pos = div.position();
	   var x = pos.left;
	   x -= delta;
	   var minx = -(div.width() - cont.width());
	   if( x < minx ) x = minx;
	   if( x > 0 ) x = 0;
		div.animate({left: x + "px"});
	};

	Gallery.prototype.onContinuousResize = function(onConstruct) {
		if (this.type === "masonry")
			this.galleryElem.children().first().children().first().masonry();
	};

	Gallery.prototype.onResize = function(onConstruct) {
		Element.prototype.onResize.call(this, onConstruct);

		var thisClass = this;
		var w = this.getWidth();
		var h = this.getHeight();

		var cont = this.galleryElem.children().first();

		if (this.type === "list") {
			cont.css({width: w + "px", height: h + "px"});

			//var tw = this.fullThumbWidth;
			var th = this.fullThumbHeight;

			if (this.listImgCont) {
				this.listImgCont.css({width: w + "px", height: (h - th - 10) + "px"});
			}
			$(this.thumbImgCont).css({width: (w-32) + "px", height: (th + 10) + "px"});
			if (this.thumbImgCont) {
				$(this.thumbImgCont.parentNode).css({width: w + "px", height: (th + 10) + "px"});
			}
		}

		if (this.type === "slideshow") {
			cont.css({width: w + "px", height: h + "px"});
		}

		if (this.type === "masonry")
			cont.children().first().masonry();

		if (this.displayedImage)
			this.updateImageSize(this.displayedImage);
		if( this.loadingImage )
			this.updateImageSize(this.loadingImage);
		this.elem.trigger("elementresize", [this]);
	};

	Gallery.prototype.updateImageSize = function(imageCont) {
		var size = imageCont.data("_wb_size_");
		var stl = this.calcImageStyles(this.listImgCont, imageCont, size);
		imageCont.css({
			left: stl.left + "px",
			top: stl.top + "px"
		});
		var img = imageCont.children('img').first();
		if (img && img.size()) {
			img.css({
				width: stl.image_width + "px",
				height: stl.image_height + "px"
			});
			img = img.get(0);
			img.width = stl.image_width;
			img.height = stl.image_height;
		}
	};

	Gallery.prototype.calcImageStyles = function(displayCont, cont, image) {
		if (image) {
			var bw, bh;
			var cover = this.isFullWidth || this.imageCover;
			if( cover ) {
				bw = bh = 0;
			}
			else if( typeof this.border === "object" && this.border.weight && typeof this.border.weight === "object" ) {
				bh = ((this.border.style[0] === "none") ? 0 : this.border.weight[0]) + ((this.border.style[2] === "none") ? 0 : this.border.weight[2]);
				bw = ((this.border.style[1] === "none") ? 0 : this.border.weight[1]) + ((this.border.style[3] === "none") ? 0 : this.border.weight[3]);
			}
			else {
				bw = ((this.border.style === "none") ? 0 : (this.border.weight * 2));
				bh = ((this.border.style === "none") ? 0 : (this.border.weight * 2));
			}
			var pad = cover ? 0 : this.padding;
			var maxWidth = (displayCont.innerWidth() - pad * 2 - bw);
			var maxHeight = (displayCont.innerHeight() - pad * 2 - bh);
			var w = image.width;
			var h = image.height;
			if(cover || w > maxWidth || h > maxHeight) { // One of these is larger than the window
				var ratio1 = w / maxWidth;
				var ratio2 = h / maxHeight;
				var ratio = cover ? Math.min(ratio1, ratio2) : Math.max(ratio1, ratio2);
				w = Math.floor(w / ratio);
				h = Math.floor(h / ratio);
			}
			var imgs = {
				left: Math.floor((maxWidth - w) / 2 + pad),
				top: Math.floor((maxHeight - h) / 2 + pad),
				image_width: w,
				image_height: h
			};
			return imgs;
		}
		else {
			return {
				left: 0,
				top: 0,
				image_width: 0,
				image_height: 0
			};
		}
	};

	Gallery.prototype.displayImage = function(displayCont, callback) {
		if (!displayCont)
			return false;

		var thisClass = this;
		
		if (typeof callback === 'function') callback();

		var image = this.images[this.imageIndex];
		if (!image) return;
		var cont = $("<div></div>");
		cont.addClass("gallery-image");
//		cont.css((this.isFullWidth || this.imageCover) ? {"border": "none"} : thisClass.border.css);

		var thisDisplayCont = displayCont;
		cont.css({ display: "none", position: "absolute" });
		var img = new Image();
		//cont.append(img);
		img.alt = "";
		img.onload = function() {
			if (thisClass.displayedImage) {
				var caption = thisClass.displayedImage.data("caption");
				thisClass.displayedImage.fadeOut(thisClass.slideshowSpeed, function() {
					$(this).remove();
				});
				if( caption ) {
					caption.fadeOut(thisClass.slideshowSpeed, function() {
						$(this).remove();
					});
				}
			}
			var size = { width: this.width, height: this.height };
			cont.data("_wb_size_", size);
			cont.append(img);
			var stl = thisClass.calcImageStyles(thisDisplayCont, cont, size);
			cont.css({ left: stl.left + "px", top: stl.top + "px" });
			$(img).css({ width: stl.image_width + "px", height: stl.image_height + "px" });
			this.width = stl.image_width;
			this.height = stl.image_height;
			cont.fadeIn(thisClass.slideshowSpeed, function() {
				thisClass.displayedImage = (cont.parent() && cont.parent().size()) ? cont : null;
				thisClass.loadingImage = null;
			});
		};
		$(img).css((this.isFullWidth || this.imageCover) ? {"border": "none"} : this.border.css);
		displayCont.append(cont);
		this.loadingImage = cont;

		// WARNING: Meta must be requested after cont is added to displayCont because of the inner if condition, but
		// before setting src!
		Service.mediaLibrary.getPathMeta(image, function(meta) {
			if( cont.parent() && cont.parent().size() ) {
				var caption = $('<div class="wb-picture-caption" style="display: none;"/>').css("background-color", thisClass.captionBackground);
				if( thisClass.fillCaptionContainer(caption, meta, true) ) {
					caption.fadeIn(thisClass.slideshowSpeed);
					displayCont.append(caption);
					cont.data("caption", caption);
				}
			}
		});

		img.src = this.system.makeLocalUrl(image);
	};

	Gallery.prototype.slideshowNext = function(callback) {
		if (this.images.length === 0) return;
		this.imageIndex++;
		if (this.imageIndex >= this.images.length)
			this.imageIndex = 0;
		this.displayImage(this.listImgCont, callback);
	};

	Gallery.prototype.slideshowPrev = function(callback) {
		if (this.images.length === 0) return;
		this.imageIndex--;
		if (this.imageIndex < 0)
			this.imageIndex = this.images.length - 1;
		this.displayImage(this.listImgCont, callback);
	};

	Gallery.prototype.addImage = function(cont, image, closebtn, nolightbox) {
		var isThumbsOnlyMode = (this.type === "thumbs" || this.type === "masonry");
		var img_thumb_url = this.system.makeLocalUrl(image);

		var div = $('<div class="wb_thumb"/>');

		var tw = this.getThumbWidth();
		var th = this.getThumbHeight();
		var wrp = $("<div/>");
		wrp.css({
			zIndex: "1",
			width: tw + "px",
			overflow: "hidden",
			boxSizing: "content-box"
		});
		if (this.type !== 'masonry')
			wrp.css('height', th + "px");
		var brd = this.getBorder();
		if (isThumbsOnlyMode) {
			if (brd && brd.css) wrp.css(brd.css);
		}
		div.append(wrp);

		var thisClass = this;
		var img = $('<img src="" alt="" />');
		img.get(0).onload = function() {
			var w = this.width;
			var h = this.height;
			var k;
			if (thisClass.type === 'masonry') {
				k = w / tw;
			}
			else {
				var k1 = w / tw;
				var k2 = h / th;
				k = Math.min(k1, k2);
			}
			w = w / k;
			h = h / k;
			var x = Math.round((tw - w) / 2);
			var y = (thisClass.type === 'masonry') ? 0 : Math.round((th - h) / 2);
			$(this).css({left: x + "px", top: y + "px", width: w + "px", height: h + "px"});
			if (thisClass.type === 'masonry')
				thisClass.galleryElem.children().first().children().first().masonry(); // run masonry layout update after every image load
		};
		img.get(0).src = img_thumb_url;
//		img.get(0).width = tw;
//		img.get(0).height = tw;
//		img.get(0).alt = "";
		//img.attr("alt", image.title);
		img.css({
			display: "block",
			zIndex: "1",
			maxWidth: "auto",
			position: "relative"
		});

		wrp.append(img);

		if( isThumbsOnlyMode && this.getThumbWidth() >= 100 ) {
			Service.mediaLibrary.getPathMeta(image, function(meta) {
				var descDiv = $('<div class="wb-picture-caption"/>').css("background-color", thisClass.captionBackground);
				if( thisClass.fillCaptionContainer(descDiv, meta, false) ) {
					descDiv.css({ // +3 because of the fixed padding
						left: BorderControl.getBorderWidth(brd, 3) + 3,
						right: BorderControl.getBorderWidth(brd, 1) + 3,
						bottom: BorderControl.getBorderWidth(brd, 2) + 3
					});
					//if( this.showPictureCaption === "hover" )
					//	descDiv.addClass("wb-on-hover");
					wrp.append(descDiv);
				}
			});
		}

		cont.append(div);
		return img;
	};

	Gallery.prototype.getImages = function() {
		return this.images;
	};

	Gallery.prototype.fillCaptionContainer = function($cont, meta, createDescription) {
		var title = meta.title ? __tr(meta.title, null, "", true) : "";
		if( title === "" && meta.link && meta.link.name )
			title = __tr(meta.link.name, null, "", true);
		var description = meta.description ? __tr(meta.description, null, "", true) : "";
		var titleVisible = title !== "";
		var descriptionVisible = createDescription && description !== "";
		if( !titleVisible && !descriptionVisible )
			return false;
		if( titleVisible ) {
			var $title = $('<h3 class="wb-lightbox-title">').css(this.captionTitleStyle.css).text(title);
			$cont.append($title);
		}
		if( descriptionVisible ) {
			$cont.append($('<div class="wb-lightbox-description">').css(this.captionDescriptionStyle.css).text(description));
		}
		return true;
	};

	Gallery.prototype.onSwitchLanguage = function(langCode) {
		Element.prototype.onSwitchLanguage.call(this, langCode);
		this.render();
	};

	Gallery.prototype.updateMinSize = function(onConstruct) {
		this.onResize(onConstruct);
	};

	Gallery.prototype.setType = function(type) {
		wb_builder.setPageModified(true);
		this.type = type;
		this.render();
		this.updateMinSize();
	};

	Gallery.prototype.getBgColor = function() {
		return this.bgColor;
	};

	Gallery.prototype.setBgColor = function(color) {
		this.bgColor = color;
		$(this.galleryElem).css("background-color", this.bgColor);
	};

	Gallery.prototype.getCaptionBackground = function() {
		return this.captionBackground;
	};

	Gallery.prototype.setCaptionBackground = function(color) {
		this.captionBackground = color;
		$(this.galleryElem).find(".wb-picture-caption").css("background-color", color);
	};

	Gallery.prototype.getCaptionTitleStyle = function() {
		return this.captionTitleStyle;
	};

	Gallery.prototype.setCaptionTitleStyle = function(style) {
		this.captionTitleStyle = TextControl.buildCss(style);
		delete this.captionTitleStyle.css['text-decoration'];
		$(this.galleryElem).find(".wb-lightbox-title").css(this.captionTitleStyle.css);
	};

	Gallery.prototype.getCaptionDescriptionStyle = function() {
		return this.captionDescriptionStyle;
	};

	Gallery.prototype.setCaptionDescriptionStyle = function(style) {
		this.captionDescriptionStyle = TextControl.buildCss(style);
		delete this.captionDescriptionStyle.css['text-decoration'];
		$(this.galleryElem).find(".wb-lightbox-description").css(this.captionDescriptionStyle.css);
	};

	Gallery.prototype.setFrequency = function(frequency) {
		if (frequency >= 0 && frequency <= 10) {
			this.slideshowInterval = frequency;
			this.reset();
		}
	};

	Gallery.prototype.getFrequency = function() {
		return this.slideshowInterval;
	};

	Gallery.prototype.reset = function() {
		if (this.slideshowTimer) clearInterval(this.slideshowTimer);
		var thisClass = this;
		if( this.slideshowInterval ) {
			this.slideshowTimer = setInterval(function(){
				thisClass.slideshowNext();
			}, this.slideshowInterval * 1000);
		}
		else
			this.slideshowTimer = null;
	};

	Gallery.prototype.getBackupBgColor = function() {
		return this.backupBgColor;
	};

	Gallery.prototype.setBackupBgColor = function(color) {
		this.backupBgColor = color;
	};

	Gallery.prototype.getBorder = function() {
		return this.border;
	};

	Gallery.prototype.setBorder = function(border) {
		this.border = border;
		$(this.container.find('.gallery-image')).css((this.isFullWidth || this.imageCover) ? {"border": "none"} : this.border.css);
	};
	
	Gallery.prototype.getPadding = function() {
		return this.padding;
	};
	
	Gallery.prototype.getThumbWidth = function() {
		return this.thumbWidth ? this.thumbWidth : Gallery.config.thumbWidth;
	};

	Gallery.prototype.getThumbHeight = function() {
		return this.thumbHeight ? this.thumbHeight : Gallery.config.thumbHeight;
	};

	Gallery.prototype.getThumbAlign = function() {
		return this.thumbAlign;
	};

	Gallery.prototype.setPadding = function(padding) {
		this.padding = padding;
	};
	
	Gallery.prototype.setThumbWidth = function(width) {
		this.thumbWidth = width;
	};

	Gallery.prototype.setThumbHeight = function(height) {
		this.thumbHeight = height;
	};

	Gallery.prototype.setThumbAlign = function(align) {
		this.thumbAlign = align;
	};

	Gallery.prototype.setImageCover = function(value) {
		this.imageCover = value;
	};

	Gallery.prototype.getImageCover = function() {
		return this.imageCover;
	};

	/**
	 * @param {string} value
	 */
	Gallery.prototype.setShowPictureCaption = function(value) {
		this.showPictureCaption = value;
	};

	/**
	 * @return {string}
	 */
	Gallery.prototype.getShowPictureCaption = function() {
		return this.showPictureCaption;
	};

	Gallery.prototype.updateComPropertiesGalleryType = function(type) {
		if (!this.comDialog)
			return;
		var fields = this.comDialog.fields;
		fields.imageControlsRow1.applyLayoutCellCss(0, {display: 'none'}); // galleryPaddingBlock
		fields.imageControlsRow1.applyLayoutCellCss(1, {display: 'none'}); // galleryFrequencyBlock
		fields.imageControlsRow1.applyLayoutCellCss(2, {display: 'none'}); // galleryThumbSizeBlock
		fields.galleryThumbSizeTimesLabel.setVisible(false);
		fields.galleryThumbHeight.setVisible(false);
		fields.imageControlsRow1.applyLayoutCellCss(3, {display: 'none'}); // galleryThumbAlignBlock
		fields.imageControlsRow2.applyLayoutCellCss(0, {display: 'none'}); // galleryImageCoverBlock
		if (type === 'thumbs') {
			fields.imageControlsRow1.applyLayoutCellCss(2, {display: ''}); // galleryThumbSizeBlock
			fields.galleryThumbSizeTimesLabel.setVisible(true);
			fields.galleryThumbHeight.setVisible(true);
			fields.imageControlsRow1.applyLayoutCellCss(3, {display: ''}); // galleryThumbAlignBlock
		} else if (type === 'slideshow') {
			fields.imageControlsRow1.applyLayoutCellCss(0, {display: ''}); // galleryPaddingBlock
			fields.imageControlsRow1.applyLayoutCellCss(1, {display: ''}); // galleryFrequencyBlock
			fields.imageControlsRow2.applyLayoutCellCss(0, {display: ''}); // galleryImageCoverBlock
		} else if (type === 'list') {
			fields.imageControlsRow1.applyLayoutCellCss(0, {display: ''}); // galleryPaddingBlock
			fields.imageControlsRow1.applyLayoutCellCss(1, {display: ''}); // galleryFrequencyBlock
			fields.imageControlsRow1.applyLayoutCellCss(2, {display: ''}); // galleryThumbSizeBlock
			fields.galleryThumbSizeTimesLabel.setVisible(true);
			fields.galleryThumbHeight.setVisible(true);
			fields.imageControlsRow2.applyLayoutCellCss(0, {display: ''}); // galleryImageCoverBlock
		} else if (type === 'masonry') {
			fields.imageControlsRow1.applyLayoutCellCss(2, {display: ''}); // galleryThumbWidthBlock
			fields.imageControlsRow1.applyLayoutCellCss(3, {display: ''}); // galleryThumbAlignBlock
		}
	};

	/**
	 * Extend element properties dialog
	 */
	Gallery.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {sizeClass: 'modal-md', minBodyHeight: 384},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', columnWeights: [4, 4, 4], children: [
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'galleryImagesBlock', children: [
							{type: 'Label', text: __('Gallery Pictures')},
							{type: 'ImageSelector', id: 'galleryImages', usePictureManager: true}
						]},
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'galleryBgColorBlock', children: [
							{type: 'Label', text: __('Background color')},
							{type: 'ColorSelector', id: 'galleryBgColor', big: true, change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-galleryBgColor-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'imageBorderBlock', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'imageBorder', noTransparent: false, change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-imageBorder-change', thisClass);
							}}
						]}
					]},
					{type: 'Label', css: {marginTop: 15}, text: __('Gallery Type')},
					{type: 'CustomContainer', id: 'galleryType', init: function() {
						this._ulElem = $('<ul class="thumbnails wb_gallery_wrap">' +
							'<li data-value="thumbs"><div class="thumbnail" style="text-align: center;">' +
								'<div class="wb_gallery_type_thumbs"></div>' +
								'<div>' + __('Thumbnails') + '</div>' +
							'</div></li>' +
							'<li data-value="masonry"><div class="thumbnail" style="text-align: center;">' +
								'<div class="wb_gallery_type_masonry"></div>' +
								'<div>' + __('Masonry') + '</div>' +
							'</div></li>' +
							'<li data-value="slideshow"><div class="thumbnail" style="text-align: center;">' +
								'<div class="wb_gallery_type_slideshow"></div>' +
								'<div>' + __('Slideshow') + '</div>' +
							'</div></li>' +
							'<li data-value="list"><div class="thumbnail" style="text-align: center;">' +
								'<div class="wb_gallery_type_list"></div>' +
								'<div>' + __('List') + '</div>' +
							'</div></li>' +
						'</ul>').appendTo(this._elem);
						
						this._ulElem.children('li').on('click', function() {
							$(this).parent().children('li').removeClass('active');
							$(this).addClass('active');
							thisClass.updateComPropertiesGalleryType($(this).attr('data-value'));
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-galleryType-change', thisClass);
						}).css({cursor: 'pointer'});
						
						this.getValue = function() {
							var val = this._ulElem.children('li.active').attr('data-value');
							return val ? val : 'thumbs';
						};
						this.setValue = function(val) {
							this._ulElem.children('li').removeClass('active');
							var li = this._ulElem.children("li[data-value='" + val + "']");
							thisClass.updateComPropertiesGalleryType(li.attr('data-value'));
							li.addClass('active');
						};
					}},
					{type: 'HorizontalLayout', id: 'imageControlsRow1', columnWeights: [4, 4, 4, 4], children: [
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'galleryPaddingBlock', children: [
							{type: 'Label', text: __('Gallery padding (px)')},
							{type: 'SizeSelector', id: 'galleryPadding', min: 0, max: 999, repeat: false, change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-galleryPadding-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'galleryFrequencyBlock', children: [
							{type: 'Label', text: __('Image change frequency (s)'), helpText: __('Enter 0 seconds to disable automatic image changing')},
							{type: 'SizeSelector', id: 'galleryFrequency', min: 0, max: 10, repeat: false}
						]},
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'galleryThumbSizeBlock', children: [
							{type: 'Label', text: __('Thumbnail Size')},
							{type: 'FlowLayout', verticalAlign: 'middle', spacing: 5, children: [
								{type: 'SizeSelector', id: 'galleryThumbWidth', min: 10, repeat: false},
								{type: 'Label', html: '&times;', id: 'galleryThumbSizeTimesLabel', css: {fontWeight: 'normal', fontSize: 18}},
								{type: 'SizeSelector', id: 'galleryThumbHeight', min: 10, repeat: false}
							]}
						]},
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'galleryThumbAlignBlock', children: [
							{type: 'Label', text: __('Align')},
							{type: 'HAlignSelector', id: 'galleryThumbAlign', justify: false}
						]}
					]},
					{type: 'HorizontalLayout', id: 'imageControlsRow2', children: [
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'galleryImageCoverBlock', children: [
							{type: 'CheckBox', id: 'galleryImageCover', label: __('Auto crop'), /* css: {paddingTop: 25, height: 34}, */ init: function() {

							}}
						]}
					]}
				]},
				{name: __('Captions'), children: [
					{type: 'HorizontalLayout', columnWeights: [6, 6], children: [
						{type: 'VerticalLayout', css: {marginTop: 15}, id: 'pictureCaptionBlock', children: [
							{type: 'Label', text: __('Show picture caption')},
							{type: 'RadioBox', id: 'showPictureCaptionAlways', group: 'showPictureCaption', label: __('Always')},
							{type: 'RadioBox', id: 'showPictureCaptionOnHover', group: 'showPictureCaption', label: __('On mouse hover')}
						]},
						{type: 'VerticalLayout', css: {marginTop: 15}, children: [
							{type: 'Label', text: __('Caption background colour')},
							{type: 'ColorSelector', id: 'captionBackground', big: false}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Picture title style')},
						{type: 'FontSelector', id: 'captionTitleStyle', horizontal: true}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Picture description style')},
						{type: 'FontSelector', id: 'captionDescriptionStyle', horizontal: true}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.images = fields.galleryImages.getValues();
				thisClass.setBgColor(fields.galleryBgColor.getValue());
				thisClass.setFrequency(fields.galleryFrequency.getValue());
				thisClass.setType(fields.galleryType.getValue());
				thisClass.setBorder(fields.imageBorder.getValue());
				thisClass.setPadding(fields.galleryPadding.getValue());
				thisClass.setThumbWidth(fields.galleryThumbWidth.getValue());
				thisClass.setThumbHeight(fields.galleryThumbHeight.getValue());
				thisClass.setThumbAlign(fields.galleryThumbAlign.getValue());
				thisClass.setImageCover(fields.galleryImageCover.getValue());
				if( fields.showPictureCaptionOnHover.getValue() )
					thisClass.setShowPictureCaption("hover");
				else
					thisClass.setShowPictureCaption("always");
				thisClass.setCaptionBackground(fields.captionBackground.getValue());
				thisClass.setCaptionTitleStyle(fields.captionTitleStyle.getValue());
				thisClass.setCaptionDescriptionStyle(fields.captionDescriptionStyle.getValue());
				thisClass.render();
			}
		});
		
		fields.galleryType.setValue(this.type);
		fields.galleryBgColor.setValue(this.getBgColor());
		fields.galleryImages.setValues(this.images);
		fields.imageBorder.setValue(this.getBorder());
		fields.galleryFrequency.setValue(this.getFrequency());
		fields.galleryPadding.setValue(this.getPadding());
		fields.galleryThumbWidth.setValue(this.getThumbWidth());
		fields.galleryThumbHeight.setValue(this.getThumbHeight());
		fields.galleryThumbAlign.setValue(this.getThumbAlign());
		fields.galleryImageCover.setValue(this.getImageCover());

		fields.showPictureCaptionAlways.setValue(this.showPictureCaption === "always");
		fields.showPictureCaptionOnHover.setValue(this.showPictureCaption === "hover");
		fields.captionBackground.setValue(this.getCaptionBackground());
		fields.captionTitleStyle.setValue(this.getCaptionTitleStyle());
		fields.captionDescriptionStyle.setValue(this.getCaptionDescriptionStyle());
	};

	Gallery.prototype.initContextMenu = function(elem) {
		var thisClass = this;
		Element.prototype.initContextMenu.call(this, elem);
		if (!this.menu) return;

		var idx = this.contextMenuFirstIndex;

		this.menu.insertItemAt(idx++, "editGallery", __("Change pictures"), function() {
			thisClass.changePictures();
		}, null, null, null, "glyphicon glyphicon-picture");

		this.typeSubmenu = new ContextMenu(this.id + "_type_sub");
		this.typeSubmenu.addItem("gt_thumbs", __("Thumbnails"), function() {
			thisClass.setType("thumbs");
		}, null, null, null, "glyphicon glyphicon-th");
		this.typeSubmenu.addItem("gt_slide", __("Slideshow"), function() {
			thisClass.setType("slideshow");
		}, null, null, null, "glyphicon glyphicon-film");
		this.typeSubmenu.addItem("gt_list", __("List"), function() {
			thisClass.setType("list");
		}, null, null, null, "glyphicon glyphicon-align-justify");

		this.menu.insertItemAt(idx++, "changeType", __("Change type"), this.typeSubmenu,
			null, null, null, "glyphicon glyphicon-cog");

	//	this.menu.insertItemAt(idx++, "editGallery", __("Refresh"), function() {
	//		thisClass.render();
	//	}, null, null, null, "glyphicon glyphicon-refresh");

		$(this.menu.insertItemAt(idx++, "changeColor", __("Change color"), function() {

		}, null, null, null, "glyphicon glyphicon-edit")).ColorPicker({
			WB_ColorPicker: ColorPicker,
			color: thisClass.getBgColor(),
			onShow: function (colpkr) {
				thisClass.setBackupBgColor(thisClass.getBgColor());
			},
			onHide: function (colpkr) {
				thisClass.setBgColor(thisClass.getBackupBgColor());
				$(colpkr).hide();
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				thisClass.setBgColor('#' + hex);
			},
			onSubmit: function(hsb, hex, rgb, el) {
				thisClass.setBgColor('#' + hex);
				thisClass.setBackupBgColor(thisClass.getBgColor());
				$(el).ColorPickerHide();
			},
			onBeforeShow: function() {
				$(this).ColorPickerSetColor(thisClass.getBgColor());
			}
		});

		this.menu.addSeparator(idx++);
	};

	Gallery.prototype.updateContextMenu = function() {
		Element.prototype.updateContextMenu.call(this);

		var types = {gt_thumbs: "thumbs", gt_slide: "slideshow", gt_list: "list"};

		for (var k in types) {
			this.typeSubmenu.setSelected(k, this.type === types[k]);
		}
	};

	Gallery.prototype.remove = function() {
		if( this.metaChangeHandler ) {
			BuilderEvent.GlobalEvents.off("media.meta.changed", this.metaChangeHandler);
			this.metaChangeHandler = null;
		}
		Element.prototype.remove.call(this);
	};

	return Gallery;
});
;

/** WB News **/
(window.defineModule = (window.defineModule || {})).name = 'WB News';

define('News', ['ElementRegister', 'Element', 'Site', 'URLControl', 'ToolTipControl', 'SizeSelector', 'TextField'], function(ElementRegister, Element, Site, URLControl, ToolTipControl, SizeSelector, TextField) {
	'use strict';
	
	/**
	 * News element class
	 * @param {Object} data
	 */
	var News = function(data) { if (data) this.__construct(data); };

	News.prototype = new Element();
	News.prototype.constructor = News;
	ElementRegister.registerClass("News", News);

	News.prototype.noPhotoBg = 'ico-tb-news';
	News.prototype.items = null;
	News.prototype.fullPosts = false;
	News.prototype.showNames = true;
	News.prototype.showDesc = true;
	News.prototype.showScroll = false;
	News.prototype.nameStyle = null;
	News.prototype.descStyle = null;
	News.prototype.numItems = 3;
	News.prototype.moreTitle = __("Read more...");

	/**
	 * Construct news element
	 * @param {Object} data news data object
	 */
	News.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		this.items = [];

		if (data.content.items) {
			for (var i = 0; i < data.content.items.length; i++) {
				var item = new News.NewsItem(data.content.items[i]);
				this.addItem(item);
			}
		}

		this.fullPosts = WB_Builder.isset(data.content.fullPosts) ? (data.content.fullPosts ? true : false) : this.fullPosts;
		this.showNames = WB_Builder.isset(data.content.showNames) ? (data.content.showNames ? true : false) : this.showNames;
		this.showDesc = WB_Builder.isset(data.content.showDesc) ? (data.content.showDesc ? true : false) : this.showDesc;
		this.showScroll = WB_Builder.isset(data.content.showScroll) ? (data.content.showScroll ? true : false) : this.showScroll;
		this.nameStyle = WB_Builder.isset(data.content.nameStyle) ? data.content.nameStyle : this.nameStyle;
		this.descStyle = WB_Builder.isset(data.content.descStyle) ? data.content.descStyle : this.descStyle;
		this.numItems = (WB_Builder.isset(data.content.numItems) && !isNaN(parseInt(data.content.numItems, 10))) ? parseInt(data.content.numItems, 10) : this.numItems;
		this.moreTitle = WB_Builder.isset(data.content.moreTitle) ? data.content.moreTitle : this.moreTitle;

		// generate news items for new menu
		if (!data.id) {
			var page = null, copyFrom = null;
			//find non-front page to copy from (or front if no other pages present)
			for (var pid in this.system.site.pages) {
				if (!copyFrom) copyFrom = this.system.site.pages[pid];
				if (this.system.site.pages[pid].isFront) continue;
				copyFrom = this.system.site.pages[pid];
				break;
			}
			this.system.site.addPage((page = new Site.Page({
				id: this.system.site.getFreeId(),
				title: (__("New News item") + " 1"),
				copyFrom: (copyFrom ? copyFrom.id : null)
			})));
			this.addItem(new News.NewsItem({
				name: (__("New News item") + " 1"),
				pageId: {
					type: "page",
					url: page.id
				}
			}));
			this.system.site.addPage((page = new Site.Page({
				id: this.system.site.getFreeId(),
				title: (__("New News item") + " 2"),
				copyFrom: (copyFrom ? copyFrom.id : null)
			})));
			this.addItem(new News.NewsItem({
				name: (__("New News item") + " 2"),
				pageId: {
					type: "page",
					url: page.id
				}
			}));		
		}

		this.updateStyle(true);

		var thisClass = this;
		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/**
	 * Serialize this element
	 * @return object
	 */
	News.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		var items = [];

		for (var i = 0; i < this.items.length; i++) {
			items.push(this.items[i].serialize());
		}

		data.content = {
			fullPosts: this.fullPosts,
			showNames: this.showNames,
			showDesc: this.showDesc,
			showScroll: this.showScroll,
			nameStyle: this.nameStyle,
			descStyle: this.descStyle,
			numItems: this.numItems,
			moreTitle: this.moreTitle,
			items: items
		};

		return data;
	};

	/**
	 * Add news item
	 * @param item item to add
	 */
	News.prototype.addItem = function(item) {
		if (item.parent) {
			item.parent.removeItem(item);
			item.parent = null;
			item.index = -1;
		}
		item.parent = this;
		item.index = this.items.length;
		this.items.push(item);
		this.container.append(item.elem);
	};

	/**
	 * Remove news item
	 * @param item item to remove
	 */
	News.prototype.removeItem = function(item) {
		if (!item.parent || item.parent !== this) return;
		item.parent = null;
		if (item.index < 0 || item.index >= this.items.length) {
			item.index = -1;
			return;
		}
		this.items.splice(item.index, 1);
		item.index = -1;
		item.elem.detach();
		for (var i = 0; i < this.items.length; i++) { this.items[i].index = i; } // update indexes
	};

	/**
	 * Remove all items
	 */
	News.prototype.removeAllItems = function() {
		for (var i = (this.items.length - 1); i >= 0; i--) {
			this.removeItem(this.items[i]);
		}
		this.items = [];
	};

	/**
	 * Update element style after property changes
	 */
	News.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		this.displayEmtyMessage(this.items.length === 0);

		if (!this.showNames) {
			$(".ttl", this.container.children()).hide();
		} else {
			$(".ttl", this.container.children()).show();
		}
		if (!this.showDesc) {
			$(".desc", this.container.children()).hide();
		} else {
			$(".desc", this.container.children()).show();
		}

		if (this.nameStyle) $(".ttl", this.container.children()).addClass(this.nameStyle);
		if (this.descStyle) $(".desc", this.container.children()).addClass(this.descStyle);

		this.container.css({
			"overflow-x": "hidden",
			"overflow-y": (this.showScroll ? "scroll" : "hidden")
		});
		this.container.children().show();
		if (this.numItems > 0) {
			var thisClass = this;
			this.container.children().each(function(idx) {
				if (idx < thisClass.numItems) return;
				$(this).hide();
			});
		}
	};

	/**
	 * Extend element properties dialog
	 */
	News.prototype.comProperties = function() {
		Element.prototype.comProperties.call(this);
		var thisClass = this;
		var fields = this.comDialog.fields;
		if (!fields.newsShowName) {
			this.comDialog.setMaxBodyHeight(500);
			this.comDialog.setNoScroll();
			this.comDialog.tabbedPane.setFixedHeight(240);
			this.comDialog.tabbedPane.setNoScroll();

			var gTab = this.comDialog.getGeneralTab().contentElem;
			var td = null, tds = null, lbl = null, idx = 0;

			gTab.append(tds = $('<table>' +
					'<tr><td></td><td colspan="2"></td></tr>' +
					'<tr><td rowspan="2"></td><td></td><td></td></tr>' +
					'<tr><td></td><td></td></tr>' +
					'<tr><td></td><td colspan="2"></td></tr>' +
				'</table>'));
			tds.css({ width: "100%" });
			tds = $('td', tds);
			tds.css({ verticalAlign: "top" });

			td = tds.eq(idx++);
			td.css({ width: "50%" });
			td.append('<label>' + __("Show") + '</label>');

			td = tds.eq(idx++);
			td.append('<label>' + __("Styles") + '</label>');

			td = tds.eq(idx++);
			td.append((fields.newsShowName = new WB_CheckBoxControl(__("News Names"))).elem);
			td.append((fields.newsShowDesc = new WB_CheckBoxControl(__("News Descriptions"))).elem);
			td.append((fields.newsShowScroll = new WB_CheckBoxControl(__("Scroll"))).elem);

			td = tds.eq(idx++);
			td.css({ verticalAlign: "middle" });
			td.append('<label>' + __("Names") + '</label>');

			td = tds.eq(idx++);
			td.append((fields.newsNameStyle = new WB_StyleControl()).elem);
			fields.newsNameStyle.input.css({ width: "80px" });

			td = tds.eq(idx++);
			td.css({ verticalAlign: "middle" });
			td.append('<label>' + __("Descriptions") + '</label>');

			td = tds.eq(idx++);
			td.append((fields.newsDescStyle = new WB_StyleControl()).elem);
			fields.newsDescStyle.input.css({ width: "80px" });

			td = tds.eq(idx++);
			td.append(lbl = $('<label>' + __("Number of items to show") + '</label>'));
			td.append((fields.newsNumItems = new SizeSelector(true)).elem);
			lbl.append((new ToolTipControl("?", __('Number of items = 0 means show all items.'))).elem);

			td = tds.eq(idx++);
			td.append('<label>' + __('"Read more" link text'/* ctx: Option name in News plugin properties */) + '</label>');
			td.append((fields.newsMoreTitle = new TextField()).elem);

			var itemsTab = this.comDialog.tabbedPane.addTab(__("Items"), 0);
			this.comDialog.tabbedPane.selectTab(0);

			itemsTab.contentElem.append(tds = $('<table>' +
					'<tr><td></td><td></td></tr>' +
				'</table>'));
			tds = $('td', tds); idx = 0;
			tds.css({verticalAlign: "top"});

			td = tds.eq(idx++);
			td.css({ paddingRight: "20px" });
			td.append((fields.newslistElem = new WB_ListControl({
				type: News.NewsItem,
				onSelect: function(item) {
					if (fields.newslistElem.lastSelected) {
						fields.newslistElem.lastSelected.name = fields.newsItemName.getValue();
						fields.newslistElem.lastSelected.description = fields.newsItemDesc.getValue();
						fields.newslistElem.lastSelected.pageId = fields.newsItemPage.getValue();
					}
					fields.newsItemName.setValue(item.name);
					fields.newsItemDesc.setValue(item.description);
					fields.newsItemPage.setValue(item.pageId);
					fields.newsItem.wbSetClassInstance($(this));
					fields.newsItem.show();
				}
			})).elem);

			td = tds.eq(idx++);
			td.append(fields.newsItem = $('<div></div>'));
			fields.newsItem.hide();
			td = fields.newsItem;
			td.append('<label>' + __("Name") + '</label>');
			td.append((fields.newsItemName = new TextField()).elem);
			fields.newsItemName.input.addClass("span3");
			td.append('<label>' + __("Description") + '</label>');
			td.append((fields.newsItemDesc = new WB_TextAreaControl()).elem);
			fields.newsItemDesc.input.addClass("span3");
			td.append('<label>' + __("URL") + '</label>');
			td.append((fields.newsItemPage = new URLControl()).elem);

			var cfb = fields.callbackFunc;
			fields.callbackFunc = function() {
				if (typeof(cfb) === "function") cfb.call(this);

				thisClass.showNames = fields.newsShowName.getValue();
				thisClass.showDesc = fields.newsShowDesc.getValue();
				thisClass.showScroll = fields.newsShowScroll.getValue();
				thisClass.nameStyle = fields.newsNameStyle.getValue();
				thisClass.descStyle = fields.newsDescStyle.getValue();
				thisClass.numItems = fields.newsNumItems.getValue();
				thisClass.moreTitle = fields.newsMoreTitle.getValue();

				if (fields.newslistElem.lastSelected) {
					fields.newslistElem.lastSelectedLi.trigger("click");
				}

				thisClass.removeAllItems();
				var list = fields.newslistElem.getValue();
				for (var i = 0; i < list.length; i++) {
					thisClass.addItem(list[i]);
				}

				thisClass.updateStyle();
			};
		}
		fields.newsShowName.setValue(thisClass.showNames);
		fields.newsShowDesc.setValue(thisClass.showDesc);
		fields.newsShowScroll.setValue(thisClass.showScroll);
		fields.newsNameStyle.update();
		fields.newsNameStyle.setValue(thisClass.nameStyle);
		fields.newsDescStyle.update();
		fields.newsDescStyle.setValue(thisClass.descStyle);
		fields.newsNumItems.setValue(thisClass.numItems);
		fields.newsMoreTitle.setValue(thisClass.moreTitle);

		fields.newslistElem.removeAllItems();
		for (var i = 0; i < this.items.length; i++) {
			fields.newslistElem.addItem(this.items[i]);
		}
		fields.newsItem.hide();
	};

	(function(WB_News) {

		/**
		 * News item class
		 * 
		 * @author Marius Tomas <marius@profis.lt>
		 * @version 1.0.1, 2012-09-05
		 */
		function NewsItem(data) { if (data) this.__construct(data); }
		WB_News.NewsItem = NewsItem;

		NewsItem.nextItemIdx = 0;
		NewsItem.prototype.id = null;
		NewsItem.prototype.parent = null;
		NewsItem.prototype.index = null;
		NewsItem.prototype.name = null;
		NewsItem.prototype.description = null;
		NewsItem.prototype.pageId = null;
		NewsItem.prototype.elem = null;
		NewsItem.prototype.aElem = null;
		NewsItem.prototype.dElem = null;
		NewsItem.prototype.virtual = false;

		/**
		 * Construct news item
		 * @param data news item data object
		 */
		NewsItem.prototype.__construct = function(data) {
			if (!data) data = {};
			this.id = data.id ? data.id : (NewsItem.nextItemIdx++);
			this.name = data.name ? data.name : __("New Item");
			this.description = data.description ? data.description : "";
			this.pageId = data.pageId ? data.pageId : null;
			this.virtual = data.virtual ? true : false;

			if (!this.virtual) {
				this.elem = $('<div></div>');

				this.aElem = $('<a class="ttl" href="javascript:void(0)"></a>');
				this.elem.append(this.aElem);
			}
			this.setName(this.name);

			if (!this.virtual) {
				this.dElem = $('<div class="desc"></div>');
				this.elem.append(this.dElem);
			}
			this.setDescription(this.description);
		};

		/**
		 * Serialize this element
		 * @return object
		 */
		NewsItem.prototype.serialize = function() {
			return {
				id: this.id,
				name: this.name,
				description: this.description,
				pageId: this.pageId
			};
		};

		/**
		 * Set item name
		 * @param name name to set
		 */
		NewsItem.prototype.setName = function(name) {
			this.name = name;
			if (!this.virtual) this.aElem.html(this.name);
		};

		/**
		 * Set item description
		 * @param desc description to set
		 */
		NewsItem.prototype.setDescription = function(desc) {
			this.description = desc;
			if (!this.virtual) this.dElem.html(this.description);
		};

	})(News);
	
	return News;
});
;

/** WB Blog **/
(window.defineModule = (window.defineModule || {})).name = 'WB Blog';

define('Blog', ['ElementRegister', 'Element', 'ToolTipControl', 'SizeSelector', 'ComboBox', 'TextField'], function(ElementRegister, Element, ToolTipControl, SizeSelector, ComboBox, TextField) {
	'use strict';
	
	/**
	 * Blog element class
	 * @param {Object} data
	 */
	var Blog = function(data) { if (data) this.__construct(data); };

	Blog.prototype = new Element();
	Blog.prototype.constructor = Blog;
	ElementRegister.registerClass("Blog", Blog);

	Blog.prototype.noPhotoBg = 'ico-tb-blog';
	Blog.prototype.items = null;
	Blog.prototype.fullPosts = false;
	Blog.prototype.onlyNames = false;
	Blog.prototype.showScroll = false;
	Blog.prototype.numItems = 3;

	/**
	 * Construct blog element
	 * @param data blog data object
	 */
	Blog.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		this.items = [];

		if (data.content.items) {
			for (var i = 0; i < data.content.items.length; i++) {
				var item = new Blog.BlogItem(data.content.items[i]);
				this.addItem(item);
			}
		}

		this.fullPosts = data.content.fullPosts ? true : false;
		this.onlyNames = data.content.onlyNames ? true : false;
		this.showScroll = data.content.showScroll ? true : false;
		this.numItems = (data.content.numItems*1) ? data.content.numItems : 0;

		this.updateStyle(true);

		var thisClass = this;
		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/**
	 * Serialize this element
	 * @return object
	 */
	Blog.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		var items = [];

		for (var i = 0; i < this.items.length; i++) {
			items.push(this.items[i].serialize());
		}

		data.content = {
			fullPosts: this.fullPosts,
			onlyNames: this.onlyNames,
			showScroll: this.showScroll,
			numItems: this.numItems,
			items: items
		};

		return data;
	};

	/**
	 * Add blog item
	 * @param item item to add
	 */
	Blog.prototype.addItem = function(item) {
		if (item.parent) {
			item.parent.removeItem(item);
			item.parent = null;
			item.index = -1;
		}
		item.parent = this;
		item.index = this.items.length;
		this.items.push(item);
		this.container.append(item.elem);
	};

	/**
	 * Remove blog item
	 * @param item item to remove
	 */
	Blog.prototype.removeItem = function(item) {
		if (!item.parent || item.parent !== this) return;
		item.parent = null;
		if (item.index < 0 || item.index >= this.items.length) {
			item.index = -1;
			return;
		}
		this.items.splice(item.index, 1);
		item.index = -1;
		item.elem.detach();
	};

	/**
	 * Remove all items
	 */
	Blog.prototype.removeAllItems = function() {
		for (var i = 0; i < this.items.length; i++) {
			this.removeItem(this.items[i]);
		}
		this.items = [];
	};

	/**
	 * Update element style after property changes
	 */
	Blog.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		this.displayEmtyMessage(this.items.length === 0);

		if (this.onlyNames) {
			$(".desc", this.container.children()).hide();
		} else {
			$(".desc", this.container.children()).show();
		}
		this.container.css({
			"overflow-x": "hidden",
			"overflow-y": (this.showScroll ? "scroll" : "hidden")
		});
		this.container.children().show();
		if (this.numItems > 0) {
			var thisClass = this;
			this.container.children().each(function(idx) {
				if (idx < thisClass.numItems) return;
				$(this).hide();
			});
		}
	};

	/**
	 * Extend element properties dialog
	 */
	Blog.prototype.comProperties = function() {
		Element.prototype.comProperties.call(this);
		var thisClass = this;
		var fields = this.comDialog.fields;
		if (!fields.blogOnlyName) {
			this.comDialog.setMaxBodyHeight(500);
			this.comDialog.tabbedPane.setFixedHeight(240);

			var gTab = this.comDialog.getGeneralTab().contentElem;
			var td = null, tds = null, lbl = null, idx = 0;

			gTab.append(tds = $('<table>' +
					'<tr><td></td><td colspan="2"></td></tr>' +
					'<tr><td rowspan="2"></td><td></td><td></td></tr>' +
					'<tr><td></td><td></td></tr>' +
					'<tr><td></td><td colspan="2"></td></tr>' +
				'</table>'));
			tds.css({ width: "100%" });
			tds = $('td', tds);
			tds.css({ verticalAlign: "top" });

			td = tds.eq(idx++);
			td.css({ width: "50%" });
			td.append('<label>' + __("Show") + '</label>');

			td = tds.eq(idx++);
			//td.append('<label>' + __("Styles") + '</label>');

			td = tds.eq(idx++);
			td.append((fields.blogOnlyName = new WB_CheckBoxControl(__("Show only names"))).elem);
			td.append((fields.blogShowScroll = new WB_CheckBoxControl(__("Show scroll"))).elem);

			td = tds.eq(idx++);
			td = tds.eq(idx++);
			td = tds.eq(idx++);
			td = tds.eq(idx++);

			td = tds.eq(idx++);
			td.append(lbl = $('<label>' + __("Number of items to show") + '</label>'));
			td.append((fields.blogNumItems = new SizeSelector(true)).elem);
			lbl.append((new ToolTipControl("?", __('Number of items = 0 means show all items.'))).elem);

			var itemsTab = this.comDialog.tabbedPane.addTab(__("Items"), 0);
			this.comDialog.tabbedPane.selectTab(0);

			itemsTab.contentElem.append(tds = $('<table>' +
					'<tr><td></td><td></td></tr>' +
				'</table>'));
			tds = $('td', tds);
			tds.css({verticalAlign: "top"});

			td = tds.eq(idx++);
			fields.bloglistElem = $('<div class="wb_list"></div>');
			fields.bloglistElem.addItem = function(item) {
				var elem = $('<a class="wb_list_item"></a>');
				elem.wbSetClassInstance(item);
				elem.html(item.name);
				elem.bind("click", function() {
					$(this).parent().children().removeClass("active");
					$(this).addClass("active");
					fields.blogItemPage.removeAllOptions();
					var firstPid = null;
					for (var pid in thisClass.system.site.pages) {
						if (!firstPid) firstPid = pid;
						var p = thisClass.system.site.pages[pid];
						fields.blogItemPage.addOption(p.id, p.title);
					}
					if (!item.pageId) item.pageId = firstPid;
					fields.blogItemName.setValue(item.name);
					fields.blogItemDesc.setValue(item.description);
					fields.blogItemPage.setValue(item.pageId);
					fields.blogItem.wbSetClassInstance(elem);
					fields.blogItem.show();
				});
				fields.bloglistElem.append(elem);
			};
			td.append(fields.bloglistElem);
			fields.bloglistElem.css({
				width: "200px",
				height: "190px",
				overflowY: "scroll",
				border: "1px solid #dddddd",
				margin: "0px 10px 0px 0px"
			});
			var addBtn = $('<button class="btn"><i class="icon-plus"></i>&nbsp;' +
					__("Add item") + '</button>');
			addBtn.css({marginTop: "10px"});
			addBtn.bind("click", function() {
				fields.bloglistElem.addItem(new Blog.BlogItem());
			});
			td.append(addBtn);

			td = tds.eq(idx++);
			td.append(fields.blogItem = $('<div></div>'));
			fields.blogItem.hide();
			td = fields.blogItem;
			td.append('<label>' + __("Name") + '</label>');
			td.append((fields.blogItemName = new TextField()).elem);
			fields.blogItemName.input.addClass("span3");
			fields.blogItemName.input.bind("blur change", function() {
				var elem = fields.blogItem.wbGetClassInstance();
				var item = elem.wbGetClassInstance();
				item.setName(fields.blogItemName.getValue());
				elem.html(item.name);
			});
			td.append('<label>' + __("Description") + '</label>');
			td.append((fields.blogItemDesc = new WB_TextAreaControl()).elem);
			fields.blogItemDesc.input.addClass("span3");
			fields.blogItemDesc.input.bind("blur change", function() {
				var elem = fields.blogItem.wbGetClassInstance();
				var item = elem.wbGetClassInstance();
				item.setDescription(fields.blogItemDesc.getValue());
			});
			td.append('<label>' + __("Page") + '</label>');
			td.append((fields.blogItemPage = new ComboBox()).elem);
			fields.blogItemPage.input.addClass("span3");
			fields.blogItemPage.input.bind("blur change", function() {
				var elem = fields.blogItem.wbGetClassInstance();
				var item = elem.wbGetClassInstance();
				item.pageId = fields.blogItemPage.getValue();
			});

			var cfb = fields.callbackFunc;
			fields.callbackFunc = function() {
				if (typeof(cfb) === "function") cfb.call(this);
				thisClass.onlyNames = fields.blogOnlyName.getValue();
				thisClass.showScroll = fields.blogShowScroll.getValue();
				thisClass.numItems = fields.blogNumItems.getValue();

				thisClass.removeAllItems();
				fields.bloglistElem.children().each(function() {
					thisClass.addItem($(this).wbGetClassInstance());
				});

				thisClass.updateStyle();
			};
		}
		fields.blogOnlyName.setValue(thisClass.onlyNames);
		fields.blogShowScroll.setValue(thisClass.showScroll);
		fields.blogNumItems.setValue(thisClass.numItems);

		fields.bloglistElem.empty();
		for (var i = 0; i < this.items.length; i++) {
			//console.log(this.items[i].name);
			fields.bloglistElem.addItem(this.items[i]);
		}
		fields.blogItem.hide();
	};

	(function(Blog) {

		/**
		 * Blog item class
		 * @param {Object} data
		 */
		var BlogItem = function(data) { if (data) this.__construct(data); };
		Blog.BlogItem = BlogItem;

		BlogItem.nextItemIdx = 0;
		BlogItem.prototype.id = null;
		BlogItem.prototype.parent = null;
		BlogItem.prototype.index = null;
		BlogItem.prototype.name = null;
		BlogItem.prototype.description = null;
		BlogItem.prototype.pageId = null;
		BlogItem.prototype.elem = null;
		BlogItem.prototype.aElem = null;
		BlogItem.prototype.dElem = null;

		/**
		 * Construct blog item
		 * @param data blog item data object
		 */
		BlogItem.prototype.__construct = function(data) {
			if (!data) data = {};
			this.id = data.id ? data.id : (BlogItem.nextItemIdx++);
			this.name = data.name ? data.name : __("New Item");
			this.description = data.description ? data.description : "";
			this.pageId = data.pageId ? data.pageId : null;

			this.elem = $('<div></div>');

			this.aElem = $('<a href="javascript:void(0)"></a>');
			this.elem.append(this.aElem);
			this.setName(this.name);

			this.dElem = $('<div class="desc"></div>');
			this.elem.append(this.dElem);
			this.setDescription(this.description);
		};

		/**
		 * Serialize this element
		 * @return object
		 */
		BlogItem.prototype.serialize = function() {
			return {
				id: this.id,
				name: this.name,
				description: this.description,
				pageId: this.pageId
			};
		};

		/**
		 * Set item name
		 * @param name name to set
		 */
		BlogItem.prototype.setName = function(name) {
			this.name = name;
			this.aElem.html(this.name);
		};

		/**
		 * Set item description
		 * @param desc description to set
		 */
		BlogItem.prototype.setDescription = function(desc) {
			this.description = desc;
			this.dElem.html(this.description);
		};

	})(Blog);

	return Blog;
});
;

/** WB Form **/
(window.defineModule = (window.defineModule || {})).name = 'WB Form';

define('Form', [
	'ElementRegister',
	'Element',
	'Service',
	'ModeManager'
], function(ElementRegister, Element, Service, ModeManager) {
	
	var wb_builder = window.wb_builder;
	
	/**
	 * Form element class
	 * @param {Object} data
	 * @param {boolean} initial
	 * @param {boolean} virtual
	 */
	var Form = function(data, initial, virtual) { if (data) this.__construct(data, initial, virtual); };

	Form.prototype = new Element();
	Form.prototype.constructor = Form;
	ElementRegister.registerClass("Form", Form);

	Form.defaultFields = [
		{checked: true, type: "input", name: __("Name"), options: "", required: true},
		{checked: true, type: "input", name: __("Email"), options: "", required: true},
		{checked: false, type: "input", name: __("Country"), options: "", required: true},
		{checked: false, type: "input", name: __("City"), options: "", required: true},
		{checked: false, type: "input", name: __("Address"), options: "", required: true},
		{checked: false, type: "input", name: __("Your Field"), options: "", required: true},
		{checked: false, type: "input", name: __("Your Field"), options: "", required: true},
		{checked: false, type: "select", name: __("How did you find us?"), options: __("Found on google;Followed link from other site;Friend told me"), required: true},
		{checked: false, type: "select", name: __("Your Question?"), options: __("Yes;No;May be"), required: true},
		{checked: true, type: "textarea", name: __("Message"), options: "", required: true},
		{checked: false, type: "file", name: __("Attachments"), options: "", required: false},
		{checked: false, type: "checkbox", name: __("I want to receive newsletters"), options: "", required: false},
		{checked: false, type: "checkbox", name: __("I agree to the Terms and Conditions"), options: "", required: true}
	];
	Form.prototype.fields = null;
	Form.prototype.email = "";
	Form.prototype.emailFrom = "";
	Form.prototype.subject = __("Email from the site");
	Form.prototype.formSentMessage = __("Form was sent.");
	Form.prototype.button = __("Submit");
	Form.prototype.smtpEnable = false;
	Form.prototype.smtpHost = null;
	Form.prototype.smtpPort = null;
	Form.prototype.smtpEncryption = null;
	Form.prototype.smtpUsername = null;
	Form.prototype.smtpPassword = null;
	Form.prototype.recSiteKey = null;
	Form.prototype.recSecretKey = null;
	Form.prototype.form = null;
	Form.prototype.textStyle = null;
	Form.prototype.labelStyle = null;
	Form.prototype.labelColWidth = 0;
	Form.prototype.regularsTab = null;
	Form.prototype.maxFileSizeTotal = 2;

	/**
	 * Construct form element
	 * @param {Object} data form data object
	 * @param {boolean} initial
	 * @param {boolean} virtual
	 */
	Form.prototype.__construct = function(data, initial, virtual) {
		if (!data.width) {
			data.width = 350;
			data.height = 216;
		}
		Element.prototype.__construct.call(this, data, initial, virtual);
		this.addLangLabel();

		this.setMinSize(200, 200);
		this.container.css({overflow: "hidden"});
		this.fields = $.extend(true, {}, Form.defaultFields);
		// deserialize

		if (WB_Builder.isset(data.content.fields)) {
			this.fields = data.content.fields;
			for (var i = 0; i < Form.defaultFields.length; i++) {
				if (!this.fields[i] || typeof this.fields[i] !== 'object') this.fields[i] = $.extend(true, {}, Form.defaultFields[i]);
				else if (!('type' in this.fields[i] && "required" in this.fields[i])) this.fields[i] = $.extend({}, Form.defaultFields[i], this.fields[i]);
			}
			this.email = data.content.email;
			this.emailFrom = data.content.emailFrom ? data.content.emailFrom : '';
			this.subject = data.content.subject ? data.content.subject : this.subject;
			this.formSentMessage = data.content.sentMessage ? data.content.sentMessage : this.formSentMessage;
			this.button = data.content.button;
			this.smtpEnable = data.content.smtpEnable ? data.content.smtpEnable : false;
			this.smtpHost = data.content.smtpHost ? data.content.smtpHost : null;
			this.smtpPort = data.content.smtpPort ? data.content.smtpPort : null;
			this.smtpEncryption = data.content.smtpEncryption ? data.content.smtpEncryption : null;
			this.smtpUsername = data.content.smtpUsername ? data.content.smtpUsername : null;
			this.smtpPassword = data.content.smtpPassword ? data.content.smtpPassword : null;
			this.recSiteKey = data.content.recSiteKey ? data.content.recSiteKey : null;
			this.recSecretKey = data.content.recSecretKey ? data.content.recSecretKey : null;
			this.maxFileSizeTotal = data.content.maxFileSizeTotal ? data.content.maxFileSizeTotal : 2;
			this.labelColWidth = data.content.labelColWidth ? data.content.labelColWidth : this.labelColWidth;
		}

		this.textStyle = data.content.textStyle ? data.content.textStyle : {
			color: "#333333",
			size: 13,
			decoration: "none",
			font: "Arial,sans-serif",
			style: { },
			align: "left",
			lineHeight: 18, 
			css: {
				font: "normal normal 13px Arial,sans-serif",
				color: "#333333",
				"text-align": "left",
				"text-decoration": "none",
				"line-height": "18px"
			}
		};

		var thisClass = this;
		this.elem.bind('resize', function() {
			var i, tds, field,
				row,
				rows = $('tr', thisClass.container),
				count = rows.length,
				w = thisClass.getWidth(),
				h = thisClass.getHeight(),
				flex,
				flexH = h - 4,
				lws = [],
				flexElem = null;
			// $('input[type=text],select,textarea', thisClass.container).css({width: w});
			for (i = 0; i < count; i++) {
				lws[i] = rows.eq(i).children('td,th').eq(0).outerWidth(true);
			}
			for (i = 0; i < count; i++) {
				row = rows.eq(i);
				flex = ($('textarea', row).size() > 0);
				if (!flex) {
					flexH -= row.outerHeight(true);
				} else {
					flexElem = $('textarea', row);
					var thh = $('th', row).outerHeight();
					if (thh < row.outerHeight(true)) {
						flexH -= thh;
					}
				}
				tds = row.children('td,th');
				if (tds.length === 2) {
					field = tds.eq(1).find('input[type=text],input[type=file],select,textarea').eq(0);
					// field.css({width: (w - lws[i])});
				}
			}
			if (flexElem) {
				flexElem.css({height: flexH + 'px'});
			}
		});

		this.labelStyle = WB_Builder.isset(data.content.labelStyle) ? data.content.labelStyle : this.labelStyle;

		this.updateStyle(true);

		setTimeout(function() { thisClass.elem.trigger("resize"); }, 0);
		setTimeout(function() { thisClass.elem.trigger("resize"); }, 1000);

		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/**
	 * @param {Object} data
	 * @return {Form.Mode}
	 */
	Form.prototype.modeClass = function(data) {
		return new Form.Mode(data);
	};
	
	/** @return {String} */
	Form.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = this.subject ? this.subject : '';
		return opts;
	};
	
	/**
	 * Rechecking all form (editing) fields and styling as needed
	 */
	Form.prototype.recheckInactive = function() {

	};

	/**
	 * Serialize this element
	 * @return {Object}
	 */
	Form.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);
		var m;
		if (Service.modeManager.getUseModes()) {
			var mode = ModeManager.getMode();
			m = this.modes[mode].serialize();
		} else {
			m = {
				labelColWidth: this.labelColWidth,
				fieldsWidth: this.container.find('input[type=text],input[type=file],select,textarea').outerWidth(),
				flexHeight:	this.container.find('textarea').outerHeight()
			};
		}

		//var color = this.textColor;
		var d = new Date();

		data.content = {
			labelColWidth: m.labelColWidth,
			fieldsWidth:m.fieldsWidth,
			flexHeight:	m.flexHeight,
			fields:		this.fields,
			email:		this.email,
			emailFrom:	this.emailFrom,
			subject:	this.subject,
			sentMessage:this.formSentMessage,
			button:		this.button,
			smtpEnable: this.smtpEnable,
			smtpHost: this.smtpHost,
			smtpPort: this.smtpPort,
			smtpEncryption: this.smtpEncryption,
			smtpUsername: this.smtpUsername,
			smtpPassword: this.smtpPassword,
			recSiteKey: this.recSiteKey,
			recSecretKey: this.recSecretKey,
			maxFileSizeTotal: this.maxFileSizeTotal,
			textStyle:	this.textStyle,
			labelStyle:	this.labelStyle,
			timestamp:	d.getTime()
		};

		return data;
	};
	
	Form.prototype.switchMode = function(fromMode, toMode, initial, manual) {
		Element.prototype.switchMode.call(this, fromMode, toMode, initial, manual);
		if (!Service.modeManager.getUseModes()) return;
		if (toMode === ModeManager.MODE_PHONE) {
			var formId = this.id + '_form';
			if (!this.mobStyle) {
				this.mobStyle = $('<style type="text/css">' +
					'#' + formId + ' table td, #' + formId + ' table th, #' + formId + ' table tr { display: block; height: auto!important; } ' +
					'#' + formId + ' table td input, #' + formId + ' table td textarea { width: 100%!important; }' +
					'#' + formId + ' table td .checkbox-label input { width: auto!important; }' +
				'</style>');
			}
			this.form.attr('id', formId);
			this.elem.prepend(this.mobStyle);
		} else {
			if (this.mobStyle) this.mobStyle.detach();
			this.form.removeAttr('id');
		}
	};

	/**
	 * Update element style after property changes
	 * @param {String} langCode
	 */
	Form.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		langCode = langCode || this.system.site.currSelLang;
		var thisClass = this, html, field, i, w, h, fld;
		var langRtl = wb_builder.site.isRtlLang(langCode);
		if (!this.form) {
			this.form = $('<form class="wb_form"></form>');
			this.form.bind("submit", function() { return false; });
			this.form.css({width: "100%", height: "100%"});
			this.container.append(this.form);
		}
		if (langRtl) {
			this.form.addClass('wb_form_rtl');
		} else {
			this.form.removeClass('wb_form_rtl');
		}
		this.form.empty();
		html = "";
		html += '<table>';
		for (i = 0; i < Form.defaultFields.length; i++) {
			field = this.fields[i];
			if (!field || !field.checked || !__tr(field.name, langCode))
				continue;
			w = (this.labelColWidth ? (' width: ' + this.labelColWidth + 'px; white-space: normal;') : '');
			h = (field.type === 'textarea') ? '' : ' height: 1%;';
			fld = "";
			switch (field.type) {
				case "input":
					fld += '<input type="text" class="form-control form-field" value="" />';
					break;
				case "select":
					fld += '<select class="form-control form-field">';
					var opts = __tr(field.options, langCode).split(";");
					for( var j = 0; j < opts.length; j++ )
						fld += '<option>' + $.trim(opts[j]).replace("<", "&lt;").replace(">", "&gt;") + '</option>';
					fld += '</select>';
					break;
				case "textarea":
					fld += '<textarea class="form-control form-field"></textarea>';
					break;
				case "file":
					fld += '<input class="form-control form-field" type="file" multiple="multiple" />';
					break;
				case "checkbox":
					fld += '<label class="checkbox-label"><input type="checkbox" class="form-control form-field" value="1" /> ' + __tr(field.name, langCode) + '</label>';
					break;
			}
			html += '<tr>' +
					'<th style="' + h + w + '">' +
						(w ? '<div style="' + w + '">' : '') +
							((field.type === 'checkbox') ? '' : __tr(field.name, langCode)) + '&nbsp;&nbsp;' +
						(w ? '</div>' : '') +
					'</th>' +
					'<td style="' + h + '">' + fld + '</td>' +
				'</tr>';
		}
		if (this.recSiteKey && this.recSecretKey) {
			// reCAPTCHA is enabled
			html += '<tr>' +
						'<th style="height: 1%;">&nbsp;</th>' +
						'<td style="height: 1%;"><div class="wb-recaptcha-placeholder"><span>' + __("I'm not a robot") + '</span></div></td>' +
					'</tr>';
		}
		html += '<tr>' +
					'<td height="20" colspan="2">' +
						'<button type="submit" class="btn btn-default">' + __tr(this.button, langCode) + '</button>' +
					'</td>' +
				'</tr>' +
			'</table>';
		this.form.append(html);
		this.form.css({width: "100%", height: "100%"});

		this.form.css(this.textStyle.css);
		//$("th", this.form).css(this.textStyle.css);
		if (this.labelStyle) $("th,.checkbox-label", this.form).addClass(this.labelStyle);
		if (langRtl) {
			$("td", this.form).css({textAlign: "left"});
		} else {
			$("td", this.form).css({textAlign: "right"});
		}

		thisClass.elem.trigger("resize");
	};

	Form.prototype.createSimpleFieldUI = function(index, textArea, baseUIObject, onEnabledChange, onNameChange) {
		var id = 'formField' + index;
		var onToggleChange = onEnabledChange;
		if( typeof baseUIObject !== "object" )
			baseUIObject = {};
		var $asterisk = $('<div class="req-asterisk">');
		$asterisk.css({
			position: "absolute",
			left: wb_builder.rtl ? "8.5px" : "1.5px",
			top: "-10px",
			color: "#E00",
			fontSize: "10px"
		});
		$asterisk.attr("title", __("Required"));
		$asterisk.html('<i class="fa fa-asterisk"></i>');
		setTimeout(function() { $asterisk.tooltip(); }, 0);
		return $.extend(true, baseUIObject, {
			type: 'CheckBox', id: id + 'Enable',
			label: [
				{type: "FlowLayout", css: {width: 260}, children: [
					{type: 'MultilangTextField', id: id, textArea: textArea, css: {top: '-7px', width: 220}, onChange: onNameChange},
					{type: 'CheckBox', id: id + 'Required', label: [
						{type: "CustomContainer", id: id + "Asterisk", content: $asterisk}
					], change: function(fields) {
						fields[id + "Asterisk"].getElem().find(".req-asterisk").css("color", fields[id + "Required"].getValue() ? "#E00" : "#222");
					}}
				]}
			],
			change: function(fields) {
				var enabled = fields[id + 'Enable'].getValue();
				fields[id].setEnabled(enabled);
				fields[id + "Required"].setVisible(enabled);
				if( typeof onToggleChange === "function" )
					onToggleChange.apply(this, arguments);
			}
		});
	};

	Form.prototype.createWysiwygFieldUI = function(index, textArea, baseUIObject, onEnabledChange, onNameChange) {
		var id = 'formField' + index;
		var onToggleChange = onEnabledChange;
		if( typeof baseUIObject !== "object" )
			baseUIObject = {};
		var $asterisk = $('<div class="req-asterisk">');
		$asterisk.css({
			position: "absolute",
			left: wb_builder.rtl ? "8.5px" : "1.5px",
			top: "-10px",
			color: "#E00",
			fontSize: "10px"
		});
		$asterisk.attr("title", __("Required"));
		$asterisk.html('<i class="fa fa-asterisk"></i>');
		setTimeout(function() { $asterisk.tooltip(); }, 0);
		return $.extend(true, baseUIObject, {
			type: 'CheckBox', id: id + 'Enable',
			label: [
				{type: "FlowLayout", css: {width: 260}, children: [
					{type: 'WYSIWYGControl', id: id, css: {top: '-7px', width: 220}, onChange: onNameChange, config: {
						forcePasteAsPlainText: true
					}},
					{type: 'CheckBox', id: id + 'Required', label: [
						{type: "CustomContainer", id: id + "Asterisk", content: $asterisk}
					], change: function(fields) {
						fields[id + "Asterisk"].getElem().find(".req-asterisk").css("color", fields[id + "Required"].getValue() ? "#E00" : "#222");
					}}
				]}
			],
			change: function(fields) {
				var enabled = fields[id + 'Enable'].getValue();
				fields[id].setEnabled(enabled);
				fields[id + "Required"].setVisible(enabled);
				if( typeof onToggleChange === "function" )
					onToggleChange.apply(this, arguments);
			}
		});
	};

	Form.prototype.createSelectFieldUI = function(index, baseUIObject, onEnabledChange, onNameChange, onOptionsChange) {
		var id = 'formField' + index;
		var onToggleChange = onEnabledChange;
		if( typeof baseUIObject !== "object" )
			baseUIObject = {};
		return $.extend(true, baseUIObject, {
			type: 'CheckBox', id: id + 'Enable',
			label: [
				{type: 'MultilangTextField', id: id, css: {top: '-7px'}, onChange: onNameChange},
				{type: 'Tooltip', text: __('Write options as separate lines')},
				{type: 'MultilangTextField', id: id + "Opts", textArea: true, onChange: onOptionsChange}
			],
			css: {position: 'relative', marginTop: 11},
			change: function(fields) {
				var enabled = fields[id + 'Enable'].getValue();
				fields[id].setEnabled(enabled);
				fields[id + "Opts"].setEnabled(enabled);
				if( typeof onToggleChange === "function" )
					onToggleChange.apply(this, arguments);
			}
		});
	};

	/**
	 * Extend element properties dialog
	 */
	Form.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 356},
			tabs: [
				{name: __('Fields'), children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', spacing: 5, children: [
							{type: 'Label', text: __('Simple fields')},
							this.createSimpleFieldUI(0, false, {css: {marginTop: 11}}),
							this.createSimpleFieldUI(1, false),
							this.createSimpleFieldUI(2, false),
							this.createSimpleFieldUI(3, false),
							this.createSimpleFieldUI(4, false),
							this.createSimpleFieldUI(5, false),
							this.createSimpleFieldUI(6, false),
							this.createSimpleFieldUI(9, true, {css: {margin: 0}}, null, function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formField9-change', thisClass);
								console.log('item-plugin-' + thisClass.getClassType() + '-prop-formField9-change');
							}),
							this.createSimpleFieldUI(10, false)
						]},
						{type: 'VerticalLayout', spacing: 5, children: [
							{type: 'Label', text: __('Options')},
							this.createSelectFieldUI(7, {}, function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formField7Enable-change', thisClass);
								console.log('item-plugin-' + thisClass.getClassType() + '-prop-formField7Enable-change');
							}, null, function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formField7Opts-change', thisClass);
								console.log('item-plugin-' + thisClass.getClassType() + '-prop-formField7Opts-change');
							}),
							this.createSelectFieldUI(8),
							{type: 'Label', text: __('Checkboxes'), css: {marginTop: 11}},
							this.createWysiwygFieldUI(11, false),
							this.createWysiwygFieldUI(12, false),
							{type: 'Label', text: __('Submit button text')},
							{type: 'MultilangTextField', id: 'formFromSubmit', css: {top: '-7px'}}
						]}
					]}
				]},
				{name: __('Email settings'), type: 'mailSettings', children: [
					{type: 'VerticalLayout', children: [
						{type: 'HorizontalLayout', children: [
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Form will be sent to this Email'),
									helpText: __('You can specify several emails separated by semicolons.')
								},
								{type: 'TextField', id: 'formFromEmail', placeholder: 'example@yourmail.com',
									change: function() {
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formFromEmail-change', thisClass);
									}
								}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Form will be sent from this Email')},
								{type: 'TextField', id: 'formFromSenderEmail', placeholder: ('no-reply@' + wb_builder.siteDomain),
									change: function() {
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formFromSenderEmail-change', thisClass);
									}
								}
							]}
						]},
						{type: 'Label', text: __('With Subject'), css: {marginTop: 15}},
						{type: 'TextField', id: 'formFromSubject'},
						{type: 'Label', text: __('Form sent Message'), css: {marginTop: 15}},
						{type: 'MultilangTextField', id: 'formFromSentMessage'},
						{type: 'Label', text: __('Maximum size of attachments'), helpText: __('This field should contain either maximum allowed size for uploads on your server or maximum size your email server will accept in a message (whichever is smaller). Don\'t change this field if you don\'t know what limits apply on your server or not sure what it is.'), css: {marginTop: 15}},
						{type: 'FlowLayout', children: [
							{type: 'SizeSelector', min: 1, value: 2, units: __('MB'), id: 'maxFileSizeTotal'}
						]}
					]}
				]},
				{name: __('SMTP'), type: 'smtpSettings', children: [
					{type: 'CheckBox', label: __('SMTP Enable'), id: 'smtpEnable', change: function() {
						if (this.getValue()) {
							fields.smtpLine2.setEnabled(true);
							fields.smtpLine3.setEnabled(true);
						} else {
							fields.smtpLine2.setEnabled(false);
							fields.smtpLine3.setEnabled(false);
						}
					}},
					{type: 'HorizontalLayout', id: 'smtpLine2',
						columnWeights: [4, 3, 5],
						enabled: false,
						children: [
							{type: 'TextField', id: 'smtpHost',
								placeholder: __('SMTP Host'),
								title: __('SMTP Host')
							},
							{type: 'TextField', id: 'smtpPort',
								placeholder: __('SMTP Port'),
								title: __('SMTP Port')
							},
							{type: 'FlowLayout', css: {marginTop: 5}, children: [
								{type: 'RadioBox', label: __('None'), id: 'smtpEncryptionNone',
									inline: true,
									group: 'encryption',
									title: __('SMTP Encryption')
								},
								{type: 'RadioBox', label: __('TLS'), id: 'smtpEncryptionTLS',
									inline: true,
									group: 'encryption',
									title: __('SMTP Encryption')
								},
								{type: 'RadioBox', label: __('SSL'), id: 'smtpEncryptionSSL',
									inline: true,
									group: 'encryption',
									title: __('SMTP Encryption')
								}
							]}
						]
					},
					{type: 'HorizontalLayout', id: 'smtpLine3',
						css: {marginTop: 10},
						enabled: false,
						children: [
							{type: 'TextField', id: 'smtpUsername',
								placeholder: __('SMTP Username'),
								title: __('SMTP Username')
							},
							{type: 'TextField', id: 'smtpPassword',
								placeholder: __('SMTP Password'),
								title: __('SMTP Password')
							}
						]
					}
				]},
				{name: __('Settings'), type: 'settings', children: [
					{type: 'Label', text: __('Google reCAPTCHA') + ' (v2)',
						helpText: __('Go to %s and register new site to get keys.').replace('%s', '<a href="https://www.google.com/recaptcha/" target="_blank">Google ReCaptcha</a>')
					},
					{type: 'HorizontalLayout', children: [
						{type: 'TextField', id: 'recSiteKey',
							placeholder: __('Site key'),
							title: __('Site key'),
							change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-recSiteKey-change', thisClass);
							}
						},
						{type: 'TextField', id: 'recSecretKey',
							placeholder: __('Secret Key'),
							title: __('Secret Key'),
							change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-recSecretKey-change', thisClass);
							}
						}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Label Style')},
							{type: 'StyleSelector', id: 'formLabelStyle', emptyChoice: true,
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formLabelStyle-change', thisClass);
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'FlowLayout', children: [
								{type: 'CheckBox', label: '', id: 'formLabelWidthFixed', change: function(fields) {
									fields.formLabelWidth.setEnabled(this.getValue());
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formLabelWidthFixed-change', thisClass);
								}},
								{type: 'Label', text: __('Label Column Width'), click: function(e, fields) {
									fields.formLabelWidthFixed.setValue(!fields.formLabelWidthFixed.getValue());
									fields.formLabelWidthFixed.trigger('change');
								}}
							]},
							{type: 'SizeSelector', id: 'formLabelWidth', enabled: false, noFixedWidth: true, min: 0,
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-formLabelWidth-change', thisClass);
								}
							}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				var m, i, j, k, field, value;
				for (k in fields) {
					if (!(m = ('' + k).match(/^formField([0-9]+)Enable$/))) continue;
					i = parseInt(m[1], 10);
					field = thisClass.fields[i];
					field.checked = fields[k].getValue();
					field.name = fields['formField' + i].getValue();
					if (field.type === "checkbox") {
						var cleanVal = function(val) {
							if (typeof val !== 'string') return val;
							return val.replace(/<p[^>]*>/ig, "").replace(/<\/p[^>]*>/ig, "<br /><br />").replace(/\s*(?:(?:<br[^>]*>|&nbsp;)\s*)+$/i, "");
						};
						if ((typeof field.name === 'object') && field.name) {
							// multilang field
							for (var k in field.name) { field.name[k] = cleanVal(field.name[k]); }
						} else {
							field.name = cleanVal(field.name);
						}
					}
					if(fields.hasOwnProperty('formField' + i + 'Required'))
						field.required = !!fields['formField' + i + 'Required'].getValue();
					if (field.type === 'select') {
						value = fields['formField' + i + 'Opts'].getValue();
						if (typeof value === 'object') {
							field.options = {};
							for (j in value) {
								field.options[j] = value[j].split("\n").join(';');
							}
						} else {
							field.options = value.split("\n").join(';');
						}
					}
				}
				thisClass.email = fields.formFromEmail.getValue();
				thisClass.emailFrom = fields.formFromSenderEmail.getValue();
				thisClass.subject = fields.formFromSubject.getValue();
				thisClass.formSentMessage = fields.formFromSentMessage.getValue();
				thisClass.button = fields.formFromSubmit.getValue();
				
				thisClass.smtpEnable = fields.smtpEnable.getValue();
				thisClass.smtpHost = fields.smtpHost.getText();
				thisClass.smtpPort = fields.smtpPort.getText();
				if (fields.smtpEncryptionTLS.getValue()) {
					thisClass.smtpEncryption = 'tls';
				} else if (fields.smtpEncryptionSSL.getValue()) {
					thisClass.smtpEncryption = 'ssl';
				} else {
					thisClass.smtpEncryption = null;
				}
				thisClass.smtpUsername = fields.smtpUsername.getText();
				thisClass.smtpPassword = fields.smtpPassword.getText();
				
				thisClass.recSiteKey = fields.recSiteKey.getText();
				thisClass.recSecretKey = fields.recSecretKey.getText();

				thisClass.maxFileSizeTotal = fields.maxFileSizeTotal.getValue();

				thisClass.labelStyle = fields.formLabelStyle.getValue();
				thisClass.labelColWidth = ((fields.formLabelWidthFixed.getValue() && fields.formLabelWidth.getValue()) ? fields.formLabelWidth.getValue() : 0);

				thisClass.updateStyle();
			}
		});
		
		var m, i, j, k, field, value;
		for (k in fields) {
			if (!(m = ('' + k).match(/^formField([0-9]+)Enable$/))) continue;
			i = parseInt(m[1], 10);
			field = (this.fields && this.fields[i]) ? this.fields[i] : Form.defaultFields[i];
			fields[k].setValue(field.checked);
			fields[k].trigger('change');
			fields['formField' + i].setValue(field.name);
			if(fields.hasOwnProperty('formField' + i + 'Required')) {
				fields['formField' + i + 'Required'].setValue(field.required);
				fields['formField' + i + 'Required'].trigger("change");
			}
			if (field.type === 'select') {
				if (typeof field.options === 'object') {
					value = {};
					for (j in field.options) {
						value[j] = field.options[j].split(';').join("\n");
					}
				} else {
					value = field.options.split(';').join("\n");
				}
				fields['formField' + i + 'Opts'].setValue(value);
			}
		}
		fields.formFromEmail.setValue(this.email);
		fields.formFromSenderEmail.setValue(this.emailFrom);
		fields.formFromSubject.setValue(this.subject);
		fields.formFromSentMessage.setValue(this.formSentMessage);
		fields.formFromSubmit.setValue(this.button);
		
		fields.smtpEnable.setValue(this.smtpEnable);
		fields.smtpEnable.trigger('change');
		fields.smtpHost.setText(this.smtpHost ? this.smtpHost : '');
		fields.smtpPort.setText(this.smtpPort ? this.smtpPort : '');
		fields.smtpEncryptionNone.setValue(true);
		fields.smtpEncryptionTLS.setValue((this.smtpEncryption === 'tls'));
		fields.smtpEncryptionSSL.setValue((this.smtpEncryption === 'ssl'));
		fields.smtpUsername.setText(this.smtpUsername ? this.smtpUsername : '');
		fields.smtpPassword.setText(this.smtpPassword ? this.smtpPassword : '');
		
		fields.recSiteKey.setText(this.recSiteKey ? this.recSiteKey : '');
		fields.recSecretKey.setText(this.recSecretKey ? this.recSecretKey : '');

		fields.maxFileSizeTotal.setValue(this.maxFileSizeTotal ? this.maxFileSizeTotal : 2);

		fields.formLabelStyle.setValue(this.labelStyle);
		fields.formLabelWidth.setValue((this.labelColWidth ? this.labelColWidth : 0));
		fields.formLabelWidthFixed.setValue((this.labelColWidth ? true : false));
		fields.formLabelWidthFixed.trigger('change');
	};

	Form.prototype.onSwitchLanguage = function(langCode) {
		Element.prototype.onSwitchLanguage.call(this, langCode);
		this.updateStyle(false, langCode);
	};

	Form.Mode = (function() {
		'use strict';

		/**
		 * @param {Form.Mode} mode
		 * @param {Object} data
		 */
		var applyData = function(mode, data) {
			mode.labelColWidth = (data.labelColWidth ? data.labelColWidth : 0);
			mode.fieldsWidth = data.fieldsWidth;
			mode.flexHeight = data.flexHeight;
		};

		/**
		 * @param {Object} data
		 * @class WB_Form.Mode
		 */
		var self = function(data) { Element.Mode.prototype.constructor.call(this, data); if (data) applyData(this, data); };
		self.prototype = Object.create(Element.Mode.prototype);
		/** @type Number */
		self.prototype.labelColWidth = 0;
		/** @type Number */
		self.prototype.fieldsWidth = 0;
		/** @type Number */
		self.prototype.flexHeight = 0;
		/** @param {Form.Mode} mode */
		self.prototype.copy = function(mode) {
			Element.Mode.prototype.copy.call(this, mode);
			applyData(this, mode);
		};
		/** @param {Form} elem */
		self.prototype.store = function(elem) {
			Element.Mode.prototype.store.call(this, elem);
			var wasHidden = (elem.isHidden() || elem.isHidden(true));
			elem.elem.show();
			applyData(this, {
				labelColWidth: (elem.labelColWidth ? elem.labelColWidth : 0),
				fieldsWidth: elem.container.find('input[type=text],input[type=file],select,textarea').outerWidth(),
				flexHeight:	elem.container.find('textarea').outerHeight()
			});
			if (wasHidden) elem.elem.hide();
		};
		/** @param {Form} elem */
		self.prototype.applyTo = function(elem) {
			Element.Mode.prototype.applyTo.call(this, elem);
			elem.labelColWidth = (this.labelColWidth ? this.labelColWidth : 0);
		};
		/** @return {Object} */
		self.prototype.serialize = function() {
			var obj = Element.Mode.prototype.serialize.call(this);
			obj.labelColWidth = (this.labelColWidth ? this.labelColWidth : 0);
			obj.fieldsWidth = this.fieldsWidth;
			obj.flexHeight = this.flexHeight;
			return obj;
		};

		return self;
	})();
	
	window.WB_Form = Form;
	
	return Form;
});
;

/** WB Line **/
(window.defineModule = (window.defineModule || {})).name = 'WB Line';

define('Line', ['ElementRegister', 'Element', 'ContextMenu', 'Service', 'ColorPicker'], function(ElementRegister, Element, ContextMenu, Service, ColorPicker) {

	/**
	 * Line class
	 * @param {Object} data
	 */
	var Line = function(data) { if (data) this.__construct(data); };
	
	Line.prototype = new Element();
	Line.prototype.constructor = Line;
	ElementRegister.registerClass("Line", Line);

	Line.styleList = [
		{ "name": __("Solid"),  "value": "solid"  },
		{ "name": __("Dashed"), "value": "dashed" },
		{ "name": __("Dotted"), "value": "dotted" },
		{ "name": __("Double"), "value": "double" }
	];
	Line.sizeList = [
		{ "name": "1px", "value": "1" },
		{ "name": "2px", "value": "2" },
		{ "name": "3px", "value": "3" },
		{ "name": "4px", "value": "4" }
	];
	Line.prototype.miOrientation = null;
	Line.prototype.miStyle = null;
	Line.prototype.miSize = null;
	Line.prototype.line = null;
	Line.prototype.orientation = 1; // 0 - vertical, 1 - horizontal
	Line.prototype.size = 3;
	Line.prototype.style = "solid";
	Line.prototype.color = "#303030";
	Line.prototype.backupColor = null;

	/**
	 * Construct line element
	 * @param {Object} data element data object
	 */
	Line.prototype.__construct = function(data) {
		if (!data.width) {
			data.width = 600;
			data.height = 100;
		}
		Element.prototype.__construct.call(this, data);
		var thisClass = this;

		this.setMinSize(1, 1);

		this.line = $("<div></div>");
		this.line.css({
			"font-size":	"1px",
			"overflow":		"hidden",
			"line-height":	"1px",
			"margin":		"0",
			"padding":		"0",
			"background":	"transparent",
			"float":		"none",
			"position":		"relative"
		});
		this.container.empty().append(this.line);
		this.orientation 	= (("orientation" in data.content) && !isNaN(data.content.orientation)) ? data.content.orientation : this.orientation;
		this.size			= data.content.size ? data.content.size : this.size;
		this.style			= data.content.style ? data.content.style : this.style;
		this.color			= data.content.color ? data.content.color : this.color;
		this.setOrientation(this.orientation);
		this.updateLineSize();

		this.elem.bind("resize", function() {
			thisClass.updateLineSize();
		});

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};
	
	Line.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = 'e, w, s, n';
	};
	
	Line.prototype.supportsFullWidth = function() {
		return true;
	};

	/** @return {Object} */
	Line.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this), brd = (this.size + 'px ' + this.style + ' ' + this.color);
		opts.text = '';
		opts.thumb = $('<span>').css({position: 'relative', fontSize: 1, lineHeight: 1, minHeight: 1, minWidth: 1});
		if (parseInt(this.orientation, 10) === 0) {
			opts.thumb.css({
				margin: 0,
				width: 1,
				height: '100%',
				left: '50%',
				top: 0,
				borderLeft: brd
			});
		} else {
			opts.thumb.css({
				margin: 0,
				width: '100%',
				height: 1,
				left: 0,
				top: '50%',
				borderTop: brd
			});
		}
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	Line.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			orientation:this.orientation,
			size:		this.size,
			style:		this.style,
			color:		this.color
		};
		return data;
	};

	Line.prototype.updateLineSize = function() {
		if (this.orientation === 0) {
			this.line.css({
				"margin":	"0 0 0 1px",
				"width":	"1px",
				"height":	"100%",
				"left":		"50%",
				"top":		"0"
			});
		} else {
			this.line.css({
				"margin":	"1px 0 0 0",
				"width":	"100%",
				"height":	"1px",
				"left":		"0",
				"top":		"50%"
			});
		}
	};

	Line.prototype.setOrientation = function(o) {
		this.orientation = o * 1;
		if (this.orientation === 0) {
			this.line.css({borderLeft: this.size + "px " + this.style + " " + this.color});
			this.line.css({borderTop: "none"});
		} else {
			this.line.css({borderLeft: "none"});
			this.line.css({borderTop: this.size + "px " + this.style + " " + this.color});
		}
	};

	Line.prototype.setBorderSize = function(s) {
		this.size = s;
		this.setOrientation(this.orientation);
	};

	Line.prototype.setStyle = function(s) {
		this.style = s;
		this.setOrientation(this.orientation);
	};

	Line.prototype.getColor = function() {
		return this.color;
	};

	Line.prototype.setColor = function(c) {
		this.color = c;
		this.setOrientation(this.orientation);
	};

	Line.prototype.getBackupColor = function() {
		return this.backupColor;
	};

	Line.prototype.setBackupColor = function(color) {
		this.backupColor = color;
	};

	/**
	 * Extend element properties dialog
	 */
	Line.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 350},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Orientation')},
							{type: 'RadioBox', id: 'lineOrientationVert',  label: '|', group: (this.id + '_lineOrient'),
								init: function() {
									this._input.css({marginTop: 19});
									this._labelText.empty().css({
										width: 25, height: 50, marginRight: 25,
										display: 'inline-block', borderRight: '2px solid #000000', verticalAlign: 'top'
									});
								},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineOrientationVert-change', thisClass);
								}
							},
							{type: 'RadioBox', id: 'lineOrientationHoriz', label: '-', group: (this.id + '_lineOrient'),
								init: function() {
									this._input.css({marginTop: 19});
									this._labelText.empty().css({
										width: 50, height: 27, marginBottom: 23,
										display: 'inline-block', borderBottom: '2px solid #000000', verticalAlign: 'top'
									});
								},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineOrientationHoriz-change', thisClass);
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Style')},
							{type: 'RadioBox', id: 'lineStyleSolid',  label: '-',   group: (this.id + '_lineStyle'),
								init: function() {
									this._labelText.empty().css({
										width: 100, height: 12, marginBottom: 8,
										display: 'inline-block', borderBottom: '2px solid #000000', verticalAlign: 'top'
									});
								},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineStyleSolid-change', thisClass);
								}
							},
							{type: 'RadioBox', id: 'lineStyleDashed', label: '---', group: (this.id + '_lineStyle'),
								init: function() {
									this._labelText.empty().css({
										width: 100, height: 12, marginBottom: 8,
										display: 'inline-block', borderBottom: '2px dashed #000000', verticalAlign: 'top'
									});
								},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineStyleDashed-change', thisClass);
								}
							},
							{type: 'RadioBox', id: 'lineStyleDotted', label: '...', group: (this.id + '_lineStyle'),
								init: function() {
									this._labelText.empty().css({
										width: 100, height: 12, marginBottom: 8,
										display: 'inline-block', borderBottom: '2px dotted #000000', verticalAlign: 'top'
									});
								},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineStyleDotted-change', thisClass);
								}
							},
							{type: 'RadioBox', id: 'lineStyleDouble', label: '=',   group: (this.id + '_lineStyle'),
								init: function() {
									this._labelText.empty().css({
										width: 100, height: 12, marginBottom: 8,
										display: 'inline-block', borderBottom: '3px double #000000', verticalAlign: 'top'
									});
								},
								change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineStyleDouble-change', thisClass);
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'lineSize', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineSize-change', thisClass);
							}},
							{type: 'Label', text: __('Color'), css: {marginTop: 15}},
							{type: 'ColorSelector', id: 'lineColor', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-lineColor-change', thisClass);
							}}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.setBorderSize(fields.lineSize.getValue());
				var stl = 'solid';
				if (fields.lineStyleSolid.getValue()) {
					stl = 'solid';
				} else if (fields.lineStyleDashed.getValue()) {
					stl = 'dashed';
				} else if (fields.lineStyleDotted.getValue()) {
					stl = 'dotted';
				} else if (fields.lineStyleDouble.getValue()) {
					stl = 'double';
				} 
				thisClass.setStyle(stl);
				thisClass.setColor(fields.lineColor.getValue());
				var orient = 0;
				if (fields.lineOrientationVert.getValue()) {
					orient = 0;
				} else if (fields.lineOrientationHoriz.getValue()) {
					orient = 1;
				}
				thisClass.setOrientation(orient);
				thisClass.updateLineSize();
			}
		});
		
		fields.lineOrientationVert.setValue((this.orientation === 0));
		fields.lineOrientationHoriz.setValue((this.orientation === 1));
		fields.lineSize.setValue(this.size);
		fields.lineStyleSolid.setValue((this.style === 'solid'));
		fields.lineStyleDashed.setValue((this.style === 'dashed'));
		fields.lineStyleDotted.setValue((this.style === 'dotted'));
		fields.lineStyleDouble.setValue((this.style === 'double'));
		fields.lineColor.setValue(this.color);
	};

	Line.prototype.initContextMenu = function(elem) {
		Element.prototype.initContextMenu.call(this, elem);
		if (!this.menu) return;
		var thisClass = this;

		var i, idx = this.contextMenuFirstIndex;

		this.miOrientation = new ContextMenu(this.id + "_orientation_sub");
		this.miOrientation.addItem("vertical", __("Vertical"), function() {
		   thisClass.setOrientation(0);
		   thisClass.updateLineSize();
		}, this.orientation === 0, false);
		this.miOrientation.addItem("horizontal", __("Horizontal"), function() {
		   thisClass.setOrientation(1);
		   thisClass.updateLineSize();
		}, this.orientation === 1, false);
		this.menu.insertItemAt(idx++, 'orientation', __("Orientation"), this.miOrientation, null, null, null, "glyphicon glyphicon-repeat");

		this.miStyle = new ContextMenu(this.id + "_style_sub");
		for (i = 0; i < Line.styleList.length; i++) {
			this.miStyle.addItem('style' + i, Line.styleList[i].name, function(e, style) {
			   thisClass.setStyle(style.value);
			}, this.style === Line.styleList[i].value, false, Line.styleList[i]);
		}
		this.menu.insertItemAt(idx++, 'style', __("Style"), this.miStyle, null, null, null, "glyphicon glyphicon-adjust");

		this.miSize = new ContextMenu(this.id + "_size_sub");
		for (i = 0; i < Line.sizeList.length; i++) {
			this.miSize.addItem('size' + i, Line.sizeList[i].name, function(e, size) {
				thisClass.setBorderSize(size.value);
			}, this.size == Line.sizeList[i].value, false, Line.sizeList[i]);
		}
		this.menu.insertItemAt(idx++, 'size', __("Size"), this.miSize, null, null, null, "glyphicon glyphicon-resize-full");

		$(this.menu.insertItemAt(idx++, 'changeColor', __("Change color"), function() {

		}, null, null, null, "glyphicon glyphicon-edit")).ColorPicker({
			WB_ColorPicker: ColorPicker,
			color: thisClass.color,
			onShow: function (colpkr) {
				thisClass.setBackupColor(thisClass.getColor());
			},
			onHide: function (colpkr) {
				thisClass.setColor(thisClass.getBackupColor());
				$(colpkr).hide();
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				thisClass.setColor('#' + hex);
			},
			onSubmit: function(hsb, hex, rgb, el) {
				thisClass.setColor('#' + hex);
				thisClass.setBackupColor(thisClass.getColor());
				$(el).ColorPickerHide();
			},
			onBeforeShow: function () {
				$(this).ColorPickerSetColor(thisClass.color);
			}
		});

		this.menu.addSeparator(idx++);
	};

	Line.prototype.updateContextMenu = function() {
		Element.prototype.updateContextMenu.call(this);
		var i;
		for (i = 0; i < Line.styleList.length; i++ )
		   this.miStyle.setSelected("style" + i, this.style === Line.styleList[i].value);
		for (i = 0; i < Line.sizeList.length; i++ )
		   this.miSize.setSelected("size" + i, this.size == Line.sizeList[i].value);
		this.miOrientation.setSelected("vertical", this.orientation === 0);
		this.miOrientation.setSelected("horizontal", this.orientation === 1);
	};
	
	return Line;
});
;

/** WB Button **/
(window.defineModule = (window.defineModule || {})).name = 'WB Button';

define('Button', [
	'ElementRegister',
	'Element',
	'Service'
], function(ElementRegister, Element, Service) {
	'use strict';
	
	/**
	 * Button class
	 * @param {Object} data
	 */
	var Button = function (data) { if (data) this.__construct(data); };

	Button.prototype = new Element();
	Button.prototype.constructor = Button;
	ElementRegister.registerClass("Button", Button);

	Button.prototype.text = "";
	Button.prototype.title = "";
	Button.prototype.link = "";
	Button.prototype.txt = null;
	Button.prototype.border = null;

	Button.prototype.bgNormal = null;
	Button.prototype.bgHover = null;
	Button.prototype.bgActive = null;
	Button.prototype.txtNormal = null;
	Button.prototype.txtHover = null;
	Button.prototype.txtActive = null;

	/**
	 * Construct Button element
	 * @param data element data object
	 */
	Button.prototype.__construct = function(data) {
		if (!data.width) {
			data.width = 100;
			data.height = 30;
		}
		Element.prototype.__construct.call(this, data);

		this.setMinSize(1, 1);

		this.button = $('<a class="wb_button"><span>' + __("Button") + '</span></a>');
		this.button.css({width: '100%', height: '100%'});
		this.buttonClass = "wb_button-"+ this.id;
		this.button.addClass(this.buttonClass);
		this.container.append(this.button);

		this.text = (data.content.text || (typeof data.content.text === "string")) ? data.content.text : __("Just Do It!");
		this.title = (data.content.title || (typeof data.content.title === "string")) ? data.content.title : "";
		this.link = data.content.link ? data.content.link : {};
		if (typeof this.link !== "object") {
			this.link = { url: this.link };
		}

		this.txt = data.content.txt ? data.content.txt : {
			size: 14,
			decoration: "none",
			font: "Helvetica,Arial,sans-serif",
			style: { },
			align: "center",
			css: {
				"font-family": "Helvetica, Arial, sans-serif",
				"font-size": "14px",
				"text-align": "center"
			}
		};
		this.border = data.content.border ? data.content.border : {
			color: "#cccccc",
			style: "solid",
			weight: 1,
			radius: 6,
			css: { 
				border: "1px solid #cccccc",
				"border-radius"			: "6px",
				"-webkit-border-radius"	: "6px", 
				"-moz-border-radius"	: "6px"
			}
		};

		this.txtNormal = data.content.txtNormal ? data.content.txtNormal : {
			color: "#333333",
			style: { },
			align: "center",
			css: {
				color: "#333333",
				"text-decoration": "none"
			}
		};
		this.bgNormal = data.content.bgNormal ? data.content.bgNormal : {
			color: "#f5f5f5",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "#f5f5f5 none repeat scroll left top" }
		};
		this.txtHover = data.content.txtHover ? data.content.txtHover : {
			color: "#333333",
			style: { },
			align: "center",
			css: {
				color: "#333333",
				"text-decoration": "none"
			}
		};
		this.bgHover = data.content.bgHover ? data.content.bgHover : {
			color: "#E6E6E6",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "#E6E6E6 none repeat scroll left top" }
		};
		this.txtActive = data.content.txtActive ? data.content.txtActive : {
			color: "#333333",
			style: { },
			align: "center",
			css: {
				color: "#333333",
				"text-decoration": "none"
			}
		};
		this.bgActive = data.content.bgActive ? data.content.bgActive : {
			color: "#E6E6E6",
			image: "none",
			position: "left top",
			repeat: "repeat",
			css: { background: "#E6E6E6 none repeat scroll left top" }
		};

		var thisClass = this;

		this.updateStyle(true);
		setTimeout(function() { thisClass.updateStyle(true); }, 100);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/** @return {Object} */
	Button.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this), txt = String(this.text).replace(/<[^>]+>/g, '');
		opts.text = txt.substring(0, 100);
		if (opts.text.length < txt.length) opts.text += '...';
		return opts;
	};

	Button.prototype.getUsedMediaGalleryItems = function() {
		var items = Element.prototype.getUsedMediaGalleryItems.call(this);
		if( this.bgNormal.image )
			items.push(this.bgNormal.image);
		if( this.bgHover.image )
			items.push(this.bgHover.image);
		if( this.bgActive.image )
			items.push(this.bgActive.image);
		return items;
	};

	/**
	 * Serialize this element
	 * @return object
	 */
	Button.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);
		
		data.content = {
			text:		this.text,
			//title:		this.title,
			link:		this.link,
			txt:		this.txt,
			border:		this.border,
			txtNormal:	this.txtNormal,
			bgNormal:	this.bgNormal,
			txtHover:	this.txtHover,
			bgHover:	this.bgHover,
			txtActive:	this.txtActive,
			bgActive:	this.bgActive
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 * @param {String} langCode
	 * @param {Boolean} initial if true it will prevent on pageModified flag setting
	 */
	Button.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		langCode = langCode || this.system.site.currSelLang;
		this.button.css(this.txt.css);
		this.button.css(this.border.css);
		this.button.children('span').css(this.txtNormal.css);

		var bg = this.bgNormal;
		var css = $.extend(true, {}, bg.css);
		if (css.background && bg.image && bg.image !== "none") {
			css.background = css.background.replace(/url\([^\)]+\)/i, 'url("' + wb_builder.makeLocalUrl(bg.image) + '")');
		}
		this.button.css(css);
		this.button.children("span").html(__tr(this.text, langCode));

		this.onResize(initial);
	};

	/* Button.prototype.onResize = function(onConstruct) {
		Element.prototype.onResize.call(this, onConstruct);

		var w = this.getWidth();
		var h = this.getHeight();
		
		this.button.css({ width: w + "px", height: h + "px" });

		if (this.border.weight > 0 && this.border.style !== "none") {
			w -= this.border.weight * 2;
			h -= this.border.weight * 2;
		}
		this.elem.trigger("elementresize", [this]);
	}; */

	/**
	 * Extend element properties dialog
	 */
	Button.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {/*width: 580, height: 550, maxBodyHeight: 465,*/ minBodyHeight: 380},
			tabs: [
				{children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Text')},
						{type: 'MultilangTextField', id: 'buttonText', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-buttonText-change', thisClass);
						}},
						{type: 'Label', text: __('URL'), css: {marginTop: 15}},
						{type: 'LinkSelector', id: 'buttonUrl', multilang: true, change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-buttonUrl-change', thisClass);
						}}
					]},
					{type: 'FlowLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Font')},
							{type: 'FlowLayout', spacing: -1, children: [
								{type: 'FontFamilySelector', id: 'txtFont', css: {width: 117}, change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-txtFont-change', thisClass);
								}},
								{type: 'Button', icon: "glyphicon glyphicon-pencil", click: function(e, fields) {
									fields.txtFont.getWrappedControl().openEditFontsDialog();
								}}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'txtSize', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-txtSize-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Align')},
							{type: 'HAlignSelector', id: 'txtAlign', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-txtAlign-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'border', showRadius: true, change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-border-change', thisClass);
							}}
						]}
					]},
					{type: 'TabbedPane', css: {marginTop: 15}, tabs: [
						{name: __('Default'), children: [
							{type: 'FlowLayout', css: {marginTop: 15}, children: [
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Style')},
									{type: 'FontStyleSelector', id: 'textNormalStyle'}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Color')},
									{type: 'ColorSelector', id: 'textNormalColor', noTransparent: true}
								]}
							]},
							{type: 'VerticalLayout', css: {marginTop: 15}, children: [
								{type: 'Label', text: __('Background')},
								{type: 'BackgroundSelector', id: 'bgNormal', change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-bgNormal-change', thisClass);
								}}
							]}
						]},
						{name: __('Hover'), children: [
							{type: 'FlowLayout', css: {marginTop: 15}, children: [
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Style')},
									{type: 'FontStyleSelector', id: 'textHoverStyle'}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Color')},
									{type: 'ColorSelector', id: 'textHoverColor', noTransparent: true}
								]}
							]},
							{type: 'VerticalLayout', css: {marginTop: 15}, children: [
								{type: 'Label', text: __('Background')},
								{type: 'BackgroundSelector', id: 'bgHover', change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-bgHover-change', thisClass);
								}}
							]}
						]},
						{name: __('Active'), children: [
							{type: 'FlowLayout', css: {marginTop: 15}, children: [
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Style')},
									{type: 'FontStyleSelector', id: 'textActiveStyle'}
								]},
								{type: 'VerticalLayout', children: [
									{type: 'Label', text: __('Color')},
									{type: 'ColorSelector', id: 'textActiveColor', noTransparent: true}
								]}
							]},
							{type: 'VerticalLayout', css: {marginTop: 15}, children: [
								{type: 'Label', text: __('Background')},
								{type: 'BackgroundSelector', id: 'bgActive', change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-bgActive-change', thisClass);
								}}
							]}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.text = fields.buttonText.getValue();
				//thisClass.title = fields.buttonTitle.getValue();
				thisClass.link = fields.buttonUrl.getValue();

				thisClass.txt = {
					font:	fields.txtFont.getValue(),
					size:	fields.txtSize.getValue(),
					align:	fields.txtAlign.getValue(),
					css:	{
						"font-family": fields.txtFont.getValue(),
						"font-size": fields.txtSize.getValue() + "px",
						"text-align": fields.txtAlign.getValue()
					}
				};
				thisClass.border = fields.border.getValue();

				var s = fields.textNormalStyle.getValue();
				thisClass.txtNormal = {
					style:	s,
					color:	fields.textNormalColor.getValue(),
					css: {
						color: fields.textNormalColor.getValue()
					}
				};
				thisClass.txtNormal.css["font-style"] = s.italic ? "italic" : "normal";
				thisClass.txtNormal.css["font-weight"] = s.bold ? "bold" : "normal";
				thisClass.txtNormal.css["text-decoration"] = s.underline ? "underline" : "none";

				s = fields.textHoverStyle.getValue();
				thisClass.txtHover = {
					style:	s,
					color:	fields.textHoverColor.getValue(),
					css: {
						color: fields.textHoverColor.getValue()
					}
				};
				thisClass.txtHover.css["font-style"] = s.italic ? "italic" : "normal";
				thisClass.txtHover.css["font-weight"] = s.bold ? "bold" : "normal";
				thisClass.txtHover.css["text-decoration"] = s.underline ? "underline" : "none";

				s = fields.textActiveStyle.getValue();
				thisClass.txtActive = {
					style:	s,
					color:	fields.textActiveColor.getValue(),
					css: {
						color: fields.textActiveColor.getValue()
					}
				};
				thisClass.txtActive.css["font-style"] = s.italic ? "italic" : "normal";
				thisClass.txtActive.css["font-weight"] = s.bold ? "bold" : "normal";
				thisClass.txtActive.css["text-decoration"] = s.underline ? "underline" : "none";


				thisClass.bgNormal = fields.bgNormal.getValue();
				thisClass.bgHover = fields.bgHover.getValue();
				thisClass.bgActive = fields.bgActive.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.buttonText.setValue(this.text ? this.text : "");
		//fields.buttonTitle.setValue(this.title ? this.title : "");
		fields.buttonUrl.setValue(this.link);

		fields.txtFont.setValue(thisClass.txt.font);
		fields.txtSize.setValue(thisClass.txt.size);
		fields.txtAlign.setValue(thisClass.txt.align);
		fields.border.setValue(thisClass.border);

		fields.textNormalStyle.setValue(thisClass.txtNormal.style);
		fields.textHoverStyle.setValue(thisClass.txtHover.style);
		fields.textActiveStyle.setValue(thisClass.txtActive.style);

		fields.textNormalColor.setValue(thisClass.txtNormal.color);
		fields.textHoverColor.setValue(thisClass.txtHover.color);
		fields.textActiveColor.setValue(thisClass.txtActive.color);

		fields.bgNormal.setValue(thisClass.bgNormal);
		fields.bgHover.setValue(thisClass.bgHover);
		fields.bgActive.setValue(thisClass.bgActive);

	};

	Button.prototype.onSwitchLanguage = function(langCode) {
		Element.prototype.onSwitchLanguage.call(this, langCode);
		this.updateStyle(false, langCode);
	};
	
	window.WB_Button = Button;
	
	return Button;
});
;

/** WB Youtube **/
(window.defineModule = (window.defineModule || {})).name = 'WB Youtube';

define('Youtube', ['ElementRegister', 'Element', 'Service'], function(ElementRegister, Element, Service) {

	/**
	 * YouTube class
	 * @param {Object} data
	 */
	var Youtube = function(data) { if (data) this.__construct(data); };

	Youtube.prototype = new Element();
	Youtube.prototype.constructor = Youtube;
	ElementRegister.registerClass("Youtube", Youtube);

	Youtube.prototype.noPhotoBg = 'ico-tb-youtube';
	Youtube.prototype.videoId = null;
	Youtube.prototype.videoUrl = null;
	Youtube.prototype.startAt = null;
	Youtube.prototype.showControls = null;
	Youtube.prototype.nocookieDomain = null;
	Youtube.prototype.playerMode = "iframe"; // iframe or object or hide
	Youtube.prototype.hideSelf = true;
	Youtube.prototype.player = null;
	Youtube.prototype.previewLoader = null;
	Youtube.prototype.previewReady = false;

	/**
	 * Construct YouTube element
	 * @param {Object} data element data object
	 */
	Youtube.prototype.__construct = function(data) {
		if (!data.width) {
			data.width = 420;
			data.height = 315;
		}
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		if (this.hideSelf) {
			this.player = $('<div style="width: 100%; height: 100%;"><img alt="" style="width: 100%; height: 100%;" /></div>');
			this.player.css({background: "#000000", position: "relative"});
			this.player.children("img").css({position: "absolute"});
			var playBtn = $('<div></div>');
			playBtn.css({
				position: "absolute", zIndex: 4,
				left: "0px", top: "0px",
				width: "100%", height: "100%",
				background: "transparent url('" + wb_builder.modBaseUrl + "img/play_btn.png') no-repeat center center"
			});
			this.player.append(playBtn);
		} else if (this.playerMode === 'iframe') {
			this.player = $('<iframe title="YouTube video player" class="youtube-player" type="text/html"' +
				' width="560" height="345" src="about:blank" frameborder="0"></iframe>');
		} else {
			this.player = $('<object width="560" height="340" data="" type="application/x-shockwave-flash">' +
					'<param name="src" value=""></param>' +
					'<param name="movie" value=""></param>' +
					'<param name="allowFullScreen" value="true"></param>' +
					'<param name="allowscriptaccess" value="always"></param>' +
				'</object>');
		}

		this.container.append(this.player);

		this.videoId = data.content.videoId ? data.content.videoId : 'UF8uR6Z6KLc';
		this.startAt = data.content.startAt ? data.content.startAt : '';
		this.showControls = ('showControls' in data.content) ? (data.content.showControls ? true : false) : true;
		this.nocookieDomain = ('nocookieDomain' in data.content) ? (data.content.nocookieDomain ? true : false) : false;

		var thisClass = this;
		this.elem.bind("resize", function() {
			var w = thisClass.getWidth();
			var h = thisClass.getHeight();
			if( thisClass.isFullWidth ) {
				thisClass.player.css({ "width": "100%", "height": h + "px", overflow: "hidden" });
				thisClass.player.attr("width", "100%");
			}
			else {
				thisClass.player.css({ "width": w + "px", "height": h + "px", overflow: "hidden" });
				thisClass.player.attr("width", w);
			}
			thisClass.player.attr("height", h);
			if (thisClass.previewReady) {
				/*
				 * iw - 
				 * ih - h
				 */
				//alert(thisClass.previewLoader.width + "x" + thisClass.previewLoader.height);
				var img = thisClass.player.children("img");
				var iw = w;
				var ih = Math.floor(thisClass.previewLoader.height * w / thisClass.previewLoader.width);
				var px = 0;
				var py = Math.floor((h - ih) / 2);
				if (ih > h) {
					ih = h;
					iw = Math.floor(thisClass.previewLoader.width * h / thisClass.previewLoader.height);
					py = 0;
					px = Math.floor((w - iw) / 2);
				}
				img.css({width: iw + "px", height: ih + "px", left: px + "px", top: py + "px"});
			}
		});
		this.updateStyle(true);

		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};
	
	Youtube.prototype.supportsFullWidth = function() {
		return true;
	};

	/** @return {Object} */
	Youtube.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = 'ID: ' + this.videoId;
		opts.thumb = this.getVideoImageUrl();
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	Youtube.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			videoId:	this.videoId,
			startAt:	this.startAt,
			showControls: this.showControls,
			nocookieDomain:	this.nocookieDomain,
			videoUrl:	this.videoUrl
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	Youtube.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var thisClass = this, start = (this.startAt ? this.parseTime(this.startAt) : 0);
		this.displayEmtyMessage(this.videoId ? false: true);

		var params = [];
		if (start) params.push('start=' + start);
		params.push('controls=' + (this.showControls ? '1' : '0'));

		if (this.nocookieDomain) {
			this.videoUrl = this.videoId
				? ('//www.youtube-nocookie.com/embed/' + this.videoId + '?' + params.join('&amp;'))
				: 'about:blank';
		} else {
			this.videoUrl = this.videoId ? ((this.playerMode === 'iframe')
				? ("//www.youtube.com/embed/" + this.videoId + '?' + params.join('&amp;'))
				: ("//www.youtube-nocookie.com/v/" + this.videoId + "?fs=1&amp;hl=en_US")
			) : "about:blank";
		}
		if (this.hideSelf) {
			if (this.videoId) {
				this.previewReady = false;
				this.previewLoader = new Image();
				this.previewLoader.onload = function() {
					thisClass.previewReady = true;
					thisClass.elem.trigger("resize");
				};
				this.previewLoader.src = this.getVideoImageUrl();
				this.player.children("img").attr("src", this.getVideoImageUrl());
				this.player.css({visibility: "visible"});
			} else {
				this.player.css({visibility: "hidden"});
			}
		} else if (this.playerMode === 'iframe') {
			this.player.attr("src", this.videoUrl);
		} else {
			this.player.attr("data", this.videoUrl);
			$("param[name=src]", this.player).attr("value", this.videoUrl);
			$("param[name=movie]", this.player).attr("value", this.videoUrl);
		}
		this.elem.trigger("resize");
	};
	
	/** @return {String} */
	Youtube.prototype.getVideoImageUrl = function() {
		return this.videoId ? ('//i2.ytimg.com/vi/' + this.videoId + '/hqdefault.jpg') : null;
	};
	
	/**
	 * Extend element properties dialog
	 */
	Youtube.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			tabs: [
				{children: [
					{type: 'HorizontalLayout', columnWeights: [9, 3], children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Youtube URL or ID')},
							{type: 'TextField', id: 'videoId',
								init: function() {
									this.on('paste', function() {
										setTimeout(function() {
											var vidId = thisClass.extractId(fields.videoId.getValue());
											if (vidId) fields.videoId.setValue(vidId);
											fields.videoPreview.setVideoId(vidId);
											fields.videoPreview.update();
											Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-videoId-change', thisClass);
										}, 100);
									});
								}, change: function() {
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-videoId-change', thisClass);
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Start at')},
							{type: 'TextField', id: 'startAt', placeholder: '00:00'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						/* {type: 'CheckBox', id: 'showRelated',
							label: __('Show suggested videos when the video finishes'),
							change: function(fields) { fields.videoPreview.update(); }
						}, */
						{type: 'CheckBox', id: 'showControls',
							label: __('Show player controls'),
							change: function(fields) { fields.videoPreview.update(); }
						},
						/* {type: 'CheckBox', id: 'showTitle',
							label: __('Show video title and player actions'),
							change: function(fields) { fields.videoPreview.update(); }
						}, */
						{type: 'CheckBox', id: 'nocookieDomain',
							label: __('Use nocookie domain'), helpText: __('for GDPR compliance')
						}
					]},
					{type: 'CustomContainer', id: 'videoPreview',
						styleClass: 'thumbnail',
						css: {height: 200, marginTop: 15, marginBottom: 0},
						init: function() {
							this._vidId = null;
							this.setVideoId = function(vidId) {
								this._vidId = vidId;
							};
							this.update = function() {
								var html;
								if (this._vidId) {
									var controls = fields.showControls.getValue();
									html = '<iframe width="100%" height="100%"'
										+ ' style="width: 100%; height: 100%;"'
										+ ' src="https://www.youtube.com/embed/' + this._vidId
										+ '?controls=' + (controls ? '1' : '0') + '"'
										+ ' frameborder="0" allowfullscreen=""></iframe>';
								} else {
									html = '';
								}
								this._elem.html(html);
								this.setVisible((html ? true : false));
							};
							this.destroy = function() {
								this._vidId = null;
								this.update();
							};
						}
					}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.videoId = thisClass.extractId(fields.videoId.getValue());
				thisClass.startAt = fields.startAt.getValue();
				thisClass.showControls = fields.showControls.getValue();
				thisClass.nocookieDomain = fields.nocookieDomain.getValue();
				thisClass.updateStyle();
			},
			close: function() {
				fields.videoPreview.destroy();
			}
		});

		if (this.videoId) {
			fields.videoId.setValue(this.videoId);
			fields.startAt.setValue(this.startAt);
			fields.showControls.setValue(this.showControls);
			fields.nocookieDomain.setValue(this.nocookieDomain);
			fields.videoId.trigger('paste');
		}
	};

	/**
	 * Extract youtube video id
	 * @param {string} str URL string
	 */
	Youtube.prototype.extractId = function(str) {
		var m = null;

		try {
			if (str.indexOf("?") >= 0) {
				var url = str.split("?");
				str = "";
				if (url.length > 1) {
					url = url[1].split("&");
					for (var i = 0; i < url.length; i++) {
						var kv = url[i].split("=");
						if (kv.length < 2) continue;
						if (kv[0].toLowerCase() === "v") {
							str = kv[1];
							break;
						}
					}
				}
			} else if ((m = str.match(/^(?:(?:http|https)\:\/\/youtu\.be\/|youtu\.be\/)(.*)$/i))) {
				str = m[1];
			} else if (str.match(/^((?:http|https)\:\/\/|www\.).*$/i)) {
				str = "";
			}
			str = str.replace(/[^a-zA-Z0-9\_\-]/i, "");
		} catch(err) {}

		return str;
	};
	
	/**
	 * Parse time string
	 * @param {string} time
	 * @return {number} time in seconds
	 */
	Youtube.prototype.parseTime = function(time) {
		var h = 0, m = 0, s = 0, parts = time.split(':');
		if (parts.length >= 3) {
			h = parseInt(parts.shift(), 10);
			if (isNaN(h)) h = 0;
		}
		if (parts.length >= 2) {
			m = parseInt(parts.shift(), 10);
			if (isNaN(m)) m = 0;
		}
		s = parseInt(parts.shift(), 10);
		if (isNaN(s)) s = 0;
		
		return (h * 60 * 60) + (m * 60) + s;
	};
	
	return Youtube;
});
;

/** WB MusicPlayer **/
(window.defineModule = (window.defineModule || {})).name = 'WB MusicPlayer';

define('MusicPlayer', ['ElementRegister', 'Element'], function(ElementRegister, Element) {
	'use strict';
	
	/**
	 * MusicPlayer class
	 * @param {Object} data
	 */
	var MusicPlayer = function(data) { if (data) this.__construct(data); };

	MusicPlayer.prototype = new Element();
	MusicPlayer.prototype.constructor = MusicPlayer;
	ElementRegister.registerClass("MusicPlayer", MusicPlayer);
	
	MusicPlayer.onScriptReadyOptions = {loading: false, ready: false, listeners: []};
	MusicPlayer.onScriptReady = function(inst, func) {
		if (this.onScriptReadyOptions.ready) {
			func.call(inst);
		} else {
			this.onScriptReadyOptions.listeners.push({inst: inst, func: func});	
			if (!this.onScriptReadyOptions.loading) {
				this.onScriptReadyOptions.loading = true;
				var self = this;
				$.getScript(wb_builder.modBaseUrl + 'site/js/MusicPlayer.js', function() {
					$.getScript(wb_builder.modBaseUrl + 'js/lib/audiojs/audio.min.js', function() {
						self.onScriptReadyOptions.ready = true;
						self.onScriptReadyOptions.loading = false;
						for (var i = 0; i < self.onScriptReadyOptions.listeners.length; i++) {
							self.onScriptReadyOptions.listeners[i].func.call(self.onScriptReadyOptions.listeners[i].inst);
						}
					});
				});
			}
		}
	};
	
	MusicPlayer.prototype.noPhotoBg = 'ico-tb-musicplayer';
	MusicPlayer.prototype.audioUrl = false;
	MusicPlayer.prototype.autoPlay = true;
	MusicPlayer.prototype.hideSelf = true;
	MusicPlayer.prototype.player = null;

	/**
	 * Construct MusicPlayer element
	 * @param {Object} data element data object
	 */
	MusicPlayer.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.setMinSize(100, 20);

		this.displayEmtyMessage(true);

		this.audioUrl = data.content.audioUrl ? data.content.audioUrl : null;
		this.autoPlay = data.content.autoPlay ? data.content.autoPlay : false;

		this.setSize(this.width, this.height);

		if (!this.audioUrl) {
			this.audioUrl = [];
		} else if (!(this.audioUrl instanceof Array)) {
			this.audioUrl = [this.audioUrl];
		}

		var thisClass = this;
		this.elem.bind("resize", function() {
			var w = thisClass.getWidth();
			var h = thisClass.getHeight();
			$(thisClass.player).css({width: w + "px", height: h + "px"});
		});

		this.updateStyle(true);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});

	};
	
	/** @return {String} */
	MusicPlayer.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (this.audioUrl ? this.audioUrl : '');
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	MusicPlayer.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			audioUrl: this.audioUrl,
			autoPlay: this.autoPlay
		};
		return data;
	};

	/**
	 * Update element style after property changes
	 */
	MusicPlayer.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		this.displayEmtyMessage(false);
		
		MusicPlayer.onScriptReady(this, function() {
			if (!this.player) {
				this.player = window.WBMusicPlayer.create(this.container.get(0), {noInit: true});
				this.player.addAllItems(this.audioUrl);
			} else {
				this.player.removeAllItems();
				this.player.addAllItems(this.audioUrl);
			}
		});
	};
	
	MusicPlayer.prototype.getParamsString = function(width, height) {
		var w = (width ? width : this.width), h = (height ? height : this.height),
			params = "showplaylistnumbers=0&mp3=" + this.getMP3String(this.audioUrl) + "&title=" + this.getTitleString(this.audioUrl) + "&width=" + w + "&height=" + h;
		if (this.autoPlay) { params += "&autoplay=1"; }
		return params;
	};
	
	MusicPlayer.prototype.getMP3String = function(audioUrl) {
		var paramsString = "";
		for (var i=0, url; (url = audioUrl[i]); i++) {
			paramsString += "|" + encodeURIComponent(url);
		}
		return paramsString.substring(1);
	};

	MusicPlayer.prototype.getTitleString = function(audioUrl) {
		if (!audioUrl) { audioUrl = this.audioUrl; }
		var titlesString = "";
		for (var i=0, url; (url = audioUrl[i]); i++) {
			if (url.indexOf('/') === 0)
				url = url.substring(1);
			if (url.lastIndexOf('/') === url.length - 1)
				url = url.substring(0, url.length - 1);
			var parts = url.split("/"), title;
			if ((title = parts.pop())) {
				titlesString += "|" + title;
			}
		}
		return titlesString.substring(1);
	};

	/**
	 * Extend element properties dialog
	 */
	MusicPlayer.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 330},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('MP3 file(s)')},
							{type: 'ImageSelector', id: 'audioUrl',
								mode: 'audio',
								multiselect: true,
								mediatabs: false,
								css: {marginBottom: '20px'},
								select: function() {
									fields.testPlayer.update(this.getValues());
								}
							},
							{type: 'CheckBox', id: 'autoPlay', label: __('Start playing when page is loaded')}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Preview')},
							{type: 'CustomContainer', id: 'testPlayer',
								styleClass: 'thumbnail',
								css: {maxHeight: 210, overflowY: 'hidden'},
								init: function() {
									var player = null;
									this.update = function(audioUrl) {
										var thisSelf = this, urls = [], i;
										if (audioUrl) {
											for (i = 0; i < audioUrl.length; i++) {
												urls.push(wb_builder.userBaseUrl + audioUrl[i]);
											}
										}
										if (!player) {
											MusicPlayer.onScriptReady(this, function() {
												player = window.WBMusicPlayer.create(thisSelf._elem.get(0), {noInit: false});
												player.addAllItems(urls);
											});
										} else {
											player.removeAllItems();
											player.addAllItems(urls);
										}
									};
								}
							}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.audioUrl = fields.audioUrl.getValues();
				thisClass.autoPlay = fields.autoPlay.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.audioUrl.setValues(this.audioUrl);
		fields.autoPlay.setValue(this.autoPlay);
	};
	
	return MusicPlayer;
});
;

/** WB Facebook Like **/
(window.defineModule = (window.defineModule || {})).name = 'WB Facebook Like';

define('FacebookLike', ['ElementRegister', 'Element', 'Service', 'ToolTipControl', 'IFrameControl'], function(ElementRegister, Element, Service, ToolTipControl, IFrameControl) {
	'use strict';
	
	/**
	 * FacebookLike class
	 * @param {Object} data
	 */
	var FacebookLike = function(data) { if (data) this.__construct(data); };

	FacebookLike.prototype = new Element();
	FacebookLike.prototype.constructor = FacebookLike;
	ElementRegister.registerClass("FacebookLike", FacebookLike);

	FacebookLike.prototype.noPhotoBg = 'ico-tb-facebook-like';
	FacebookLike.prototype.ifrm = false;
	FacebookLike.prototype.params = false;

	/**
	 * Construct facebook like element
	 * @param {Object} data element data object
	 */
	FacebookLike.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.setMinSize(null, 24);

		this.displayEmtyMessage(true);

		this.ifrm = $("<iframe></iframe>");
		this.ifrm.attr("scrolling", "no");
		this.ifrm.attr("frameborder", "0");
		this.ifrm.attr("allowTransparency", "true");
		this.ifrm.css({border: "none", overflow: "hidden"});
		this.container.append(this.ifrm);

		var thisClass = this;
		this.params = {
			url:		data.content.url ? data.content.url : location.protocol + '//' + location.host,
			//locale:		data.content.locale ? data.content.locale : "en_US",
			locale:		wb_builder.locale,
			layout:		data.content.layout ? data.content.layout : "standard",
			show_faces:	data.content.show_faces ? true : false,
			action:		data.content.action ? data.content.action : "like",
			colorscheme:data.content.colorscheme ? data.content.colorscheme : "light",
			fburl:		data.content.fburl ? data.content.fburl : "about:blank"
		};

		this.elem.bind("resize", function() {
			var w = thisClass.getWidth();
			var h = thisClass.getHeight();
			thisClass.ifrm.css({"width": w + "px", "height": h + "px"});
		});
		this.elem.bind("resizestop", function() { thisClass.updateStyle(); });

		this.updateStyle(true);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/** @return {String} */
	FacebookLike.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = '';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	FacebookLike.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			url:		this.params.url,
			// locale:		this.params.locale,
			locale:		wb_builder.locale,
			layout:		this.params.layout,
			show_faces:	this.params.show_faces,
			action:		this.params.action,
			colorscheme:this.params.colorscheme,
			fburl:		this.params.fburl
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	FacebookLike.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var params = this.params;
		if (typeof(params) !== "object") params = {};

		this.displayEmtyMessage(params.url ? false : true);

		params.url = params.url ? params.url : "";
		params.locale = params.locale ? params.locale : "en_US";
		params.layout = params.layout ? params.layout : "standard";
		params.show_faces = params.show_faces ? true : false;
		params.action = params.action ? params.action : "like";
		params.colorscheme = params.colorscheme ? params.colorscheme : "light";
		params.fburl = "https://www.facebook.com/plugins/like.php" +
			"?locale=" + params.locale + 
			"&href=" + encodeURIComponent(params.url) +
			"&layout=" + encodeURIComponent(params.layout) +
			"&show_faces=" + (params.show_faces ? "true" : "false") +
			"&width=" + this.getWidth() +
			"&height=" + this.getHeight() +
			"&action=" + encodeURIComponent(params.action) +
			"&colorscheme=" + encodeURIComponent(params.colorscheme);

		this.ifrm.attr("src", params.fburl);

		this.params = params;
		this.elem.trigger("resize");
	};

	/**
	 * Extend element properties dialog
	 */
	FacebookLike.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 360},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('URL to Like (required)')},
							{type: 'TextField', id: 'fbUrl', change: function() {
								fields.fbPreview.setParam('href', this.getValue());
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbUrl-change', thisClass);
							}},
							{type: 'Label', text: __('Verb to display'),
								helpText: __("The verb to display in the button. Currently only 'like' and 'recommend' are supported."),
								css: {marginTop: '20px'}
							},
							{type: 'RadioBox', label: __('Like'),
								id: 'fbActionLike',
								group: 'fbAction',
								change: function() {
									fields.fbPreview.setParam('action', 'like');
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbActionLike-change', thisClass);
								}
							},
							{type: 'RadioBox', label: __('Recommend'),
								id: 'fbActionRecommend',
								group: 'fbAction',
								change: function() {
									fields.fbPreview.setParam('action', 'recommend');
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbActionRecommend-change', thisClass);
								}
							},
							{type: 'CheckBox', label: __('Show Faces'),
								id: 'fbShowFaces',
								helpText: __("Show profile pictures below the button."),
								css: {marginTop: '20px'},
								change: function() {
									fields.fbPreview.setParam('show_faces', (this.getValue() ? 'true' : 'false'));
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbShowFaces-change', thisClass);
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Layout Style'),
								helpText: __('determines the size and amount of social context next to the button')
							},
							{type: 'DropdownBox', id: 'fbLayout',
								options: [
									{name: __('Standard'), id: 'standard'},
									{name: __('Count button'), id: 'button_count'},
									{name: __('Count box'), id: 'box_count'}
								],
								change: function() {
									fields.fbPreview.setParam('layout', this.getSelectedItem().getId());
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbLayout-change', thisClass);
								}
							},
							{type: 'Label', text: __('Color Scheme'), css: {marginTop: '20px'}},
							{type: 'RadioBox', label: __('Light'),
								id: 'fbColorSchemeLight',
								group: 'fbColorScheme',
								change: function() {
									fields.fbPreview.setParam('colorscheme', 'light');
									fields.fbPreview.css({backgroundColor: '#ffffff'}); // "#3d3d3d"
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbColorSchemeLight-change', thisClass);
								}
							},
							{type: 'RadioBox', label: __('Dark'),
								id: 'fbColorSchemeDark',
								group: 'fbColorScheme',
								change: function() {
									fields.fbPreview.setParam('colorscheme', 'dark');
									fields.fbPreview.css({backgroundColor: '#3d3d3d'});
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbColorSchemeDark-change', thisClass);
								}
							}
						]}
					]},
					{type: 'Label', text: __('Preview'), css: {marginTop: '20px'}},
					{type: IFrameControl.IFrameControl, id: 'fbPreview',
						url: 'https://www.facebook.com/plugins/like.php',
						params: {
							href: this.params.url,
							locale: this.params.locale,
							show_faces: (this.params.show_faces ? 'true' : 'false'),
							layout: this.params.layout,
							action: this.params.action,
							width: 540, height: 60,
							colorscheme: this.params.colorscheme
						},
						css: {width: 540, height: 60}
					}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.url = fields.fbUrl.getValue();
				//thisClass.params.locale = fields.fbLocale.getValue();
				thisClass.params.layout = fields.fbLayout.getSelectedItem().getId();
				thisClass.params.show_faces = fields.fbShowFaces.getValue();
				thisClass.params.action = (fields.fbActionLike.getValue() ? 'like' : 'recommend');
				thisClass.params.colorscheme = (fields.fbColorSchemeLight.getValue() ? 'light' : 'dark');
				thisClass.updateStyle();
			}
		});
		
		fields.fbUrl.setValue(this.params.url);
		//fields.fbLocale.setValue(this.params.locale);
		var item = fields.fbLayout.getItemById(this.params.layout);
		if (!item) item = fields.fbLayout.getItem(0);
		fields.fbLayout.selectItem(item);
		fields.fbShowFaces.setValue(this.params.show_faces);
		if (this.params.action === 'like') {
			fields.fbActionLike.setValue(true);
		} else {
			fields.fbActionRecommend.setValue(true);
		}
		if (this.params.colorscheme === 'light') {
			fields.fbColorSchemeLight.setValue(true);
		} else {
			fields.fbColorSchemeDark.setValue(true);
		}
	};

	return FacebookLike;
});
;

/** WB Facebook Fans **/
(window.defineModule = (window.defineModule || {})).name = 'WB Facebook Fans';

define('FacebookFans', ['ElementRegister', 'Element', 'Service', 'IFrameControl'], function(ElementRegister, Element, Service, IFrameControl) {

	/**
	 * FacebookFans class
	 * @param {Object} data
	 */
	var FacebookFans = function(data) { if (data) this.__construct(data); };

	FacebookFans.prototype = new Element();
	FacebookFans.prototype.constructor = FacebookFans;
	ElementRegister.registerClass("FacebookFans", FacebookFans);

	FacebookFans.prototype.noPhotoBg = 'ico-tb-facebook-fans';
	FacebookFans.prototype.ifrm = false;
	FacebookFans.prototype.cover = false;
	FacebookFans.prototype.params = false;

	/**
	 * Construct facebook fans element
	 * @param data element data object
	 */
	FacebookFans.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.setMinSize(null, 24);

		this.displayEmtyMessage(true);

		this.ifrm = $("<iframe></iframe>");
		this.ifrm.attr("scrolling", "no");
		this.ifrm.attr("frameborder", "0");
		this.ifrm.attr("allowTransparency", "true");
		this.ifrm.css({border: "none", overflow: "hidden"});
		this.container.append(this.ifrm);

		var thisClass = this;
		this.params = {
			url:		data.content.url ? data.content.url : 'https://www.facebook.com/platform',
			//locale:		data.content.locale ? data.content.locale : "en_US",
			locale:		wb_builder.locale,
			small_header:	WB_Builder.isset(data.content.small_header) ? (data.content.small_header ? true : false) : true,
			hide_cover:		WB_Builder.isset(data.content.hide_cover) ? (data.content.hide_cover ? true : false) : false,
			hide_friends:	data.content.hide_friends ? true : false,
			hide_timeline:	data.content.hide_timeline ? true : false,
			fburl:		data.content.fburl ? data.content.fburl : "about:blank"
		};

		this.elem.bind("resize", function() {
			var w = thisClass.getWidth();
			var h = thisClass.getHeight();
			thisClass.ifrm.css({"width": w + "px", "height": h + "px"});
		});
		this.elem.bind("resizestop", function() { thisClass.updateStyle(); });

		this.updateStyle(true);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	FacebookFans.prototype.fitToParent = function() {
		return false;
	};
	
	/** @return {String} */
	FacebookFans.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = '';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	FacebookFans.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			url:		this.params.url,
			// locale:		this.params.locale,
			locale:		wb_builder.locale,
			small_header:	this.params.small_header,
			hide_cover:		this.params.hide_cover,
			hide_friends:	this.params.hide_friends,
			hide_timeline:	this.params.hide_timeline,
			fburl:		this.params.fburl
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	FacebookFans.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var params = this.params;
		if (typeof(params) !== "object") params = {};

		this.displayEmtyMessage(params.url ? false : true);

		params.url = params.url ? params.url : "https://www.facebook.com/platform";
		params.locale = params.locale ? params.locale : "en_US";
		params.small_header = params.small_header ? true : false;
		params.hide_cover = params.hide_cover ? true : false;
		params.hide_friends = params.hide_friends ? true : false;
		params.fburl = "https://www.facebook.com/plugins/page.php" +
			"?href=" + encodeURIComponent(params.url) +
			"&tabs=" +
			"&locale=" + params.locale +
			"&small_header=" + (params.small_header ? "true" : "false") +
			"&hide_cover=" + (params.hide_cover ? "true" : "false") +
			"&show_facepile=" + (params.hide_friends ? "false" : "true") +
			"&tabs=" + (params.hide_timeline ? "" : "timeline") +
			"&width=" + this.getWidth() +
			"&height=" + this.getHeight() +
			"&adapt_container_width=true";

		this.ifrm.attr("src", params.fburl);

		this.params = params;

		this.elem.trigger("resize");
	};

	/**
	 * Extend element properties dialog
	 */
	FacebookFans.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 340},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Page URL'), helpText: __('Only for Facebook pages, not for profiles')},
							{type: 'TextField', id: 'fbUrl', change: function() {
								fields.fbPreview.setParam('href', this.getValue());
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbUrl-change', thisClass);
							}},
							{type: 'VerticalLayout', css: {marginTop: '20px', marginBottom: '20px'}, children: [
								{type: 'CheckBox', label: __('Hide cover'),
									id: 'fbHideCover',
									helpText: __('Hide cover photo in the header.'),
									change: function() {
										fields.fbPreview.setParam('hide_cover', (this.getValue() ? 'true' : 'false'));
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbHideCover-change', thisClass);
									}
								},
								{type: 'CheckBox', label: __('Hide friends'),
									id: 'fbHideFriends',
									helpText: __("Hide faces of friends."),
									change: function() {
										fields.fbPreview.setParam('show_facepile', (this.getValue() ? 'false' : 'true'));
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbHideFriends-change', thisClass);
									}
								},
								{type: 'CheckBox', label: __('Hide timeline'),
									id: 'fbHideTimeline',
									helpText: __("Hide page timeline."),
									change: function() {
										fields.fbPreview.setParam('tabs', (this.getValue() ? '' : 'timeline'));
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbHideTimeline-change', thisClass);
									}
								},
								{type: 'CheckBox', label: __('Small header'),
									id: 'fbSmallHeader',
									helpText: __('Use smaller header.'),
									change: function() {
										fields.fbPreview.setParam('small_header', (this.getValue() ? 'true' : 'false'));
										Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-fbSmallHeader-change', thisClass);
									}
								}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Preview')},
							{type: IFrameControl.IFrameControl, id: 'fbPreview',
								url: 'https://www.facebook.com/plugins/page.php',
								params: {
									href: this.params.url,
									locale: this.params.locale,
									small_header: (this.params.small_header ? 'true' : 'false'),
									hide_cover: (this.params.hide_cover ? 'true' : 'false'),
									show_facepile: (this.params.hide_friends ? 'false' : 'true'),
									tabs: (this.params.hide_timeline ? '' : 'timeline'),
									width: 260, height: 260
								},
								css: {width: 260, height: 260}
							}
						]}
					]}	
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.url = fields.fbUrl.getValue();
				//thisClass.params.locale = fields.fbLocale.getValue();
				thisClass.params.small_header = fields.fbSmallHeader.getValue();
				thisClass.params.hide_cover = fields.fbHideCover.getValue();
				thisClass.params.hide_friends = fields.fbHideFriends.getValue();
				thisClass.params.hide_timeline = fields.fbHideTimeline.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.fbUrl.setValue(this.params.url);
		//fields.fbLocale.setValue(this.params.locale);
		fields.fbSmallHeader.setValue(this.params.small_header);
		fields.fbHideCover.setValue(this.params.hide_cover);
		fields.fbHideFriends.setValue(this.params.hide_friends);
		fields.fbHideTimeline.setValue(this.params.hide_timeline);
	};
	
	return FacebookFans;
});
;

/** WB Twitter **/
(window.defineModule = (window.defineModule || {})).name = 'WB Twitter';

define('Twitter', ['ElementRegister', 'Element', 'Service'], function(ElementRegister, Element, Service) {
	'use strict';
	
	/**
	 * Twitter class
	 * @param {Object} data
	 */
	var Twitter = function(data) { if (data) this.__construct(data); };

	Twitter.prototype = new Element();
	Twitter.prototype.constructor = Twitter;
	ElementRegister.registerClass("Twitter", Twitter);

	Twitter.scriptLoaded = false;
	Twitter.defaultId = 'https://twitter.com/twitter';
	Twitter.prototype.noPhotoBg = 'ico-tb-twitter';
	Twitter.prototype.widget = null;
	Twitter.prototype.params = null;

	/**
	 * Construct Twitter element
	 * @param {Object} data element data object
	 */
	Twitter.prototype.__construct = function(data) {
		if (!data.width) {
			data.width = 230;
			data.height = 530;
		}
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(false);

		this.setMinSize(150, 100);

		this.container.css({overflow: "hidden"});

		var thisClass = this;
		if (!Twitter.scriptLoaded) {
			Twitter.scriptLoaded = true;
			window.twttr = (function (d,s,id) {
				var t, js, fjs = d.getElementsByTagName(s)[0];
				if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
				js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
				return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f); } });
			  }(document, "script", "twitter-wjs"));
		}

		var colors = (data.content.colors && typeof(data.content.colors) === "object")
			? data.content.colors : {};

		this.params = {
			id:				data.content.id ? data.content.id : Twitter.defaultId,
			numTweets:		(data.content.numTweets*1) ? (data.content.numTweets*1) : 3,		
			theme:			data.content.theme ? data.content.theme : 'light',		
			noHeader:		data.content.noHeader ? true : false,
			noFooter:		data.content.noFooter ? true : false,
			noBorders:		data.content.noBorders ? true : false,
			noScrollbar:	data.content.noScrollbar ? true : false,
			transparent:	data.content.transparent ? true : false,
			colors:			{
				border:		colors.border ? colors.border : '',
				links:		colors.links ? colors.links : '' 
			}
		};

		this.elem.bind("resizestop", function() {
			thisClass.container.children(".twitter-timeline").width(thisClass.getWidth());
			//thisClass.updateStyle();
		});

		setTimeout(function() {
			thisClass.updateStyle(true);
		}, 500);

		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});	
	};
	
	/** @return {String} */
	Twitter.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (this.params.id ? this.params.id : '');
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	Twitter.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			id:				this.params.id,
			numTweets:		this.params.numTweets,
			theme:			this.params.theme,
			noHeader:		this.params.noHeader,
			noFooter:		this.params.noFooter,
			noBorders:		this.params.noBorders,
			noScrollbar:	this.params.noScrollbar,
			transparent:	this.params.transparent,
			colors:	{
				border:		this.params.colors.border,
				links:		this.params.colors.links
			}
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	Twitter.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var params = this.params;
		if (typeof(params) !== "object") params = {};

		params.id = params.id ? params.id : Twitter.defaultId;
		params.theme = params.theme ? params.theme : 'light';
		params.noHeader = params.noHeader ? true : false;
		params.noFooter = params.noFooter ? true : false;
		params.noBorders = params.noBorders ? true : false;
		params.noScrollbar = params.noScrollbar ? true : false;
		params.transparent = params.transparent ? true : false;
		if (typeof(params.colors) !== "object") params.colors = {};
		params.colors.border = params.colors.border ? params.colors.border : ''; 
		params.colors.links = params.colors.links ? params.colors.links : ''; 

		this.params = params;

		this.container.empty();
		this.container.css('overflow-y', 'auto');

		if (!window.twttr || !window.twttr.widgets) return;

		var thisClass = this;
		var chrome = '';
		if (params.noHeader)
			chrome += (' noheader');
		if (params.noFooter)
			chrome += (' nofooter');
		if (params.noBorders)
			chrome += (' noborders');
		if (params.noScrollbar)
			chrome += (' noscrollbar');
		if (params.transparent)
			chrome += (' transparent');
		chrome = $.trim(chrome);
		var c = {
			theme: params.theme,
			chrome: chrome,
			width: params.width,
			height: params.height
		};
		if (params.numTweets)
			c.tweetLimit = params.numTweets;
		if (params.colors.border)
			c.borderColor = params.colors.border;
		if (params.colors.links)
			c.linkColor = params.colors.links;

		var sourceData;
		if (params.id.indexOf('http') === 0) {
			sourceData = {
				sourceType: "url",
				url: params.id
			};
		} else {
			sourceData = {
				sourceType: "widget",
				widgetId: params.id
			};
		}

		try {
			twttr.widgets.createTimeline(
				sourceData,
				thisClass.container.get(0),
				function (el) { },
				c
			);
		} catch (err) { }

		this.elem.trigger("resize");
		this.elem.trigger("resizestop");
	};

	/**
	 * Called when trying to filt in parent
	 */
	Twitter.prototype.fitToParent = function(preserveAspectRatio, oriBounds, initial) {
		Element.prototype.fitToParent.call(this, preserveAspectRatio, oriBounds, initial);
		this.elem.trigger("resizestop");
	};

	Twitter.prototype.setParent = function(parent) {
		Element.prototype.setParent.call(this, parent);
		this.updateStyle();
	};

	/**
	 * Extend element properties dialog
	 */
	Twitter.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 386},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Widget ID or profile URL'), helpText: __('To get Widget Id go to %s. Create new widget "Create New > Search". After create, go back to widgets list and click on it again, copy the ID from the url address OR insert in this field your profile URL').replace('%s', '<a href="https://twitter.com/settings/widgets" target="_blank"> https://twitter.com/settings/widgets</a>')},
							{type: 'TextField', id: 'tweetId', change: function() {
								fields.tweetPreview.setParam('id', this.getValue());
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetId-change', thisClass);
							}},
							{type: 'Label', text: __('Number of Tweets'), css: {marginTop: 15}},
							{type: 'SizeSelector', id: 'tweetNumTweets', min: 0, change: function() {
								fields.tweetPreview.setParam('numTweets', this.getValue());
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetNumTweets-change', thisClass);
							}},
							{type: 'Label', text: __('Theme'), css: {marginTop: 15}},
							{type: 'DropdownBox', id: 'tweetTheme',
								options: [
									{name: __('Light'), id: 'light'},
									{name: __('Dark'), id: 'dark'}
								],
								change: function() {
									fields.tweetPreview.setParam('theme', this.getSelectedItem().getId());
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetTheme-change', thisClass);
								}
							},
							{type: 'CheckBox', label: __('Hide header'),
								id: 'tweetNoHeader',
								css: {marginTop: 15},
								change: function() {
									fields.tweetPreview.setParam('noHeader', (this.getValue() ? true : false));
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetNoHeader-change', thisClass);
								}
							},
							{type: 'CheckBox', label: __('Hide footer'),
								id: 'tweetNoFooter',
								change: function() {
									fields.tweetPreview.setParam('noFooter', (this.getValue() ? true : false));
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetNoFooter-change', thisClass);
								}
							},
							{type: 'CheckBox', label: __('No borders'),
								id: 'tweetNoBorders',
								change: function() {
									fields.tweetPreview.setParam('noBorders', (this.getValue() ? true : false));
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetNoBorders-change', thisClass);
								}
							},
							{type: 'CheckBox', label: __('Hide scrollbar'),
								id: 'tweetNoScrollbar',
								change: function() {
									fields.tweetPreview.setParam('noScrollbar', (this.getValue() ? true : false));
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetNoScrollbar-change', thisClass);
								}
							},
							{type: 'CheckBox', label: __('Transparent background'),
								id: 'tweetTransparent',
								change: function() {
									fields.tweetPreview.setParam('transparent', (this.getValue() ? true : false));
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetTransparent-change', thisClass);
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Preview')},
							{type: 'CustomContainer', id: 'tweetPreview',
								css: {height: 342, overflow: 'auto'},
								init: function(fields) {
									var params = {};
									var autoUpdate = false,
										thisSelf = this;
								
									var update = function() {
										if (!window.twttr || !window.twttr.widgets) return;
										
										params.id = params.id ? params.id : Twitter.defaultId;
										params.theme = params.theme ? params.theme : 'light';
										params.noHeader = params.noHeader ? true : false;
										params.noFooter = params.noFooter ? true : false;
										params.noBorders = params.noBorders ? true : false;
										params.noScrollbar = params.noScrollbar ? true : false;
										params.transparent = params.transparent ? true : false;
										if (typeof(params.colors) !== "object") params.colors = {};
										params.colors.border = params.colors.border ? params.colors.border : '';
										params.colors.links = params.colors.links ? params.colors.links : '';
										
										thisSelf._elem.empty();
										
										var chrome = '';
										if (params.noHeader)
											chrome += (' noheader');
										if (params.noFooter)
											chrome += (' nofooter');
										if (params.noBorders)
											chrome += (' noborders');
										if (params.noScrollbar)
											chrome += (' noscrollbar');
										if (params.transparent)
											chrome += (' transparent');
										chrome = $.trim(chrome);
										var c = {
											theme: params.theme,
											chrome: chrome,
											width: '260',
											height: '300'
										};
										if (params.numTweets)
											c.tweetLimit = params.numTweets;
										if (params.colors.border)
											c.borderColor = params.colors.border;
										if (params.colors.links)
											c.linkColor = params.colors.links;
										
										var sourceData;
										if (params.id.indexOf('http') === 0) {
											sourceData = {
												sourceType: "url",
												url: params.id
											};
										} else {
											sourceData = {
												sourceType: "widget",
												widgetId: params.id
											};
										}
										
										try {
											twttr.widgets.createTimeline(
												sourceData,
												thisSelf._elem.get(0),
												function (el) { },
												c
											);
										} catch (err) { alert(err); }
									};
									this.setAutoUpdate = function(upd) {
										autoUpdate = upd ? true : false;
										if (autoUpdate) update();
									};
									this.setParam = function(name, value) {
										params[name] = value;
										if (autoUpdate) update();
									};
									this.getParam = function(name) {
										return params[name];
									};
								}
							}
						]}
					]}
				]},
				{name: __('Colors'), type: 'colors', children: [
					{type: 'Label', text: __('Border color')},
					{type: 'ColorSelector', id: 'tweetColBorder', change: function() {
						fields.tweetPreview.setParam('borderColor', this.getValue());
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetColBorder-change', thisClass);
					}},
					{type: 'Label', text: __('Links color'), css: {marginTop: 15}},
					{type: 'ColorSelector', id: 'tweetColLinks', change: function() {
						fields.tweetPreview.setParam('linkColor', this.getValue());
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-tweetColLinks-change', thisClass);
					}}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.id = fields.tweetId.getValue();
				thisClass.params.numTweets = fields.tweetNumTweets.getValue();
				thisClass.params.theme = fields.tweetTheme.getValue();
				thisClass.params.noHeader = fields.tweetNoHeader.getValue();
				thisClass.params.noFooter = fields.tweetNoFooter.getValue();
				thisClass.params.noBorders = fields.tweetNoBorders.getValue();
				thisClass.params.noScrollbar = fields.tweetNoScrollbar.getValue();
				thisClass.params.transparent = fields.tweetTransparent.getValue();
				thisClass.params.colors.border = fields.tweetColBorder.getValue();
				thisClass.params.colors.links = fields.tweetColLinks.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.tweetPreview.setAutoUpdate(false);
		fields.tweetId.setValue(this.params.id);
		fields.tweetNumTweets.setValue(this.params.numTweets);
		fields.tweetTheme.setValue(this.params.theme);
		fields.tweetNoHeader.setValue(this.params.noHeader);
		fields.tweetNoFooter.setValue(this.params.noFooter);
		fields.tweetNoBorders.setValue(this.params.noBorders);
		fields.tweetNoScrollbar.setValue(this.params.noScrollbar);
		fields.tweetTransparent.setValue(this.params.transparent);
		fields.tweetColBorder.setValue(this.params.colors.border);
		fields.tweetColLinks.setValue(this.params.colors.links);
		fields.tweetPreview.setAutoUpdate(true);
	};
	
	return Twitter;
});
;

/** WB FlickrGallery **/
(window.defineModule = (window.defineModule || {})).name = 'WB FlickrGallery';

define('FlickrGallery', ['ElementRegister', 'Element'], function(ElementRegister, Element) {
	'use strict';
	
	/**
	 * FlickrGallery class
	 * @param {Object} data
	 */
	var FlickrGallery = function(data) { if (data) this.__construct(data); };

	FlickrGallery.prototype = new Element();
	FlickrGallery.prototype.constructor = FlickrGallery;
	ElementRegister.registerClass("FlickrGallery", FlickrGallery);

	FlickrGallery.prototype.noPhotoBg = 'ico-tb-flickr-gallery';
	FlickrGallery.prototype.galleryObject = null;
	FlickrGallery.prototype.params = false;

	/**
	 * Construct FlickrGallery element
	 * @param {Object} data element data object
	 */
	FlickrGallery.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		this.setMinSize(null, 24);

		this.container.css({overflow: "hidden"});

		var thisClass = this;

		this.params = {
			url:	data.content.url ? data.content.url : null,
			uid:	data.content.uid ? data.content.uid : null,
			isSet:	data.content.isSet ? true : false,
			iid:	data.content.iid ? data.content.iid : null,
			mv:		data.content.mv ? data.content.mv : "",
			fv:		data.content.fv ? data.content.fv : ""
		};

		this.updateStyle(true);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};
	
	FlickrGallery.prototype.supportsFullWidth = function() {
		return true;
	};

	/** @return {String} */
	FlickrGallery.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (this.params.uid ? this.params.uid : '');
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	FlickrGallery.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			url:	this.params.url,
			uid:	this.params.uid,
			isSet:	this.params.isSet,
			iid:	this.params.iid,
			mv:		this.params.mv,
			fv:		this.params.fv
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	FlickrGallery.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var params = this.params;
		if (typeof(params) !== "object") params = {};

		params.url = params.url ? params.url : null;
		params.uid = params.uid ? params.uid : null;
		params.isSet = params.isSet ? params.isSet : false;
		params.iid = params.iid ? params.iid : null;

		params.mv = "http://www.flickr.com/apps/slideshow/show.swf?v=107931";
		params.fv = "offsite=true" +
			"&lang=en-us" +
			"&page_show_url=" + encodeURI("/photos/" + params.uid +
				(params.isSet ? "/sets" : "") + 
				(params.iid ? ("/" + params.iid) : "") + "/show/") +
			"&page_show_back_url=" + encodeURI("/photos/" + params.uid +
				(params.isSet ? "/sets" : "") +
				(params.iid ? ("/" + params.iid) : "") + "/") +
			(params.isSet
				? ("&set_id=" + (params.iid ? encodeURI(params.iid) : ""))
				: ("&user_id=" + encodeURI(params.uid))) +
			"&jump_to=" + ((!params.isSet && params.iid) ? encodeURI(params.iid) : "");

		this.params = params;

		if (this.galleryObject) {
			this.galleryObject.remove();
			this.galleryObject.empty();
			this.galleryObject = null;
		}

		if (params.uid) {
			this.galleryObject = $('<object></object>');
			this.galleryObject.attr("data", params.mv);
			this.galleryObject.attr("type", "application/x-shockwave-flash");
			this.galleryObject.css({width: "100%", height: "100%"});
			var p = $('<param name="movie" />');
			p.val(params.mv);
			this.galleryObject.append(p);
			this.galleryObject.append('<param name="menu" value="false" />');
			this.galleryObject.append('<param name="allowFullScreen" value="false" />');
			this.galleryObject.append('<param name="wmode" value="transparent" />');
			p = $('<param name="flashvars" />');
			p.val(params.fv);
			this.galleryObject.append(p);
			this.container.append(this.galleryObject);

			this.displayEmtyMessage(false);
		} else {
			this.displayEmtyMessage(true);
		}

		this.elem.trigger("resize");
	};

	/**
	 * Extend element properties dialog
	 */
	FlickrGallery.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 330},
			tabs: [
				{children: [
					{type: 'VerticalLayout', fluid: true, children: [
						{type: 'Label', text: __('Flickr gallery or set URL')},
						{type: 'TextField', id: 'flickrUrl', fixedWidth: 12},
						{type: 'CustomContainer', css: {fontSize: '12px', color: '#999999'}, init: function() {
							this._elem.text(__('Ex.') + ' http://www.flickr.com/photos/gifrancis/galleries/72157622562924322/');
						}}
					]}
				]}
			],
			callbackFunc: function(fields) {
				var p = thisClass.params;

				p.uid = null;
				p.isSet = false;
				p.iid = null;
				p.url = fields.flickrUrl.getValue();
				var url = p.url.split("/photos/");
				url = (url.length > 1) ? url[1] : null;
				if (url) {
					url = url.split("/");
					p.uid = url[0];
					p.isSet = ((url.length > 1) && url[1].toLowerCase() === "sets");
					if (!p.isSet && url.length > 1 && /^[0-9]+$/i.test(url[1])) {
						p.iid = url[1];
					} else if (p.isSet && url.length > 2 && /^[0-9]+$/i.test(url[2])) {
						p.iid = url[2];
					}
				}
				if (!(/^[0-9]+\@[a-zA-Z0-9]+$/i.test(p.uid))) {
					window.jsonFlickrApi = function(res) {
						if (res.user && res.user.id) {
							thisClass.params.uid = res.user.id;
							thisClass.updateStyle();
						}
					};
					//var uid = (p.uid + "").escapeEx();
					p.uid = null;
					thisClass.params = p;
					thisClass.updateStyle();
					$.getScript("https://api.flickr.com/services/rest/?" +
						"method=flickr.urls.lookupUser" +
						"&format=json" +
						"&api_key=83907c66938b15201d5ad2f56026cc97" +
						"&url=" + p.url);
				} else {
					thisClass.params = p;
					thisClass.updateStyle();
				}

				thisClass.updateStyle();
			}
		});
		
		fields.flickrUrl.setValue(this.params.url);
	};
	
	return FlickrGallery;
});
;

/** WB CustomHtml **/
(window.defineModule = (window.defineModule || {})).name = 'WB CustomHtml';

define('CustomHtml', ['ElementRegister', 'Element', 'Service'], function(ElementRegister, Element, Service) {
	'use strict';
	
	/**
	 * CustomHtml class
	 * @param {Object} data
	 */
	var CustomHtml = function(data) { if (data) this.__construct(data); };

	CustomHtml.prototype = new Element();
	CustomHtml.prototype.constructor = CustomHtml;
	ElementRegister.registerClass("CustomHtml", CustomHtml);

	CustomHtml.prototype.noPhotoBg = 'ico-tb-html';
	CustomHtml.prototype.customHtml = null;
	CustomHtml.prototype.customHtmlDeactivate = true;
	CustomHtml.prototype.customHtmlAutoHeight = false;

	/**
	 * Construct custom html element
	 * @param data element data object
	 */
	CustomHtml.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		this.setMinSize(null, 24);

		this.container.css({overflow: "hidden"});

		this.customHtml = data.content.html ? data.content.html : null;
		// this.customHtmlDeactivate = (typeof data.content.htmlDeactivate === 'undefined' || data.content.htmlDeactivate) ? true : false;
		// Always deactivate, because to many broken scripts from users break builder
		// and because of that we need to manually disable them.
		this.customHtmlDeactivate = true;
		this.customHtmlAutoHeight = data.content.htmlAutoHeight ? true : false;

		this.updateStyle(true);

		var thisClass = this;
		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	CustomHtml.prototype.supportsFullWidth = function() {
		return true;
	};

	/** @return {String} */
	CustomHtml.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = '';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	CustomHtml.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			html: (this.customHtml ? this.customHtml : ""),
			htmlDeactivate: this.customHtmlDeactivate,
			htmlAutoHeight: this.customHtmlAutoHeight
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	CustomHtml.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		if (this.customHtmlDeactivate) {
			this.displayEmtyMessage(true);
			this.container.html("");
		} else {
			this.displayEmtyMessage(this.customHtml ? false : true);

			try {
				var m, maxCycles = 1000,
					html = this.customHtml ? this.customHtml : "",
					rg = /['"]gallery\/[^'"]+\-ts[0-9]+\.[^\.'"]+['"]/;
				while (maxCycles > 0 && (m = html.match(rg))) {
					html = html.replace(m[0], m[0].substring(0, 1) + wb_builder.userBaseUrl + m[0].substring(1));
					maxCycles--;
				}
				this.container.html(html);
			} catch(ex) {}
		}
	};

	/**
	 * Extend element properties dialog
	 */
	CustomHtml.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 330},
			tabs: [
				{children: [
					{type: 'VerticalLayout', fluid: true, children: [
						{type: 'CheckBox', label: __('Deacitvate content while in builder (recomended)'),
							id: 'customHtmlDeactivate',
							helpText: __("Some scripts may interfere with a Zyro Builder, so it's recomended to deactivate them. Failing to do so may result in inaccessable page in builder.") + '<br />' + __('Note that this option is enabled automatically when builder is opened next time.')
						},
						{type: 'CheckBox', label: __('Auto height (experimental)'),
							id: 'customHtmlAutoHeight',
							helpText: __("This will allow element to expand depending on content.")
						},
						{type: 'HorizontalLayout', css: {marginTop: 15}, columnWeights: [9, 3], children: [
							{type: 'Label', text: __('HTML code')},
							{type: 'Button', text: __('Insert'),
								icon: 'glyphicon glyphicon-picture',
								styleClass: 'btn-xs pull-right',
								click: function(e, fields) {
									if (!this.libDlg) {
										this.libDlg = Service.mediaLibrary.open(__('Select media'), false, 'all', false);
										var dlg = this.libDlg;
										dlg.addButton(__('Cancel'));
										dlg.addButton(__('Select'), function() {
											var list = dlg.getSelectedFiles(false);
											if (list.length > 0) {
												fields.customHtml.focus();
												fields.customHtml.insertAtCursor(list[0]);
											}
											dlg.hide();
										}, true);
									}
									this.libDlg.clearFileSelection();
									this.libDlg.show();
								}
							}
						]},
						{type: 'TextField', id: 'customHtml', textArea: true, fixedWidth: 12, css: {height: 214, marginBottom: 0},
							placeholder: __('HTML is a code which usually contains tags wrapped between < ... > symbols.') + '\n'
									+ __('Example') + ': ' + '<div> ... ' + __('HTML code').toLowerCase() + ' ... </div>'
						}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.customHtml = fields.customHtml.getValue();
				thisClass.customHtmlDeactivate = fields.customHtmlDeactivate.getValue();
				thisClass.customHtmlAutoHeight = fields.customHtmlAutoHeight.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.customHtml.setValue(this.customHtml ? this.customHtml : '');
		fields.customHtmlDeactivate.setValue(this.customHtmlDeactivate);
		fields.customHtmlAutoHeight.setValue(this.customHtmlAutoHeight);
	};
	
	return CustomHtml;
});
;

/** WB BookmarksShare **/
(window.defineModule = (window.defineModule || {})).name = 'WB BookmarksShare';

define('BookmarksShare', ['ElementRegister', 'Element', 'Service', 'ToolTipControl'], function(ElementRegister, Element, Service, ToolTipControl) {
	'use strict';
	
	/**
	 * BookmarksShare class
	 * @param {Object} data
	 */
	var BookmarksShare = function(data) { if (data) this.__construct(data); };

	BookmarksShare.prototype = new Element();
	BookmarksShare.prototype.constructor = BookmarksShare;
	ElementRegister.registerClass("BookmarksShare", BookmarksShare);

	BookmarksShare.scriptLoaded = false;
	BookmarksShare.prototype.noPhotoBg = 'ico-tb-share';
	BookmarksShare.prototype.widget = null;
	BookmarksShare.prototype.params = null;

	/**
	 * Construct BookmarksShare element
	 * @param {Object} data element data object
	 */
	BookmarksShare.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		this.setMinSize(null, 24);

		this.container.css({overflow: "hidden"});
		this.container.attr("id", this.id + "_addthis-widget");

		var thisClass = this;
		if (!BookmarksShare.scriptLoaded) {
			BookmarksShare.scriptLoaded = true;
			$.getScript("//s7.addthis.com/js/250/addthis_widget.js#domready=1", function() {
				thisClass.updateStyle(true);
			});
		}
		/* wb_builder.addCSSRule('.demo.addthis_button_facebook',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left 0px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_twitter',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -20px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_email',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -40px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_google',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -60px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_print',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -80px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_compact',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -100px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_facebook_like',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -120px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_tweet',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -140px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button_google_plusone',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -160px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;');
		wb_builder.addCSSRule('.demo.addthis_button',
			'background: transparent url("images/bookmarks_share_demo.png") no-repeat left -180px;'+
			'width: 126px; height: 20px; display: block; float: left; padding: 0; margin: 0;'+
			'text-decoration: none; border: none;'); */

		var buttons = (data.content.buttons && typeof(data.content.buttons) === "object") ?
			data.content.buttons : {
				facebook: true,
				twitter: true,
				email: true
			};

		this.params = {
			user: data.content.user ? data.content.user : "",
			size: data.content.size ? data.content.size : "16x16",
			buttons: {
				facebook:			buttons.facebook ? true : false,
				twitter:			buttons.twitter ? true : false,
				vk:					buttons.vk ? true : false,
				odnoklassniki_ru:	buttons.odnoklassniki_ru ? true : false,
				email:				buttons.email ? true : false,
				google:				buttons.google ? true : false,
				print:				buttons.print ? true : false,
				compact:			buttons.compact ? true : false,
				counter_bubble:		buttons.counter_bubble ? true : false,
				facebook_like:		buttons.facebook_like ? true : false,
				tweet:				buttons.tweet ? true : false,
				linkedin:			buttons.linkedin ? true : false,
				google_plusone:		buttons.google_plusone ? true : false,
				share:				buttons.share ? true : false,
				telegram:			buttons.telegram ? true : false
			}
		};

		this.updateStyle(true);

		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/** @return {String} */
	BookmarksShare.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = '';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	BookmarksShare.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			user: this.params.user,
			size: this.params.size,
			buttons: {
				facebook:	this.params.buttons.facebook,
				twitter:	this.params.buttons.twitter,
				vk:			this.params.buttons.vk,
				odnoklassniki_ru:	this.params.buttons.odnoklassniki_ru,
				email:		this.params.buttons.email,
				google:		this.params.buttons.google,
				print:		this.params.buttons.print,
				compact:	this.params.buttons.compact,
				counter_bubble:	this.params.buttons.counter_bubble,
				facebook_like:	this.params.buttons.facebook_like,
				tweet:			this.params.buttons.tweet,
				linkedin:		this.params.buttons.linkedin,
				google_plusone:	this.params.buttons.google_plusone,
				share:		this.params.buttons.share,
				telegram:	this.params.buttons.telegram
			}
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	BookmarksShare.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var params = this.params;
		if (typeof(params) !== "object") params = {};

		this.container.empty();

		params.user = params.user ? params.user : "";
		params.size = params.size ? params.size : "16x16";

		if (typeof(params.buttons) !== "object") params.buttons = {"share": true};
		params.buttons.facebook = params.buttons.facebook ? params.buttons.facebook : false;
		params.buttons.twitter = params.buttons.twitter ? params.buttons.twitter : false;
		params.buttons.vk = params.buttons.vk ? params.buttons.vk : false;
		params.buttons.odnoklassniki_ru = params.buttons.odnoklassniki_ru ? params.buttons.odnoklassniki_ru : false;
		params.buttons.email = params.buttons.email ? params.buttons.email : false;
		params.buttons.google = params.buttons.google ? params.buttons.google : false;
		params.buttons.print = params.buttons.print ? params.buttons.print : false;
		params.buttons.compact = params.buttons.compact ? params.buttons.compact : false;
		params.buttons.counter_bubble = params.buttons.counter_bubble ? params.buttons.counter_bubble : false;
		params.buttons.facebook_like = params.buttons.facebook_like ? params.buttons.facebook_like : false;
		params.buttons.tweet = params.buttons.tweet ? params.buttons.tweet : false;
		params.buttons.linkedin = params.buttons.linkedin ? params.buttons.linkedin : false;
		params.buttons.google_plusone = params.buttons.google_plusone ? params.buttons.google_plusone : false;
		params.buttons.share = params.buttons.share ? params.buttons.share : false;
		params.buttons.telegram = params.buttons.telegram ? params.buttons.telegram : false;

		this.params = params;

		this.container.children("a").css("display", "none");

		var cc = 0;
		for (var k in params.buttons) {
			if (!params.buttons[k]) continue;
			var kid = this.id + "_" + k;
			var kc = "addthis_button_" + k;
			if (k === "counter_bubble") kc = "addthis_counter addthis_bubble_style";
			if (k === "share") kc = "addthis_button";

			if (this.container.children("#" + kid).length === 0) {
				this.container.append('<a id="' + kid + '"' +
					' style="float: left;' + ((cc > 0) ? ' margin-left: 4px;' : '') + '"' +
					' class="' + kc + '"></a>');
			} else {
				this.container.children("#" + kid).css("display", "block");
				this.container.children("#" + kid).parent().append(this.container.children("#" + kid));
			}
			cc++;
		}
		this.displayEmtyMessage((cc > 0) ? false : true);
		if (params.size === "32x32") {
			this.container.children("a").addClass("addthis_32x32_style");
		} else {
			this.container.children("a").removeClass("addthis_32x32_style");
		}
		this.container.children("div").remove();
		var config = {};
		var share_config = {};
		if (window.addthis) {
			addthis.toolbox(this.container.get(0), config, share_config);
		}
	};

	/**
	 * Extend element properties dialog
	 */
	BookmarksShare.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 356},
			tabs: [
				{children: [
					{type: 'Label', text: __('Size')},
					{type: 'DropdownBox', id: 'shareSize', options: [
						{name: __('16x16'), id: '16x16'},
						{name: __('32x32'), id: '32x32'}
					], change: function() {
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareSize-change', thisClass);
					}},
					{type: 'Label', text: __('Buttons'), css: {marginTop: '20px'}},
					{type: 'HorizontalLayout', children: [
						//'<img src="' + wb_builder.modBaseUrl + 'img/addthis_facebook.png" /> '
						//'<img src="' + wb_builder.modBaseUrl + 'img/addthis_twitter.png /> '
						//'<img src="' + wb_builder.modBaseUrl + 'img/addthis_email.png" /> '
						{type: 'CheckBox', label: __('Facebook'), id: 'shareBtnFacebook', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnFacebook-change', thisClass);
						}},
                        {type: 'CheckBox', label: __('Email'), id: 'shareBtnEmail', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnEmail-change', thisClass);
						}},
                        {type: 'CheckBox', label: __('Facebook Like'), id: 'shareBtnFacebookLike', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnFacebookLike-change', thisClass);
						}}
					]},
                    {type: 'HorizontalLayout', children: [
                        {type: 'CheckBox', label: __('Twitter'), id: 'shareBtnTwitter', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnTwitter-change', thisClass);
						}},
                        {type: 'CheckBox', label: __('Print'), id: 'shareBtnPrint', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnPrint-change', thisClass);
						}},
                        {type: 'CheckBox', label: __('Tweet button'), id: 'shareBtnTweet', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnTweet-change', thisClass);
						}}
                    ]},
					{type: 'HorizontalLayout', children: [
						//'<img src="' + wb_builder.modBaseUrl + 'img/addthis_google.png" /> '
						//'<img src="' + wb_builder.modBaseUrl + 'img/addthis_print.png" /> '
						//'<img src="' + wb_builder.modBaseUrl + 'img/addthis_more.png" /> '
                        {type: 'CheckBox', label: __('Google'), id: 'shareBtnGoogle', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnGoogle-change', thisClass);
						}},
						{type: 'CheckBox', label: __('AddThis share'), id: 'shareBtnCompact', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnCompact-change', thisClass);
						}},
                        {type: 'CheckBox', label: __('Google Plus'), id: 'shareBtnGooglePlusone', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnGooglePlusone-change', thisClass);
						}}
					]},
					{type: 'HorizontalLayout', columnWeights: [4, 4], children: [
                        {type: 'CheckBox', label: __('LinkedIn'), id: 'shareBtnLinkedin', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnLinkedin-change', thisClass);
						}}, ///////
                        {type: 'CheckBox', label: __('Telegram'), id: 'shareBtnTelegram', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnTelegram-change', thisClass);
						}} ///////
					]},
					{type: 'HorizontalLayout', columnWeights: [4, 4], children: [
                        {type: 'CheckBox', label: __('VKontakte'), id: 'shareBtnVKontakte', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnVKontakte-change', thisClass);
						}} ///////
					]},
					{type: 'HorizontalLayout', columnWeights: [4, 4], children: [
                        {type: 'CheckBox', label: __('Odnoklassniki'), id: 'shareBtnOdnoklassniki', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareBtnOdnoklassniki-change', thisClass);
						}} ///////
					]},
					{type: 'Label', text: __('Profile ID (optional)'),
						helpText: __('AddThis.com profile ID. You can register to get statistics.'),
						css: {marginTop: '20px'}
					},
					{type: 'TextField', id: 'shareUser', change: function() {
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-shareUser-change', thisClass);
					}}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.user = fields.shareUser.getValue();
				thisClass.params.size = fields.shareSize.getSelectedItem().getId();
				thisClass.params.buttons.facebook = fields.shareBtnFacebook.getValue();
				thisClass.params.buttons.twitter = fields.shareBtnTwitter.getValue();
				thisClass.params.buttons.vk = fields.shareBtnVKontakte.getValue();
				thisClass.params.buttons.odnoklassniki_ru = fields.shareBtnOdnoklassniki.getValue();
				thisClass.params.buttons.email = fields.shareBtnEmail.getValue();
				thisClass.params.buttons.google = fields.shareBtnGoogle.getValue();
				thisClass.params.buttons.print = fields.shareBtnPrint.getValue();
				thisClass.params.buttons.compact = fields.shareBtnCompact.getValue();
				//thisClass.params.buttons.counter_bubble = fields.shareBtnCounterBubble.getValue();
				thisClass.params.buttons.facebook_like = fields.shareBtnFacebookLike.getValue();
				thisClass.params.buttons.tweet = fields.shareBtnTweet.getValue();
				thisClass.params.buttons.linkedin = fields.shareBtnLinkedin.getValue();
				thisClass.params.buttons.google_plusone = fields.shareBtnGooglePlusone.getValue();
				thisClass.params.buttons.telegram = fields.shareBtnTelegram.getValue();
				//thisClass.params.buttons.share = fields.shareBtnShare.getValue();

				thisClass.updateStyle();
			}
		});
		
		fields.shareUser.setValue(this.params.user);
		var item = fields.shareSize.getItemById(this.params.size);
		if (!item) item = fields.shareSize.getItem(0);
		fields.shareSize.selectItem(item);
		fields.shareBtnFacebook.setValue(this.params.buttons.facebook);
		fields.shareBtnTwitter.setValue(this.params.buttons.twitter);
		fields.shareBtnVKontakte.setValue(this.params.buttons.vk);
		fields.shareBtnOdnoklassniki.setValue(this.params.buttons.odnoklassniki_ru);
		fields.shareBtnEmail.setValue(this.params.buttons.email);
		fields.shareBtnGoogle.setValue(this.params.buttons.google);
		fields.shareBtnPrint.setValue(this.params.buttons.print);
		fields.shareBtnCompact.setValue(this.params.buttons.compact);
		//fields.shareBtnCounterBubble.setValue(this.params.buttons.counter_bubble);
		fields.shareBtnFacebookLike.setValue(this.params.buttons.facebook_like);
		fields.shareBtnTweet.setValue(this.params.buttons.tweet);
		fields.shareBtnLinkedin.setValue(this.params.buttons.linkedin);
		fields.shareBtnGooglePlusone.setValue(this.params.buttons.google_plusone);
		fields.shareBtnTelegram.setValue(this.params.buttons.telegram);
		//fields.shareBtnShare.setValue(this.params.buttons.share);
	};
	
	return BookmarksShare;
});
;

/** WB GoogleMaps **/
(window.defineModule = (window.defineModule || {})).name = 'WB GoogleMaps';

define('GoogleMaps', ['ElementRegister', 'Element', 'Service'], function(ElementRegister, Element, Service) {
	
	var wb_builder = window.wb_builder;
	
	/**
	 * GoogleMaps class
	 * @param {Object} data
	 */
	var GoogleMaps = function(data) { if (data) this.__construct(data); };

	window["WB_GoogleMaps_script_fn"] = function() {
		for (var i in GoogleMaps.callbacks) {
			if (typeof(GoogleMaps.callbacks[i]) === 'function') {
				GoogleMaps.callbacks[i]();
				GoogleMaps.callbacks[i] = null;
			}
		}
	};
	
	GoogleMaps.getThemeDefaultStyle = function() {
		return [];
	};
	GoogleMaps.getThemeLightStyle = function(color) {
		return [
			{
				"featureType": "administrative",
				"elementType": "labels.text.fill",
				"stylers": [
					{
						"color": "#444444"
					}
				]
			},
			{
				"featureType": "landscape",
				"elementType": "all",
				"stylers": [
					{
						"color": "#f2f2f2"
					}
				]
			},
			{
				"featureType": "poi",
				"elementType": "all",
				"stylers": [
					{
						"visibility": "off"
					}
				]
			},
			{
				"featureType": "road",
				"elementType": "all",
				"stylers": [
					{
						"saturation": -100
					},
					{
						"lightness": 45
					}
				]
			},
			{
				"featureType": "road.highway",
				"elementType": "all",
				"stylers": [
					{
						"visibility": "simplified"
					}
				]
			},
			{
				"featureType": "road.arterial",
				"elementType": "labels.icon",
				"stylers": [
					{
						"visibility": "off"
					}
				]
			},
			{
				"featureType": "transit",
				"elementType": "all",
				"stylers": [
					{
						"visibility": "off"
					}
				]
			},
			{
				"featureType": "water",
				"elementType": "all",
				"stylers": [
					{
						"color": (color ? color : '#cccccc')
					},
					{
						"visibility": "on"
					}
				]
			}
		];
	};
	GoogleMaps.getThemeDarkStyle = function(color) {
		return [
			{
				"featureType": "all",
				"elementType": "labels.text.fill",
				"stylers": [
					{
						"saturation": 36
					},
					{
						"color": "#000000"
					},
					{
						"lightness": 40
					}
				]
			},
			{
				"featureType": "all",
				"elementType": "labels.text.stroke",
				"stylers": [
					{
						"visibility": "on"
					},
					{
						"color": "#000000"
					},
					{
						"lightness": 16
					}
				]
			},
			{
				"featureType": "all",
				"elementType": "labels.icon",
				"stylers": [
					{
						"visibility": "off"
					}
				]
			},
			{
				"featureType": "administrative",
				"elementType": "geometry.fill",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 20
					}
				]
			},
			{
				"featureType": "administrative",
				"elementType": "geometry.stroke",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 17
					},
					{
						"weight": 1.2
					}
				]
			},
			{
				"featureType": "landscape",
				"elementType": "geometry",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 20
					}
				]
			},
			{
				"featureType": "poi",
				"elementType": "geometry",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 21
					}
				]
			},
			{
				"featureType": "road.highway",
				"elementType": "geometry.fill",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 17
					}
				]
			},
			{
				"featureType": "road.highway",
				"elementType": "geometry.stroke",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 29
					},
					{
						"weight": 0.2
					}
				]
			},
			{
				"featureType": "road.arterial",
				"elementType": "geometry",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 18
					}
				]
			},
			{
				"featureType": "road.local",
				"elementType": "geometry",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 16
					}
				]
			},
			{
				"featureType": "transit",
				"elementType": "geometry",
				"stylers": [
					{
						"color": "#000000"
					},
					{
						"lightness": 19
					}
				]
			},
			{
				"featureType": "water",
				"elementType": "geometry",
				"stylers": [
					{
						"color": (color ? color : '#333333')
					},
					{
						"lightness": 17
					}
				]
			}
		];
	};
	GoogleMaps.getThemeMonochromeStyle = function(color) {
		return [
			{
				"featureType": "all",
				"elementType": "geometry",
				"stylers": [
					{
						"color": (color ? color : '#3e44b5')
					}
				]
			},
			{
				"featureType": "all",
				"elementType": "labels.text.fill",
				"stylers": [
					{
						"gamma": 0.01
					},
					{
						"lightness": 20
					}
				]
			},
			{
				"featureType": "all",
				"elementType": "labels.text.stroke",
				"stylers": [
					{
						"saturation": -31
					},
					{
						"lightness": -33
					},
					{
						"weight": 2
					},
					{
						"gamma": 0.8
					}
				]
			},
			{
				"featureType": "all",
				"elementType": "labels.icon",
				"stylers": [
					{
						"visibility": "off"
					}
				]
			},
			{
				"featureType": "landscape",
				"elementType": "geometry",
				"stylers": [
					{
						"lightness": 30
					},
					{
						"saturation": 30
					}
				]
			},
			{
				"featureType": "poi",
				"elementType": "geometry",
				"stylers": [
					{
						"saturation": 20
					}
				]
			},
			{
				"featureType": "poi.park",
				"elementType": "geometry",
				"stylers": [
					{
						"lightness": 20
					},
					{
						"saturation": -20
					}
				]
			},
			{
				"featureType": "road",
				"elementType": "geometry",
				"stylers": [
					{
						"lightness": 10
					},
					{
						"saturation": -30
					}
				]
			},
			{
				"featureType": "road",
				"elementType": "geometry.stroke",
				"stylers": [
					{
						"saturation": 25
					},
					{
						"lightness": 25
					}
				]
			},
			{
				"featureType": "water",
				"elementType": "all",
				"stylers": [
					{
						"lightness": -20
					}
				]
			}
		];
	};
	
	GoogleMaps.prototype = new Element();
	GoogleMaps.prototype.constructor = GoogleMaps;
	ElementRegister.registerClass("GoogleMaps", GoogleMaps);

	GoogleMaps.scriptLoaded = false;
	GoogleMaps.callbacks = {};
	GoogleMaps.prototype.noPhotoBg = 'ico-tb-google-maps';
	GoogleMaps.prototype.mapDiv = null;
	GoogleMaps.prototype.map = null;
	GoogleMaps.prototype.disabledOverlay = null;
	GoogleMaps.prototype.mapMarker = null;
	GoogleMaps.prototype.params = false;
	GoogleMaps.prototype.mapAddress = null;

	/**
	 * Construct GoogleMaps element
	 * @param data element data object
	 */
	GoogleMaps.prototype.__construct = function(data) {
		if (!data.width) {
			data.width = 602;
			data.height = 327;
		}
		Element.prototype.__construct.call(this, data);

		this.setMinSize(null, 24);

		this.displayEmtyMessage(true);

		this.map = null;
		this.mapMarker = null;

		var thisClass = this;

		GoogleMaps.callbacks[this.id] = function() {
			thisClass.updateStyle();
		};

		if (!GoogleMaps.scriptLoaded) {
			GoogleMaps.scriptLoaded = true;
			
			var region, lang, locale = (wb_builder.locale ? wb_builder.locale : null);
			if (wb_builder.site.currSelLang) {
				lang = wb_builder.getLanguageByCode(wb_builder.site.currSelLang);
				if (lang) locale = lang.locale;
			}
			region = (locale && locale.indexOf('_') >= 0) ? locale.split('_')[1].toUpperCase() : null;
			$.getScript(Element.httpProtocol + "://maps.googleapis.com/maps/api/js?v=3.exp&key=" + wb_builder.mapsConfig.googleMapsApiKey + "&sensor=false" +
					(region ? ("&region=" + region + "&language=" + locale) : '') +
					"&callback=WB_GoogleMaps_script_fn&libraries=places");
		}
		
		this.params = {
			address:		data.content.address ? data.content.address
									: (wb_builder.mapsConfig.address ? wb_builder.mapsConfig.address : "Liberty Island, New York, NY 10004"),
			ll:				data.content.ll ? data.content.ll : (wb_builder.mapsConfig.ll ? wb_builder.mapsConfig.ll : "40.689247,-74.044502"),
			zoom:			data.content.zoom ? data.content.zoom*1 : 16,
			mapTypeId:		data.content.mapTypeId ? data.content.mapTypeId : null,
			key:			(data.content.key ? data.content.key : null),
			theme:			data.content.theme ? data.content.theme : 'default',
			color:			data.content.color ? data.content.color : '#eeeeee',
			showSatellite:	(!('showSatellite' in data.content) || data.content.showSatellite),
			showZoom:		(!('showZoom' in data.content) || data.content.showZoom),
			showStreetView:	(!('showStreetView' in data.content) || data.content.showStreetView),
			showFullscreen:	(!('showFullscreen' in data.content) || data.content.showFullscreen),
			allowDragging:	(!('allowDragging' in data.content) || data.content.allowDragging),
			showRoads:		(!('showRoads' in data.content) || data.content.showRoads),
			showLandmarks:	(!('showLandmarks' in data.content) || data.content.showLandmarks),
			showLabels:		(!('showLabels' in data.content) || data.content.showLabels)
		};
		
		this.cover.on("click mousemove", function(e) {
			if (!thisClass.disabledOverlay) return;
			var px = e.pageX, py = e.pageY, isHover = false;
			var alist = thisClass.disabledOverlay.find('a');
			alist.each(function() {
				var a = $(this);
				var ao = a.offset();
				var as = {width: a.width(), height: a.height()};
				if (px >= ao.left && px <= (ao.left + as.width) && py >= ao.top && py <= (ao.top + as.height)) {
					if (e.type === "click") {
						a.eq(0).trigger("click");
					}
					isHover = true;
					return false;
				}
			});
			if (e.type === "mousemove") {
				thisClass.cover.css("cursor", (isHover ? "pointer" : "default"));
			}
		});

		this.updateStyle(true);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
		
		this.elem.bind("resizestop", function() { thisClass.updateStyle(false, null, true); });
	};
	
	GoogleMaps.prototype.supportsFullWidth = function() {
		return true;
	};

	GoogleMaps.prototype.onFullWidthChanged = function() {
		Element.prototype.onFullWidthChanged.call(this);
		this.updateStyle(false, null, true);
	};

	/** @return {Object} */
	GoogleMaps.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (('address' in this.params) && this.params.address) ? this.params.address : '';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	GoogleMaps.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			address:		this.params.address,
			ll:				this.params.ll,
			zoom:			this.params.zoom,
			mapTypeId:		this.params.mapTypeId,
			key:			this.params.key,
			theme:			this.params.theme,
			color:			this.params.color,
			showSatellite:	this.params.showSatellite,
			showZoom:		this.params.showZoom,
			showStreetView:	this.params.showStreetView,
			showFullscreen:	this.params.showFullscreen,
			allowDragging:	this.params.allowDragging,
			showRoads:		this.params.showRoads,
			showLandmarks:	this.params.showLandmarks,
			showLabels:		this.params.showLabels
		};

		return data;
	};
	
	GoogleMaps.prototype.updateNoKeyMsg = function() {
		if (!this.params.key && !wb_builder.mapsConfig.googleMapsClientApiKey) {
			var thisClass = this;
			if (!this.disabledOverlay) {
				var text = __('Get %sAPI key from Google%s and insert it to %splugin properties%s to enable maps on your website.');
				var parts = text.split('%s');
				var text_start = parts[0],
					text_link_1 = ((parts.length > 0) && parts[1]) ? parts[1] : null,
					text_middle = ((parts.length > 1) && parts[2]) ? parts[2] : null,
					text_link_2 = ((parts.length > 2) && parts[3]) ? parts[3] : null,
					text_end = ((parts.length > 3) && parts[4]) ? parts[4] : null;
				if (!text_start || !text_link_1 || !text_middle || !text_link_2 || !text_end) {
					text_start = 'Get ';
					text_link_1 = 'API key from Google';
					text_middle = ' and insert it to ';
					text_link_2 = 'plugin properties';
					text_end = ' to enable maps on your website.';
				}
				var link_1 = $('<a>').text(text_link_1).attr('href', 'javascript:void(0)').on('click', function() {
					window.open('https://developers.google.com/maps/documentation/javascript/get-api-key', '_blank');
					return false;
				});
				var link_2 = $('<a>').text(text_link_2).attr('href', 'javascript:void(0)').on('click', function() {
					thisClass.comProperties();
					return false;
				});
				this.disabledOverlay = $('<div class="wb_google_maps_overlay">')
						.append(text_start)
						.append(link_1)
						.append(text_middle)
						.append(link_2)
						.append(text_end);
			}
			setTimeout(function() {
				thisClass.disabledOverlay.appendTo(thisClass.mapDiv);
				thisClass.disabledOverlay.show();
			}, 250);
		} else {
			if (this.disabledOverlay) {
				this.disabledOverlay.hide();
			}
		}
	};

	/**
	 * Update element style after property changes
	 */
	GoogleMaps.prototype.updateStyle = function(initial, langCode, onResize) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var prms = this.params;
		if (typeof(prms) !== "object") prms = {};

		prms.address = prms.address ? prms.address : "";
		prms.ll = prms.ll ? prms.ll : "";
		prms.zoom = prms.zoom ? prms.zoom*1 : 0;
		prms.mapTypeId = prms.mapTypeId ? prms.mapTypeId : null;

		prms.width = prms.width ? prms.width : Math.round(this.getWidth());
		prms.height = prms.height ? prms.height : Math.round(this.getHeight());

		this.params = prms;
		var thisClass = this;
		var google = window.google;
		
		if (prms.ll && google) {
			if (onResize) {
				this.map = null;
				this.mapDiv.detach();
				this.mapDiv = null;
			}
			if (!this.map) {
				if (!this.mapDiv) {
					this.mapDiv = $('<div>').css({width: '100%', height: '100%'}).appendTo(this.container);
				}

				if (!prms.mapTypeId) prms.mapTypeId = google.maps.MapTypeId.ROADMAP;

				setTimeout(function() {
					var zeroll = new google.maps.LatLng(0, 0);
					thisClass.map = new google.maps.Map(thisClass.mapDiv.get(0), {
						zoom: 0,
						center: zeroll,
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						mapTypeControl: prms.showSatellite,
						zoomControl: prms.showZoom,
						streetViewControl: prms.showStreetView,
						fullscreenControl: prms.showFullscreen,
						draggable: prms.allowDragging,
						styles: thisClass.getStyles(prms)
					});

					thisClass.mapMarker = new google.maps.Marker({
						position: zeroll,
						clickable: false,
						map: thisClass.map
					});
				}, 50);
				
				this.updateNoKeyMsg();
			}

			var init = function() {
				if( !thisClass.map ) {
					// map property is not ready yet. retry.
					setTimeout(init, 10);
					return;
				}
				var ll = prms.ll.split(",");
				ll[0] *= 1; ll[1] *= 1;
				thisClass.map.setZoom(prms.zoom*1);
				thisClass.map.setCenter(new google.maps.LatLng(ll[0], ll[1]));
				thisClass.mapMarker.setPosition(new google.maps.LatLng(ll[0], ll[1]));
				thisClass.map.setMapTypeId(prms.mapTypeId);
				thisClass.map.setOptions({
					mapTypeControl: prms.showSatellite,
					zoomControl: prms.showZoom,
					streetViewControl: prms.showStreetView,
					fullscreenControl: prms.showFullscreen,
					draggable: prms.allowDragging,
					styles: thisClass.getStyles(prms)
				});
			};
			setTimeout(init, 50);

			this.mapDiv.css("display", "block");
			this.displayEmtyMessage(false);
		} else {
			if (this.mapDiv) this.mapDiv.css("display", "none");
			this.displayEmtyMessage(true);
		}

		this.elem.trigger("resize");
	};
	
	GoogleMaps.getThemeStyle = function(theme, color) {
		if (theme === 'light') {
			return GoogleMaps.getThemeLightStyle(color);
		} else if (theme === 'dark') {
			return GoogleMaps.getThemeDarkStyle(color);
		} else if (theme === 'monochrome') {
			return GoogleMaps.getThemeMonochromeStyle(color);
		}
		return GoogleMaps.getThemeDefaultStyle();
	};
	
	GoogleMaps.prototype.getStyles = function(params, fields) {
		var showRoads = true,
			showLandmarks = true,
			showLabels = true,
			theme = 'default',
			color = null;
		if (params && typeof(params) === 'object') {
			showRoads = params.showRoads;
			showLandmarks = params.showLandmarks;
			showLabels = params.showLabels;
			theme = params.theme;
			color = params.color;
		} else if (fields && typeof(fields) === 'object') {
			showRoads = fields.gmapShowRoads.getValue();
			showLandmarks = fields.gmapShowLandmarks.getValue();
			showLabels = fields.gmapShowLabels.getValue();
			theme = fields.gmapTheme.getValue();
			color = fields.gmapColor.getValue();
		}
		var styles = GoogleMaps.getThemeStyle(theme, color);
		var extraStyles = [
			{
				featureType: 'road',
				stylers: [
					{visibility: (showRoads ? 'on' : 'off')}
				]
			},
			{
				featureType: 'poi',
				stylers: [
					{visibility: (showLandmarks ? 'on' : 'off')}
				]
			},
			{
				elementType: 'labels',
				stylers: [
					{visibility: (showLabels ? 'on' : 'off')}
				]
			}
		];
		return styles.concat(extraStyles);
	};

	/**
	 * Extend element properties dialog
	 */
	GoogleMaps.prototype.comProperties = function() {
		var google = window.google;
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 386},
			tabs: [
				{children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('API Key'), helpText: __('Get API Key from %s').replace('%s', '<br /><a style="display: inline-block; max-width: 100%; word-break: break-all;" href="https://developers.google.com/maps/documentation/javascript/get-api-key" target="_blank">https://developers.google.com/maps/documentation/javascript<br/>/get-api-key</a>')},
						{type: 'TextField', id: 'gmapKey', placeholder: __('Example') + ': AGySLaWeMhg9uBek_wDG-xCA3p33eTZ-vazFRnh', change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-gmapKey-change', thisClass);
						}}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Address'), helpText: __('The same as in Google Maps')},
							{type: 'TextField', id: 'gmapAddress', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-gmapAddress-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Zoom level'), helpText: __('ex. 4')},
							{type: 'SizeSelector', id: 'gmapZoomLevel', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-gmapZoomLevel-change', thisClass);
							}}
						]}
					]},
					{type: 'Label', text: __('Drag marker to set your location'), css: {marginTop: 15}},
					{type: 'CustomContainer', id: 'gmap', init: function() {
						var gmap, gmapMarker, gmapInit = false,
							gmapElem = this._elem.get(0),
							mapAddress,
							addressLatLng = null,
							changeAddress = function(loc) {
								if (!(loc instanceof Array && (0 in loc) && (1 in loc))) {
									var places = mapAddress.getPlaces(), l;
									for (var i=0, place; (place = places[i]); i++) {
										if (place && place.geometry && (l = place.geometry.location)) {
											loc = [l.lat(), l.lng()];
										}
									}
									if (!loc) { return; }
								}
								addressLatLng = loc[0] + ',' + loc[1];
								gmap.setCenter(new google.maps.LatLng(loc[0], loc[1]));
								gmapMarker.setPosition(new google.maps.LatLng(loc[0], loc[1]));
							};
						this.getLatLng = function() { return addressLatLng; };
						this.setLatLng = function(latLng) {
							if (!latLng) return;
							addressLatLng = latLng;
							var ll = addressLatLng.split(","); ll[0] *= 1; ll[1] *= 1;
							gmap.setCenter(new google.maps.LatLng(ll[0], ll[1]));
							gmapMarker.setPosition(new google.maps.LatLng(ll[0], ll[1]));
						};
						this.getMapTypeId = function() { return gmap.getMapTypeId(); };
						this.setMapTypeId = function(mapTypeId) {
							if (!mapTypeId) return;
							gmap.setMapTypeId(mapTypeId);
						};
						this.setZoom = function(zoom) { gmap.setZoom(zoom * 1); };
						this.initOnView = function() {
							if (gmapInit) return;
							gmapInit = true;
							// Google Maps requires hardcoded width to work
							this.css({width: this._elem.width()});
							var zeroll = new google.maps.LatLng(0, 0);
							gmap = new google.maps.Map(gmapElem, {
								zoom: 0,
								center: zeroll,
								mapTypeId: google.maps.MapTypeId.ROADMAP,
								streetViewControl: false
							});
							gmapMarker = new google.maps.Marker({
								position: zeroll,
								draggable: true,
								clickable: false,
								optimized: false,
								map: gmap
							});
							google.maps.event.addListener(gmapMarker, 'dragend', function() {
								var pos = this.getPosition();
								fields.gmapAddress.setText(pos.lat() + ', ' + pos.lng());
								changeAddress([pos.lat(), pos.lng()]);
							});
							google.maps.event.addListener(gmap, 'zoom_changed', function() {
								fields.gmapZoomLevel.setValue(this.getZoom());
							});
							fields.gmapZoomLevel.on('change', function() {
								gmap.setZoom(fields.gmapZoomLevel.getValue()*1);
							});
							fields.gmapAddress.on('change', function() {
								var _this = this;
								setTimeout(function() {
									_this.focus();
									google.maps.event.trigger(_this, 'keydown', {keyCode: 13});
									_this.blur();
								}, 50);
							});
							fields.gmapShowSatellite.on('change', function() {
								gmap.setOptions({mapTypeControl: fields.gmapShowSatellite.getValue()});
							});
							fields.gmapShowZoom.on('change', function() {
								gmap.setOptions({zoomControl: fields.gmapShowZoom.getValue()});
							});
							fields.gmapShowStreetView.on('change', function() {
								gmap.setOptions({streetViewControl: fields.gmapShowStreetView.getValue()});
							});
							fields.gmapShowFullscreen.on('change', function() {
								gmap.setOptions({fullscreenControl: fields.gmapShowFullscreen.getValue()});
							});
							fields.gmapAllowDragging.on('change', function() {
								gmap.setOptions({draggable: fields.gmapAllowDragging.getValue()});
							});
							fields.gmapShowRoads.on('change', function() {
								gmap.setOptions({styles: thisClass.getStyles(null, fields)});
							});
							fields.gmapShowLandmarks.on('change', function() {
								gmap.setOptions({styles: thisClass.getStyles(null, fields)});
							});
							fields.gmapShowLabels.on('change', function() {
								gmap.setOptions({styles: thisClass.getStyles(null, fields)});
							});
							fields.gmapTheme.on('change', function() {
								gmap.setOptions({styles: thisClass.getStyles(null, fields)});
							});
							fields.gmapColor.on('change', function() {
								gmap.setOptions({styles: thisClass.getStyles(null, fields)});
							});
							mapAddress = new google.maps.places.SearchBox(fields.gmapAddress.getElem().get(0));
							google.maps.event.addListener(mapAddress, 'places_changed', function() {
								changeAddress();
							});
						};
					}, styleClass: 'wb_gmap', css: {height: 234, border: '1px solid #aaaaaa'}},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Theme')},
							{type: 'DropdownBox', id: 'gmapTheme', options: [
								{id: 'default', name: __('Default')},
								{id: 'light', name: __('Light')},
								{id: 'dark', name: __('Dark')},
								{id: 'monochrome', name: __('Monochrome')}
							], change: function(fields) {
								fields.colorBlock.setVisible((this.getValue() !== 'default'));
							}}
						]},
						{type: 'VerticalLayout', id: 'colorBlock', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'gmapColor', noTransparent: true}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'CheckBox', id: 'gmapShowSatellite', label: __('Show map and satellite control')},
							{type: 'CheckBox', id: 'gmapShowZoom', label: __('Show zoom control')},
							{type: 'CheckBox', id: 'gmapShowStreetView', label: __('Show Street View control')},
							{type: 'CheckBox', id: 'gmapShowFullscreen', label: __('Show full screen control')},
							{type: 'CheckBox', id: 'gmapAllowDragging', label: __('Allow dragging')}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'CheckBox', id: 'gmapShowRoads', label: __('Show roads')},
							{type: 'CheckBox', id: 'gmapShowLandmarks', label: __('Show landmarks')},
							{type: 'CheckBox', id: 'gmapShowLabels', label: __('Show labels')}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.address = fields.gmapAddress.getText();
				thisClass.params.zoom = fields.gmapZoomLevel.getValue();
				thisClass.params.mapTypeId = fields.gmap.getMapTypeId();
				thisClass.params.ll = fields.gmap.getLatLng();
				thisClass.params.key = fields.gmapKey.getValue();
				thisClass.params.theme = fields.gmapTheme.getValue();
				thisClass.params.color = fields.gmapColor.getValue();
				thisClass.params.showSatellite = fields.gmapShowSatellite.getValue();
				thisClass.params.showZoom = fields.gmapShowZoom.getValue();
				thisClass.params.showStreetView = fields.gmapShowStreetView.getValue();
				thisClass.params.showFullscreen = fields.gmapShowFullscreen.getValue();
				thisClass.params.allowDragging = fields.gmapAllowDragging.getValue();
				thisClass.params.showRoads = fields.gmapShowRoads.getValue();
				thisClass.params.showLandmarks = fields.gmapShowLandmarks.getValue();
				thisClass.params.showLabels = fields.gmapShowLabels.getValue();
				thisClass.updateStyle();
				thisClass.updateNoKeyMsg();
			},
			open: function(fields) {
				// Google Maps can only be initialized on visible elements
				fields.gmap.initOnView();
				fields.gmap.setZoom(fields.gmapZoomLevel.getValue());
				fields.gmap.setLatLng(thisClass.params.ll);
				fields.gmap.setMapTypeId(thisClass.params.mapTypeId);
				fields.gmapTheme.trigger('change');
				fields.gmapColor.trigger('change');
				fields.gmapShowSatellite.trigger('change');
				fields.gmapShowZoom.trigger('change');
				fields.gmapShowStreetView.trigger('change');
				fields.gmapShowFullscreen.trigger('change');
				fields.gmapAllowDragging.trigger('change');
				fields.gmapShowRoads.trigger('change');
				fields.gmapShowLandmarks.trigger('change');
				fields.gmapShowLabels.trigger('change');
			}
		});
		
		fields.gmapAddress.setText(this.params.address);
		fields.gmapZoomLevel.setValue(this.params.zoom);
		fields.gmapKey.setValue(this.params.key);
		fields.gmapTheme.setValue(this.params.theme);
		fields.gmapColor.setValue(this.params.color);
		fields.gmapShowSatellite.setValue(this.params.showSatellite);
		fields.gmapShowZoom.setValue(this.params.showZoom);
		fields.gmapShowStreetView.setValue(this.params.showStreetView);
		fields.gmapShowFullscreen.setValue(this.params.showFullscreen);
		fields.gmapAllowDragging.setValue(this.params.allowDragging);
		fields.gmapShowRoads.setValue(this.params.showRoads);
		fields.gmapShowLandmarks.setValue(this.params.showLandmarks);
		fields.gmapShowLabels.setValue(this.params.showLabels);
		fields.gmapTheme.trigger('change');
	};
	
	return GoogleMaps;
});
;

/** WB GoogleAdSense **/
(window.defineModule = (window.defineModule || {})).name = 'WB GoogleAdSense';

define('GoogleAdSense', ['ElementRegister', 'Element', 'Dialog'], function(ElementRegister, Element, Dialog) {
	'use strict';
	
	/**
	 * GoogleAdSense class
	 * @param {Object} data
	 */
	var GoogleAdSense = function(data) { if (data) this.__construct(data); };

	GoogleAdSense.prototype = new Element();
	GoogleAdSense.prototype.constructor = GoogleAdSense;
	ElementRegister.registerClass("GoogleAdSense", GoogleAdSense);

	GoogleAdSense.prototype.noPhotoBg = 'ico-tb-google-adsense';
	GoogleAdSense.prototype.ifrm = false;
	GoogleAdSense.prototype.params = false;
	GoogleAdSense.prototype.bg = false;
	GoogleAdSense.prototype.htmlDeactivate = true;

	/**
	 * Construct GoogleAdSense element
	 * @param {Object} data element data object
	 */
	GoogleAdSense.prototype.__construct = function(data) {
		if (!data.width) {
			data.width = 200;
			data.height = 200;
		}
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		// this.htmlDeactivate = (typeof data.content.htmlDeactivate === 'undefined' || data.content.htmlDeactivate) ? true : false;
		// Always deactivate, because to many broken scripts from users break builder
		// and because of that we need to manually disable them.
		this.htmlDeactivate = true;

		this.setMinSize(null, 24);

		this.container.css({overflow: "hidden"});

		var ln = $.inArray(CKEDITOR.config.language, ['en', 'lt', 'ru', 'es']) ? CKEDITOR.config.language : 'en';
		this.customHtml = data.content.html ? data.content.html : 
			'';//<a href="http://' + ln + '.ambuba.com/" style="background:#fff;display:block;"><img src="http://' + ln + '.ambuba.com/images/ambuba_' + ln + '.png" alt="" /></a>';

		this.updateStyle(true);

		var thisClass = this;
		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};
	
	/** @return {String} */
	GoogleAdSense.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = '';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	GoogleAdSense.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			html: this.customHtml ? this.customHtml : "",
			htmlDeactivate: this.htmlDeactivate
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	GoogleAdSense.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		if (this.htmlDeactivate) {
			this.displayEmtyMessage(true);
			this.container.html("");
		} else {
			this.displayEmtyMessage(this.customHtml ? false : true);

			try {
				this.container.html(this.customHtml ? this.customHtml : "");
			} catch (ex) {}
		}
	};

	GoogleAdSense.prototype.changeProperties = function() {
		var thisClass = this;
		if (!this.dialog) {
			this.dialog = new Dialog("Change properties");
			this.dialog.setSize(420, false);

			this.dialog.fields.html = this.dialog.addElement('<table>' +
					'<tr><td style="width: 130px;">' + __('HTML code') + ' ' +
						'<a class="wb_tip"><span><span></span>Generate your ad in your Google AdSense account<br/>and copy & paste it\'s HTML code here.</span>(?)</a>' +
						': </td></tr>' +
					'<tr><td><textarea style="width: 380px" cols="40" rows="10" name="html"></textarea></td></tr>' +
				'</table>');

			this.dialog.addButton("Ok", function() {
				var f = thisClass.dialog.fields, p = thisClass.params;
				thisClass.system.setPageModified(true);
				p.html = $("[name=html]", f.html).val();

				thisClass.params = p;
				thisClass.updateStyle();
				thisClass.dialog.hide();
			});
			this.dialog.addButton("Cancel", function() { thisClass.dialog.hide(); });
		}
		var f = this.dialog.fields, p = this.params;

		$("[name=html]", f.html).val(p.html);

		this.dialog.setVisible(true);
	};

	/**
	 * Extend element properties dialog
	 */
	GoogleAdSense.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 330},
			tabs: [
				{children: [
					{type: 'VerticalLayout', fluid: true, children: [
						{type: 'CheckBox', label: __('Deacitvate content while in builder (recomended)'),
							id: 'htmlDeactivate',
							helpText: __("Some scripts may interfere with a Zyro Builder, so it's recomended to deactivate them. Failing to do so may result in inaccessable page in builder.")
						},
						{type: 'Label', text: __('HTML code'),
							helpText: __("Generate your ad in your Google AdSense account and copy & paste it's HTML code here."),
							css: {marginTop: '20px'}
						},
						{type: 'TextField', id: 'customHtml', textArea: true, fixedWidth: 12, css: {height: 214, marginBottom: 0},
							placeholder: '<script async src="..."></script>\n<ins class="adsbygoogle" ...></ins>\n<script> ... </script>'
						}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.customHtml = fields.customHtml.getValue();
				thisClass.htmlDeactivate = fields.htmlDeactivate.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.customHtml.setValue(this.customHtml ? this.customHtml : '');
		fields.htmlDeactivate.setValue(this.htmlDeactivate);
	};
	
	return GoogleAdSense;
});
;

/** WB Flash **/
(window.defineModule = (window.defineModule || {})).name = 'WB Flash';

define('Flash', ['ElementRegister', 'Element'], function(ElementRegister, Element) {
	'use strict';

	/**
	 * Flash class
	 * @param {Object} data
	 */
	var Flash = function(data) { if (data) this.__construct(data); };

	Flash.prototype = new Element();
	Flash.prototype.constructor = Flash;
	ElementRegister.registerClass("Flash", Flash);

	Flash.prototype.noPhotoBg = 'ico-tb-flash';
	Flash.prototype.flash = false;
	Flash.prototype.params = false;
	Flash.prototype.isNew = false;

	/**
	 * Construct Flash element
	 * @param {Object} data element data object
	 */
	Flash.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.setMinSize(48, 24);

		this.displayEmtyMessage(true);

		this.isNew = data.id ? false : true;

		var thisClass = this;

		this.params = {
			image: data.content.image ? {
					file: data.content.image,
					width: (data.content.owidth ? data.content.owidth : 0),
					height: (data.content.oheight ? data.content.oheight : 0),
					size: 0
				}: { file: "", width: 0, height: 0, size: 0 },
			wmode: data.content.wmode ? data.content.wmode : "opaque"
		};

		this.elem.bind("resize", function() {
			var w = thisClass.getWidth();
			var h = thisClass.getHeight();

			if (thisClass.flash && thisClass.params.image && thisClass.params.image.file) {
				if( thisClass.isFullWidth )
					thisClass.flash.css({"width": "100%", "height": h + "px"});
				else
					thisClass.flash.css({"width": w + "px", "height": h + "px"});
			}
		});

		this.updateStyle(true);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	Flash.prototype.supportsFullWidth = function() {
		return true;
	};

	/** @return {String} */
	Flash.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (this.params.image.file ? this.params.image.file : '');
		return opts;
	};

	/**
	 * Serialize this element
	 * @return {Object}
	 */
	Flash.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			image: this.params.image.file,
			wmode: this.params.wmode,
			owidth: this.params.image.width,
			oheight: this.params.image.height
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	Flash.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var params = this.params;
		if (typeof(params) !== "object") params = {};

		this.displayEmtyMessage((params.image && params.image.file) ? false : true);

		params.image = params.image ? params.image : { file: "", width: 0, height: 0, size: 0 };
		params.wmode = params.wmode ? params.wmode : "opaque";

		this.params = params;

		if (this.flash) {
			this.flash.remove();
			this.flash.empty();
			this.flash = null;
		}

		if (params.image && params.image.file) {
			this.flash = $('<object></object>');
			this.flash.attr("data", this.makeLocalUrl(params.image.file));
			this.flash.attr("type", "application/x-shockwave-flash");
			this.flash.css({width: "100%", height: "100%"});
			var p = $('<param name="movie" />');
			p.val(this.makeLocalUrl(params.image.file));
			this.flash.append(p);
			this.flash.append('<param name="menu" value="false" />');
			p = $('<param name="wmode" />');
			p.val(params.wmode);
			this.flash.append(p);
			this.flash.append('<param name="flashvars" value="" />');
		}

		if (this.flash) {
			this.container.append(this.flash);
		}

		this.elem.trigger("resize");
	};

	Flash.prototype.onResize = function(onConstruct) {
		Element.prototype.onResize.call(this, onConstruct);
		this.elem.trigger("resize");
	};

	Flash.prototype.resetFlashSize = function() {
		/*var width = 0, height = 0;
		try {
			width	= this.flash.get(0).TGetPropertyAsNumber("/", 8);
			height	= this.flash.get(0).TGetPropertyAsNumber("/", 9);
		} catch(ex) {}
		if (width > 0 && height > 0) {
			this.setSize(width, height);
			this.onResize();
		} else*/
		if (this.params.image.width > 0 && this.params.image.height > 0) {
			this.setSize(this.params.image.width, this.params.image.height);
			this.onResize();
		}
	};

	/**
	 * Extend element properties dialog
	 */
	Flash.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 330},
			tabs: [
				{children: [
					{type: 'VerticalLayout', fluid: true, children: [
						{type: 'Label', text: __('Flash file')},
						{type: 'ImageSelector', id: 'flashImage', mode: 'flash'},
						{type: 'CheckBox', label: __('Transparent'), id: 'flashWmode', css: {marginTop: 15}}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.image = fields.flashImage.getValues(true);
				thisClass.params.image = (thisClass.params.image && thisClass.params.image.length > 0)
					? thisClass.params.image[0]
					: { file: '', width: 0, height: 0, size: 0 };
				thisClass.params.wmode = fields.flashWmode.getValue() ? 'transparent' : 'opaque';
				thisClass.updateStyle();
				if (thisClass.isNew) {
					thisClass.isNew = false;
					thisClass.resetFlashSize();
				}
			}
		});
		
		fields.flashImage.setValue(this.params.image);
		fields.flashWmode.setValue((this.params.wmode === 'transparent'));
	};

	Flash.prototype.initContextMenu = function(elem) {
		var thisClass = this;
		Element.prototype.initContextMenu.call(this, elem);
		if (!this.menu) return;
		var idx = this.contextMenuFirstIndex;

		if (this.isResizable) {
			this.menu.insertItemAt(idx++, 'resetSize', __("Reset to original size"), function() {
				thisClass.system.setPageModified(true);
				thisClass.resetFlashSize();
			}, null, null, null, "icon-fullscreen");
		}

		this.menu.addSeparator(idx++);
	};
	
	return Flash;
});
;

/** WB SkypeImOnline **/
(window.defineModule = (window.defineModule || {})).name = 'WB SkypeImOnline';

define('SkypeImOnline', ['ElementRegister', 'Element'], function(ElementRegister, Element) {
	'use strict';
	
	/**
	 * SkypeImOnline class
	 * @param {Object} data
	 */
	var SkypeImOnline = function(data) { if (data) this.__construct(data); };

	SkypeImOnline.prototype = new Element();
	SkypeImOnline.prototype.constructor = SkypeImOnline;
	ElementRegister.registerClass("SkypeImOnline", SkypeImOnline);

	SkypeImOnline.prototype.action = false;
	SkypeImOnline.prototype.members = false;
	SkypeImOnline.prototype._button = false;
	SkypeImOnline.prototype._bubblePlaceholder = null;
	SkypeImOnline.prototype.size = false;
	SkypeImOnline.prototype.id = false;
	
	SkypeImOnline.lastId = 0;

	/**
	 * Construct Skype I'm Online element
	 * @param {Object} data element data object
	 */
	SkypeImOnline.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);
		this.elem.addClass('wb_skype_element');
		
		this.setMinSize(60, 34);
		
		SkypeImOnline.lastId++;
		this.id = SkypeImOnline.lastId;

		this.container.append('<script type="text/javascript" src="https://download.skype.com/share/skypebuttons/js/skypeCheck.js"></script>');
		
		this._button = $('<span class="skype-button">');
		this.container.append(this._button);
		
		this._bubblePlaceholder = $('<div class="wb_caption smaller">' + 
				'<div><i class="ico-tb-skype-imonline"></i> <strong>Skype</strong><br />' +
					__('Bubble element will appear at the page bottom right side') + 
				'</div>' +
			'</div>').hide();
		this.container.append(this._bubblePlaceholder);
		
		var thisClass = this;
		this.params = {
			style:	data.content.style ? data.content.style : 'rounded',
			label:	data.content.label ? data.content.label : __('Contact us'),
			showIcon: (!('showIcon' in data.content) || data.content.showIcon),
			btnColor: data.content.btnColor ? data.content.btnColor : '#00AFF0',
			msgColor: data.content.msgColor ? data.content.msgColor : '#80DDFF',
			name:	data.content.name ? data.content.name : "echo123"
		};
		
		if (!SkypeImOnline.scriptAdded) {
			$.getScript('https://swc.cdn.skype.com/sdk/v1/sdk.min.js');
			SkypeImOnline.scriptAdded = true;
		}
		
		setTimeout(function() {
			thisClass.updateStyle(true);
		}, 1000);
		
		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};
	
	SkypeImOnline.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = '';
	};
	
	/** @return {String} */
	SkypeImOnline.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (this.params.name ? this.params.name : '');
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	SkypeImOnline.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			style:	this.params.style,
			label:	this.params.label,
			showIcon: this.params.showIcon,
			btnColor: this.params.btnColor,
			msgColor: this.params.msgColor,
			name:	this.params.name
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	SkypeImOnline.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		if (!('SkypeWebControl' in window) || !window.SkypeWebControl) return;
		
		var params = this.params, thisClass = this;
		if (typeof(params) !== "object") params = {};
		params.style = params.style ? params.style : 'rounded';
		params.label = params.label ? params.label : __('Contact us');
		params.showIcon = (!('showIcon' in params) || params.showIcon);
		params.btnColor = params.btnColor ? params.btnColor : '#00AFF0';
		params.msgColor = params.msgColor ? params.msgColor : '#80DDFF';
		params.name = params.name ? params.name : "echo123";
		this.params = params;
		
		this._button.empty();
		if (params.style === 'bubble') {
			this._button.hide();
			this._bubblePlaceholder.show();
			this.setSize(190, 70);
		} else {
			this._bubblePlaceholder.hide();
			this._button.show();
			this._button.attr('class', 'skype-button');
			this._button.addClass(params.style);
			this._button.attr('data-text', params.label);
			if (params.showIcon) {
				this._button.removeClass('textonly');
			} else {
				this._button.addClass('textonly');
			}
			this._button.attr('data-color', params.btnColor);
			this._button.attr('data-color-message', params.msgColor);
			this._button.attr('data-contact-id', params.name);

			SkypeWebControl.SDK.Buttons.refresh();

			setTimeout(function() {
				var btn = thisClass._button.children('.lwc-chat-button');
				thisClass.setSize(btn.outerWidth(), btn.outerHeight());
			}, 10);
		}
	};

	/**
	 * Extend element properties dialog
	 */
	SkypeImOnline.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 330},
			tabs: [
				{children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Skype Name')},
						{type: 'TextField', id: 'skypeName', change: function() {
							fields.skypePreview.setParam('name', this.getValue());
						}}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Style')},
						{type: 'DropdownBox', id: 'skypeStyle', options: [
							{id: 'bubble', name: __('Bubble')},
							{id: 'rounded', name: __('Rounded')},
							{id: 'rectangle', name: __('Rectangle')}
						], change: function(fields) {
							fields.styleOpts.setVisible((this.getValue() !== 'bubble'));
							fields.skypePreview.setParam('style', this.getValue());
						}}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, id: 'styleOpts', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Show Icon')},
							{type: 'RadioBox', label: __('Yes'),
								id: 'skypeShowIconYes',
								group: 'skypeShowIcon',
								change: function() {
									fields.skypePreview.setParam('showIcon', true);
								}
							},
							{type: 'RadioBox', label: __('No'),
								id: 'skypeShowIconNo',
								group: 'skypeShowIcon',
								change: function() {
									fields.skypePreview.setParam('showIcon', false);
								}
							}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label')},
							{type: 'TextField', id: 'skypeButtonLabel', change: function() {
								fields.skypePreview.setParam('label', this.getValue());
							}}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Color')},
							{type: 'ColorSelector', id: 'skypeButtonColor', change: function() {
								fields.skypePreview.setParam('btnColor', this.getValue());
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Message Color')},
							{type: 'ColorSelector', id: 'skypeMessageColor', change: function() {
								fields.skypePreview.setParam('msgColor', this.getValue());
							}}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Preview')},
						{type: 'CustomContainer', id: 'skypePreview', init: function() {
							var loader = $('<i>').addClass('icon-loading').css({position: 'absolute'}).appendTo(this._elem);
							var button = $('<span class="skype-button">');
							var cont = $('<div>').addClass('wb-skype-preview');
							cont.append($('<div>').addClass('wb-skype-preview-backdrop'));
							cont.append(button);
							this._elem.append(cont);
							var params = {
								style: thisClass.params.style,
								label: thisClass.params.label,
								showIcon: thisClass.params.showIcon,
								btnColor: thisClass.params.btnColor,
								msgColor: thisClass.params.msgColor,
								name: thisClass.params.name
							};
							var autoUpdate = false;
							var update = function() {
								cont.fadeOut(200, function() {
									button.empty();
									loader.fadeIn(100);
									loader.fadeOut(100);
									cont.fadeIn(300);
									
									button.attr('class', 'skype-button');
									button.addClass(params.style);
									button.attr('data-text', params.label);
									if (params.showIcon) {
										button.removeClass('textonly');
									} else {
										button.addClass('textonly');
									}
									button.attr('data-color', params.btnColor);
									button.attr('data-color-message', params.msgColor);
									button.attr('data-contact-id', params.name);
									
									SkypeWebControl.SDK.Buttons.refresh();
								});
							};
							this.setAutoUpdate = function(upd) {
								autoUpdate = upd ? true : false;
								if (autoUpdate) update();
							};
							this.setParam = function(name, value) {
								params[name] = value;
								if (autoUpdate) update();
							};
							this.getParam = function(name) {
								return params[name];
							};
						}}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.style = fields.skypeStyle.getValue();
				thisClass.params.label = fields.skypeButtonLabel.getValue();
				thisClass.params.showIcon = fields.skypeShowIconYes.getValue();
				thisClass.params.btnColor = fields.skypeButtonColor.getValue();
				thisClass.params.msgColor = fields.skypeMessageColor.getValue();
				thisClass.params.name = fields.skypeName.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.skypePreview.setAutoUpdate(false);
		fields.skypeName.setValue(this.params.name);
		
		fields.skypeStyle.setValue(this.params.style);
		fields.skypeStyle.trigger('change');
		fields.skypeButtonLabel.setValue(this.params.label);
		if (this.params.showIcon) {
			fields.skypeShowIconYes.setValue(true);
			fields.skypeShowIconYes.trigger('change');
		} else {
			fields.skypeShowIconNo.setValue(true);
			fields.skypeShowIconNo.trigger('change');
		}
		fields.skypeButtonColor.setValue(this.params.btnColor);
		fields.skypeButtonColor.trigger('change');
		fields.skypeMessageColor.setValue(this.params.msgColor);
		fields.skypeMessageColor.trigger('change');
		
		fields.skypePreview.setAutoUpdate(true);
	};
	
	return SkypeImOnline;
});
;

/** WB Chat **/
(window.defineModule = (window.defineModule || {})).name = 'WB Chat';

define('Chat', ['ElementRegister', 'Element', 'ToolTipControl', 'SizeSelector', 'TextField'], function(ElementRegister, Element, ToolTipControl, SizeSelector, TextField) {
	'use strict';
	
	/**
	 * Chat class
	 * @param {Object} data
	 */
	var Chat = function(data) { if (data) this.__construct(data); };

	Chat.prototype = new Element();
	Chat.prototype.constructor = Chat;
	ElementRegister.registerClass("Chat", Chat);

	Chat.prototype.noPhotoBg = 'ico-tb-chat';
	Chat.prototype.videoId = null;
	Chat.prototype.videoUrl = null;
	Chat.prototype.params = null;
	Chat.prototype.opts_def = null;
	Chat.prototype.chId = null;
	Chat.prototype.player = null;

	/**
	 * Construct Chat element
	 * @param {Object} data element data object
	 */
	Chat.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		this.chId = (new Date()).getTime();
		this.videoId = data.content.videoId ? data.content.videoId : "examplegroup";
		this.videoUrl = data.content.videoUrl ? data.content.videoUrl : null;
		var params = (data.content.params && typeof(data.content.params) === "object") ?
			data.content.params : {};
		this.params = {
			roundCorners:	WB_Builder.isset(params.roundCorners) ? (params.roundCorners ? true : false) : true,
			showTitle:	WB_Builder.isset(params.showTitle) ? (params.showTitle ? true : false) : true,
			showOMsg:	WB_Builder.isset(params.showOMsg) ? (params.showOMsg ? true : false) : true,
			canCFBD:	WB_Builder.isset(params.canCFBD) ? (params.canCFBD ? true : false) : true,
			fontSize:	params.fontSize ? params.fontSize : 11
		};

		var thisClass = this;

		this.updateStyle(true);

		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/**
	 * Serialize this element
	 * @return {Object}
	 */
	Chat.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			videoId:	this.videoId,
			videoUrl:	this.videoUrl,
			chId:		this.chId,
			params:		{
				roundCorners: this.params.roundCorners,
				showTitle:	this.params.showTitle,
				showOMsg:	this.params.showOMsg,
				canCFBD:	this.params.canCFBD,
				fontSize:	this.params.fontSize
			}
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	Chat.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		this.videoUrl = this.videoId ? ("http://" + this.videoId + ".chatango.com/group") : "";

		this.displayEmtyMessage(this.videoId ? false : true);

		if (!this.player) {
			this.player = $('<object></object>');
			this.player.attr("id", "obj_" + this.chId);
			this.player.attr("data", "");
			this.player.attr("type", "application/x-shockwave-flash");
			this.player.css({width: "100%", height: "100%"});
			this.player.append('<param name="movie" value="" />');
			this.player.append('<param name="menu" value="false" />');
			this.player.append('<param name="wmode" value="transparent" />');
			this.player.append('<param name="AllowScriptAccess" value="always" />');
			this.player.append('<param name="AllowNetworking" value="all" />');
			this.player.append('<param name="AllowFullScreen" value="true" />');
			this.player.append('<param name="flashvars" value="" />');
			this.container.append(this.player);
		}

		this.player.css({display: this.videoId ? "block" : "none"});
		var pFlashVars = this.player.children("param[name=flashvars]");
		pFlashVars.val(
				"cid=" + this.chId + "&b=60&f=50&l=999999&q=999999&r=100" +
				"&s=" + (this.params.roundCorners ? "1" : "") +
				"&v=" + (this.params.showTitle ? "" : "0") +
				"&w=" + (this.params.showOMsg ? "" : "0") +
				"&ab=" + (this.params.canCFBD ? "" : "0") +
				"&p=" + (this.params.fontSize ? this.params.fontSize : 11)
			);
		this.player.attr("data", this.videoUrl);
		var pMovie = this.player.children("param[name=movie]");
		pMovie.val(this.videoUrl);

		this.elem.trigger("resize");
	};

	/**
	 * Extend element properties dialog
	 */
	Chat.prototype.comProperties = function() {
		Element.prototype.comProperties.call(this);
		var thisClass = this;
		var fields = this.comDialog.fields;
		if (!fields.chatVideoId) {
			var gTab = this.comDialog.getGeneralTab().contentElem;

			var td = null, tds = null, lbl = null, idx = 0;
			gTab.append(tds = $('<table>' +
				'<tr><td></td><td></td></tr>' +
				'<tr><td colspan="2"></td></tr>' +
				'<tr><td colspan="2"></td></tr>' +
				'<tr><td colspan="2"></td></tr>' +
				'<tr><td colspan="2"></td></tr>' +
			'</table>'));
			$('td', tds).css({ paddingRight: "20px"});
			tds = $('td', tds);
			tds.css({verticalAlign: "top"});

			td = tds.eq(idx++);
			td.append(lbl = $('<label>' + __("Group URL or ID") + '</label>'));
			td.append((fields.chatVideoId = new TextField()).elem);
			fields.chatVideoId.elem.addClass("span2");
			lbl.append((new ToolTipControl("?", __("Register at http://chatango.com and start new group."))).elem);

			td = tds.eq(idx++);
			td.append('<label>' + __("Font size") + '</label>');
			td.append((fields.chatFontSize = new SizeSelector()).elem);

			td = tds.eq(idx++);
			td.append((fields.chatRoundCorners = new WB_CheckBoxControl(__("Round corners"))).elem);

			td = tds.eq(idx++);
			td.append((fields.chatShowTitle = new WB_CheckBoxControl(__("Show title"))).elem);

			td = tds.eq(idx++);
			td.append((fields.chatShowOMsg = new WB_CheckBoxControl(__("Show custom message under title"))).elem);

			//td = tds.eq(idx++);
			//td.append((fields.chatCanCFBD = new WB_CheckBoxControl(__("Can control fonts by default"))).elem);

			var cfb = fields.callbackFunc;
			fields.callbackFunc = function() {
				if (typeof(cfb) === "function") cfb.call(this);

				thisClass.videoId = fields.chatVideoId.getValue();
				thisClass.videoId = thisClass.videoId.replace(/^http[s]*:\/\//i, "");
				thisClass.videoId = thisClass.videoId.split(".")[0];
				thisClass.videoId = thisClass.videoId.replace(/[^a-zA-Z0-9\-\_]/i, "");

				thisClass.params.roundCorners = fields.chatRoundCorners.getValue();
				thisClass.params.showTitle = fields.chatShowTitle.getValue();
				thisClass.params.showOMsg = fields.chatShowOMsg.getValue();
				//thisClass.params.canCFBD = fields.chatCanCFBD.getValue();
				thisClass.params.fontSize = fields.chatFontSize.getValue();
				if (!thisClass.params.fontSize) thisClass.params.fontSize = 11;

				thisClass.updateStyle();
			};
		}
		fields.chatVideoId.setValue(this.videoId);
		fields.chatRoundCorners.setValue(this.params.roundCorners);
		fields.chatShowTitle.setValue(this.params.showTitle);
		fields.chatShowOMsg.setValue(this.params.showOMsg);
		//fields.chatCanCFBD.setValue(this.params.canCFBD);
		fields.chatFontSize.setValue(this.params.fontSize);
	};
	
	return Chat;
});
;

/** WB Banner **/
(window.defineModule = (window.defineModule || {})).name = 'WB Banner';

define('Banner', ['ElementRegister', 'Element', 'ToolTipControl'], function(ElementRegister, Element, ToolTipControl) {
	'use strict';
	
	/**
	 * Banner class
	 * @param {Object} data
	 */
	var Banner = function(data) { if (data) this.__construct(data); };

	Banner.prototype = new Element();
	Banner.prototype.constructor = Banner;
	ElementRegister.registerClass("Banner", Banner);

	Banner.prototype.noPhotoBg = 'ico-tb-banner';
	Banner.prototype.banner = null;
	Banner.prototype.params = null;
	Banner.prototype.scriptDeactivate = true;

	/**
	 * Construct Banner element
	 * @param data element data object
	 */
	Banner.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.setMinSize(null, 24);

		this.displayEmtyMessage(true);

		this.scriptDeactivate = (typeof data.content.scriptDeactivate === 'undefined' || data.content.scriptDeactivate) ? true : false;

		var thisClass = this;
		this.params = {
			url:		data.content.url ? data.content.url : "",
			image:		data.content.image ? data.content.image : "",
			forceflurl:	data.content.forceflurl ? true : false,
			script:		data.content.script ? data.content.script : ""
		};

		this.elem.bind("resize", function() {
			var w = thisClass.getWidth();
			var h = thisClass.getHeight();

			if (thisClass.banner && thisClass.params.image) {
				thisClass.banner.css({"width": w + "px", "height": h + "px"});
				thisClass.banner.children("img").css({"width": w + "px", "height": h + "px"});
			}
		});

		this.updateStyle(true);

		this.controls.bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/** @return {String} */
	Banner.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (this.params.url ? this.params.url : '');
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	Banner.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			url:		this.params.url,
			image:		this.params.image,
			forceflurl:	this.params.forceflurl,
			script:		this.params.script,
			deactivate:	this.scriptDeactivate
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	Banner.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		var params = this.params;
		if (typeof(params) !== "object") params = {};

		this.displayEmtyMessage((params.image || params.script) ? false : true);

		params.url = params.url ? params.url : "";
		params.image = params.image ? params.image : "";
		params.forceflurl = params.forceflurl ? true : false;
		params.script = params.script ? params.script : "";

		this.params = params;
		var thisClass = this;

		if (this.banner) {
			this.banner.remove();
			this.banner.empty();
			this.banner = null;
		}

		if (params.image) {
			if (!params.image.split("?")[0].match(/^.*\.swf$/i)) {
				this.banner = $('<a></a>');
				var img = $('<img alt="" />');
				this.banner.append(img);
				this.banner.attr("href", params.url);
				img.attr("src", this.makeLocalUrl(params.image));
				img.css({border: "none"});

				if (img.get(0).width <= 0) {
					img.bind("load", function() { thisClass.elem.trigger("resize"); });
				}
			} else {
				this.banner = $('<object></object>');
				this.banner.attr("data", this.makeLocalUrl(params.image));
				this.banner.attr("type", "application/x-shockwave-flash");
				this.banner.css({width: "100%", height: "100%"});
				var p = $('<param name="movie" />');
				p.val(this.makeLocalUrl(params.image));
				this.banner.append(p);
				this.banner.append('<param name="menu" value="false" />');
				this.banner.append('<param name="wmode" value="transparent" />');
				p = $('<param name="flashvars" />');
				p.val("clickTAG=" + escape(encodeURI(params.url)));
				this.banner.append(p);
			}
		} else if (params.script) {
			if (!this.scriptDeactivate) {
				this.banner = $('<div style="width: 100%; height: 100%;"></div>');
				this.banner.html(params.script);
			} else {
				this.banner = null;
			}
		}
		if (this.banner) {
			this.container.append(this.banner);
		}

		this.elem.trigger("resize");
	};

	/**
	 * Extend element properties dialog
	 */
	Banner.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 360},
			tabs: [
				{name: __('Static banner'), children: [
					{type: 'VerticalLayout', fluid: true, children: [
						{type: 'Label', text: __('Picture/Flash file')},
						{type: 'ImageSelector', id: 'bannerImage', mode: 'all'},
						{type: 'Label', text: __('Banner URL'),
							helpText: __('For flash banner this url will be passed using "clickTAG".'),
							css: {marginTop: 15}
						},
						{type: 'TextField', id: 'bannerUrl', fixedWidth: 12},
						{type: 'CheckBox', label: __('Force Flash URL'),
							id: 'bannerForceFlUrl',
							helpText: __('If flash has no url hardcoded and has no support for "clickTAG" you can force URL on it. If you force URL flash will not be interactive.')
						}
					]}
				]},
				{name: __('Script banner'), children: [
					{type: 'VerticalLayout', fluid: true, children: [
						{type: 'CheckBox', label: __('Deacitvate content while in builder (recomended)'),
							id: 'scriptDeactivate',
							helpText: __("Some scripts may interfere with a Zyro Builder, so it's recomended to deactivate them. Failing to do so may result in inaccessable page in builder.")
						},
						{type: 'Label', text: __('Script'), css: {marginTop: '20px'}},
						{type: 'TextField', id: 'bannerScript', textArea: true, fixedWidth: 12, css: {height: 240, marginBottom: 0}}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.url = fields.bannerUrl.getValue();
				thisClass.params.image = fields.bannerImage.getValue();
				thisClass.params.forceflurl = fields.bannerForceFlUrl.getValue();
				thisClass.params.script = fields.bannerScript.getValue();
				thisClass.scriptDeactivate = fields.scriptDeactivate.getValue();
				thisClass.updateStyle();
			}
		});
		
		fields.bannerUrl.setValue(this.params.url);
		fields.bannerImage.setValue(this.params.image);
		fields.bannerForceFlUrl.setValue(this.params.forceflurl);
		fields.bannerScript.setValue(this.params.script);
		fields.scriptDeactivate.setValue(this.scriptDeactivate);
	};
	
	return Banner;
});
;

/** WB BuyNow **/
(window.defineModule = (window.defineModule || {})).name = 'WB BuyNow';

define('BuyNow', ['ElementRegister', 'Element', 'DropdownBox'], function(ElementRegister, Element, DropdownBox) {
	'use strict';

	/**
	 * BuyNow class
	 * @param {Object} data
	 */
	var BuyNow = function(data) { if (data) this.__construct(data); };

	BuyNow.prototype = new Element();
	BuyNow.prototype.constructor = BuyNow;
	ElementRegister.registerClass("BuyNow", BuyNow);
	ElementRegister.registerPaymentGateway({
		name: 'PayPal',
		id: 'paypal',
		priority: 1,
		pageUrl: 'https://www.paypal.com/',
		className: 'BuyNow',
		keyField: __('Email'),
		keyFieldId: 'business',
		
		keyField2Id: 'test',
		keyFieldDef: {type: 'VerticalLayout', noPadding: true, children: [
			{type: 'TextField', placeholder: __('Email'), id: 'key'},
			{type: 'CheckBox', label: __('Test mode'), id: 'key2', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
				this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
			}}
		]},
	
		titleFieldId: null,
		nameFieldId: 'itemName',
		priceFieldId: 'amount',
		currencyFieldId: 'currencyCode'
	});
	
	BuyNow.currencies = [
		"USD", "AUD", "BRL", "GBP", "CAD", "CZK", "DKK", "EUR", "HKD", "HUF", "ILS",
		"JPY", "MYR", "MXN", "TWD", "NZD", "NOK", "PHP", "PLN", "RUB", "SGD", "SEK",
		"CHF", "THB"
	];
	BuyNow.supportedLocales = [
		'en_US', 'en_AU', 'en_GB', 'fr_CA', 'es_ES',
		'it_IT', 'fr_FR', 'de_DE', 'pt_BR', 'zh_CN',
		'da_DK', 'zh_HK', 'he_IL', 'no_NO', 'pl_PL',
		'pt_PT', 'ru_RU', 'sv_SE', 'th_TH', 'zh_TW',
		'nl_NL'
	];
	BuyNow.filterLocale = function(locale) {
		locale = locale || wb_builder.locale;
		for (var i in BuyNow.supportedLocales) {
			if (BuyNow.supportedLocales[i] === locale) {
				if (locale === 'nl_NL') return 'nl_NL/NL';
				return locale;
			}
		}
		return 'en_US';
	};
	BuyNow.prototype.noPhotoBg = 'ico-tb-buynow';
	BuyNow.prototype.params = null;
	BuyNow.prototype.form = null;

	/**
	 * Construct buy now button element
	 * @param {Object} data element data object
	 */
	BuyNow.prototype.__construct = function(data) {
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(true);

		this.setMinSize(null, 24);
		this.setSize(107, 26);
		this.setResizingEnabled(false, true);
		//this.elem.resizable("destroy");

		this.container.css({overflow: "hidden"});

		this.params = {
			business: (data.content.business ? data.content.business : null),
			itemName: (data.content.itemName ? data.content.itemName : null),
			amount: (data.content.amount ? data.content.amount : 0),
			currencyCode: (data.content.currencyCode ? data.content.currencyCode : BuyNow.currencies[0]),
			shipping: (data.content.shipping ? data.content.shipping : 0),
			test: (data.content.test ? true : false)
		};

		this.updateStyle(true);

		var thisClass = this;
		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
	};

	/** @return {String} */
	BuyNow.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = (this.params.itemName ? this.params.itemName : '')
				+ (this.params.amount ? (': ' + this.params.amount) : '')
				+ (this.params.currencyCode ? (' ' + this.params.currencyCode) : '');
		return opts;
	};

	/**
	 * Serialize this element
	 * @return {Object}
	 */
	BuyNow.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			business: this.params.business,
			itemName: this.params.itemName,
			amount: this.params.amount,
			currencyCode: this.params.currencyCode,
			shipping: this.params.shipping,
			test: this.params.test,
			html: this.getHtmlValue()
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 * @param {string} langCode
	 */
	BuyNow.prototype.updateStyle = function(initial, langCode, returnFormHtml) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		langCode = langCode || this.system.site.currSelLang;
		var btnLocale;
		var currLang = langCode ? wb_builder.getLanguageByCode(langCode) : null;
		if (currLang) btnLocale = currLang.locale;
		btnLocale = BuyNow.filterLocale(btnLocale);
		var thisClass = this;
		var btnImgSrc = 'https://www.paypalobjects.com/' + btnLocale + '/i/btn/btn_buynow_LG.gif';
		
		if (!returnFormHtml) {
			var img = new Image();
			img.onload = function() {
				thisClass.setSize(this.width, this.height);
			};
			img.src = btnImgSrc;
			this.setSize(img.width, img.height);
			if (this.form) {
				this.form.detach();
				this.form.remove();
				this.form = null;
			}
		}
		
		var url = this.params.test
			? 'https://www.sandbox.paypal.com/cgi-bin/webscr'
			: 'https://www.paypal.com/cgi-bin/webscr';
		
		this.form = $('<form action="' + url + '" method="post" target="_blank" class="paypal">' +
				'<input type="hidden" name="cmd" value="_xclick" />' +
				'<input type="hidden" name="business" value="" />' +
				'<input type="hidden" name="lc" value="US" />' +
				'<input type="hidden" name="item_name" value="" />' +
				'<input type="hidden" name="amount" value="" />' +
				'<input type="hidden" name="currency_code" value="" />' +
				'<input type="hidden" name="button_subtype" value="services" />' +
				'<input type="hidden" name="no_note" value="0" />' +
				'<input type="hidden" name="shipping" value="" />' +
				'<input type="hidden" name="bn" value="JSCProfis_SP" />' +
				'<input type="image" src="' + btnImgSrc + '" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" />' +
				'<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" />' +
			'</form>');
		this.container.append(this.form);
		this.form.children("input[name=business]").val(this.params.business);
		this.form.children("input[name=item_name]").val(__tr(this.params.itemName, langCode));
		this.form.children("input[name=amount]").val(this.params.amount);
		this.form.children("input[name=currency_code]").val(this.params.currencyCode);
		this.form.children("input[name=shipping]").val(this.params.shipping);
		
		if (returnFormHtml) {
			return $('<div>').append(this.form).html();
		}

		if (true || this.params.business) {
			this.form.show();
			this.displayEmtyMessage(false);
		} else {
			this.form.hide();
			this.displayEmtyMessage(true);
		}
	};

	/**
	 * Extend element properties dialog
	 */
	BuyNow.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 246},
			tabs: [
				{children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Item Name'),
							helpText: __('Item name to be shown in paypal checkout window.')
						},
						{type: 'MultilangTextField', id: 'buyNowItemName'},
						{type: 'HorizontalLayout', columnWeights: [4, 4, 4], css: {marginTop: 15}, children: [
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Price')},
								{type: 'TextField', id: 'buyNowAmount'}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Shipping')},
								{type: 'TextField', id: 'buyNowShipping'}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Currency')},
								{type: 'DropdownBox', id: 'buyNowCurrencyCode', init: function() {
									for (var i = 0; i < BuyNow.currencies.length; i++) {
										var item = new DropdownBox.Item(BuyNow.currencies[i], BuyNow.currencies[i]);
										this.addItem(item);
										if (i === 0) this.selectItem(item);
									}
								}}
							]}
						]},
						{type: 'Label', text: __('Email address to receive payments'),
							css: {marginTop: 15},
							helpText: __('Email registered to your PayPal account.')
						},
						{type: 'TextField', id: 'buyNowBusiness'}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.params.business = fields.buyNowBusiness.getValue();
				thisClass.params.itemName = fields.buyNowItemName.getValue();
				thisClass.params.amount = fields.buyNowAmount.getValue();
				thisClass.params.currencyCode = fields.buyNowCurrencyCode.getValue();
				thisClass.params.shipping = fields.buyNowShipping.getValue();
				thisClass.updateStyle();
			}
		});

		fields.buyNowBusiness.setValue(this.params.business);
		fields.buyNowItemName.setValue(this.params.itemName);
		fields.buyNowAmount.setValue(this.params.amount);
		fields.buyNowCurrencyCode.setValue(this.params.currencyCode);
		fields.buyNowShipping.setValue(this.params.shipping);
	};

	BuyNow.prototype.getHtmlValue = function() {
		var html = null;
		if (this.system.site.languages.length) {
			html = {};
			for (var i=0, lang; (lang = this.system.site.languages[i]); i++) {
				html[lang.code] = this.updateStyle(false, lang.code, true);
			}
		} else {
			html = this.updateStyle(false, null, true);
		}
		return html;
	};

	BuyNow.prototype.onSwitchLanguage = function(langCode) {
		Element.prototype.onSwitchLanguage.call(this, langCode);
		this.updateStyle(false, langCode);
	};

	return BuyNow;
});
;

/** WB Shape **/
(window.defineModule = (window.defineModule || {})).name = 'WB Shape';

define('Shape', ['ElementRegister', 'Element', 'Service'], function(ElementRegister, Element, Service) {
	'use strict';
	
	/**
	 * Shape class
	 * @param {Object} data
	 */
	var Shape = function(data) { if (data) this.__construct(data); };

	Shape.prototype = new Element();
	Shape.prototype.constructor = Shape;
	ElementRegister.registerClass("Shape", Shape);

	Shape.prototype.noPhotoBg = 'ico-tb-shape';
	Shape.prototype.shape = null;
	Shape.prototype.background = null;
	Shape.prototype.border = null;
	Shape.prototype.opacity = null;
	Shape.prototype.borderRadius = null;
	Shape.prototype.link = null;

	/**
	 * Construct shape element
	 * @param {Object} data element data object
	 */
	Shape.prototype.__construct = function(data) {
		this.ignoreParentBounds = true;
		Element.prototype.__construct.call(this, data);

		this.displayEmtyMessage(false);

		//this.setMinSize(24, 24);
		this.setMinSize(1, 1);

		this.container.css({overflow: "hidden"});

		this.shape = $('<div></div>');
		this.shape.css({ width: "100%", height: "100%" });
		this.container.append(this.shape);

//		this.background = data.content.background ? data.content.background : "#ffffff";
		var bgColor = (data.content.background && (typeof data.content.background === 'string')) ? data.content.background : '#ffffff';
		this.background = (data.content.background && (typeof data.content.background === 'object')) ? data.content.background : {
			color: bgColor,
			image: "none",
			position: "left top",
			repeat: "repeat",
			size: "auto auto",
			attachment: "scroll",
			css: { background: bgColor + " none repeat scroll left top", "background-size": "auto auto" }
		};

		this.border = data.content.border ? data.content.border : {
			color: "#C0C0C0",
			style: "solid",
			weight: 5,
			css: { border: "5px solid #C0C0C0" }
		};

		this.opacity = (data.content.opacity || parseInt(data.content.opacity) === 0) ? data.content.opacity : 0.95;

		this.borderRadius = data.content.borderRadius ? data.content.borderRadius : {
			lt: 10, rt: 10, rb: 10, lb: 10,
			css: { 
				"border-radius"			: "10px",
				"-webkit-border-radius"	: "10px", 
				"-moz-border-radius"	: "10px"
			}
		};

		this.link = ("link" in data.content) ? data.content.link : null;

		this.updateStyle(true);
//		this.onResize();

		var thisClass = this;
		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
		/* this.elem.bind("resize", function() {
			thisClass.onResize();
		}); */
	};
	
	Shape.prototype.supportsFullWidth = function() {
		return true;
	};

	Shape.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = this.isFullWidth ? 'n, s' : 'n, e, s, w, ne, se, sw, nw';
	};

	/** @return {Object} */
	Shape.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = '';
		opts.thumb = $('<span>').css({background: this.background, opacity: this.opacity}).css(this.border.css).css(this.borderRadius.css);
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return {Object}
	 */
	Shape.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			background: this.background,
			border: this.border,
			opacity: this.opacity,
			borderRadius: this.borderRadius,
			link: this.link
		};

		return data;
	};

	/**
	 * Update element style after property changes
	 */
	Shape.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		//this.shape.css(this.background.css);
//		this.shape.css("background", this.background);
		var bg = this.background;
		var css = $.extend(true, {}, bg.css);
		if (css.background && bg.image && bg.image !== "none") {
			css.background = css.background.replace(/url\([^\)]+\)/i, 'url("' + wb_builder.makeLocalUrl(bg.image) + '")');
		}
		this.shape.css(css);
		this.shape.css(this.border.css);
		this.shape.css("opacity", this.opacity);
		this.shape.css(this.borderRadius.css);
	};

	/* Shape.prototype.onResize = function(onConstruct) {
		Element.prototype.onResize.call(this, onConstruct);
		this.shape.css({ width: this.isFullWidth ? "100%" : (this.getWidth() + "px"), height: this.getHeight() + "px" });
		this.elem.trigger("elementresize", [this]);
	}; */
	
	Shape.prototype.getUsedMediaGalleryItems = function() {
		var items = Element.prototype.getUsedMediaGalleryItems.call(this);
		return (this.background && this.background.image) ? items.concat(this.background.image) : items;
	};

	/**
	 * Extend element properties dialog
	 */
	Shape.prototype.comProperties = function() {
		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 330},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', columnWeights: [4, 8], children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: (__('Shape Opacity') + ' (%)')},
							{type: 'TextField', id: 'opacity', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-opacity-change', thisClass);
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'border', change: function() {
								Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-border-change', thisClass);
							}}
						]}
					]},
					{type: 'Label', text: __('Rounded corners'), css: {marginTop: 15}},
					{type: 'RoundCornersSelector', id: 'borderRadius', change: function() {
						Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-borderRadius-change', thisClass);
					}},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Background')},
						{type: 'BackgroundSelector', id: 'background', useSize: true, useAttachment: true, change: function() {
							Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-background-change', thisClass);
						}}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('URL')},
						{type: 'LinkSelector', id: 'link', multilang: true}
					]}
				]}
			],
			callbackFunc: function(fields) {
				thisClass.background = fields.background.getValue();
				thisClass.border = fields.border.getValue();
				thisClass.opacity = fields.opacity.getValue();
				thisClass.opacity = parseInt(thisClass.opacity, 10);
				if (isNaN(thisClass.opacity)) thisClass.opacity = 1; else thisClass.opacity = thisClass.opacity / 100;
				thisClass.borderRadius = fields.borderRadius.getValue();
				thisClass.link = fields.link.getValue();
				thisClass.updateStyle();
//				thisClass.onResize();
			}
		});
		
		fields.background.setValue(this.background);
		fields.border.setValue(this.border);
		fields.opacity.setValue(this.opacity*100);
		fields.borderRadius.setValue(this.borderRadius);
		fields.link.setValue(this.link);
	};
	
	return Shape;
});
;

/** WB LinkExchangeBadge **/
(window.defineModule = (window.defineModule || {})).name = 'WB LinkExchangeBadge';

define('LinkExchangeBadge', ['ElementRegister', 'Element', 'UIComponent', 'RadioBox', 'Confirm'], function(ElementRegister, Element, UIComponent, RadioBox, Confirm) {

	/**
	 * CustomHtml class
	 * @param {Object} data
	 */
	var LinkExchangeBadge = function(data) { if (data) this.__construct(data); };

	LinkExchangeBadge.prototype = new Element();
	LinkExchangeBadge.prototype.constructor = LinkExchangeBadge;
	ElementRegister.registerClass("ZyroBadge", LinkExchangeBadge);
	ElementRegister.registerClass("LinkExchangeBadge", LinkExchangeBadge);

	LinkExchangeBadge.badgeTypes = null;

	LinkExchangeBadge.prototype.badgeType = "iZyro";
	LinkExchangeBadge.prototype.badgeHtml = null;
	LinkExchangeBadge.prototype.customLock = false;
	/** Store timeout instance for delayed size calculations. */
	LinkExchangeBadge.prototype.updateSizeTimeout = null;

	/**
	 * Construct custom html element
	 * @param data element data object
	 */
	LinkExchangeBadge.prototype.__construct = function(data) {
		this.customLock = data.customLock ? data.customLock : false;
		if( LinkExchangeBadge.badgeTypes === null ) {
			var badgeTypeLogo = '<i class="icon-wb-logo"></i><a href="http://' + wb_builder.siteProHost + '/" target="_blank" title="' + wb_builder.builderName + '">' + wb_builder.builderShortName + '</a>';
			LinkExchangeBadge.badgeTypes = {
				poweredBy: __("Powered by %s").replace("%s", badgeTypeLogo),
				memberOf: __("Member of %s").replace("%s", badgeTypeLogo),
				voteForMeOn: __("Vote for me on %s").replace("%s", badgeTypeLogo),
				iZyro: __("I %s").replace("%s", badgeTypeLogo)
			};
		}

		this.badgeHtml = LinkExchangeBadge.badgeTypes[this.badgeType];

		data.isCommon = ("isCommon" in data) ? (data.isCommon ? true : false) : true;
		Element.prototype.__construct.call(this, data);

		this.setMinSize(48, 24);
		//this.setSize(100, 22);

		this.container.css({overflow: "hidden"});
//		this.setResizingEnabled(false, true);

		this.badgeType = data.content.type ? data.content.type : this.badgeType;
		if (this.badgeType in LinkExchangeBadge.badgeTypes) {
			this.badgeHtml = LinkExchangeBadge.badgeTypes[this.badgeType];
		}

		this.updateStyle(true);

		var thisClass = this;
		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
		this.elem.bind("resize", function() {
			thisClass.onResize();
		});
		thisClass.onResize();
	};
	
	LinkExchangeBadge.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = 'e';
	};

	LinkExchangeBadge.prototype.onResize = function(onConstruct) {
		if (!onConstruct) this.system.setPageModified(true);
		var w = this.getWidth();
		var h = this.container.children('div').height();
		this.setSize(w, h);
		this.elem.trigger("elementresize", [this]);
	};

	/**
	 * Serialize this element
	 * @return object
	 */
	LinkExchangeBadge.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);
		data.customLock = this.customLock;
		data.content = {
			type: this.badgeType,
			html: (this.badgeHtml ? this.badgeHtml : "")
		};

		return data;
	};
	
	LinkExchangeBadge.prototype.setSize = function(w, h) {
		Element.prototype.setSize.call(this, w, h);
	};

	/**
	 * Update element style after property changes
	 */
	LinkExchangeBadge.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		this.container.empty();
		var cont = $("<div></div>");
		cont.addClass("wb-stl-footer");
		cont.css({/*whiteSpace: "nowrap", overflow: "hidden", */display: "inline-block"});
		cont.html(this.badgeHtml);
		this.container.html(cont);
		if (this.updateSizeTimeout) clearTimeout(this.updateSizeTimeout);
		var w = this.container.outerWidth(true);
		if (initial) {
			var thisClass = this;
			this.updateSizeTimeout = setTimeout(function() {
//				var w = Math.max(cont.outerWidth(true), 100);
				var h = Math.max(cont.outerHeight(true), 20);
				thisClass.setSize(w, h);
			}, 100);
		} else {
//			var w = Math.max(cont.outerWidth(true), 100);
			var h = Math.max(cont.outerHeight(true), 20);
			this.setSize(w, h);
		}
	};
	
	LinkExchangeBadge.prototype.initContextMenu = function(elem) {
		if (this.customLock)
			return;
		Element.prototype.initContextMenu.call(this, elem);
	};

	/**
	 * Remove this element
	 * @param {Boolean} noHistory if true deletion will not be recorded to history
	 */
	LinkExchangeBadge.prototype.remove = function(noHistory, noConfirm) {
		if (this.customLock)
			return;
		var thisClass = this;
		if (!noConfirm) {
			var thisNoHistory = noHistory;
			var dialogTitle = __("Remove Site.pro Badge").replace(/site\.pro/i, wb_builder.builderShortName);
			Confirm.showDialog(
				dialogTitle,
				$('<div class="wb_change_template_dlg">' +
					'<div class="qq">' + __("Do you really want to remove it?") + '</div>' +
					'<div class="red">' + __("This is a Link Exchange label. It helps to have a higher rank in Google Search.") + '</div>' + 
				'</div>'),
				[
					{
						title: __("No, keep it")
					},
					{
						title: __("Yes, remove it"),
						cssClass: "btn-danger",
						func: function() {
							thisClass.remove(thisNoHistory, true);
						}
					}
				],
				480
			);
			Confirm.dialog.setCenterButtons(true);
			return;
		}
		Element.prototype.remove.call(this, noHistory);
	};

	/**
	 * Extend element properties dialog
	 */
	LinkExchangeBadge.prototype.comProperties = function() {
		var thisClass = this, k, fields = Element.prototype.comProperties.call(this, {
			tabs: [
				{children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Widget type')},
						{type: 'VerticalLayout', id: 'badgeType', children: [],
							init: function() {
								var label, cEvent;
								this.items = {};
								for (k in LinkExchangeBadge.badgeTypes) {
									this.items[k] = new RadioBox(
											(label = UIComponent.UIComponent.wrapControl({elem: $('<div>')})),
											null, 'badge_type', false, null
										);
									cEvent = (function(cb) { return function() { cb.setValue(true); return false; }; })(this.items[k]);
									label.getElem()
										.css({cursor: 'pointer'})
										.append(LinkExchangeBadge.badgeTypes[k])
										.on('click', cEvent)
										.find('a').attr({href: 'javascript:void(0)'});
									this.addChild(this.items[k]);
								}
							}
						}
					]}
				]}
			],
			callbackFunc: function(fields) {
				for (k in fields.badgeType.items) {
					if (!fields.badgeType.items[k].getValue()) continue;
					thisClass.badgeType = k;
					thisClass.badgeHtml = LinkExchangeBadge.badgeTypes[thisClass.badgeType];
				}
				thisClass.updateStyle();
			}
		});

		if (!fields.badgeType.items[this.badgeType]) {
			this.badgeType = 'iZyro';
		}
		for (k in fields.badgeType.items) {
			fields.badgeType.items[k].setValue((this.badgeType === k));
		}
	};
	
	return LinkExchangeBadge;
});
;

/** WB Languages **/
(window.defineModule = (window.defineModule || {})).name = 'WB Languages';

define('Languages', ['ElementRegister', 'Element', 'Confirm', 'UIButton', 'DropdownBox', 'ComboBox', 'Service', 'BorderControl'], function(ElementRegister, Element, Confirm, UIButton, DropdownBox, ComboBox, Service, BorderControl) {
	'use strict';
	
	/**
	 * Languages class
	 * @param {Object} data
	 */
	var Languages = function(data, initial) { if (data) this.__construct(data, initial); };

	Languages.prototype = new Element();
	Languages.prototype.constructor = Languages;
	ElementRegister.registerClass('Languages', Languages);

	Languages.prototype.noPhotoBg = 'ico-tb-lang';
	Languages.prototype.type = null;
	Languages.prototype.flagSize = null;
	Languages.prototype.flagSpacing = null;
	Languages.prototype.flagBorder = null;
	Languages.prototype.flagBorderActive = null;
	Languages.prototype.flagUseSquare = false;

	Languages.prototype.comboBox = null;
	Languages.prototype._elem = null;
	Languages.elemList = [];
	Languages.reloadAll = function(initial, except) {
		for (var i=0, item; (item = Languages.elemList[i]); i++) {
			if (item === except) { continue; }
			item.updateStyle(initial);
		}
	};

	/**
	 * Construct languages element
	 * @param data element data object
	 */
	Languages.prototype.__construct = function(data, initial) {
		this.ignoreParentBounds = true;
		Element.prototype.__construct.call(this, data, initial);
		if (!this.system.site.languages.length && initial) {
			this.remove(true, true);
			return;
		}
		
		this.setEmtyMessageText(__('Double click to change languages'));

		var thisClass = this;

		this.type = data.content.type ? data.content.type : 'flags';
		this.isCommon = data.isCommon ? data.isCommon : true;
		this.includePages = data.includePages ? data.includePages : {};

		this.flagSize = data.content.hasOwnProperty("flagSize") ? data.content.flagSize : 16;
		this.flagUseSquare = data.content.hasOwnProperty("flagUseSquare") ? data.content.flagUseSquare : false;
		this.flagSpacing = data.content.hasOwnProperty("flagSpacing") ? data.content.flagSpacing : 1;
		this.flagBorder = (data.content.hasOwnProperty("flagBorder") && data.content.flagBorder) ? data.content.flagBorder : {
			differ: false,
			weight: 1,
			style: "solid",
			color: "#EEEEEE",
			css: {border: "1px solid #EEEEEE"}
		};
		this.flagBorderActive = (data.content.hasOwnProperty("flagBorderActive") && data.content.flagBorderActive) ? data.content.flagBorderActive : {
			differ: false,
			weight: 2,
			style: "solid",
			color: "#777777",
			css: {border: "2px solid #777777"}
		};

		/* if (!this.system.site.languages.length) {
			var builderLang = this.system.getLanguageByLocale(this.system.locale);
			this.system.site.languages.push({
				code: builderLang.code,
				locale: builderLang.locale,
				hrefLang: builderLang.hrefLang,
				name: builderLang.name,
				isDefault: true
			});
			this.system.site.setLastDefLang(builderLang.code);
			this.system.site.currSelLang = builderLang.code;
			setTimeout(function() {
				thisClass.system.site.onUpdateLanguages();
			}, 50);
		} */

		this.setMinSize(18, 14);

		this.cover.on('click mousemove', function(e) {
			var px = e.pageX, py = e.pageY, isHover = false;
			if (thisClass.type === 'flags') {
				if (!thisClass._elem) { return; }
				thisClass._elem.find('a').each(function() {
					var thisA = $(this);
					var ao = thisA.offset();
					var as = {width: thisA.width(), height: thisA.height()};
					if (px >= ao.left && px <= (ao.left + as.width) && py >= ao.top && py <= (ao.top + as.height)) {
						if (e.type === 'click') {
							thisA.trigger('click');
						}
						isHover = true;
						return;
					}
				});
			} else if (thisClass.type === 'select') {
				if (!thisClass.comboBox) { return; }
				if (e.type === 'click') {
					thisClass.comboBox.input.trigger('click');
				}
				isHover = true;
			}
			if (e.type === 'mousemove') {
				thisClass.cover.css("cursor", (isHover ? "pointer" : "default"));
			}
		});

		this.updateStyle(true);
		setTimeout(function() {
			thisClass.updateStyle(true);
		}, 50);

		$(this.controls).bind("dblclick", function(e) {
			thisClass.comProperties();
		});
		this.elem.bind("resize", function() {
			thisClass.onResize(false);
		});
		this.elem.bind("resizestop", function(event, ui) {
			thisClass.onResize(false, true, event);
		});
		if (!this.system.site.languages.length) {
			setTimeout(function() {
				thisClass.comProperties();
			}, 50);
		}
		Languages.elemList.push(this);
		if (!this.system.site.languages.length) this.comProperties();
	};

	Languages.prototype.initResizable = function(options) {
		Element.prototype.initResizable.call(this, options);
		options.handles = 'e';
	};

	/** @return {String} */
	Languages.prototype.boxItemOptions = function() {
		var opts = Element.prototype.boxItemOptions.call(this);
		opts.text = '';
		return opts;
	};
	
	/**
	 * Serialize this element
	 * @return object
	 */
	Languages.prototype.serialize = function() {
		var data = Element.prototype.serialize.call(this);

		data.content = {
			type: this.type,
			flagSize: this.flagSize,
			flagUseSquare: this.flagUseSquare,
			flagSpacing: this.flagSpacing,
			flagBorder: this.flagBorder,
			flagBorderActive: this.flagBorderActive
		};

		return data;
	};

	Languages.prototype.getFlagDimensionData = function() {
		var dim = {
			wrapper: {width: 0, height: 0},
			inactiveFlag: {left: 0, top: 0, width: 0, height: 0},
			activeFlag: {left: 0, top: 0, width: 0, height: 0}
		};

		var inactiveLeftWidth = BorderControl.getBorderWidth(this.flagBorder, 3);
		var activeLeftWidth = BorderControl.getBorderWidth(this.flagBorderActive, 3);
		var inactiveTopWidth = BorderControl.getBorderWidth(this.flagBorder, 0);
		var activeTopWidth = BorderControl.getBorderWidth(this.flagBorderActive, 0);
		var k = this.flagUseSquare ? 1 : 0.75;

		dim.inactiveFlag.left = 1 * this.flagSpacing + ((inactiveLeftWidth >= activeLeftWidth) ? 0 : (activeLeftWidth - inactiveLeftWidth));
		dim.inactiveFlag.top = 1 * this.flagSpacing + ((inactiveTopWidth >= activeTopWidth) ? 0 : (activeTopWidth - inactiveTopWidth));
		dim.inactiveFlag.width = 1 * this.flagSize + inactiveLeftWidth + BorderControl.getBorderWidth(this.flagBorder, 1);
		dim.inactiveFlag.height = Math.round(k * this.flagSize) + inactiveTopWidth + BorderControl.getBorderWidth(this.flagBorder, 2);

		dim.activeFlag.left = 1 * this.flagSpacing + ((activeLeftWidth >= inactiveLeftWidth) ? 0 : (inactiveLeftWidth - activeLeftWidth));
		dim.activeFlag.top = 1 * this.flagSpacing + ((activeTopWidth >= inactiveTopWidth) ? 0 : (inactiveTopWidth - activeTopWidth));
		dim.activeFlag.width = 1 * this.flagSize + activeLeftWidth + BorderControl.getBorderWidth(this.flagBorderActive, 1);
		dim.activeFlag.height = Math.round(k * this.flagSize) + activeTopWidth + BorderControl.getBorderWidth(this.flagBorderActive, 2);

		dim.wrapper.width = 2 * this.flagSpacing + Math.max(dim.inactiveFlag.width, dim.activeFlag.width);
		dim.wrapper.height = 2 * this.flagSpacing + Math.max(dim.inactiveFlag.height, dim.activeFlag.height);

		return dim;
	};

	Languages.prototype.onResize = function(onConstruct, stop, stopEvent) {
		Element.prototype.onResize.call(this, onConstruct);

		var langCount = this.system.site.languages.length;
		if (langCount) {
			if (this.type === 'flags') {
				var dim = this.getFlagDimensionData();
				if (stop) {
					if (stopEvent) stopEvent.skipStopEvent = true;
					var rowCount = Math.min(langCount, Math.floor(this.getWidth() / dim.wrapper.width));
					this.setSize(dim.wrapper.width * rowCount, null);
				} else {
					this.setSize(this.getWidth(), this._elem.height());
					this.editBtn.css({ left: "-30px", right: "" });
					this.moveBtn.css({ left: "-30px", top: "-30px" });
				}
			} else if (this.type === 'select') {
				this.setSize(null, 34);
				if (!this.comboBox) return;
				this.comboBox.setWidth(this.getSize().width);
				this.editBtn.css({ left: "", right: "-1px" });
				this.moveBtn.css({ left: "-1px", top: "-1px" });
			}
		} else {
			this.setSize(100, 100);
		}
		this.elem.trigger("elementresize", [this]);
	};

	/**
	 * Update element style after property changes
	 * @param {string} langCode
	 */
	Languages.prototype.updateStyle = function(initial, langCode) {
		Element.prototype.updateStyle.call(this, initial, langCode);
		langCode = langCode || this.system.site.currSelLang;
		this.displayEmtyMessage(false);

		if (this._elem) {
			this._elem.remove();
			this._elem.empty();
			this._elem = null;
		}

		var i, lang, langs = this.system.site.languages, thisClass = this;
		if (langs.length) {
			if (this.type === 'flags') {
				this.comboBox = null;
				this._elem = $('<div class="langs_flags langs_flags_noa"></div>');
				var dim = this.getFlagDimensionData();
				for (i = 0; (lang = langs[i]); i++) {
					var a = $('<a href="' + wb_builder.baseUrl + lang.code + '/" ' + (lang.code === langCode ? 'class="active"' : '') + 'title="' + lang.name + '" data-lang="' + lang.code + '">');
					var icon = $('<i class="flag-icon-' + wb_builder.getCountryCode(lang.code) + (this.flagUseSquare ? ' flag-icon-squared' : '') + '">');
					a.append(icon);

					icon.css((lang.code === langCode) ? this.flagBorderActive.css : this.flagBorder.css);
					icon.css((lang.code === langCode) ? dim.activeFlag : dim.inactiveFlag);
					a.css(dim.wrapper);

					a.bind('click', function() {
						thisClass.system.site.switchLanguage($(this).data('lang'));
					});

					this._elem.append(a);
				}
				this.container.append(this._elem);
			}
			else if (this.type === 'select') {
				var opts = {};
				for (i = 0; (lang = langs[i]); i++) {
					opts[lang.code] = lang.name;
				}
				this.comboBox = new ComboBox(opts, langCode);
				this.comboBox.onChange = function(e) {
					thisClass.system.site.switchLanguage(thisClass.comboBox.getValue());
				};
				this._elem = this.comboBox.elem;
				this.container.append(this._elem);
				this.setSize(180, 30);
			}
		} else {
			this.displayEmtyMessage(true);
		}
		
		this.onResize(initial);
		this.onResize(initial, true);
	};

	Languages.prototype.exclude = function(noRemove, onConstruct) {
		if (onConstruct) {
			Element.prototype.exclude.call(this, noRemove, onConstruct);
		} else {
			Element.prototype.exclude.call(this, true);
			this.remove(false, true);
		}
	};

	Languages.prototype.remove = function(noHistory, noConfirm) {
		var thisClass = this;
		if (!noConfirm && this.system.site.languages.length) {
			var thisNoHistory = noHistory;
			Confirm.showDialog(__('Remove languages'),
				(new WB_RadioBox({
					'onlyitem': __('Delete only current item'),
					'all': __('Delete all languages and all language items')
				}, 'onlyitem', 'delete_langs')).elem,
				[
					{title: __("Cancel")},
					{title: __("Delete"), cssClass: 'btn-danger', func: function() {
						var type = Confirm.dialog.content.find('input[name="delete_langs"]:checked').val();
						if (type === 'onlyitem') {
							thisClass.remove(thisNoHistory, true);
						} else if (type === 'all') {
							while (Languages.elemList.length) {
								Languages.elemList[0].remove(true, true);
							}
							thisClass.system.site.languages = [];
							thisClass.system.site.switchLanguage(thisClass.system.site.getLastDefLang());
							thisClass.system.site.currSelLang = null;
							thisClass.system.site.onUpdateLanguages();
							wb_builder.setPageModified(true);
						}
					}}
				], 480);
			Confirm.dialog.setCenterButtons(true);
			return;
		}
		for (var i=0, elem; (elem = Languages.elemList[i]); i++) {
			if (this === elem) {
				Languages.elemList.splice(i, 1);
				break;
			}
		}
		Element.prototype.remove.call(this, noHistory);
	};
	
	Languages.prototype.setApplyDisabled = function(disabled) {
		var btn = $(this.comDialog.buttons).find('.btn-success');
		if (btn.length) {
			if (disabled) {
				btn.attr('disabled', 'disabled');
			} else {
				btn.removeAttr('disabled');
			}
		}
	};

	Languages.prototype.comProperties = function() {
		var updateFlagSizeSelect = function() {
			fields.flagSize.reload(fields.flagUseSquare.getValue() ? [
				{id: 16, name: "16x16"},
				{id: 20, name: "20x20"},
				{id: 24, name: "24x24"},
				{id: 28, name: "28x28"},
				{id: 32, name: "32x32"},
				{id: 36, name: "36x36"},
				{id: 40, name: "40x40"},
				{id: 44, name: "44x44"},
				{id: 48, name: "48x48"},
				{id: 52, name: "52x52"},
				{id: 56, name: "56x56"},
				{id: 60, name: "60x60"}
			] : [
				{id: 16, name: "16x12"},
				{id: 20, name: "20x15"},
				{id: 24, name: "24x18"},
				{id: 28, name: "28x21"},
				{id: 32, name: "32x24"},
				{id: 36, name: "36x27"},
				{id: 40, name: "40x30"},
				{id: 44, name: "44x33"},
				{id: 48, name: "48x36"},
				{id: 52, name: "52x39"},
				{id: 56, name: "56x42"},
				{id: 60, name: "60x45"}
			]);
		};

		var thisClass = this, fields = Element.prototype.comProperties.call(this, {
			size: {minBodyHeight: 340},
			tabs: [
				{children: [
					{type: 'HorizontalLayout', columnWeights: [5, 7], children: [
						{type: 'VerticalLayout', id: 'langsList', styleClass: 'wb_langs', children: [
							{type: 'Label', text: __('Language')},
							{type: 'CustomContainer', id: 'languageList',
								css: {maxHeight: '176px', overflowY: 'auto'},
								init: function() {
									this.languages = []; var thisSelf = this;
									this._elem.sortable({
										items: '.lang-item',
										tolerance: 'pointer',
										update: function(e, ui) {
											var i, lang,
												code = ui.item.data('langs-code'),
												index = ui.item.index();
											for (i = 0; i < thisSelf.languages.length; i++) {
												if (thisSelf.languages[i].code === code) {
													lang = thisSelf.languages[i];
													thisSelf.languages.splice(i, 1);
													thisSelf.languages.splice(index, 0, lang);
													break;
												}
											}
											fields.preview.update(thisSelf.languages);
										}
									});
									this.removeAllItems = function() {
										this._elem.empty();
										this.languages.splice(0, this.languages.length);
										this._updateApplyButton();
									};
									this.addLanguage = function(lang, isDefault) {
										var thisLang;
										this.languages.push(thisLang = {
											name: lang.name,
											code: lang.code,
											locale: lang.locale,
											hrefLang: lang.hrefLang,
											isDefault: (isDefault ? true : false),
											elem: null,
											setDefault: function(isDefault) {
												if (this.isDefault !== (isDefault ? true : false)) {
													this.isDefault = isDefault ? true : false;
													if (this.isDefault) {
														this.elem.addClass('default');
													} else {
														this.elem.removeClass('default');
													}
												}
											}
										});
										thisLang.elem = $('<div>').addClass('lang-item').data('langs-code', thisLang.code);
										if (isDefault) thisLang.elem.addClass('default');
										(new UIButton.UIButton(null, UIButton.UIButton.STYLE_LINK, 'glyphicon glyphicon-star-empty'))
											.addClass('btn-make-default')
											.setTitle(__('Make default'))
											.on('click', function() {
												for (var i = 0; i < thisSelf.languages.length; i++) {
													thisSelf.languages[i].setDefault((thisSelf.languages[i] === thisLang));
												}
												fields.preview.update(thisSelf.languages);
											})
											.getElem().appendTo(thisLang.elem);
										$('<i>').addClass('glyphicon glyphicon-star').attr({title: __('Default')}).appendTo(thisLang.elem);
										$('<span>').text(lang.name).appendTo(thisLang.elem);
										(new UIButton.UIButton(null, UIButton.UIButton.STYLE_LINK, 'glyphicon glyphicon-remove'))
											.addClass('btn-delete')
											.setTitle(__('Remove'))
											.on('click', function() {
												var idx = thisSelf.languages.indexOf(thisLang);
												if (idx >= 0) thisSelf.languages.splice(idx, 1);
												thisLang.elem.remove();
												thisLang.elem = null;
												if (thisLang.isDefault && thisSelf.languages.length > 0) {
													thisSelf.languages[0].setDefault(true);
												}
												fields.langSelector.reloadSelector(thisSelf.languages);
												fields.preview.update(thisSelf.languages);
												thisSelf._updateApplyButton();
											})
											.getElem().appendTo(thisLang.elem);
										this._elem.append(thisLang.elem);
										this._updateApplyButton();
									};
									this._updateApplyButton = function() {
										thisClass.setApplyDisabled(this.languages.length < 2);
									};
								}
							},
							{type: 'Button', text: ('+ ' + __('Add language')), id: 'langsAddBtn',
								buttonStyle: UIButton.UIButton.STYLE_LINK,
								styleClass: 'add-lang',
								click: function() {
									fields.langsAddBlock.setVisible(true);
									fields.langsAddBtn.setVisible(false);
									Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-langsAddBtn-click', thisClass);
								}
							},
							{type: 'FlowLayout', id: 'langsAddBlock',
								styleClass: 'add-lang-block',
								spacing: 0,
								visible: false,
								children: [
									{type: 'DropdownBox', id: 'langSelector',
										init: function() {
											this.reloadSelector = function(exclude) {
												var i, item, lang, excludeIndex = {};
												for (i = 0; i < exclude.length; i++) {
													excludeIndex[exclude[i].code] = true;
												}
												this.removeAllItem();
												for (i = 0; i < wb_builder.availableLanguages.length; i++) {
													lang = wb_builder.availableLanguages[i];
													if (lang.code in excludeIndex) continue;
													item = new DropdownBox.Item(lang.name, lang.code, lang);
													this.addItem(item);
												}
											};
										},
										change: function() {
											Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-langSelector-change', thisClass);
										}
									},
									{type: 'Button', text: __('Cancel'), id: 'cancelBtn',
										buttonStyle: UIButton.UIButton.STYLE_LINK,
										click: function() {
											fields.langsAddBlock.setVisible(false);
											fields.langsAddBtn.setVisible(true);
										}
									},
									{type: 'Button', text: __('Add'), id: 'addBtn',
										buttonStyle: UIButton.UIButton.STYLE_LINK,
										click: function() {
											var item = fields.langSelector.getSelectedItem();
											if (item) {
												fields.languageList.addLanguage(item.getOriginal(), (fields.languageList.languages.length <= 0));
												fields.langSelector.reloadSelector(fields.languageList.languages);
												fields.preview.update(fields.languageList.languages);
											}
											fields.cancelBtn.trigger('click');
											Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-addBtn-click', thisClass);
										}
									}
								]
							}
						]},
						{type: 'VerticalLayout', id: 'preview',
							styleClass: 'wb_switcher',
							children: [
								{type: 'Label', text: __('Language switcher')},
								{type: 'FlowLayout', verticalAlign: 'middle', css: {marginTop: 1}, children: [
									{type: 'RadioBox', label: __('Flags'), id: 'typeFlags', group: 'type',
										change: function() {
											var tab = thisClass.comDialog.tabbedPane.getTabByType("flagOptions");
											if( tab )
												thisClass.comDialog.tabbedPane.setTabVisible(tab, !!fields.typeFlags.getValue());
										}
									}, // flags
									{type: 'CustomContainer', id: 'flagsWrap', styleClass: 'langs_flags', css: {verticalAlign: 'middle'}, init: function() {
											this.update = function(languages) {
												var i, item;
												this._elem.empty();
												for (i = 0; i < languages.length; i++) {
													item = $('<a>')
														.attr({href: 'javascript:void(0)', title: languages[i].name})
														.append($('<i>').addClass('flag-icon-' + wb_builder.getCountryCode(languages[i].code)))
														.on('click', function() {
															var item = $(this);
															item.parent().children().removeClass('active');
															item.addClass('active');
														})
														.appendTo(this._elem);
													if (languages[i].isDefault) item.addClass('active');
												}
												this.setVisible((languages.length > 0));
											};
										}}
								]},
								{type: 'FlowLayout', verticalAlign: 'middle', css: {marginTop: 5}, children: [
									{type: 'RadioBox', label: __('Dropdown select'), id: 'typeSelect', group: 'type',
										change: function() {
											var tab = thisClass.comDialog.tabbedPane.getTabByType("flagOptions");
											if( tab )
												thisClass.comDialog.tabbedPane.setTabVisible(tab, !!fields.typeFlags.getValue());
											Service.HelpSystemPlayer.notify('item-plugin-' + thisClass.getClassType() + '-prop-typeSelect-change', thisClass);
										}
									}, // select
									{type: 'DropdownBox', id: 'selectWrap', css: {marginTop: 4}, init: function() {
											this.update = function(languages) {
												var i, item, def;
												this.removeAllItem();
												for (i = 0; i < languages.length; i++) {
													this.addItem(item = new DropdownBox.Item(languages[i].name, languages[i].code, languages[i]));
													if (languages[i].isDefault) def = item;
												}
												if (def) this.selectItem(def);
												this.setVisible((languages.length > 0));
											};
										}}
								]}
							],
							init: function() {
								this.update = function(languages) {
									fields.flagsWrap.update(languages);
									fields.selectWrap.update(languages);
								};
							}
						}
					]}
				]},
				{name: __("Flag settings"), type: "flagOptions", visible: (this.type === "flags"), children: [
					{type: "VerticalLayout", children: [
						{type: "HorizontalLayout", verticalAlign: "top", css: {marginTop: 5}, children: [
							{type: "VerticalLayout", children: [
								{type: "Label", text: __("Inactive border")},
								{type: "BorderSelector", id: "flagBorder", noTransparent: false, showRadius: true}
							]},
							{type: "VerticalLayout", children: [
								{type: "Label", text: __("Active border")},
								{type: "BorderSelector", id: "flagBorderActive", noTransparent: false, showRadius: true}
							]}
						]},
						{type: "HorizontalLayout", verticalAlign: "top", css: {marginTop: 5}, children: [
							{type: "VerticalLayout", children: [
								{type: "Label", text: __("Size")},
								{type: "DropdownBox", id: "flagSize"}
							]},
							{type: "VerticalLayout", children: [
								{type: "Label", text: __("Spacing")},
								{type: "DropdownBox", id: "flagSpacing", options: [
									{id: 0, name: "0"},
									{id: 1, name: "1"},
									{id: 2, name: "2"},
									{id: 3, name: "3"},
									{id: 4, name: "4"},
									{id: 5, name: "5"}
								]}
							]}
						]},
						{type: "HorizontalLayout", verticalAlign: "top", css: {marginTop: 5}, children: [
							{type: "CheckBox", id: "flagUseSquare", label: __("Use square flags"), change: updateFlagSizeSelect}
						]}
					]}
				]}
			],
			callbackFunc: function(fields) {
				var i, lang, defaultLang = null;
				thisClass.flagUseSquare = fields.flagUseSquare.getValue();
				thisClass.flagSize = fields.flagSize.getValue();
				thisClass.flagSpacing = fields.flagSpacing.getValue();
				thisClass.flagBorder = fields.flagBorder.getValue();
				thisClass.flagBorderActive = fields.flagBorderActive.getValue();

				for (i = 0; (lang = fields.languageList.languages[i]); i++) {
					if (lang.isDefault) defaultLang = lang.code;
				}
				if (!defaultLang && fields.languageList.languages.length > 0) {
					fields.languageList.languages[0].setDefault(true);
				}
				if (defaultLang) {
					thisClass.system.site.setLastDefLang(defaultLang);
				}
				thisClass.system.site.languages.splice(0, thisClass.system.site.languages.length);
				for (i = 0; (lang = fields.languageList.languages[i]); i++) {
					thisClass.system.site.languages.push({
						name: lang.name,
						code: lang.code,
						locale: lang.locale,
						hrefLang: lang.hrefLang,
						isDefault: lang.isDefault});
				}
				thisClass.type = fields.typeFlags.getValue() ? 'flags' : 'select';
				thisClass.system.site.onUpdateLanguages();
				thisClass.system.site.switchLanguage(thisClass.system.site.getLastDefLang());
				wb_builder.setPageModified(true);
			}
		});
		
		var dialogCloseClb = this.comDialog.onClose;
		this.comDialog.onClose = function() {
			if (typeof(dialogCloseClb) === 'function') dialogCloseClb();
			if (!thisClass.system.site.languages.length) {
				thisClass.remove(false, true);
			}
		};

		fields.languageList.removeAllItems();
		for (var i = 0; i < this.system.site.languages.length; i++) {
			fields.languageList.addLanguage(this.system.site.languages[i], this.system.site.languages[i].isDefault);
		}
		
		fields.langSelector.reloadSelector(fields.languageList.languages);
		fields.preview.update(fields.languageList.languages);
		
		if (this.type === 'flags') {
			fields.typeFlags.setValue(true);
		} else {
			fields.typeSelect.setValue(true);
		}
		fields.flagUseSquare.setValue(this.flagUseSquare);
		updateFlagSizeSelect();
		fields.flagSize.setValue(this.flagSize);
		fields.flagSpacing.setValue(this.flagSpacing);
		fields.flagBorder.setValue(this.flagBorder);
		fields.flagBorderActive.setValue(this.flagBorderActive);
	};

	Languages.prototype.onSwitchLanguage = function(langCode) {
		Element.prototype.onSwitchLanguage.call(this, langCode);
		this.updateStyle(false, langCode);
	};
	
	return Languages;
});
;

/** WB Main **/
(window.defineModule = (window.defineModule || {})).name = 'WB Main';

define('Service', [], function() {
	var Service = {};
	return Service;
});

define('jquery', [], function() {
	return window.$;
});

define('Main', ['Builder'], function(Builder) {
	'use strict';
	window.wb_builder = new Builder();
	
	return window.wb_builder;
});

require([
		'Main', 'DefaultUI/DefaultUI', 'UIBuilder', 'Dialog', 'ImagePicker', 'MediaLibrary', 'URLControl',
		'TextArea', 'Menu', 'Body', 'Picture', 'Banner', 'Blog',
		'BookmarksShare', 'BuyNow', 'Button', 'Chat', 'CustomHtml', 'FacebookFans',
		'FacebookLike', 'Flash', 'FlickrGallery', 'Form', 'Gallery', 'GoogleAdSense',
		'GoogleMaps', 'Youtube', 'Languages', 'Line', 'LinkExchangeBadge', 'Menu',
		'MusicPlayer', 'News', 'Shape', 'SkypeImOnline', 'Table', 'TextArea', 'Twitter',
		'store/Store', 'store/StoreCart', 'Blocks', 'ElementStyles'
	], function() {
	'use strict';
	
	/** On document ready */
	$(function() { window.wb_builder.init(); });
});

		$.jstree._themes = "modules/builder/js/lib/jstree/themes/";
		wb_builder.adminMode = false;
		wb_builder.siteDomain = "37462a07.test.test";
		wb_builder.isReseller = false;
		wb_builder.isEnterprise = false;
		wb_builder.isModRewrite = true;
		wb_builder.routeGetKey = "route";
		wb_builder.apiUrl = "";
		wb_builder.baseUrl = "http://sitepro4.mychrome.pt/";
		wb_builder.lnBaseUrl = "http://sitepro4.mychrome.pt/pt-BR/";
		wb_builder.loadPageUrl = "http://sitepro4.mychrome.pt/pt-BR/loadpage/";
		wb_builder.publishUrl = "http://sitepro4.mychrome.pt/pt-BR/publish/";
		wb_builder.previewUrl = "http://sitepro4.mychrome.pt/pt-BR/preview/";
		wb_builder.resetUrl = "http://sitepro4.mychrome.pt/pt-BR/template/?reset=1";
		wb_builder.templateUrl = "http://sitepro4.mychrome.pt/pt-BR/template/";
		wb_builder.buyProUrl = "https://site.pro/buy-pro/?return=aHR0cDovL3NpdGVwcm80Lm15Y2hyb21lLnB0L3B0LUJSLw&domain=37462a07.test.test";
		wb_builder.reportUrl = "http://sitepro4.mychrome.pt/pt-BR/feedback/";
		wb_builder.tplBaseUrl = "";
		wb_builder.modBaseUrl = "modules/builder/";
		wb_builder.userBaseUrl = "http://sitepro4.mychrome.pt/data/3/7/37462a07.test.test/";
		wb_builder.userGalleyUrl = "http://sitepro4.mychrome.pt/data/3/7/37462a07.test.test/gallery/";
		wb_builder.upgradeUrl = null;
		wb_builder.helpUrl = null;
		wb_builder.resizeSiteUrl = "http://sitepro4.mychrome.pt/pt-BR/resize-site/";
		wb_builder.enableAutoLayoutUrl = "http://sitepro4.mychrome.pt/pt-BR/enable-auto-layout/";
		wb_builder.disableAutoLayoutUrl = "http://sitepro4.mychrome.pt/pt-BR/disable-auto-layout/";
		wb_builder.getFontAwesomeIconsUrl = "http://sitepro4.mychrome.pt/pt-BR/get-font-awesome-icons/";
		wb_builder.availableFontsUrl = "http:\/\/sitepro4.mychrome.pt\/assets\/pers\/google-fonts.json?t=1553162713";
		wb_builder.fontThumbsUrl = "http:\/\/sitepro4.mychrome.pt\/assets\/pers\/font-thumbs.json?t=1553163101";
		wb_builder.logoutUrl = "http:\/\/sitepro4.mychrome.pt\/?logout=1";
		wb_builder.siteProHost = "site.pro";
		wb_builder.builderName = "Site.pro Website builder";
		wb_builder.builderShortName = "Site.pro";
		wb_builder.commonErrorMessage = "";
		wb_builder.sesso = "MN22OWNkMmdta2h1MG9wNnFyODViajQ1djI=";
		wb_builder.pageId = "0";
		wb_builder.template = {"id":null,"localId":null,"name":"Unnamed","categoryId":null,"categoryName":null,"isResponsive":false,"isPrivate":false,"nonTranslatable":false};
		wb_builder.meta = {"title":"","keywords":"","description":"","image":"","sitemapUrl":"http:\/\/37462a07.test.test\/sitemap.xml"};
		wb_builder.locale = "pt_BR";
		wb_builder.langCode = "pt";
		wb_builder.oriSiteWidth = 0;
		wb_builder.favicon = {"href":"https:\/\/site.pro\/assets\/logos\/ae03bb7bf2a6aeace6eeaba961dce321_favicon.png","type":"image\/png","rel":"icon"};
		wb_builder.devTestMode = false;
		wb_builder.devDebugMode = false;
		wb_builder.testMode = true;
		wb_builder.tinyMode = false;
		wb_builder.testSignUpBtn = null;
		wb_builder.availableLanguages = [{"id":52,"locale":"pt_PT","hrefLang":"pt","code":"pt2","countryCode":"pt","name":"Portugu\u00eas","default":false,"active":true,"hidden":false,"sortOrder":46,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":1,"locale":"ar_AE","hrefLang":"ar","code":"ar","countryCode":"ae","name":"\u0627\u0644\u0639\u0631\u0628\u064a\u0629","default":false,"active":true,"hidden":false,"sortOrder":2,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":72,"locale":"az_AZ","hrefLang":"az","code":"az","countryCode":"az","name":"Az\u0259rbaycan","default":false,"active":true,"hidden":false,"sortOrder":4,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":12,"locale":"id_ID","hrefLang":"id","code":"id","countryCode":"id","name":"Bahasa Indonesia","default":false,"active":true,"hidden":false,"sortOrder":6,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":6,"locale":"en_US","hrefLang":"en","code":"en","countryCode":"us","name":"English","default":true,"active":true,"hidden":false,"sortOrder":20,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":18,"locale":"ms_MY","hrefLang":"ms","code":"ms","countryCode":"my","name":"Bahasa Malaysia","default":false,"active":true,"hidden":false,"sortOrder":7,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":37,"locale":"be_BY","hrefLang":"be","code":"be","countryCode":"by","name":"\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f","default":false,"active":true,"hidden":false,"sortOrder":8,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":34,"locale":"bg_BG","hrefLang":"bg","code":"bg","countryCode":"bg","name":"\u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438","default":false,"active":true,"hidden":false,"sortOrder":9,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":33,"locale":"cs_CZ","hrefLang":"cs","code":"cs","countryCode":"cz","name":"\u010ce\u0161tina","default":false,"active":true,"hidden":false,"sortOrder":13,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":7,"locale":"es_ES","hrefLang":"es","code":"es","countryCode":"es","name":"Espa\u00f1ol","default":false,"active":true,"hidden":false,"sortOrder":21,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":3,"locale":"da_DK","hrefLang":"da","code":"da","countryCode":"dk","name":"Dansk","default":false,"active":true,"hidden":false,"sortOrder":16,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":4,"locale":"de_DE","hrefLang":"de","code":"de","countryCode":"de","name":"Deutsch","default":false,"active":true,"hidden":false,"sortOrder":17,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":5,"locale":"el_GR","hrefLang":"el","code":"el","countryCode":"gr","name":"\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac","default":false,"active":true,"hidden":false,"sortOrder":19,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":8,"locale":"et_EE","hrefLang":"et","code":"et","countryCode":"ee","name":"Eesti","default":false,"active":true,"hidden":false,"sortOrder":22,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":9,"locale":"fr_FR","hrefLang":"fr","code":"fr","countryCode":"fr","name":"Fran\u00e7ais","default":false,"active":true,"hidden":false,"sortOrder":24,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":10,"locale":"he_IL","hrefLang":"he","code":"he","countryCode":"il","name":"\u05e2\u05d1\u05e8\u05d9\u05ea","default":false,"active":true,"hidden":false,"sortOrder":26,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":49,"locale":"hi_IN","hrefLang":"hi","code":"hi","countryCode":"in","name":"\u0939\u093f\u0928\u094d\u0926\u0940","default":false,"active":true,"hidden":false,"sortOrder":27,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":11,"locale":"hr_HR","hrefLang":"hr","code":"hr","countryCode":"hr","name":"Hrvatski","default":false,"active":true,"hidden":false,"sortOrder":28,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":13,"locale":"it_IT","hrefLang":"it","code":"it","countryCode":"it","name":"Italiano","default":false,"active":true,"hidden":false,"sortOrder":30,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":48,"locale":"ja_JP","hrefLang":"ja","code":"ja","countryCode":"jp","name":"\u65e5\u672c\u8a9e","default":false,"active":true,"hidden":false,"sortOrder":31,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":54,"locale":"ka_GE","hrefLang":"ka","code":"ka","countryCode":"ge","name":"\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8","default":false,"active":true,"hidden":false,"sortOrder":32,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":14,"locale":"ko_KR","hrefLang":"ko","code":"ko","countryCode":"kr","name":"\ud55c\uad6d\uc5b4","default":false,"active":true,"hidden":false,"sortOrder":35,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":15,"locale":"lt_LT","hrefLang":"lt","code":"lt","countryCode":"lt","name":"Lietuvi\u0173","default":false,"active":true,"hidden":false,"sortOrder":36,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":16,"locale":"lv_LV","hrefLang":"lv","code":"lv","countryCode":"lv","name":"Latvie\u0161u","default":false,"active":true,"hidden":false,"sortOrder":37,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":17,"locale":"hu_HU","hrefLang":"hu","code":"hu","countryCode":"hu","name":"Magyar","default":false,"active":true,"hidden":false,"sortOrder":38,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":35,"locale":"mk_MK","hrefLang":"mk","code":"mk","countryCode":"mk","name":"\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438","default":false,"active":true,"hidden":false,"sortOrder":39,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":19,"locale":"nl_NL","hrefLang":"nl","code":"nl","countryCode":"nl","name":"Nederlands","default":false,"active":true,"hidden":false,"sortOrder":41,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":41,"locale":"no_NO","hrefLang":"no","code":"no","countryCode":"no","name":"Norsk","default":false,"active":true,"hidden":false,"sortOrder":42,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":40,"locale":"fa_IR","hrefLang":"fa","code":"fa","countryCode":"ir","name":"\u0641\u0627\u0631\u0633\u06cc","default":false,"active":true,"hidden":false,"sortOrder":43,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":20,"locale":"pl_PL","hrefLang":"pl","code":"pl","countryCode":"pl","name":"Polski","default":false,"active":true,"hidden":false,"sortOrder":44,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":21,"locale":"pt_BR","hrefLang":"pt-br","code":"pt","countryCode":"br","name":"Portugu\u00eas (BR)","default":false,"active":true,"hidden":false,"sortOrder":45,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":22,"locale":"ro_RO","hrefLang":"ro","code":"ro","countryCode":"ro","name":"Rom\u00e2n\u0103","default":false,"active":true,"hidden":false,"sortOrder":47,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":23,"locale":"ru_RU","hrefLang":"ru","code":"ru","countryCode":"ru","name":"\u0420\u0443\u0441\u0441\u043a\u0438\u0439","default":false,"active":true,"hidden":false,"sortOrder":48,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":60,"locale":"sr_CS","hrefLang":"sr-cs","code":"sr2","countryCode":"cs","name":"Srpski","default":false,"active":true,"hidden":false,"sortOrder":49,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":32,"locale":"sr_RS","hrefLang":"sr-rs","code":"sr","countryCode":"rs","name":"\u0421\u0440\u043f\u0441\u043a\u0438","default":false,"active":true,"hidden":false,"sortOrder":50,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":24,"locale":"sk_SK","hrefLang":"sk","code":"sk","countryCode":"sk","name":"Sloven\u010dina","default":false,"active":true,"hidden":false,"sortOrder":51,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":36,"locale":"sl_SI","hrefLang":"sl","code":"sl","countryCode":"si","name":"Sloven\u0161\u010dina","default":false,"active":true,"hidden":false,"sortOrder":53,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":25,"locale":"fi_FI","hrefLang":"fi","code":"fi","countryCode":"fi","name":"Suomi","default":false,"active":true,"hidden":false,"sortOrder":54,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":26,"locale":"sv_SE","hrefLang":"sv","code":"sv","countryCode":"se","name":"Svenska","default":false,"active":true,"hidden":false,"sortOrder":55,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":27,"locale":"th_TH","hrefLang":"th","code":"th","countryCode":"th","name":"\u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22","default":false,"active":true,"hidden":false,"sortOrder":56,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":28,"locale":"tr_TR","hrefLang":"tr","code":"tr","countryCode":"tr","name":"T\u00fcrk\u00e7e","default":false,"active":true,"hidden":false,"sortOrder":57,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":29,"locale":"uk_UA","hrefLang":"uk","code":"uk","countryCode":"ua","name":"\u0423\u043a\u0440\u0430\u0457\u0301\u043d\u0441\u044c\u043a\u0430","default":false,"active":true,"hidden":false,"sortOrder":58,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":84,"locale":"uz_UZ","hrefLang":"uz","code":"uz","countryCode":"uz","name":"O'zbek","default":false,"active":true,"hidden":false,"sortOrder":60,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":30,"locale":"vi_VN","hrefLang":"vi","code":"vi","countryCode":"vn","name":"Ti\u1ebfng Vi\u1ec7t","default":false,"active":true,"hidden":false,"sortOrder":61,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":64,"locale":"tl_PH","hrefLang":"tl-ph","code":"tl","countryCode":"ph","name":"Wikang Tagalog","default":false,"active":true,"hidden":false,"sortOrder":62,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":31,"locale":"zh_HK","hrefLang":"zh-hk","code":"zh","countryCode":"hk","name":"\u7e41\u9ad4","default":false,"active":true,"hidden":false,"sortOrder":63,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":47,"locale":"zh_CN","hrefLang":"zh-cn","code":"zh3","countryCode":"cn","name":"\u7b80\u4f53","default":false,"active":true,"hidden":false,"sortOrder":65,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":55,"locale":"bs_BA","hrefLang":"bs","code":"bs","countryCode":"ba","name":"Bosanski","default":false,"active":true,"hidden":true,"sortOrder":10,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":2,"locale":"es_SV","hrefLang":"es-sv","code":"esc","countryCode":"sv","name":"Castellano","default":false,"active":true,"hidden":true,"sortOrder":11,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":56,"locale":"sr_ME","hrefLang":"sr-me","code":"me","countryCode":"me","name":"Crnogorski","default":false,"active":false,"hidden":true,"sortOrder":14,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":68,"locale":"de_AT","hrefLang":"de-at","code":"de2","countryCode":"at","name":"\u00d6sterreichisches Deutsch","default":false,"active":false,"hidden":true,"sortOrder":18,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":80,"locale":"ht_HT","hrefLang":"ht","code":"ht","countryCode":"ht","name":"krey\u00f2l ayisyen","default":false,"active":false,"hidden":true,"sortOrder":29,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":88,"locale":"km_KH","hrefLang":"km","code":"km","countryCode":"kh","name":"\u1797\u17b6\u179f\u17b6\u1781\u17d2\u1798\u17c2\u179a","default":false,"active":true,"hidden":true,"sortOrder":34,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":92,"locale":"ar_SA","hrefLang":"ar-sa","code":"ar2","countryCode":"sa","name":"(\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0644\u0633\u0639\u0648\u062f\u064a\u0629","default":false,"active":false,"hidden":true,"sortOrder":3,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":38,"locale":"kk_KZ","hrefLang":"kk","code":"kk","countryCode":"kz","name":"\u049a\u0430\u0437\u0430\u049b","default":false,"active":true,"hidden":true,"sortOrder":33,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":50,"locale":"gl_GL","hrefLang":"gl","code":"gl","countryCode":"gl","name":"Galicia","default":false,"active":false,"hidden":true,"sortOrder":25,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":51,"locale":"eu_EU","hrefLang":"eu","code":"eu","countryCode":"eu","name":"Euskara","default":false,"active":false,"hidden":true,"sortOrder":23,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":53,"locale":"cy_GB","hrefLang":"cy","code":"cy","countryCode":"gb","name":"Cymraeg","default":false,"active":false,"hidden":true,"sortOrder":15,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":44,"locale":"ca_CT","hrefLang":"ca","code":"ca","countryCode":"ct","name":"Catal\u00e1n","default":false,"active":false,"hidden":true,"sortOrder":12,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":46,"locale":"zh_TW","hrefLang":"zh-tw","code":"zh2","countryCode":"tw","name":"\u7e41\u9ad4","default":false,"active":false,"hidden":true,"sortOrder":64,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":43,"locale":"hy_AM","hrefLang":"hy","code":"hy","countryCode":"am","name":"\u0540\u0561\u0575\u0565\u0580\u0565\u0576","default":false,"active":false,"hidden":true,"sortOrder":5,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":76,"locale":"ur_PK","hrefLang":"ur","code":"ur","countryCode":"pk","name":"\u0627\u0631\u062f\u0648","default":false,"active":false,"hidden":true,"sortOrder":59,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":39,"locale":"sq_AL","hrefLang":"sq","code":"sq","countryCode":"al","name":"Shqiptar","default":false,"active":false,"hidden":true,"sortOrder":52,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"},{"id":42,"locale":"af_ZA","hrefLang":"af","code":"af","countryCode":"za","name":"Afrikaans","default":false,"active":false,"hidden":true,"sortOrder":1,"timeCreated":"2019-03-22 11:03:42","timeModified":"2019-03-22 11:03:42"}];
		wb_builder.rtlLanguages = {"ar":true,"he":true,"fa":true};
		wb_builder.premiumButtonType = "";
		
		
		wb_builder.isB2CFree = false;
		wb_builder.formsAllowed = true;
wb_builder.autoBackupsEnable = false;
wb_builder.autoBackupsSavingInterval = 600;
wb_builder.allowDemoBackup = false;	
		wb_builder.we = false;
		wb_builder.enableForcedHttpsPort = false;
		wb_builder.publishOnLoad = false;
		wb_builder.mapsConfig = {"address":"38.733160, -9.144645","ll":"38.733160, -9.144645","daumMapsApiKey":null,"naverMapsApiKey":null,"googleMapsApiKey":"AIzaSyChpsOrBxEG_GeV-KIABgsxtIZ-IXneudg","googleMapsClientApiKey":null,"bingMapsApiKey":"ApYgKMTwiqvCv6Efb4k39laozs9DbbRYXIl9UwwF0YJGsowPfC89FOSa0730FfgT","yandexMapsApiKey":null};
		wb_builder.instagramConfig = {"clientId":"65a7c609924f4c918d0d8081fca3aa95","redirectUrl":"https:\/\/apps-api.xyz\/instagram\/"};
		wb_builder.sessUniqKey = "249564324";
		wb_builder.translateStoreItems = false;
		wb_builder.addElements([], true);
		wb_builder.maxUploadFileSize = 104857600;
		wb_builder.maxUploadImageFileSize = 3145728;
		wb_builder.maxUploadImageSize = 9437184;
		wb_builder.maxUploadBackupFileSize = "512 MB";
		wb_builder.maxUploadBackupFileSizeInt = 536870912;
		wb_builder.predefinedElementStyles = [];
		wb_builder.whiteLabel = {"builder":true,"title":"Chrome SitePro","logo":"https:\/\/site.pro\/assets\/logos\/22cd1e250042f27126d0ce1b101a3211.png"};
wb_builder.ecwidConfig = [];
wb_builder.helpScenario = null;

		CKEDITOR.timestamp = 123456897;
		CKEDITOR.config.language = "pt";
		wb_builder.pluginGroups = {"wb-group-standard":{"id":"wb-group-standard","icon":"ico-tb-text","borderless":false,"name":"Padr\u00e3o"},"wb-group-additional":{"id":"wb-group-additional","icon":"ico-tb-shape","borderless":false,"name":"Adicional"},"wb-group-complex":{"id":"wb-group-complex","icon":"ico-tb-blocks","name":"Conjunto","collapsable":false},"wb-group-advanced":{"id":"wb-group-advanced","icon":"icon-wb-advanced","name":"Avan\u00e7ado"},"wb-group-social":{"id":"wb-group-social","icon":"icon-wb-social","name":"Social"},"wb-group-commerce":{"id":"wb-group-commerce","icon":"icon-wb-commerce","borderless":true,"name":"E-commerce"},"wb-group-maps":{"id":"wb-group-maps","icon":"icon-wb-maps","borderless":false,"name":"Mapas"},"wb-group-new":{"id":"wb-group-new","icon":"ico-tb-reset","borderless":false,"name":"Novo"},"wb-group-dev":{"id":"wb-group-dev","icon":"icon-wb-advanced","name":"Dev"}};
wb_builder.enableAutoLayout = true;
wb_builder.demoConfig = {"useRegForm":false,"useRemoteRegForm":false,"inlineRemoteForm":false,"remoteData":null,"useLoginForm":false,"loginRegApiUrl":"","loginRegMsg":"","hidePublishSubMenu":false,"bannerImageUrl":"","loginHash":"37462a07"};
var WB_IMPORT_URL = "http:\/\/sitepro4.mychrome.pt\/pt-BR\/import\/begin\/";
var WB_IMPORT_STATUS_URL = "http:\/\/sitepro4.mychrome.pt\/pt-BR\/import\/get-status\/";
wb_builder.hideImport = false;
wb_builder.enableImport = true;
wb_builder.websiteImportStatus = null;
wb_builder.pluginData = {"extReferenceId":null};
wb_builder.userType = "external";
wb_builder.maxMenuItems = 0;
wb_builder.availableElements = {"TextArea":true,"Picture":true,"Gallery":true,"Youtube":true,"GoogleMaps":true,"LinkExchangeBadge":true,"ZyroBadge":true,"Shape":true,"Line":true,"Button":true,"Form":true,"Menu":true,"Languages":true,"Blocks":true,"FacebookFans":true,"FacebookLike":true,"BookmarksShare":true,"vkontakte_community":true,"vkontakte_like":true,"Twitter":true,"odnoklassniki":true,"odnoklassniki_share":true,"FlickrGallery":true,"facebook_comment":true,"pinterest":true,"instagram":true,"SkypeImOnline":true,"MusicPlayer":true,"Banner":true,"GoogleAdSense":true,"google_calendar":true,"CustomHtml":true,"Table":true,"vimeo":true,"youku":true,"zopim":true,"olark":true,"tawkto":true,"effect":true,"Store":true,"StoreCart":true,"BuyNow":true,"webmoney_button":true,"webmoney_widget":true,"skrill":true,"alipay":true,"pagseguro":true,"ecwid":true,"mercado":true,"2checkout":true,"stripe":true,"braintree":true,"bank_transfer":true,"cash_on_delivery":true,"yandex_maps":true,"bing_maps":true,"baidu_maps":true,"daum_maps":true,"naver_maps":true};
require(['ElementRegister'], function(ElementRegister) { ElementRegister.registerClassAll({"TextArea":{"id":"TextArea","icon":"ico-tb-text","name":"Texto","active":true},"Picture":{"id":"Picture","icon":"ico-tb-picture","name":"Imagem","active":true},"Table":{"id":"Table","icon":"ico-tb-table","name":"Tabela","active":true},"Gallery":{"id":"Gallery","icon":"ico-tb-gallery","name":"Galeria","active":true},"Youtube":{"id":"Youtube","icon":"ico-tb-youtube","name":"YouTube","active":true},"GoogleMaps":{"id":"GoogleMaps","icon":"ico-tb-google-maps","name":"Mapas","active":true},"Shape":{"id":"Shape","icon":"ico-tb-shape","name":"Forma","active":true},"Line":{"id":"Line","icon":"ico-tb-line","name":"Linha","active":true},"Button":{"id":"Button","icon":"ico-tb-button","name":"Bot\u00e3o","active":true},"Form":{"id":"Form","icon":"ico-tb-form","name":"Formul\u00e1rio","active":true},"Menu":{"id":"Menu","icon":"ico-tb-menu","name":"Menu","active":true},"Languages":{"id":"Languages","icon":"ico-tb-lang","name":"Idiomas","active":true},"Blocks":{"id":"Blocks","icon":"ico-tb-blocks","name":"Blocos","active":true},"Store":{"id":"Store","icon":"ico-tb-store","name":"Loja","active":true},"StoreCart":{"id":"StoreCart","icon":"ico-tb-store-cart","name":"Carrinho de compras","active":true},"BuyNow":{"id":"BuyNow","icon":"ico-tb-buynow","name":"Bot\u00e3o Paypal","active":true},"MusicPlayer":{"id":"MusicPlayer","icon":"ico-tb-musicplayer","name":"M\u00fasica","active":true},"Banner":{"id":"Banner","icon":"ico-tb-banner","name":"Banner","active":true},"Flash":{"id":"Flash","icon":"ico-tb-flash","name":"Flash","borderless":true,"active":false},"GoogleAdSense":{"id":"GoogleAdSense","icon":"ico-tb-google-adsense","name":"An\u00fancio","active":true},"CustomHtml":{"id":"CustomHtml","icon":"ico-tb-html","name":"HTML","active":true},"FacebookFans":{"id":"FacebookFans","icon":"ico-tb-facebook-fans","name":"F\u00e3s","borderless":true,"active":true},"FacebookLike":{"id":"FacebookLike","icon":"ico-tb-facebook-like","name":"Curtir","borderless":true,"active":true},"BookmarksShare":{"id":"BookmarksShare","icon":"ico-tb-share","name":"Compartilhar","borderless":true,"active":true},"SkypeImOnline":{"id":"SkypeImOnline","icon":"ico-tb-skype-imonline","name":"Skype","borderless":true,"active":true},"Twitter":{"id":"Twitter","icon":"ico-tb-twitter","name":"Twitter","borderless":true,"active":true},"FlickrGallery":{"id":"FlickrGallery","icon":"ico-tb-flickr-gallery","name":"Flickr","borderless":true,"active":true}}); });
wb_builder.pluginToolbar = [{"id":"wb-group-standard","items":["TextArea","Picture","Gallery","Youtube","GoogleMaps"]},{"id":"wb-group-additional","items":["Shape","Line","Button","Form","Menu","Languages"]},{"id":"wb-group-complex","items":["Blocks"]},{"id":"wb-group-social","items":["FacebookFans","FacebookLike","BookmarksShare","vkontakte_community","vkontakte_like","Twitter","odnoklassniki","odnoklassniki_share","FlickrGallery","facebook_comment","pinterest","instagram"]},{"id":"wb-group-advanced","items":["SkypeImOnline","MusicPlayer","Banner","GoogleAdSense","google_calendar","CustomHtml","Table","vimeo","youku","zopim","olark","tawkto","effect"]},{"id":"wb-group-commerce","items":["Store","StoreCart","BuyNow","webmoney_button","webmoney_widget","skrill","alipay","pagseguro","ecwid","mercado","2checkout","stripe","braintree","bank_transfer","cash_on_delivery"]},{"id":"wb-group-maps","items":["yandex_maps","bing_maps","baidu_maps","daum_maps","naver_maps"]}];
wb_builder._loadPlugins = function() {
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"paysera","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/paysera\/main.png";
PluginWrapper._config.template = "<form method=\"POST\" data-gateway-id=\"Paysera\" action=\"https:\/\/www.paysera.com\/pay\/\"{{^content.store}} target=\"_blank\"{{\/content.store}}>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" data-multiplier=\"100\" data-fixed-decimal=\"0\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"hidden\" name=\"orderid\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"accepturl\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"cancelurl\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"callbackurl\" value=\"{callbackUrl}\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n    <button type=\"submit\"\r\n\t\t\tstyle=\"background: url({{^isPublished}}plugins\/paysera\/site\/{{\/isPublished}}gallery_gen\/paysera\/paysera.png) center center no-repeat;\r\n\t\t\t\t   background-size: contain;\r\n\t\t\t\t   vertical-align: middle;\r\n\t\t\t       border: none;\r\n\t\t\t       width: {{#width}}{{width}}px;{{\/width}}{{^width}}140px;{{\/width}}\r\n\t\t\t       height: {{#height}}{{height}}px;{{\/height}}{{^width}}30px;{{\/width}}\"><\/button>\r\n<\/form>\r\n";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/paysera/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'Paysera',
	id: 'paysera',
	pageUrl: 'https://www.paysera.com/',
	keyField: __('Project ID'),
	keyFieldId: 'projectid',
	keyField2: __('Password'),
	keyField2Id: 'password',
	keyField3Id: 'test',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [6,6,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Project ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Password'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'paytext',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['projectid', 'password', 'test']
});
PluginWrapper.registerPlugin('paysera', {
	name: 'Paysera',
	element: {
		minSize: {width: 140, height: 30},
		defaultSize: {width: 200, height: 43},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Project ID'), helpText: __('Unique project number')},
							{type: 'TextField', id: 'projectid'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Password')},
							{type: 'TextField', id: 'password'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', html: '&nbsp;'},
							{type: 'CheckBox', id: 'test', label: __('Test mode'), css: {marginTop: 5},
								helpText: __('For testing purpose without real payments'),
								helpPlacement: 'top'
							}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name'), helpText:__('Necessary to include the following variables [order_nr] - payment number, [site_name] - site name')},
							{type: 'TextField', id: 'paytext'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText:__('Amount to be transferred')},
							{type: 'TextField', id: 'amount'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: '#AED', name: 'AED', value: 'AED'},
								{id: '#ALL', name: 'ALL', value: 'ALL'},
								{id: '#AMD', name: 'AMD', value: 'AMD'},
								{id: '#ARS', name: 'ARS', value: 'ARS'},
								{id: '#AUD', name: 'AUD', value: 'AUD'},
								{id: '#AZN', name: 'AZN', value: 'AZN'},
								{id: '#BAM', name: 'BAM', value: 'BAM'},
								{id: '#BDT', name: 'BDT', value: 'BDT'},
								{id: '#BGN', name: 'BGN', value: 'BGN'},
								{id: '#BHD', name: 'BHD', value: 'BHD'},
								{id: '#BOB', name: 'BOB', value: 'BOB'},
								{id: '#BRL', name: 'BRL', value: 'BRL'},
								{id: '#BYN', name: 'BYN', value: 'BYN'},
								{id: '#CAD', name: 'CAD', value: 'CAD'},
								{id: '#CHF', name: 'CHF', value: 'CHF'},
								{id: '#CLP', name: 'CLP', value: 'CLP'},
								{id: '#CNY', name: 'CNY', value: 'CNY'},
								{id: '#COP', name: 'COP', value: 'COP'},
								{id: '#CRC', name: 'CRC', value: 'CRC'},
								{id: '#CVE', name: 'CVE', value: 'CVE'},
								{id: '#CZK', name: 'CZK', value: 'CZK'},
								{id: '#DKK', name: 'DKK', value: 'DKK'},
								{id: '#DOP', name: 'DOP', value: 'DOP'},
								{id: '#DZD', name: 'DZD', value: 'DZD'},
								{id: '#EGP', name: 'EGP', value: 'EGP'},
								{id: '#ETB', name: 'ETB', value: 'ETB'},
								{id: '#EUR', name: 'EUR', value: 'EUR'},
								{id: '#GBP', name: 'GBP', value: 'GBP'},
								{id: '#GEL', name: 'GEL', value: 'GEL'},
								{id: '#GNF', name: 'GNF', value: 'GNF'},
								{id: '#GTQ', name: 'GTQ', value: 'GTQ'},
								{id: '#HKD', name: 'HKD', value: 'HKD'},
								{id: '#HNL', name: 'HNL', value: 'HNL'},
								{id: '#HRK', name: 'HRK', value: 'HRK'},
								{id: '#HUF', name: 'HUF', value: 'HUF'},
								{id: '#IDR', name: 'IDR', value: 'IDR'},
								{id: '#ILS', name: 'ILS', value: 'ILS'},
								{id: '#INR', name: 'INR', value: 'INR'},
								{id: '#IQD', name: 'IQD', value: 'IQD'},
								{id: '#IRR', name: 'IRR', value: 'IRR'},
								{id: '#ISK', name: 'ISK', value: 'ISK'},
								{id: '#JOD', name: 'JOD', value: 'JOD'},
								{id: '#JPY', name: 'JPY', value: 'JPY'},
								{id: '#KES', name: 'KES', value: 'KES'},
								{id: '#KGS', name: 'KGS', value: 'KGS'},
								{id: '#KRW', name: 'KRW', value: 'KRW'},
								{id: '#KWD', name: 'KWD', value: 'KWD'},
								{id: '#KZT', name: 'KZT', value: 'KZT'},
								{id: '#LBP', name: 'LBP', value: 'LBP'},
								{id: '#LKR', name: 'LKR', value: 'LKR'},
								{id: '#MAD', name: 'MAD', value: 'MAD'},
								{id: '#MDL', name: 'MDL', value: 'MDL'},
								{id: '#MGA', name: 'MGA', value: 'MGA'},
								{id: '#MKD', name: 'MKD', value: 'MKD'},
								{id: '#MNT', name: 'MNT', value: 'MNT'},
								{id: '#MXN', name: 'MXN', value: 'MXN'},
								{id: '#MYR', name: 'MYR', value: 'MYR'},
								{id: '#MZN', name: 'MZN', value: 'MZN'},
								{id: '#NGN', name: 'NGN', value: 'NGN'},
								{id: '#NIO', name: 'NIO', value: 'NIO'},
								{id: '#NOK', name: 'NOK', value: 'NOK'},
								{id: '#NZD', name: 'NZD', value: 'NZD'},
								{id: '#OMR', name: 'OMR', value: 'OMR'},
								{id: '#PEN', name: 'PEN', value: 'PEN'},
								{id: '#PHP', name: 'PHP', value: 'PHP'},
								{id: '#PKR', name: 'PKR', value: 'PKR'},
								{id: '#PLN', name: 'PLN', value: 'PLN'},
								{id: '#PYG', name: 'PYG', value: 'PYG'},
								{id: '#QAR', name: 'QAR', value: 'QAR'},
								{id: '#RON', name: 'RON', value: 'RON'},
								{id: '#RSD', name: 'RSD', value: 'RSD'},
								{id: '#RUB', name: 'RUB', value: 'RUB'},
								{id: '#SAR', name: 'SAR', value: 'SAR'},
								{id: '#SEK', name: 'SEK', value: 'SEK'},
								{id: '#SGD', name: 'SGD', value: 'SGD'},
								{id: '#SYP', name: 'SYP', value: 'SYP'},
								{id: '#THB', name: 'THB', value: 'THB'},
								{id: '#TJS', name: 'TJS', value: 'TJS'},
								{id: '#TND', name: 'TND', value: 'TND'},
								{id: '#TRY', name: 'TRY', value: 'TRY'},
								{id: '#TWD', name: 'TWD', value: 'TWD'},
								{id: '#TZS', name: 'TZS', value: 'TZS'},
								{id: '#UAH', name: 'UAH', value: 'UAH'},
								{id: '#UGX', name: 'UGX', value: 'UGX'},
								{id: '#USD', name: 'USD', value: 'USD'},
								{id: '#UYU', name: 'UYU', value: 'UYU'},
								{id: '#UZS', name: 'UZS', value: 'UZS'},
								{id: '#VEF', name: 'VEF', value: 'VEF'},
								{id: '#VND', name: 'VND', value: 'VND'},
								{id: '#XAF', name: 'XAF', value: 'XAF'},
								{id: '#XOF', name: 'XOF', value: 'XOF'},
								{id: '#YER', name: 'YER', value: 'YER'},
								{id: '#ZAR', name: 'ZAR', value: 'ZAR'}
							]}
						]}
					]}
				]}
			]}
		]
	},
	resizeAction: function (data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function () {
				self.resizeTimeout = null;
				self.updateElement();
			}, 1000);
		}
	},
	openAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.projectid.setText(data.content.projectid);
		fields.password.setText(data.content.password);
		fields.paytext.setText(data.content.paytext);
		fields.amount.setText(data.content.amount);
		fields.test.setValue(data.content.test ? true : false);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.projectid = fields.projectid.getText();
		data.content.password = fields.password.getText();
		data.content.paytext = fields.paytext.getText();
		data.content.amount = fields.amount.getText();
		data.content.test = fields.test.getValue();
	},
	loadAction: function (data) {
		if (!data.content.projectid)
			data.content.projectid = '';
		if (!data.content.password)
			data.content.password = '';
		if (!data.content.paytext)
			data.content.paytext = 'Payment for goods made to order [order_nr] in website [site_name]';
		if (!data.content.amount)
			data.content.amount = '1';
		if (!data.content.currency)
			data.content.currency = 'EUR';
		if (!data.content.test) data.content.test = false;
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"gplus_badge","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/gplus_badge\/main.png";
PluginWrapper._config.template = "<div id=\"{{id}}_gp_comunity\"><\/div>\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\">\r\n\twindow.___gcfg = {parsetags: 'explicit'};\r\n<\/script>\r\n<script src=\"https:\/\/apis.google.com\/js\/platform.js\" type=\"text\/javascript\"><\/script>\r\n{{\/isPublished}}\r\n<script type=\"text\/javascript\">\r\n\tif (window.gapi) {\r\n\t\twindow.gapi.{{{content.btype}}}.render('{{id}}_gp_comunity', {\r\n\t\t\tlayout: '{{content.mode}}',\r\n\t\t\tshowcoverphoto: '{{content.cover}}',\r\n\t\t\tshowtagline: '{{content.tagline}}',\r\n\t\t\ttheme: '{{content.theme}}',\r\n\t\t\twidth: '{{width}}',\r\n\t\t\thref: 'https:\/\/plus.google.com\/{{{content.community}}}{{content.profileId}}'\r\n\t\t});\r\n\t}\r\n<\/script>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
PluginWrapper.registerPlugin('gplus_badge', {
	name: 'Badge',
	noButton: true,
	element: {
		minSize: {width: 250, height: 100},
		defaultSize: {width: 400, height: 100},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('ID'),
						helpText: __('Please type profile, page or community ID and check respective badge type')
					},
					{type: 'TextField', id: 'profileId'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Badge type')},
						{type: 'RadioBox', id: 'btype0', label: __('Profile badge'), group: 'btype'},
						{type: 'RadioBox', id: 'btype1', label: __('Google+ page badge'), group: 'btype'},
						{type: 'RadioBox', id: 'btype2', label: __('Community badge'), group: 'btype'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Layout'), helpText: __('Orientation of the badge')},
						{type: 'RadioBox', id: 'mode0', label: __('Landscape'), group: 'mode'},
						{type: 'RadioBox', id: 'mode1', label: __('Portrait'), group: 'mode'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Theme'),
							helpText: __('Color theme of the badge. Light for light pages and dark theme for dark pages')
						},
						{type: 'RadioBox', id: 'light', label: __('Light'), group: 'theme'},
						{type: 'RadioBox', id: 'dark', label: __('Dark'), group: 'theme'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, columnWeights: [4, 8], children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Cover photo'), helpText: __('Show cover photo if exists')},
						{type: 'RadioBox', id: 'cover0', label: __('Yes'), group: 'cover'},
						{type: 'RadioBox', id: 'cover1', label: __('No'), group: 'cover'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Tag line'), helpText: __('Show tag line if exists')},
						{type: 'RadioBox', id: 'tagline0', label: __('Yes'), group: 'tagline'},
						{type: 'RadioBox', id: 'tagline1', label: __('No'), group: 'tagline'}
					]}
				]}
			]}
		]
	},

	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('https://apis.google.com/js/platform.js', function() {
					self.scriptReady = true;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst);
					}
				});
			}
		}
	},
	resizeTimeout: null,

	resizeAction: function(data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function() {
				self.resizeTimeout = null;
				self.updateElement();
			}, 2000);
		}
	},
	openAction: function(fields, data, elem) {
		fields.profileId.setText(data.content.profileId);
		
		fields.mode0.setValue(data.content.mode === 'landscape');
		fields.mode1.setValue(data.content.mode === 'portrait');

		fields.btype0.setValue(data.content.btype === 'person');
		fields.btype1.setValue(data.content.btype === 'page');
		fields.btype2.setValue(data.content.btype === 'community');

		fields.cover0.setValue(data.content.cover === 'true');
		fields.cover1.setValue(data.content.cover === 'false');
		
		fields.tagline0.setValue(data.content.tagline === 'true');
		fields.tagline1.setValue(data.content.tagline === 'false');

		fields.light.setValue(data.content.theme === 'light');
		fields.dark.setValue(data.content.theme === 'dark');
	},
	applyAction: function(fields, data, elem) {
		data.content.profileId = fields.profileId.getText();
		if (fields.mode0.getValue()) data.content.mode = 'landscape';
		if (fields.mode1.getValue()) data.content.mode = 'portrait';

		if (fields.btype0.getValue()) data.content.btype = 'person';
		if (fields.btype1.getValue()) data.content.btype = 'page';
		if (fields.btype2.getValue()) data.content.btype = 'community';
		if (data.content.btype === 'community') {
			data.content.community = 'communities/';
		} else {
			data.content.community = '';
		}
		if (fields.light.getValue()) data.content.theme = 'light';
		if (fields.dark.getValue()) data.content.theme = 'dark';

		if (fields.cover0.getValue()) data.content.cover = 'true';
		if (fields.cover1.getValue()) data.content.cover = 'false';

		if (fields.tagline0.getValue()) data.content.tagline = 'true';
		if (fields.tagline1.getValue()) data.content.tagline = 'false';
		if (data.content.mode === 'portrait') {
			if (data.content.cover === 'true') {
				this.setSize('', 400);
			} else {
				this.setSize('', 245);
			}
		}
		if (data.content.mode === 'landscape') {
			this.setSize('', 100);
		}
	},
	loadAction: function(data) {
		if (!data.content.mode) data.content.mode = 'landscape';
		if (!data.content.btype) data.content.btype = 'page';
		if (!data.content.theme) data.content.theme = 'light';
		if (!data.content.cover) data.content.cover = 'false';
		if (!data.content.tagline) data.content.tagline = 'false';

		if (!data.content.profileId) data.content.profileId = '+googleplus';
		if (data.content.btype === 'community') {
			data.content.community = 'communities/';
		} else {
			data.content.community = '';
		}
	},
	loadedAction: function(data, elem) {
		window.___gcfg = {parsetags: 'explicit'};
		this.pluginScoped.addListener(this, function() {
			window.gapi[data.content.btype].render(data.id + '_gp_comunity', {
				layout: data.content.mode,
				showcoverphoto: data.content.cover,
				showtagline: data.content.tagline,
				theme: data.content.theme,
				width: data.width,
				href: 'https://plus.google.com/' + data.content.community + data.content.profileId
			});
		});
	},

	saveAction: function(data, elem) {
		// TODO: save data
	}

});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"vkontakte_like","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/vkontakte_like\/main.png";
PluginWrapper._config.template = "{{#isPublished}}\r\n\t{{#isPreview}}\r\n\t\t{{{content.previewHtml}}}\r\n\t{{\/isPreview}}\r\n\t{{^isPreview}}\r\n\t\t{{#firstOnPage}}\r\n<script type=\"text\/javascript\" src=\"\/\/vk.com\/js\/api\/openapi.js?116\"><\/script>\r\n<script type=\"text\/javascript\"> VK.init({apiId: '{{content.appId}}', onlyWidgets: true}); <\/script>\r\n\t\t{{\/firstOnPage}}\r\n<div id=\"{{id}}_vk_like\" class=\"vk_like\"><\/div>\r\n<script type=\"text\/javascript\">\r\n\tif (window.VK) VK.Widgets.Like('{{id}}_vk_like', {type: '{{content.type}}', verb: {{content.verb}}, height: {{content.height}}});\r\n<\/script>\r\n\t{{\/isPreview}}\r\n{{\/isPublished}}\r\n{{^isPublished}}\r\n<!-- dynamic -->\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;

PluginWrapper.registerPlugin('vkontakte_like', {
	name: 'Like',
	noButton: true,
	element: {
		minSize: {width: 20, height: 20},
		defaultSize: {width: 110, height: 30},
		renderOnce: true,
		resizable: true
	},
	propertyDialog: {
		//size: {width: 500, height: 400},
		noScroll: true,
		tabs: [
			{name: 'General', children: [
				{type: 'VerticalLayout', children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('App ID'), helpText: __('Create app at %s').replace('%s', 'https://vk.com/apps?act=manage')},
						{type: 'TextField', id: 'appId', change: function(fields) {
							fields.__self.notifyHelpSystemPlayer('prop-appId-change');
						}}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Layout')},
							{type: 'RadioBox', id: 'typeButton', label: __('Button with mini counter'), group: 'bl', change: function(fields) {
								fields.__self.notifyHelpSystemPlayer('prop-typeButton-change');
							}},
							{type: 'RadioBox', id: 'typeFull', label: __('Button with text counter'), group: 'bl', change: function(fields) {
								fields.__self.notifyHelpSystemPlayer('prop-typeFull-change');
							}},
							{type: 'RadioBox', id: 'typeMini', label: __('Mini button'), group: 'bl', change: function(fields) {
								fields.__self.notifyHelpSystemPlayer('prop-typeMini-change');
							}},
							{type: 'RadioBox', id: 'typeVertical', label: __('Mini button with counter at the top'), group: 'bl', change: function(fields) {
								fields.__self.notifyHelpSystemPlayer('prop-typeVertical-change');
							}}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Height')},
							{type: 'DropdownBox', id: 'height', options: [
								{id: '#18', name: '18 px', value: 18},
								{id: '#20', name: '20 px', value: 20},
								{id: '#22', name: '22 px', value: 22},
								{id: '#24', name: '24 px', value: 24}
							], change: function(fields) {
								fields.__self.notifyHelpSystemPlayer('prop-height-change');
							}},
							{type: 'Label', text: __('Button Name'), css: {marginTop: 15}},
							{type: 'DropdownBox', id: 'verb', options: [
								{id: '#0', name: __('Like'), value: 0},
								{id: '#1', name: __('This is interesting'), value: 1}
							], change: function(fields) {
								fields.__self.notifyHelpSystemPlayer('prop-verb-change');
							}}
						]}
					]}
				]}
			]}
		]
	},
	
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('http://vk.com/js/api/openapi.js?116', function() {
					self.scriptReady = true;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst);
					}
				});
			}
		}
	},
	previewHelper: {
		parentElem: null,
		elem: null,
		btnElem: null,
		counterElem: null,
		textCounterElem: null,
		textElem: null,
		type: 'button',
		init: function(parent) {
			this.parentElem = parent;
			this.elem = $('<div>');
			this.btnElem = $('<div>').css({
				minWidth: '41px',
				background: '#5F83AA',
				border: 'none',
				borderRadius: '2px',
				margin: '0px',
				padding: '3px',
				fontWeight: 'bold',
				fontSize: '10px',
				lineHeight: '12px',
				fontFamily: 'tahoma,verdana,arial,sans-serif,Lucida Sans',
				color: '#ffffff',
				textAlign: 'center',
				whiteSpace: 'nowrap',
				float: 'left',
				clear: 'left'
			});
			this.counterElem = $('<div>').css({
				minWidth: '41px',
				background: '#ffffff',
				border: '1px solid #BBBFC4',
				borderRadius: '2px',
				margin: '0px 0px 8px 0px',
				padding: '2px',
				fontWeight: 'bold',
				fontSize: '10px',
				lineHeight: '12px',
				fontFamily: 'tahoma,verdana,arial,sans-serif,Lucida Sans',
				color: '#666C73',
				textAlign: 'center',
				whiteSpace: 'nowrap',
				float: 'left'
			});
			this.textCounterElem = $('<div>').css({
				padding: '2px 2px 2px 8px',
				fontWeight: 'normal',
				fontSize: '10px',
				lineHeight: '12px',
				fontFamily: 'tahoma,verdana,arial,sans-serif,Lucida Sans',
				color: '#000000',
				whiteSpace: 'nowrap',
				float: 'left'
			});
			this.textElem = $('<span>').css({
				fontWeight: 'normal',
				marginLeft: '4px',
				display: 'inline-block'
			});
			this.counterElem.text('123K');
			this.textCounterElem.html('<b>123456</b> people find this interesting');
			this.btnElem.text('VK');
			this.elem.append(this.counterElem).append(this.btnElem.append(this.textElem));
			this.parentElem.append(this.elem);
		},
		setType: function(type) {
			this.type = type;
			if (type === 'full') {
				this.counterElem.detach();
				this.textCounterElem.detach().appendTo(this.elem);
			} else if (type === 'mini') {
				this.textCounterElem.detach();
				this.counterElem.detach().appendTo(this.elem);
				this.counterElem.css({marginBottom: '0px', marginLeft: '8px'});
			} else if (type === 'vertical') {
				this.textCounterElem.detach();
				this.counterElem.detach().prependTo(this.elem);
				this.counterElem.css({marginBottom: '8px', marginLeft: '0px'});
			} else { // (type === 'button')
				this.textCounterElem.detach();
				this.counterElem.detach().appendTo(this.elem);
				this.counterElem.css({marginBottom: '0px', marginLeft: '8px'});
			}
		},
		setVerb: function(verb) {
			if (this.type === 'mini' || this.type === 'vertical') {
				this.textElem.html('<i class="icon-heart icon-white" style="color:#AFC1D5; margin-bottom: -1px; margin-top: -1px; vertical-align: top; display: inline-block;"></i>');
			} else {
				if (verb === 1) {
					this.textElem.text('This is interesting');
				} else {
					this.textElem.text('Like');
				}
			}
		},
		setHeight: function(height) {
			var fontSize, lineHeight, paddingTop, paddingBottom;
			if (height === 24) {
				fontSize = 11; lineHeight = 13; paddingTop = 4; paddingBottom = 5;
			} else if (height === 22) {
				fontSize = 11; lineHeight = 13; paddingTop = 3; paddingBottom = 4;
			} else if (height === 20) {
				fontSize = 10; lineHeight = 12; paddingTop = paddingBottom = 3;
			} else { // (height === 18)
				fontSize = 10; lineHeight = 12; paddingTop = paddingBottom = 2;
			}
			this.counterElem.css({fontSize: (fontSize + 'px'), lineHeight: (lineHeight + 'px'), paddingTop: (paddingTop + 'px'), paddingBottom: (paddingBottom + 'px')});
			this.textCounterElem.css({fontSize: (fontSize + 'px'), lineHeight: (lineHeight + 'px'), paddingTop: ((paddingTop + 1) + 'px'), paddingBottom: ((paddingBottom + 1) + 'px')});
			this.btnElem.css({fontSize: (fontSize + 'px'), lineHeight: (lineHeight + 'px'), paddingTop: ((paddingTop + 1) + 'px'), paddingBottom: ((paddingBottom + 1) + 'px')});
		}
	},
	
	openAction: function(fields, data, elem) {
		var itm;
		fields.__self = this;
		fields.appId.setText(data.content.appId);
		fields.typeButton.setValue(data.content.type === 'button');
		fields.typeFull.setValue(data.content.type === 'full');
		fields.typeMini.setValue(data.content.type === 'mini');
		fields.typeVertical.setValue(data.content.type === 'vertical');
		itm = fields.height.getItemById('#' + data.content.height);
		fields.height.selectItem(itm);
		itm = fields.verb.getItemById('#' + data.content.verb);
		fields.verb.selectItem(itm);		
	},
	applyAction: function(fields, data, elem) {
		var itm;
		data.content.appId = fields.appId.getText();
		if (fields.typeButton.getValue()) data.content.type = 'button';
		if (fields.typeFull.getValue()) data.content.type = 'full';
		if (fields.typeMini.getValue()) data.content.type = 'mini';
		if (fields.typeVertical.getValue()) data.content.type = 'vertical';
		itm = fields.height.getSelectedItem();
		data.content.height = itm.getOriginal().value;
		itm = fields.verb.getSelectedItem();
		data.content.verb = itm.getOriginal().value;
		
		this.previewHelper.setType(data.content.type);
		this.previewHelper.setVerb(data.content.verb);
		this.previewHelper.setHeight(data.content.height);
		data.content.previewHtml = this.previewHelper.elem.html();
		var rwidth = this.previewHelper.btnElem.outerWidth(true) + ((data.content.type === 'vertical') ? 0 : ((data.content.type === 'full') ? this.previewHelper.textCounterElem.outerWidth(true) : this.previewHelper.counterElem.outerWidth(true))),
			rheight = (data.content.type === 'vertical') ? (data.content.height * 2 + 8) : data.content.height;
		
		this.setSize(rwidth, rheight);
	},
	loadAction: function(data) {
		if (!data.content.appId) data.content.appId = '';
		if (!data.content.type) data.content.type = 'button';
		if (!data.content.verb) data.content.verb = 0;
		if (!data.content.height) data.content.height = 22;
		if (!data.content.previewHtml) data.content.previewHtml = '';
	},
	loadedAction: function(data, elem) {
		this.previewHelper.init(elem);
		this.previewHelper.setType(data.content.type);
		this.previewHelper.setVerb(data.content.verb);
		this.previewHelper.setHeight(data.content.height);
		data.content.previewHtml = this.previewHelper.elem.html();
		/*this.pluginScoped.addListener(this, function() {
			window.VK.init({apiId: data.content.apiId, onlyWidgets: true});
			window.VK.Widgets.Like(data.id + '_vk_like', {type: data.content.type, verb: data.content.verb, height: data.content.height});
		});*/
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"webpay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/webpay\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Webpay\" action=\"https:\/\/{{#content.demo}}sandbox{{\/content.demo}}{{^content.demo}}payment{{\/content.demo}}.webpay.by\/\" method=\"post\"{{^content.store}} target=\"_blank\"{{\/content.store}} class=\"webpay\" style=\"width: 100%; height: 100%;\">\r\n    {{^content.store}}\r\n\t<input type=\"hidden\" name=\"*scart\" \/>\r\n    <input type=\"hidden\" name=\"wsb_version\" value=\"2\" \/>\r\n    <input type=\"hidden\" name=\"wsb_storeid\" value=\"{{content.wsb_storeid}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_order_num\" value=\"{{content.wsb_order_num}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_test\" value=\"0\" \/>\r\n    <input type=\"hidden\" name=\"wsb_currency_id\" value=\"{{content.wsb_currency_id}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_seed\" value=\"{{content.wsb_seed}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_invoice_item_name[0]\" value=\"{{content.wsb_invoice_item_name}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_invoice_item_quantity[0]\" value=\"1\" \/>\r\n    <input type=\"hidden\" name=\"wsb_invoice_item_price[0]\" value=\"{{content.wsb_invoice_item_price}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_total\" value=\"{{content.wsb_total}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_tax\" value=\"{{content.wsb_tax}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_shipping_name\" value=\"{{content.wsb_shipping_name}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_shipping_price\" value=\"{{content.wsb_shipping_price}}\" \/>\r\n    <input type=\"hidden\" name=\"wsb_store\" value=\"{{content.wsb_store}}\" \/>\r\n    <input type=\"submit\" class=\"btn btn-info\" value=\"{{content.label}}\"\r\n           title=\"{{content.label}}\"\r\n           style=\"width: 100%; height: 100%;\r\n           {{#content.border}}border: {{content.border.style}} {{content.border.weight}}px {{content.border.color}};{{\/content.border}}\r\n           {{#content.background}}background: {{content.background}};{{\/content.background}}\r\n           padding: 6px 10px;\r\n           {{#content.fontColor}}color: {{content.fontColor}};{{\/content.fontColor}}\r\n           {{#content.fontSize}}font-size: {{content.fontSize}}px;{{\/content.fontSize}}\r\n           {{#content.fontFamily}}font-family: {{content.fontFamily}};{{\/content.fontFamily}}\"\r\n    \/>\r\n    {{\/content.store}}\r\n\t{{#content.demo}}\r\n\t<input type=\"hidden\" name=\"wsb_test\" value=\"1\" \/>\r\n\t{{\/content.demo}}\r\n    {{#content.store}}\r\n    <input type=\"hidden\" name=\"total\" value=\"{{content.wsb_invoice_item_price}}\" \/>\r\n    <input type=\"hidden\" name=\"currency_id\" value=\"{{content.wsb_currency_id}}\" \/>\r\n    <input type=\"hidden\" name=\"order_num\" value=\"{transactionId}\" \/>\r\n    <input type=\"hidden\" name=\"return_url\" value=\"{returnUrl}\" \/>\r\n    <input type=\"hidden\" name=\"cancel_return_url\" value=\"{cancelUrl}\" \/>\r\n    <input type=\"hidden\" name=\"notify_url\" value=\"{callbackUrl}\" \/>\r\n    <input type=\"hidden\" name=\"store\" value=\"Store\" \/>\r\n    <input type=\"submit\" class=\"btn btn-info\" value=\"{{content.label}}\" title=\"{{content.label}}\"\r\n\t\t   style=\"width: 160px;\r\n           height: 40px;\r\n           border: solid 2px #fbe116;\r\n           background: #fbe116;\r\n           padding: 6px 10px;\r\n           color: #000;\r\n           font-size: 15px;\r\n           font-family: Trebuchet MS,sans-serif;\" \/>\r\n    {{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'Webpay',
	id: 'webpay',
	pageUrl: 'https://webpay.by/',
	keyField: __('Store identifier'),
	keyFieldId: 'wsb_storeid',
	keyField2: __('Secret Key'),
	keyField2Id: 'secret_key',
	keyField3: {type: 'CheckBox', label: __('Test mode'), css: {padding: 7}},
	keyField3Id: 'demo',
	titleFieldId: 'label',
	nameFieldId: 'wsb_invoice_item_name',
	priceFieldId: 'wsb_invoice_item_price',
	currencyFieldId: 'wsb_currency_id',
	globalVars: ['wsb_storeid', 'secret_key']
});
PluginWrapper.registerPlugin('webpay', {
	name: 'Webpay',
	element: {
		minSize: {width: 100, height: 30},
		defaultSize: {width: 160, height: 40},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', css: {marginTop: 15}, columnWeights: [6, 6], children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Store identifier'), helpText: __('This identifier is created during registration in WebPay and is sent via email')},
						{type: 'TextField', id: 'wsb_storeid'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Secret Key'), helpText: __('The value of the Secret Key field in your billing account settings')},
						{type: 'TextField', id: 'secret_key'}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Item Name'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'wsb_invoice_item_name'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred')},
						{type: 'TextField', id: 'wsb_invoice_item_price'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'wsb_currency_id', options: [
							{id: '#BYN', name: 'BYN', value: 'BYN'},
							{id: '#USD', name: 'USD', value: 'USD'},
							{id: '#EUR', name: 'EUR', value: 'EUR'},
							{id: '#RUB', name: 'RUB', value: 'RUB'}
						]}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [4, 4, 4], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Delivery method')},
							{type: 'TextField', id: 'wsb_shipping_name'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Shipping'), helpText: __('The value of this field is the amount of delivery added to the total order')},
							{type: 'TextField', id: 'wsb_shipping_price'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Tax amount'), helpText: __('The value of this field is the tax amount added to the total order amount.')},
							{type: 'TextField', id: 'wsb_tax'}
						]}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label'), helpText: __('Label name on submit button')},
							{type: 'TextField', id: 'label'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Store name'), helpText: __('The store name which will be displayed on the payment form. Maximum field length is 64 characters.')},
							{type: 'TextField', id: 'wsb_store'}
						]}
					]}
				]},
				{type: 'FlowLayout', spacing: 15, css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'background'}
					]},
					{type: 'VerticalLayout', css: {width: 150}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'fontFamily', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'fontSize'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'fontColor', noTransparent: true}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'right'});
					}}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		fields.label.setText(data.content.label);
		fields.secret_key.setText(data.content.secret_key);
		fields.wsb_storeid.setText(data.content.wsb_storeid);
		fields.wsb_store.setText(data.content.wsb_store);
		fields.wsb_invoice_item_name.setText(data.content.wsb_invoice_item_name);
		fields.wsb_invoice_item_price.setText(data.content.wsb_invoice_item_price);
		fields.wsb_tax.setText(data.content.wsb_tax);
		fields.wsb_shipping_name.setText(data.content.wsb_shipping_name);
		fields.wsb_shipping_price.setText(data.content.wsb_shipping_price);
		var itm;
		itm = fields.wsb_currency_id.getItemById('#' + data.content.wsb_currency_id);
		fields.wsb_currency_id.selectItem(itm);
		fields.border.setValue(data.content.border);
		fields.background.setValue(data.content.background);
		fields.fontFamily.setValue(data.content.fontFamily);
		fields.fontSize.setValue(data.content.fontSize);
		fields.fontColor.setValue(data.content.fontColor);
		fields.demo.setValue(data.content.demo);
	},
	applyAction: function (fields, data, elem) {
		data.content.label = fields.label.getText();
		data.content.secret_key = fields.secret_key.getText();
		data.content.wsb_storeid = fields.wsb_storeid.getText();
		data.content.wsb_store = fields.wsb_store.getText();
		data.content.wsb_invoice_item_name = fields.wsb_invoice_item_name.getText();
		data.content.wsb_invoice_item_price = fields.wsb_invoice_item_price.getText();
		data.content.wsb_tax = fields.wsb_tax.getText();
		data.content.wsb_shipping_name = fields.wsb_shipping_name.getText();
		data.content.wsb_shipping_price = fields.wsb_shipping_price.getText();
		data.content.wsb_total = parseInt(data.content.wsb_invoice_item_price) + parseInt(data.content.wsb_tax) + parseInt(data.content.wsb_shipping_price);
		var itm = fields.wsb_currency_id.getSelectedItem();
		data.content.wsb_currency_id = itm.getOriginal().value;
		data.content.border = fields.border.getValue();
		data.content.background = fields.background.getValue();
		data.content.fontFamily = fields.fontFamily.getValue();
		data.content.fontSize = fields.fontSize.getValue();
		data.content.fontColor = fields.fontColor.getValue();
		data.content.demo = fields.demo.getValue();
		data.content.borderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.label) data.content.label = 'Pay via WebPay';
		if (!data.content.border) data.content.border = {color: '#fbe116', style: 'solid', weight: 2};
		if (!data.content.background) data.content.background = '#fbe116';
		if (!data.content.fontFamily) data.content.fontFamily = 'Trebuchet MS,sans-serif';
		if (!data.content.fontSize) data.content.fontSize = '15';
		if (!data.content.fontColor) data.content.fontColor = '#000';
		if (!data.content.secret_key) data.content.secret_key = '123456789';
		if (!data.content.wsb_storeid) data.content.wsb_storeid = '123456789';
		if (!data.content.wsb_store) data.content.wsb_store = 'Store name';
		if (!data.content.wsb_currency_id) data.content.wsb_currency_id = 'BYN';
		if (!data.content.wsb_seed) data.content.wsb_seed = Date.now();
		if (!data.content.wsb_invoice_item_name) data.content.wsb_invoice_item_name = 'Product 1';
		if (!data.content.wsb_invoice_item_price) data.content.wsb_invoice_item_price = '10';
		if (!data.content.wsb_total) data.content.wsb_total = '10';
		if (!data.content.wsb_tax) data.content.wsb_tax = '0';
		if (!data.content.wsb_shipping_name) data.content.wsb_shipping_name = 'Courier delivery';
		if (!data.content.wsb_shipping_price) data.content.wsb_shipping_price = '0';
		if (data.content.demo === undefined) data.content.demo = false;
		data.content.borderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"pagseguro","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/pagseguro\/main.png";
PluginWrapper._config.template = "<form method=\"post\" data-gateway-id=\"PagSeguro\"{{^content.store}} target=\"pagseguro\"{{\/content.store}} action=\"https:\/\/pagseguro.uol.com.br\/v2\/checkout\/payment.html\">\r\n\t<input name=\"receiverEmail\" type=\"hidden\" value=\"{{content.email}}\" \/>\r\n\t<input name=\"currency\" type=\"hidden\" value=\"BRL\" \/>\r\n\t<input name=\"itemDescription1\" type=\"hidden\" value=\"{{content.itemdescription}}\" \/>\r\n\t<input name=\"itemAmount1\" type=\"hidden\" value=\"{{content.itemamount}}\" data-fixed-decimal=\"2\" \/>\r\n\t<input name=\"itemQuantity1\" type=\"hidden\" value=\"{{#content.itemquantity}}{{content.itemquantity}}{{\/content.itemquantity}}{{^content.itemquantity}}1{{\/content.itemquantity}}\" \/>\r\n\t{{#content.store}}\r\n\t<input name=\"itemId1\" type=\"hidden\" value=\"{transactionId}\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<input alt=\"Pague com PagSeguro\" name=\"submit\" type=\"image\" src=\"{{^isPublished}}plugins\/pagseguro\/site\/{{\/isPublished}}gallery_gen\/pagseguro\/pagseguro.gif\" \/>\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/pagseguro/main.php';
PluginWrapper._config.active = true;
/* global PluginWrapper, wb_builder */

ElementRegister.registerPaymentGateway({
	name: 'PagSeguro',
	id: 'pagseguro',
	pageUrl: 'https://pagseguro.uol.com.br/',
	keyField: __('Email'),
	keyFieldId: 'email',
	nameFieldId: 'itemdescription',
	priceFieldId: 'itemamount',
	priceFixedDecimal: 2
});
PluginWrapper.registerPlugin('pagseguro', {
	name: 'PagSeguro',
	element: {
		minSize: {width: 120, height: 55},
		defaultSize: {width: 120, height: 55},
		resizable: false
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Email'), helpText:__("Email registered to your PagSeguro account.")},
							{type: 'TextField', id: 'email'}
						]}
					]},
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount')},
							{type: 'TextField', id: 'itemamount', helptext: __("Amount to be transferred") + ', ' + __('BRL')}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Quantity')},
							{type: 'TextField', id: 'itemquantity'}
						]}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'itemdescription'}
					]}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		fields.email.setText(data.content.email);
		fields.itemdescription.setText(data.content.itemdescription);
		fields.itemamount.setText(data.content.itemamount);
		fields.itemquantity.setText(data.content.itemquantity);
	},
	applyAction: function(fields, data, elem) {
		data.content.email = fields.email.getText();
		data.content.itemdescription = fields.itemdescription.getText();
		data.content.itemamount = fields.itemamount.getText();
		data.content.itemquantity = fields.itemquantity.getText();
	},
	loadAction: function (data) {
		if (!data.content.email) data.content.email = '';
		if (!data.content.itemdescription) data.content.itemdescription = 'Donate';
		if (!data.content.itemamount) data.content.itemamount = '1';
		if (!data.content.itemquantity) data.content.itemquantity = 1;
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"odnoklassniki_share","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/odnoklassniki_share\/main.png";
PluginWrapper._config.template = "<div id=\"{{id}}_ok_shareWidget\"><\/div>\r\n{{^isPublished}}\r\n<script type=\"text\/javascript\">\r\n\tif (window.OK) window.OK.CONNECT.insertShareWidget('{{id}}_ok_shareWidget', '{{content.url}}', \"{{{content.opts}}}\");\r\n<\/script>\r\n{{\/isPublished}}\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\">\r\n\t\/\/ -- {{#firstOnPage}}\r\n\twindow.wb_ok_group_widget = {\r\n\t\tscriptLoaded: false,\r\n\t\tscriptReady: false,\r\n\t\tlisteners: [],\r\n\t\taddListener: function(inst, func) {\r\n\t\t\tif (this.scriptReady) {\r\n\t\t\t\tfunc.call(inst);\r\n\t\t\t} else {\r\n\t\t\t\tthis.listeners.push({inst: inst, func: func});\r\n\t\t\t}\r\n\t\t\tif (!this.scriptLoaded) {\r\n\t\t\t\tthis.scriptLoaded = true;\r\n\t\t\t\tvar self = this;\r\n\t\t\t\t$.getScript('https:\/\/connect.ok.ru\/connect.js', function() {\r\n\t\t\t\t\tself.scriptReady = true;\r\n\t\t\t\t\tfor (var i = 0; i < self.listeners.length; i++) {\r\n\t\t\t\t\t\tself.listeners[i].func.call(self.listeners[i].inst);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\t\/\/ -- {{\/firstOnPage}}\r\n\twindow.wb_ok_group_widget.addListener(this, function() {\r\n\t\tOK.CONNECT.insertShareWidget('{{id}}_ok_shareWidget', '{{content.url}}', \"{{{content.opts}}}\");\r\n\t});\r\n<\/script>\r\n{{\/isPublished}}\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;

PluginWrapper.registerPlugin('odnoklassniki_share', {
	name: 'Klass',
	element: {
		minSize: {width: 25, height: 25},
		defaultSize: {width: 125, height: 25},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{name: 'General', children: [
				{type: 'VerticalLayout', children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('URL to Like (required)')},
							{type: 'TextField', id: 'url'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'DropdownBox', id: 'size', options: [
								{id: '#12', name: '12', value: 12},
								{id: '#20', name: '20', value: 20},
								{id: '#30', name: '30', value: 30},
								{id: '#45', name: '45', value: 45},
								{id: '#70', name: '70', value: 70},
								{id: '#100', name: '100', value: 100},
								{id: '#150', name: '150', value: 150}
							]}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Style')},
							{type: 'DropdownBox', id: 'style', options: [
								{id: 'oval', name: __('Oval')},
								{id: 'rounded', name: __('Rounded')},
								{id: 'straight', name: __('Straight')}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Counter position')},
							{type: 'DropdownBox', id: 'counter', options: [
								{id: 'none', name: __('None'), value: null},
								{id: 'right', name: __('Right'), value: 'right'},
								{id: 'top', name: __('Top'), value: 'top'}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Text')},
							{type: 'DropdownBox', id: 'text', options: [
								{id: '#0', name: __('None'), value: 0},
								{id: '#1', name: __('Klass'), value: 1},
								{id: '#2', name: __('Share'), value: 2},
								{id: '#3', name: __('Like'), value: 3}
							]}
						]}
					]}
				]}
			]}
		]
	},
	
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('https://connect.ok.ru/connect.js', function() {
					self.scriptReady = true;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst);
					}
				});
			}
		}
	},
	resizeTimeout: null,
	
	openAction: function(fields, data, elem) {
		var itm;
		fields.url.setText(data.content.url);
		itm = fields.size.getItemById('#' + data.content.size);
		fields.size.selectItem(itm);
		itm = fields.style.getItemById(data.content.style);
		fields.style.selectItem(itm);
		itm = fields.counter.getItemById(data.content.counter ? data.content.counter : 'none');
		fields.counter.selectItem(itm);
		itm = fields.text.getItemById('#' + data.content.text);
		fields.text.selectItem(itm);
	},
	applyAction: function(fields, data, elem) {
		var itm, width, height, rwidth, rheight;
		data.content.url = fields.url.getText();
		itm = fields.size.getSelectedItem();
		data.content.size = itm.getOriginal().value;
		itm = fields.style.getSelectedItem();
		data.content.style = itm.getOriginal().id;
		itm = fields.counter.getSelectedItem();
		data.content.counter = itm.getOriginal().value;
		itm = fields.text.getSelectedItem();
		data.content.text = itm.getOriginal().value;
		if (data.content.size === 150) {
			width = 145;
			height = 145;
			data.content.counter = null;
			data.content.text = 0;
		} else if (data.content.size === 100) {
			width = 100;
			height = 100;
			data.content.counter = null;
			data.content.text = 0;
		} else if (data.content.size === 70) {
			width = 70;
			height = 70;
			data.content.counter = null;
			data.content.text = 0;
		} else if (data.content.size === 45) {
			width = (data.content.counter ? (data.content.counter === 'top' ? 115 : 160) : 45);
			if (data.content.text === 3) {
				width += (data.content.counter === 'top' ? 55 : 125);
			} else if (data.content.text === 2) {
				width += (data.content.counter === 'top' ? 80 : 150);
			} else if (data.content.text === 1) {
				width += (data.content.counter === 'top' ? 10 : 80);
			}
			height = (data.content.counter === 'top' ? 100 : 50);
		} else if (data.content.size === 30) {
			width = (data.content.counter ? (data.content.counter === 'top' ? 85 : 115) : 30);
			if (data.content.text === 3) {
				width += (data.content.counter === 'top' ? 25 : 80);
			} else if (data.content.text === 2) {
				width += (data.content.counter === 'top' ? 40 : 95);
			} else if (data.content.text === 1) {
				width += (data.content.counter === 'top' ? 0 : 50);
			}
			height = (data.content.counter === 'top' ? 70 : 35);
		} else if (data.content.size === 20) {
			width = (data.content.counter ? (data.content.counter === 'top' ? 75 : 100) : 25);
			if (data.content.text === 3) {
				width += (data.content.counter === 'top' ? 20 : 70);
			} else if (data.content.text === 2) {
				width += (data.content.counter === 'top' ? 40 : 90);
			} else if (data.content.text === 1) {
				width += (data.content.counter === 'top' ? 0 : 45);
			}
			height = (data.content.counter === 'top' ? 65 : 30);
		} else { // 12
			width = (data.content.counter ? (data.content.counter === 'top' ? 70 : 85) : 20);
			if (data.content.text === 3) {
				width += (data.content.counter === 'top' ? 10 : 60);
			} else if (data.content.text === 2) {
				width += (data.content.counter === 'top' ? 25 : 75);
			} else if (data.content.text === 1) {
				width += (data.content.counter === 'top' ? 0 : 40);
			}
			height = (data.content.counter === 'top' ? 50 : 25);
		}
		data.content.opts = "{width:" + width
				+ ",height:" + height
				+ ",st:'" + data.content.style + "'"
				+ ",sz:" + data.content.size
				+ (data.content.counter ? ((data.content.counter === 'top') ? ",vt:'1'" : "") : ",nc:1")
				+ (data.content.text ? (",ck:" + data.content.text) : ",nt:1")
			+ "}";
		rwidth = width;
		rheight = height;
		if (data.content.counter === 'top' && data.content.size > 20) {
			rheight += data.content.size;
		} else if (data.content.size === 150) {
			rwidth += 8;
			rheight += 8;
		}
		
		this.setSize(rwidth, rheight);
	},
	loadAction: function(data) {
		if (!data.content.url) data.content.url = 'http://dev.ok.ru';
		if (!data.content.size) data.content.size = 12;
		if (!data.content.style) data.content.style = 'oval';
		if (!data.content.counter) data.content.counter = 'right';
		if (!data.content.text) data.content.text = 1;
		if (!data.content.opts) data.content.opts = "{width:125,height:25,st:'oval',sz:12,ck:1}";
	},
	loadedAction: function(data, elem) {
		this.pluginScoped.addListener(this, function() {
			window.OK.CONNECT.insertShareWidget(data.id + '_ok_shareWidget', data.content.url, data.content.opts);
		});
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"epaybg","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/epaybg\/main.png";
PluginWrapper._config.template = "<form action=\"{{#content.demo}}https:\/\/devep2.datamax.bg\/ep2\/epay2_demo\/{{\/content.demo}}{{^content.demo}}https:\/\/www.epay.bg\/{{\/content.demo}}\" method=\"post\" data-gateway-id=\"Epaybg\" style=\"width: 100%; height: 100%;\"{{^content.store}} target=\"_blank\"{{\/content.store}}>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"name\" value=\"{{content.name}}\" \/>\r\n\t<input type=\"hidden\" name=\"price\" value=\"{{content.price}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"hidden\" name=\"transactionId\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"URL_OK\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"URL_CANCEL\" value=\"{cancelUrl}\" \/>\r\n\t<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/epaybg\/epay.png\" alt=\"\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/epaybg\/site\/{{\/isPublished}}gallery_gen\/epaybg\/epay.png\" alt=\"\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/epaybg/main.php';
PluginWrapper._config.active = false;

ElementRegister.registerPaymentGateway({
	name: 'ePay.bg',
	id: 'epaybg',
	keyFieldId: 'min_number',
	keyField2Id: 'secret_key',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [6,6,12], children: [
		{type: 'TextField', placeholder: 'MIN', id: 'key'},
		{type: 'TextField', placeholder: __('Secret Key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'name',
	priceFieldId: 'price',
	currencyFieldId: 'currency',
	globalVars: ['min_number', 'secret_key', 'demo'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window.epaybg_help_dialog().setVisible(true); });
		return btn;
	}
});

(function() {
	var dlg = null;
	window.epaybg_help_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://www.epay.bg/" target="_blank">https://www.epay.bg/</a></p>'
					+ '<p><strong>Notifications URL</strong> (BG: <em>"URL за известяване"</em>)<strong>:</strong><br />'
					+ '<pre>' + base_url + 'store-callback/Epaybg' + '</pre></p>';
			
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
})();

PluginWrapper.registerPlugin('epaybg', {
	name: 'ePay.bg',
	element: {
		minSize: {width: 70, height: 35},
		defaultSize: {width: 100, height: 70},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: 'MIN', helpText: __('Customer number')},
							{type: 'TextField', id: 'min_number'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Secret Key')},
							{type: 'TextField', id: 'secret_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'name'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred')},
							{type: 'TextField', id: 'price'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label')},
							{type: 'TextField', id: 'button_label'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: 'BGN', name: 'BGN'},
								{id: 'USD', name: 'USD'},
								{id: 'EUR', name: 'EUR'}
							]}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'button_border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'button_color'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'font_size'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'label_color', noTransparent: true}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', css: {width: 120}, children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Max logo width')},
							{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Show logo')},
							{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
							{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'bottom'});
						}}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		fields.min_number.setText(data.content.min_number);
		fields.secret_key.setText(data.content.secret_key);
		fields.name.setText(data.content.name);
		fields.price.setText(data.content.price);
		itm = fields.currency.getItemById(data.content.currency);
		fields.currency.selectItem(itm);
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		data.content.min_number = fields.min_number.getText();
		data.content.secret_key = fields.secret_key.getText();
		data.content.name = fields.name.getText();
		data.content.price = fields.price.getText();
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().id;
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.min_number) data.content.min_number = '';
		if (!data.content.secret_key) data.content.secret_key = '';
		if (!data.content.name) data.content.name = '';
		if (!data.content.price) data.content.price = '1';
		if (!data.content.currency) data.content.currency = 'BGN';
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = 'transparent';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#000';
		if (!data.content.button_border) data.content.button_border = {
			color: '#ccc',
			style: 'none',
			weight: 1,
			css: { border: '1px none #ccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"mpesa","extReferenceId":null};
PluginWrapper._config.icon = null;
PluginWrapper._config.template = '';
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"iyzico","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/iyzico\/main.png";
PluginWrapper._config.template = "<button type=\"button\" class=\"btn btn-primary btn-sm\" onclick=\"showIyzico_{{id}}()\">\r\n    \u015eimdi \u00d6de\r\n<\/button>\r\n{{#isPublished}}\r\n<div class=\"modal fade\" id=\"iyzicoModal_{{id}}\" tabindex=\"-1\" role=\"dialog\">\r\n    <div class=\"modal-dialog\" role=\"document\">\r\n        <div class=\"modal-content\">\r\n            <div class=\"modal-header\">\r\n                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;<\/span><\/button>\r\n                <h4 class=\"modal-title\" id=\"myModalLabel\">iyzico<\/h4>\r\n            <\/div>\r\n            <div class=\"modal-body\">\r\n                <form id=\"iyzicoForm_{{id}}\" method=\"post\" action=\"\" data-gateway-id=\"Iyzico\">\r\n                    <input type=\"hidden\" name=\"action\" value=\"pay\"\/>\r\n                    <div class=\"row\">\r\n                        <div class=\"form-group col-sm-6\">\r\n                            <label>{{content.__t.first_name}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n                            <input class=\"form-control input-sm\" type=\"text\" name=\"first_name\" required=\"required\" \/>\r\n                        <\/div>\r\n                        <div class=\"form-group col-sm-6\">\r\n                            <label>{{content.__t.last_name}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n                            <input class=\"form-control input-sm\" type=\"text\" name=\"last_name\" required=\"required\" \/>\r\n                        <\/div>\r\n                    <\/div>\r\n                    <div class=\"form-group\">\r\n                        <label>{{content.__t.email}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n                        <input class=\"form-control input-sm\" type=\"email\" name=\"email\" required=\"required\" \/>\r\n                    <\/div>\r\n                    <div class=\"form-group\">\r\n                        <label>{{content.__t.identity_number}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n                        <input class=\"form-control input-sm\" type=\"text\" name=\"identity_number\" minlength=\"6\" required=\"required\" \/>\r\n                        <p class=\"help-block\">{{content.__t.identity_number_helper}}<\/p>\r\n                    <\/div>\r\n                    <hr>\r\n                    <div class=\"form-group\">\r\n                        <label>{{content.__t.address}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n                        <input class=\"form-control input-sm\" type=\"text\" name=\"address\" required=\"required\" \/>\r\n                    <\/div>\r\n                    <div class=\"row\">\r\n                        <div class=\"form-group col-sm-6\">\r\n                            <label>{{content.__t.country}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n                            <input class=\"form-control input-sm\" type=\"text\" name=\"country\" required=\"required\" \/>\r\n                        <\/div>\r\n                        <div class=\"form-group col-sm-6\">\r\n                            <label>{{content.__t.city}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n                            <input class=\"form-control input-sm\" type=\"text\" name=\"city\" required=\"required\" \/>\r\n                        <\/div>\r\n                    <\/div>\r\n                    <input class=\"hidden\" type=\"submit\"\/>\r\n                    {{#content.store}}\r\n                    <input type=\"hidden\" name=\"price\" value=\"{{content.price}}\" \/>\r\n                    <input type=\"hidden\" name=\"name\" value=\"{{content.name}}\" \/>\r\n                    <input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n                    <input type=\"hidden\" name=\"callbackurl\" value=\"{callbackUrl}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"transactionId\" value=\"{transactionId}\" \/>\r\n                    {{\/content.store}}\r\n                <\/form>\r\n            <\/div>\r\n            <div class=\"modal-footer\">\r\n                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">{{content.__t.close}}<\/button>\r\n                <button type=\"button\" class=\"btn btn-primary\" onclick=\"nextIyzicoStep_{{id}}()\">{{content.__t.next}}<\/button>\r\n            <\/div>\r\n        <\/div>\r\n    <\/div>\r\n<\/div>\r\n<script>\r\n\tfunction showIyzico_{{id}}(){\r\n\t\t$('#iyzicoModal_{{id}}').appendTo(\"body\");\r\n\t\t$('#iyzicoModal_{{id}}').modal('show');\r\n\t}\r\n\tfunction nextIyzicoStep_{{id}}() {\r\n\t\tvar izycoForm = $('#iyzicoForm_{{id}}');\r\n\t\tizycoForm.find(':submit').click();\r\n\t}\r\n\t{{#content.store}}\r\n\t$('#iyzicoModal_{{id}}').on('show.bs.modal', function() {\r\n\t\tvar url = $('base').attr('href') + 'requestGetBillingInfo\/Iyzico';\r\n\t\t$.get(url, function(resp) {\r\n\t\t\tvar elems = $('#iyzicoForm_{{id}}').get(0).elements;\r\n\t\t\tif (resp.firstName) elems['first_name'].value = resp.firstName;\r\n\t\t\tif (resp.lastName) elems['last_name'].value = resp.lastName;\r\n\t\t\tif (resp.email) elems['email'].value = resp.email;\r\n\t\t\tif (resp.address1) elems['address'].value = resp.address1;\r\n\t\t\tif (resp.country) elems['country'].value = resp.country;\r\n\t\t\tif (resp.city) elems['city'].value = resp.city;\r\n\t\t});\r\n\t});\r\n\t{{\/content.store}}\r\n<\/script>\r\n{{\/isPublished}}\r\n{{^content.store}}\r\n{{{requireService}}}\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/iyzico/main.php';
PluginWrapper._config.active = false;
(function() {
	if (typeof window.iyzico_translations === 'undefined') {
		window.iyzico_translations = {
			'first_name': __c('First Name'),
			'last_name': __c('Last Name'),
			'email': __c('E-mail'),
			'identity_number': __c('Identity number'),
			'identity_number_helper': __c('Identity number of buyer. TCKN for Turkish merchants, passport number for foreign merchants'),
			'address': __c('Address'),
			'country': __c('Country'),
			'city': __c('City'),
			'close': __c('Close'),
			'next': __c('Next'),
			'buyer': __c('Buyer'),
			'price': __c('Price'),
			'pay': __c('Pay'),
			'unknown_error': __c('Unknown error')
		};
	}
})();

ElementRegister.registerPaymentGateway({
	name: 'iyzico',
	id: 'iyzico',
	pageUrl: 'https://www.iyzico.com/',
	keyFieldId: 'api_key',
	keyField2Id: 'secret_key',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [6,6,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('API Key'), id: 'key'},
		{type: 'TextField', placeholder: __('Secret Key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'name',
	priceFieldId: 'price',
	currencyFieldId: 'currency',
	globalVars: ['api_key', 'secret_key', 'demo'],
	__t: window.iyzico_translations
});

PluginWrapper.registerPlugin('iyzico', {
	name: 'iyzico',
	element: {
		minSize: {width: 80, height: 30},
		defaultSize: {width: 80, height: 30},
		resizable: false
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('API Key'), helpText: __('This key you can get in account settings page')},
							{type: 'TextField', id: 'api_key'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Secret Key'), helpText: __('This key you can get in account settings page')},
							{type: 'TextField', id: 'secret_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'name'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount')},
							{type: 'TextField', id: 'price'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: '#TRY', name: 'TRY', value: 'TRY'},
								{id: '#EUR', name: 'EUR', value: 'EUR'},
								{id: '#USD', name: 'USD', value: 'USD'},
								{id: '#GBP', name: 'GBP', value: 'GBP'},
								{id: '#IRR', name: 'IRR', value: 'IRR'}
							]}
						]}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'right'});
						}}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.name.setText(data.content.name);
		fields.price.setText(data.content.price);
		fields.api_key.setText(data.content.api_key);
		fields.secret_key.setText(data.content.secret_key);
		fields.demo.setValue(data.content.demo);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.name = fields.name.getText();
		data.content.price = fields.price.getText();
		data.content.api_key = fields.api_key.getText();
		data.content.secret_key = fields.secret_key.getText();
		data.content.demo = fields.demo.getValue();
	},
	loadAction: function (data) {
		data.content.__t = window.iyzico_translations;
		/* if (data.content.language == 'EN') {
			data.content.first_name = 'First name';
			data.content.last_name = 'Last name';
			data.content.email = 'E-mail';
			data.content.identity_number = 'Identity number';
			data.content.identity_number_helper = 'Identity number of buyer. TCKN for Turkish merchants, passport number for foreign merchants';
			data.content.address = 'Address';
			data.content.country = 'Country';
			data.content.city = 'City';
			data.content.close = 'Close';
			data.content.next = 'Next';
		}
		if (data.content.language == 'TR') {
			data.content.first_name = 'İsim';
			data.content.last_name = 'Soyadı';
			data.content.email = 'E-posta';
			data.content.identity_number = 'Kimlik numarası';
			data.content.identity_number_helper = 'Alıcının kimlik numarası. Türk tüccarları için TCKN, yabancı tüccarlar için pasaport numarası';
			data.content.address = 'Adres';
			data.content.country = 'Ülke';
			data.content.city = 'Şehir';
			data.content.close = 'Kapat';
			data.content.next = 'Sonraki';
		} */
		if (!data.content.name)
			data.content.name = ''; // Items description
		if (!data.content.price)
			data.content.price = '1'; // 129.99
		if (!data.content.currency)
			data.content.currency = 'TRY';
		if (!data.content.api_key)
			data.content.api_key = ''; // sandbox-JZsbTVGkl804lfnlvfZJmCRWS1nuFGHr
		if (!data.content.secret_key)
			data.content.secret_key = ''; // sandbox-Ins3iRwvn0uyKdlOGs2vmpj6K3SVB7aC
		if (data.content.demo === undefined)
			data.content.demo = true;
		data.serviceUrl = this.serviceUrl;
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"pinterest","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/pinterest\/main.png";
PluginWrapper._config.template = "{{#isPublished}}\r\n<script src=\"\/\/assets.pinterest.com\/js\/pinit.js\"><\/script>\r\n{{\/isPublished}}\r\n<a {{{content.param_pindo}}}\r\n   {{{content.pin_size}}}\r\n   {{{content.pin_terse}}}\r\n   {{{content.pin_count}}}\r\n   {{{content.pin_hover}}}\r\n   {{{content.pin_save}}}\r\n   {{{content.pin_lang}}}\r\n   {{{content.param_large}}}\r\n   {{{content.param_custom_image}}}\r\n   {{{content.param_round}}}\r\n   {{{content.param_color}}}\r\n   {{{content.param_s_imagewidth}}}\r\n   {{{content.param_s_boardheight}}}\r\n   {{{content.param_s_boardwidth}}}\r\n   {{{content.pinterest_url}}}>\r\n    {{{content.param_follow_title}}}\r\n    <img {{{content.img_tag}}} src=\"{{{content.image}}}\" alt=\"\"\/>\r\n<\/a>";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('pinterest', {
    name: 'Pinterest',
    element: {
        minSize: {width: 70, height: 40},
        defaultSize: {width: 70, height: 40},
        resizable: true
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {
                children: [
                    {
                        type: 'VerticalLayout', children: [
                        {
                            type: 'VerticalLayout', children: [
                            {type: 'Label', text: __('Widget type')},
                            {
                                type: 'DropdownBox', id: 'typew',
                                options: [
                                    {id: '#1', name: __('Save Button'), value: 1},
                                    {id: '#2', name: __('Follow'), value: 2},
                                    {id: '#3', name: __('Pin'), value: 3},
                                    {id: '#4', name: __('Board'), value: 4},
                                    {id: '#5', name: __('Profile'), value: 5}
                                ],
                                change: function (fields) {
                                    var type = this.getSelectedItem().getOriginal().value;
                                    if (type === 1) {
                                        fields.language_block.setVisible(true);
                                        fields.follow_block.setVisible(false);
                                        fields.image_block.setVisible(true);
                                        fields.pinit_block.setVisible(true);
                                        fields.pin_widget_block.setVisible(false);
                                        fields.sizes.setVisible(false);
                                        fields.follow_url_input.setVisible(false);
                                        fields.pin_url_input.setVisible(false);
                                        fields.board_url_input.setVisible(false);
                                        fields.profile_url_input.setVisible(false);
                                    } else if (type === 2) {
                                        fields.language_block.setVisible(false);
                                        fields.follow_block.setVisible(true);
                                        fields.image_block.setVisible(false);
                                        fields.pinit_block.setVisible(false);
                                        fields.pin_widget_block.setVisible(false);
                                        fields.sizes.setVisible(false);
                                        fields.save_button_one_image.setVisible(false);
                                        fields.pin_count_field.setVisible(false);
                                        fields.follow_url_input.setVisible(true);
                                        fields.pin_url_input.setVisible(false);
                                        fields.board_url_input.setVisible(false);
                                        fields.profile_url_input.setVisible(false);
                                    } else if (type === 3) {
                                        fields.language_block.setVisible(false);
                                        fields.follow_block.setVisible(false);
                                        fields.pinit_block.setVisible(false);
                                        fields.image_block.setVisible(false);
                                        fields.pin_widget_block.setVisible(true);
                                        fields.sizes.setVisible(false);
                                        fields.save_button_one_image.setVisible(false);
                                        fields.pin_count_field.setVisible(false);
                                        fields.follow_url_input.setVisible(false);
                                        fields.pin_url_input.setVisible(true);
                                        fields.board_url_input.setVisible(false);
                                        fields.profile_url_input.setVisible(false);
                                    } else if (type === 4) {
                                        fields.language_block.setVisible(false);
                                        fields.follow_block.setVisible(false);
                                        fields.pinit_block.setVisible(false);
                                        fields.image_block.setVisible(false);
                                        fields.pin_widget_block.setVisible(false);
                                        fields.sizes.setVisible(true);
                                        fields.save_button_one_image.setVisible(false);
                                        fields.pin_count_field.setVisible(false);
                                        fields.follow_url_input.setVisible(false);
                                        fields.pin_url_input.setVisible(false);
                                        fields.board_url_input.setVisible(true);
                                        fields.profile_url_input.setVisible(false);
                                    } else if (type === 5) {
                                        fields.language_block.setVisible(false);
                                        fields.follow_block.setVisible(false);
                                        fields.pinit_block.setVisible(false);
                                        fields.image_block.setVisible(false);
                                        fields.pin_widget_block.setVisible(false);
                                        fields.sizes.setVisible(true);
                                        fields.save_button_one_image.setVisible(false);
                                        fields.pin_count_field.setVisible(false);
                                        fields.follow_url_input.setVisible(false);
                                        fields.pin_url_input.setVisible(false);
                                        fields.board_url_input.setVisible(false);
                                        fields.profile_url_input.setVisible(true);
                                    }
                                }
                            }
                        ]
                        },
                        {
                            type: 'HorizontalLayout', id: 'pinit_block', css: {marginTop: 15}, children: [
                            {
                                type: 'VerticalLayout', id: 'button_type_block', children: [
                                {type: 'Label', text: __('Button type')},
                                {
                                    type: 'DropdownBox', id: 'type',
                                    options: [
                                        {id: 'one_image', name: __('One Image')},
                                        {id: 'any_image', name: __('Any Image')},
                                    ],
                                    change: function (fields) {
                                        var type = this.getSelectedItem().getOriginal().id;
                                        if (type === 'one_image') {
                                            fields.save_button_one_image.setVisible(true);
                                            fields.pin_count_field.setVisible(true);
                                            fields.image_block.setVisible(false);
                                        } else if (type === 'any_image') {
                                            fields.save_button_one_image.setVisible(false);
                                            fields.pin_count_field.setVisible(false);
                                            fields.image_block.setVisible(true);
                                        } else if (type === 'image_hover') {
                                            fields.save_button_one_image.setVisible(false);
                                            fields.pin_count_field.setVisible(false);
                                            fields.image_block.setVisible(false);
                                        }
                                    }
                                }
                            ]
                            },
                            {
                                type: 'VerticalLayout', children: [
                                {type: 'Label', text: __('Large')},
                                {type: 'RadioBox', id: 'large0', label: __('Yes'), group: 'large'},
                                {type: 'RadioBox', id: 'large1', label: __('No'), group: 'large'}
                            ]
                            },
                            {
                                type: 'VerticalLayout', children: [
                                {type: 'Label', text: __('Round')},
                                {
                                    type: 'RadioBox', id: 'round0', label: __('Yes'),
                                    group: 'round',
                                    change: function (fields) {
                                        fields.pin_count_field.setVisible(false);
                                        fields.lang_block.setVisible(false);
                                    }
                                },
                                {
                                    type: 'RadioBox', id: 'round1', label: __('No'),
                                    group: 'round',
                                    change: function (fields) {
                                        fields.pin_count_field.setVisible(true);
                                        fields.lang_block.setVisible(true);
                                    }
                                }
                            ]
                            }
                        ]
                        },
                        {
                            type: 'HorizontalLayout', id: 'save_button_one_image', css: {marginTop: 15}, children: [
                            {
                                type: 'VerticalLayout', css: {marginTop: 15}, children: [
                                {
                                    type: 'Label',
                                    text: __('Image source URL'),
                                    helpText: __('URL of the page containing image')
                                },
                                {type: 'TextField', id: 'one_image_url'}
                            ]
                            },
                            {
                                type: 'VerticalLayout', css: {marginTop: 15}, children: [
                                {type: 'Label', text: __('Image URL'), helpText: __('Enter image URL')},
                                {type: 'TextField', id: 'one_image_image'}
                            ]
                            },
                            {
                                type: 'VerticalLayout', css: {marginTop: 15}, children: [
                                {type: 'Label', text: __('Description'), helpText: __('Enter image description')},
                                {
                                    type: 'TextField',
                                    id: 'one_image_description',
                                }
                            ]
                            },
                        ]
                        },
                        {
                            type: 'HorizontalLayout', id: 'lang_block', css: {marginTop: 15}, children: [
                            {
                                type: 'VerticalLayout', id: 'language_block', children: [
                                {type: 'Label', text: __('Language')},
                                {
                                    type: 'DropdownBox', id: 'language', options: [
                                    {id: 'default', name: __("User's Default Language")},
                                    {id: 'en', name: "English"},
                                    {id: 'cs', name: "Czech"},
                                    {id: 'da', name: "Danish"},
                                    {id: 'de', name: "German"},
                                    {id: 'el', name: "Greek"},
                                    {id: 'es', name: "Spanish"},
                                    {id: 'fi', name: "Finnish"},
                                    {id: 'fr', name: "French"},
                                    {id: 'hi', name: "Hindu"},
                                    {id: 'hu', name: "Hungarian"},
                                    {id: 'id', name: "Indonesian"},
                                    {id: 'it', name: "Italian"},
                                    {id: 'ja', name: "Japanese"},
                                    {id: 'ko', name: "Korean"},
                                    {id: 'ms', name: "Malaysian"},
                                    {id: 'nb', name: "Norwegian"},
                                    {id: 'nl', name: "Dutch"},
                                    {id: 'pl', name: "Polish"},
                                    {id: 'pt', name: "Portuguese"},
                                    {id: 'pt-br', name: "Portuguese (Brazil)"},
                                    {id: 'ro', name: "Romanian"},
                                    {id: 'ru', name: "Russian"},
                                    {id: 'sk', name: "Slovak"},
                                    {id: 'sv', name: "Swedish"},
                                    {id: 'tl', name: "Tagalog"},
                                    {id: 'th', name: "Thai"},
                                    {id: 'tr', name: "Turkish"},
                                    {id: 'uk', name: "Ukrainian"},
                                    {id: 'vi', name: "Vietnamese"}
                                ]
                                }
                            ]
                            },
                        ]
                        },
                        {
                            type: 'HorizontalLayout', id: 'pin_count_field', css: {marginTop: 15}, children: [
                            {
                                type: 'VerticalLayout', children: [
                                {type: 'Label', text: __('Show Pin Count')},
                                {
                                    type: 'DropdownBox', id: 'pin_count', options: [
                                    {id: 'none', name: __('Not Shown')},
                                    {id: 'above', name: __('Above the Button')},
                                    {id: 'beside', name: __('Beside the Button')}
                                ]
                                }
                            ]
                            },
                        ]
                        },
                        {
                            type: 'VerticalLayout', id: 'image_block', css: {marginTop: 15}, children: [
                            {type: 'Label', text: __('Custom button image'), helpText: __('Enter image URL')},
                            {type: 'TextField', id: 'custom_image'}
                        ]
                        },
                        {
                            type: 'VerticalLayout', id: 'follow_url_input', css: {marginTop: 15}, children: [
                            {
                                type: 'Label',
                                text: __('Pinterest user URL'),
                                helpText: __('Enter URL of the profile you want to embed')
                            },
                            {type: 'TextField', id: 'follow_url'}
                        ]
                        },
                        {
                            type: 'VerticalLayout', id: 'pin_url_input', css: {marginTop: 15}, children: [
                            {
                                type: 'Label',
                                text: __('Pin URL'),
                                helpText: __('Enter URL of the pin you want to embed')
                            },
                            {type: 'TextField', id: 'pin_url'}
                        ]
                        },
                        {
                            type: 'VerticalLayout', id: 'board_url_input', css: {marginTop: 15}, children: [
                            {
                                type: 'Label',
                                text: __('Pinterest board URL'),
                                helpText: __('Enter URL of the board you want to embed')
                            },
                            {type: 'TextField', id: 'board_url'}
                        ]
                        },
                        {
                            type: 'VerticalLayout', id: 'profile_url_input', css: {marginTop: 15}, children: [
                            {
                                type: 'Label',
                                text: __('Pinterest user profile URL'),
                                helpText: __('Enter URL of the profile you want to embed')
                            },
                            {type: 'TextField', id: 'profile_url'}
                        ]
                        },
                        {
                            type: 'HorizontalLayout', id: 'pin_widget_block', css: {marginTop: 15}, children: [
                            {
                                type: 'VerticalLayout', children: [
                                {type: 'Label', text: __('Pin size')},
                                {
                                    type: 'DropdownBox', id: 'pin_size', options: [
                                    {id: 'small', name: __('Small')},
                                    {id: 'medium', name: __('Medium')},
                                    {id: 'large', name: __('Large')}
                                ]
                                }
                            ]
                            },
                            {
                                type: 'VerticalLayout', children: [
                                {
                                    type: 'Label',
                                    text: __('Hide description'),
                                    helpText: __('Select option to show photo description on Pinterest Pin widget')
                                },
                                {
                                    type: 'RadioBox', id: 'descriptionv0', label: __('Yes'),
                                    group: 'description_visibility'
                                },
                                {
                                    type: 'RadioBox', id: 'descriptionv1', label: __('No'),
                                    group: 'description_visibility'
                                }
                            ]
                            },
                        ]
                        },
                        {
                            type: 'VerticalLayout', id: 'follow_block', css: {marginTop: 15}, children: [
                            {
                                type: 'Label',
                                text: __('Full name'),
                                id: 'follow_titlel',
                                helpText: __('Enter name of the profile you want to embed')
                            },
                            {type: 'TextField', id: 'follow_title'}
                        ]
                        },
                        {
                            type: 'HorizontalLayout',
                            id: 'sizes',
                            css: {marginTop: 15},
                            columnWeights: [3, 3, 3],
                            children: [
                                {
                                    type: 'VerticalLayout', children: [
                                    {type: 'Label', text: __('Width of images')},
                                    {type: 'SizeSelector', id: 's_imagewidth'}
                                ]
                                },
                                {
                                    type: 'VerticalLayout', children: [
                                    {type: 'Label', text: __('Board height')},
                                    {type: 'SizeSelector', id: 's_boardheight'}
                                ]
                                },
                                {
                                    type: 'VerticalLayout', children: [
                                    {type: 'Label', text: __('Board width')},
                                    {type: 'SizeSelector', id: 's_boardwidth'}
                                ]
                                }
                            ]
                        }
                    ]
                    }
                ]
            }
        ]
    },
    pluginScoped: {
        scriptLoaded: false,
        scriptReady: false,
        listeners: [],
        addListener: function (inst, func) {
            if (typeof func === 'function') {
                if (this.scriptReady) {
                    func.call(inst);
                } else {
                    this.listeners.push({inst: inst, func: func});
                }
            }
            if (!this.scriptLoaded) {
                this.scriptLoaded = true;
                var self = this;
                $.getScript('https://assets.pinterest.com/js/pinit.js', function () {
                    self.scriptReady = true;
                    for (var i = 0; i < self.listeners.length; i++) {
                        self.listeners[i].func.call(self.listeners[i].inst);
                    }
                });
            }
            setTimeout(function () {
                if (window.PinUtils) {
                    window.PinUtils.build();
                }
            }, 100);
        },
    },
    retypewTimeout: null,
    openAction: function (fields, data, elem) {
        var itm;
        data.content.pinterest_url = '';
        fields.custom_image.setText(data.content.custom_image);
        fields.follow_title.setText(data.content.follow_title ? data.content.follow_title : 'Pinterest');
        fields.large0.setValue(data.content.large === 1);
        fields.large1.setValue(data.content.large === 0);

        itm = fields.type.getItemById(data.content.type);
        fields.type.selectItem(itm);

        fields.follow_url.setValue(data.content.follow_url);
        fields.pin_url.setValue(data.content.pin_url);
        fields.board_url.setValue(data.content.board_url);
        fields.profile_url.setValue(data.content.profile_url);

        fields.one_image_url.setValue(data.content.one_image_url);
        fields.one_image_image.setValue(data.content.one_image_image);
        fields.one_image_description.setValue(data.content.one_image_description);

        fields.s_imagewidth.setValue(data.content.s_imagewidth);
        fields.s_boardheight.setValue(data.content.s_boardheight);
        fields.s_boardwidth.setValue(data.content.s_boardwidth);
        fields.round0.setValue(data.content.round === 1);
        fields.round1.setValue(data.content.round === 0);
        fields.round0.trigger('change');
        if (data.content.round === 1) {
            fields.pin_count_field.setVisible(false);
            fields.lang_block.setVisible(false);
        } else {
            fields.pin_count_field.setVisible(true);
            fields.lang_block.setVisible(true);
        }
        itm = fields.typew.getItemById('#' + data.content.typew);
        if (itm) {
            fields.typew.selectItem(itm);
        } else {
            fields.typew.selectItem(fields.typew.getItem(0));
        }
        fields.typew.trigger('change');

        fields.descriptionv0.setValue(data.content.description_visibility === 1);
        fields.descriptionv1.setValue(data.content.description_visibility === 0);

        if (data.content.type == 'one_image') {
            fields.image_block.setVisible(false);
        }
        if (data.content.type == 'any_image') {
            fields.save_button_one_image.setVisible(false);
            fields.pin_count_field.setVisible(false);
            fields.image_block.setVisible(true);
        }

    },
    applyAction: function (fields, data, elem) {
        var itm;
        if (fields.large0.getValue())
            data.content.large = 1;
        if (fields.large1.getValue())
            data.content.large = 0;
        if (fields.round0.getValue())
            data.content.round = 1;
        if (fields.round1.getValue())
            data.content.round = 0;
        itm = fields.typew.getSelectedItem();
        data.content.typew = itm.getOriginal().value;
        itm = fields.type.getSelectedItem();
        data.content.type = itm.getOriginal().id;
        data.content.param_customimage = '';
        data.content.follow_title = '';
        data.content.param_follow_title = '';
        data.content.pin_size = '';
        data.content.pin_terse = '';
        data.content.pin_save = '';
        data.content.pin_lang = '';
        data.content.pin_count = '';
        data.content.pin_hover = '';
        data.content.param_round = '';
        data.content.param_one_image_url = '';
        data.content.param_one_image_image = '';
        data.content.param_one_image_description = '';
        data.content.param_custom_image = '';
        data.content.custom_image = fields.custom_image.getText();
        data.content.pinterest_url = '';
        data.content.s_imagewidth = fields.s_imagewidth.getValue();
        data.content.s_boardheight = fields.s_boardheight.getValue();
        data.content.s_boardwidth = fields.s_boardwidth.getValue();
        if (data.content.typew === 1) { //Pin it type
            var itm = fields.type.getSelectedItem();
            var current_pin_type = itm.getOriginal().id;
            if (current_pin_type === 'one_image') {
                data.content.param_pindo = 'data-pin-do="buttonPin"';
                data.content.param_one_image_url = fields.one_image_url.getText();
                data.content.param_one_image_image = fields.one_image_image.getText();
                data.content.param_one_image_description = fields.one_image_description.getText();
                var itm = fields.language.getSelectedItem();
                data.content.pin_lang = 'data-pin-lang="' + itm.getOriginal().id + '"';
                lang = itm.getOriginal().id;
                if (lang == 'default' || lang == 'en') {
                    lang = 'www';
                }
                if (lang == 'cs') {
                    lang = 'cz';
                }
                if (lang == 'da') {
                    lang = 'dk';
                }
                if (lang == 'el') {
                    lang = 'gr';
                }
                if (lang == 'hi') {
                    lang = 'in';
                }
                if (lang == 'ja') {
                    lang = 'jp';
                }
                if (lang == 'ko') {
                    lang = 'kr';
                }
                if (lang == 'nb') {
                    lang = 'no';
                }
                if (lang == 'pt-br') {
                    lang = 'pt';
                }
                if (lang == 'sv') {
                    lang = 'se';
                }
                data.content.pinterest_url = "https://" + lang + ".pinterest.com/pin/create/button/?url=" + data.content.param_one_image_url + "&media=" + data.content.param_one_image_image + "&description=" + data.content.param_one_image_description;
                data.content.pinterest_url = 'href="' + data.content.pinterest_url + '"';
                var itm = fields.pin_count.getSelectedItem();
                var pin_count = itm.getOriginal().id;
                if (pin_count === "above") {
                    data.content.pin_count = 'data-pin-count="above"';
                }
                if (pin_count === "beside") {
                    data.content.pin_count = 'data-pin-count="beside"';
                }
                if (data.content.round === 1) {
                    data.content.param_round = 'data-pin-round="true"';
                    data.content.pin_save = 'data-pin-save="false"';
                } else {
                    data.content.pin_save = 'data-pin-save="true"';
                }
                if (data.content.large === 1) {
                    data.content.param_large = 'data-pin-tall="true"';
                } else {
                    data.content.param_large = '';
                }

            }
            if (current_pin_type === 'any_image') {
                data.content.param_pindo = 'data-pin-do="buttonBookmark"';
                var itm = fields.language.getSelectedItem();
                data.content.pin_lang = 'data-pin-lang="' + itm.getOriginal().id + '"';
                data.content.pinterest_url = 'href="https://www.pinterest.com/pin/create/button/"';
                data.content.pin_save = 'data-pin-save="true"';
                if (data.content.round === 1) {
                    data.content.param_round = 'data-pin-round="true"';
                    data.content.pin_save = 'data-pin-save="false"';
                } else {
                    data.content.param_round = '';
                }
                if (data.content.large === 1) {
                    data.content.param_large = 'data-pin-tall="true"';
                } else {
                    data.content.param_large = '';
                }

                if (data.content.custom_image != '') {
                    data.content.image = data.content.custom_image;
                    data.content.param_custom_image = 'data-pin-custom="true"';
                }
            }
            if (current_pin_type === 'image_hover') {
                data.content.param_pindo = '';
                data.content.pin_save = 'data-pin-save="true"';
                data.content.pin_hover = 'data-pin-hover="true"';
                data.content.pinterest_url = '';
                data.content.image = '';
            }

            data.content.param_s_imagewidth = '';
            data.content.param_s_boardheight = '';
            data.content.param_s_boardwidth = '';

        }
        if (data.content.typew === 2) { //Follow type
            data.content.param_s_imagewidth = '';
            data.content.param_s_boardheight = '';
            data.content.param_s_boardwidth = '';
            data.content.param_pindo = 'data-pin-do="buttonFollow"';
            data.content.img_tag = 'style="display: none;"';
            data.content.param_large = '';
            data.content.param_round = '';
            data.content.follow_title = fields.follow_title.getText();
            data.content.param_follow_title = fields.follow_title.getText();
            data.content.pinterest_url = 'href="' + data.content.follow_url + '"';
        } else if (data.content.typew === 3) { //Pin type
            data.content.param_s_imagewidth = '';
            data.content.param_s_boardheight = '';
            data.content.param_s_boardwidth = '';
            data.content.param_pindo = 'data-pin-do="embedPin"';
            data.content.img_tag = 'style="display: none;"';
            var itm = fields.pin_size.getSelectedItem();
            data.content.pin_size = 'data-pin-width="' + itm.getOriginal().id + '"';
            data.content.follow_title = '';
            data.content.param_large = '';
            data.content.param_round = '';
            data.content.pinterest_url = 'href="' + data.content.pin_url + '"';
            if (fields.descriptionv0.getValue()) {
                data.content.pin_terse = 'data-pin-terse="true"';
                data.content.description_visibility = 1;
            }
            if (fields.descriptionv1.getValue()) {
                data.content.pin_terse = '';
                data.content.description_visibility = 0;
            }
        } else if (data.content.typew === 4) { //Board type
            data.content.pinterest_url = 'href="' + data.content.board_url + '"';
            data.content.param_s_imagewidth = 'data-pin-scale-width="' + data.content.s_imagewidth + '"';
            data.content.param_s_boardheight = 'data-pin-scale-height="' + data.content.s_boardheight + '"';
            data.content.param_s_boardwidth = 'data-pin-board-width="' + data.content.s_boardwidth + '"';
            data.content.param_pindo = 'data-pin-do="embedBoard"';
            data.content.img_tag = 'style="display: none;"';
            data.content.follow_title = '';
            data.content.param_large = '';
            data.content.param_round = '';
        } else if (data.content.typew === 5) {
            data.content.pinterest_url = 'href="' + data.content.profile_url + '"';
            data.content.param_s_imagewidth = 'data-pin-scale-width="' + data.content.s_imagewidth + '"';
            data.content.param_s_boardheight = 'data-pin-scale-height="' + data.content.s_boardheight + '"';
            data.content.param_s_boardwidth = 'data-pin-board-width="' + data.content.s_boardwidth + '"';
            data.content.param_pindo = 'data-pin-do="embedUser"';
            data.content.img_tag = 'style="display: none;"';
            data.content.follow_title = '';
            data.content.param_large = '';
            data.content.param_round = '';

        }
        this.pluginScoped.addListener(this, function () {
        });
    },
    loadAction: function (data) {
        if (!data.content.typew)
            data.content.typew = 1;
        if (!data.content.pin_save)
            data.content.pin_save = 'data-pin-save="true"';
        if (!data.content.image)
            data.content.image = '';
        if (!data.content.param_large)
            data.content.param_large = '';
        if (!data.content.param_round)
            data.content.param_round = '';
        if (!data.content.pin_size)
            data.content.pin_size = '';
        if (!data.content.pin_terse)
            data.content.pin_terse = '';
        if (!data.content.type)
            data.content.type = 'any_image';
        if (!data.content.param_pindo)
            data.content.param_pindo = 'data-pin-do="buttonBookmark"';
        if (!data.content.one_image_url)
            data.content.one_image_url = 'https://www.flickr.com/photos/kentbrew/6851755809/';
        if (!data.content.one_image_image)
            data.content.one_image_image = 'https://farm8.staticflickr.com/7027/6851755809_df5b2051c9_z.jpg';
        if (!data.content.one_image_description)
            data.content.one_image_description = 'Next stop: Pinterest';
        if (!data.content.img_tag)
            data.content.img_tag = '';
        if (!data.content.param_customimage)
            data.content.param_customimage = '';
        if (!data.content.large)
            data.content.large = 0;
        if (!data.content.description_visibility)
            data.content.description_visibility = 0;
        if (!data.content.round)
            data.content.round = 0;
        if (!data.content.custom_image)
            data.content.custom_image = '';
        if (!data.content.pinterest_url)
            data.content.pinterest_url = 'href="https://pinterest.com/pin/create/button/"';
        if (!data.content.follow_title)
            data.content.follow_title = 'Pinterest';
        if (!data.content.s_imagewidth)
            data.content.s_imagewidth = 400;
        if (!data.content.s_boardheight)
            data.content.s_boardheight = 240;
        if (!data.content.s_boardwidth)
            data.content.s_boardwidth = 80;
        if (!data.content.follow_url)
            data.content.follow_url = 'https://www.pinterest.com/pinterest/';
        if (!data.content.pin_url)
            data.content.pin_url = 'https://www.pinterest.com/pin/99360735500167749/';
        if (!data.content.board_url)
            data.content.board_url = 'https://www.pinterest.com/pinterest/official-news/';
        if (!data.content.profile_url)
            data.content.profile_url = 'https://www.pinterest.com/pinterest/';

        this.pluginScoped.addListener(this, function () {
        });
    },
    loadedAction: function (data, elem) {
        this.pluginScoped.addListener(this, function () {
        });
    }

});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"braintree","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/braintree\/main.png";
PluginWrapper._config.template = "{{#content.store}}\r\n<form method=\"post\" data-gateway-id=\"Braintree\" id=\"{{id}}_form\" style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"transactionId\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t<button class=\"btn btn-info\"\r\n\t\ttitle=\"Braintree\"\r\n\t\tstyle=\"width: 160px;\r\n\t\t\t   height: 40px;\r\n\t\t\t   border: 1px solid #000;\r\n\t\t\t   background: #fff;\r\n\t\t\t   padding: 6px 10px;\r\n\t\t\t   color: #000;\r\n\t\t\t   font-size: 18px;\r\n\t\t\t   font-family: Arial,Helvetica,sans-serif;\">Braintree<\/button>\r\n<\/form>\r\n<script type=\"text\/javascript\">\r\n\tsetTimeout(function() { \/\/ use timeout so that StoreModule.js assigned event to form in time\r\n\t\t$('#{{id}}_form').on('beforesend', function() {\r\n\t\t\tsetTimeout(function() {\r\n\t\t\t\twindow.{{id}}_show_braintree();\r\n\t\t\t}, 100);\r\n\t\t});\r\n\t}, 50);\r\n<\/script>\r\n{{\/content.store}}\r\n{{^content.store}}\r\n<button class=\"btn btn-info\" onclick=\"{{id}}_show_braintree()\"\r\n\ttitle=\"{{content.label}}\"\r\n\tstyle=\"width: 100%; height: 100%;\r\n\t\t   {{#content.borderCss}}{{content.borderCss}}{{\/content.borderCss}}\r\n\t\t   {{#content.background}}background: {{content.background}};{{\/content.background}}\r\n\t\t   padding: 6px 10px;\r\n\t\t   {{#content.fontColor}}color: {{content.fontColor}};{{\/content.fontColor}}\r\n\t\t   {{#content.fontSize}}font-size: {{content.fontSize}}px;{{\/content.fontSize}}\r\n\t\t   {{#content.fontFamily}}font-family: {{content.fontFamily}};{{\/content.fontFamily}}\">{{content.label}}<\/button>\r\n{{\/content.store}}\r\n\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\twindow.{{id}}_show_braintree = function() {\r\n\t\t\t$('#{{id}}_braintree_modal').modal('show');\r\n\t\t};\r\n\t\twindow.{{id}}_submit = function() {\r\n\t\t\t$('#{{id}}_form').find('input[type=\"submit\"]').trigger('click');\r\n\t\t};\r\n\t})();\r\n<\/script>\r\n<div class=\"modal fade\" id=\"{{id}}_braintree_modal\" role=\"dialog\">\r\n\t<div class=\"modal-dialog\">\r\n\t\t<div class=\"modal-content\">\r\n\t\t\t<div class=\"modal-header\">\r\n\t\t\t\t<button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;<\/button>\r\n\t\t\t\t<h4 class=\"modal-title\">Braintree<\/h4>\r\n\t\t\t<\/div>\r\n\t\t\t<div class=\"modal-body\">\r\n\t\t\t\t{{{requireService}}}\r\n\t\t\t<\/div>\r\n\t\t\t<div class=\"modal-footer\">\r\n\t\t\t\t<button type=\"button\" class=\"btn btn-default\" id=\"{{id}}_braintree-close-button\" data-dismiss=\"modal\">{{content.__t.close}}<\/button>\r\n\t\t\t\t<button type=\"button\" class=\"btn btn-primary\" id=\"{{id}}_braintree-submit-button\">{{content.__t.pay}}<\/button>\r\n\t\t\t<\/div>\r\n\t\t<\/div>\r\n\t<\/div>\r\n<\/div>\r\n<script type=\"text\/javascript\">\r\n\t$('#{{id}}_braintree_modal').appendTo('body');\r\n<\/script>\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/braintree/main.php';
PluginWrapper._config.active = true;
(function() {
	if (typeof window.braintree_translations === 'undefined') {
		window.braintree_translations = {
			'pay': __c('Pay'),
			'close': __c('Close'),
			'Error': __c('Error'),
			'loading...': __c('loading...'),
			'Unknown error': __c('Unknown error'),
			'Transaction ID': __c('Transaction ID'),
			'Payment has been submitted': __c('Payment has been submitted')
		};
	}
})();

ElementRegister.registerPaymentGateway({
    name: 'Braintree',
    id: 'braintree',
	pageUrl: 'https://www.braintreepayments.com/',
    keyFieldId: 'merchant_id',
    keyField2Id: 'public_key',
    keyField3Id: 'private_key',
	keyField4Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [12,6,6,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Public Key'), id: 'key2', css: {marginTop: 5}},
		{type: 'TextField', placeholder: __('Private Key'), id: 'key3', css: {marginTop: 5}},
		{type: 'CheckBox', label: __('Test mode'), id: 'key4', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
    priceFieldId: 'amount',
	titleFieldId: 'label',
	globalVars: ['merchant_id', 'public_key', 'private_key', 'demo'],
	__t: window.braintree_translations
});
PluginWrapper.registerPlugin('braintree', {
    name: 'Braintree',
    element: {
		minSize: {width: 100, height: 30},
		defaultSize: {width: 160, height: 40},
		resizable: true
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [4, 4, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Merchant ID'), helpText: __('This key you can get in account settings page')},
							{type: 'TextField', id: 'merchant_id'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Public Key'), helpText: __('This key you can get in account settings page')},
							{type: 'TextField', id: 'public_key'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Private Key'), helpText: __('This key you can get in account settings page')},
							{type: 'TextField', id: 'private_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred') + '. ' + __('Currency is set in accounts settings page')},
							{type: 'TextField', id: 'amount'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label')},
							{type: 'TextField', id: 'label'}
						]}
					]},
					{type: 'FlowLayout', spacing: 15, css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'background'}
						]},
						{type: 'VerticalLayout', css: {width: 150}, children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'fontFamily', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'fontSize'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'fontColor', noTransparent: true}
						]}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'right'});
						}}
					]}
				]}
			]}
        ]
    },
    openAction: function (fields, data, elem) {
        var itm;
        fields.amount.setText(data.content.amount);
        fields.merchant_id.setText(data.content.merchant_id);
        fields.public_key.setText(data.content.public_key);
        fields.private_key.setText(data.content.private_key);
        fields.label.setText(data.content.label);
		fields.border.setValue(data.content.border);
		fields.background.setValue(data.content.background);
		fields.fontFamily.setValue(data.content.fontFamily);
		fields.fontSize.setValue(data.content.fontSize);
		fields.fontColor.setValue(data.content.fontColor);
		fields.demo.setValue(data.content.demo);
    },
    applyAction: function (fields, data, elem) {
        var itm;
        data.content.amount = fields.amount.getText();
        data.content.merchant_id = fields.merchant_id.getText();
        data.content.public_key = fields.public_key.getText();
        data.content.private_key = fields.private_key.getText();
        data.content.label = fields.label.getText();
		data.content.border = fields.border.getValue();
		data.content.background = fields.background.getValue();
		data.content.fontFamily = fields.fontFamily.getValue();
		data.content.fontSize = fields.fontSize.getValue();
		data.content.fontColor = fields.fontColor.getValue();
		data.content.demo = fields.demo.getValue();
		data.content.borderCss = this.updateBorderCss(data);
    },
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
    loadAction: function (data) {
		data.content.__t = window.braintree_translations;
        if (!data.content.amount) data.content.amount = '1';
        if (!data.content.merchant_id) data.content.merchant_id = ''; // wd36rwgys9sbgp5h
        if (!data.content.public_key) data.content.public_key = ''; // pxnqqygsb8jnkgvh
        if (!data.content.private_key) data.content.private_key = ''; // 58639f7fd806508c101f9f78c61ddab3
		if (!data.content.label) data.content.label = 'Braintree';
		if (!data.content.border) data.content.border = {color: '#000', style: 'solid', weight: 1};
		if (!data.content.background) data.content.background = '#fff';
		if (!data.content.fontFamily) data.content.fontFamily = 'Roboto Slab';
		if (!data.content.fontSize) data.content.fontSize = '18';
		if (!data.content.fontColor) data.content.fontColor = '#000';
		if (data.content.demo === undefined) data.content.demo = false;
		data.content.borderCss = this.updateBorderCss(data);
    }
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"payme","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/payme\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Payme\" action=\"{{#content.demo}}https:\/\/test.paycom.uz{{\/content.demo}}{{^content.demo}}https:\/\/checkout.paycom.uz{{\/content.demo}}\" method=\"post\" style=\"width: 100%; height: 100%;\" id=\"{{id}}_payme_form\">\r\n\t<input type=\"hidden\" name=\"merchant\" value=\"{{content.merchantId}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"hidden\" name=\"description\" value=\"{{content.description}}\" \/>\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" data-multiplier=\"100\" data-fixed-decimal=\"0\" \/>\r\n\t<input type=\"hidden\" name=\"account[order_id]\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"callback\" value=\"{returnUrl}?txnid=:transaction_id\" \/>\r\n\t<button style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/payme\/payme-1-white.png\" alt=\"Payme\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<button class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal; overflow: hidden;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/payme\/site\/{{\/isPublished}}gallery_gen\/payme\/{{content.logo}}.png\" alt=\"Click\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>\r\n\r\n{{#isPublished}}{{^content.store}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\t$('#{{id}}_payme_form').on('submit', function(e, forceSubmit) {\r\n\t\t\tif (forceSubmit) return true;\r\n\t\t\tvar formElements = this.elements;\r\n\t\t\tvar formData = [];\r\n\t\t\tvar transactionId = null, orderPrice = null;\r\n\t\t\tfor (var i=0; i < formElements.length; i++) {\r\n\t\t\t\tif (!formElements[i].name) continue;\r\n\t\t\t\tif (formElements[i].name === 'account[order_id]') {\r\n\t\t\t\t\ttransactionId = formElements[i].value;\r\n\t\t\t\t} else if (formElements[i].name === 'amount') {\r\n\t\t\t\t\torderPrice = formElements[i].value;\r\n\t\t\t\t}\r\n\t\t\t\tformData.push({\r\n\t\t\t\t\tname: formElements[i].name,\r\n\t\t\t\t\tvalue: formElements[i].value,\r\n\t\t\t\t\tisPrice: false,\r\n\t\t\t\t\tfixedDecimal: -1,\r\n\t\t\t\t\tmultiplier: 0\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t\tvar thisSelf = this;\r\n\t\t\t$.ajax({\r\n\t\t\t\turl: $('base').attr('href') + 'store-submit\/Payme',\r\n\t\t\t\ttype: 'POST',\r\n\t\t\t\tcontentType: 'application\/json; charset=utf-8',\r\n\t\t\t\tdataType: 'json',\r\n\t\t\t\tdata: JSON.stringify({\r\n\t\t\t\t\tformData: formData,\r\n\t\t\t\t\ttransactionId: transactionId,\r\n\t\t\t\t\torderPrice: orderPrice\r\n\t\t\t\t}),\r\n\t\t\t\tcomplete: function() {\r\n\t\t\t\t\t$(thisSelf).trigger('submit', [true]);\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\treturn false;\r\n\t\t});\r\n\t})();\r\n<\/script>\r\n{{\/content.store}}{{\/isPublished}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/payme/main.php';
PluginWrapper._config.active = false;

ElementRegister.registerPaymentGateway({
	name: 'Payme',
	id: 'payme',
	pageUrl: 'https://payme.uz/',
	keyFieldId: 'merchantId',
	keyField2Id: 'merchantKey',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [6,6,12,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Merchant Key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['merchantId', 'merchantKey', 'demo']
});
PluginWrapper.registerPlugin('payme', {
	name: 'Payme',
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 120, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', spacing: 15, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant ID')},
						{type: 'TextField', id: 'merchantId'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant Key')},
						{type: 'TextField', id: 'merchantKey'}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [6,3,3], columnWeightsSmall: [6,3,3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'description'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred')},
						{type: 'TextField', id: 'amount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'currency', options: [
							{id: '643', name: 'RUB'},
							{id: '840', name: 'USD'},
							{id: '860', name: 'UZS'},
							{id: '978', name: 'EUR'}
						]}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Logo')},
						{type: 'DropdownBox', id: 'logo', options: [
							{id: 'payme-1-white', name: 'payme-1-white'},
							{id: 'payme-1-black', name: 'payme-1-black'},
							{id: 'payme-2-white', name: 'payme-2-white'},
							{id: 'payme-2-black', name: 'payme-2-black'}
						]}
					]},
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'right'});
					}}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		var itm;
		fields.merchantId.setText(data.content.merchantId);
		fields.merchantKey.setText(data.content.merchantKey);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		itm = fields.currency.getItemById(data.content.currency);
		fields.currency.selectItem(itm);
		itm = fields.logo.getItemById(data.content.logo);
		fields.logo.selectItem(itm);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		data.content.merchantId = fields.merchantId.getText();
		data.content.merchantKey = fields.merchantKey.getText();
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().id;
		itm = fields.logo.getSelectedItem();
		data.content.logo = itm.getOriginal().id;
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		data.content.__t = window.assist_translations;
		if (!data.content.merchantId) data.content.merchantId = '';
		if (!data.content.merchantKey) data.content.merchantKey = '';
		if (!data.content.description) data.content.description = '';
		if (!data.content.amount) data.content.amount = '1';
		if (!data.content.currency) data.content.currency = '860';
		if (!data.content.logo) data.content.logo = 'payme-1-white';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#fff';
		if (!data.content.font_family) data.content.font_family = "'Roboto Condensed',Arial,sans-serif";
		if (!data.content.font_size) data.content.font_size = '14';
		if (!data.content.label_color) data.content.label_color = '#333333';
		if (!data.content.button_border) data.content.button_border = {
			color: '#cccccc',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #cccccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"youku","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/youku\/main.png";
PluginWrapper._config.template = "<div style=\"width: 100%; height: 100%; background: #000;\">\r\n\t<div style=\"width: 0; height: 100%; display: inline-block; vertical-align: middle;\">\r\n\t<\/div><div style=\"display: inline-block; vertical-align: middle; width: 100%;\">\r\n\t\t<div style=\"position: relative; padding-bottom: 56.25%; height: 0;\">\r\n\t\t\t<iframe style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%;\" width=\"1000\" height=\"563\" src=\"https:\/\/player.youku.com\/embed\/{{content.finalGroupId}}?autoplay={{content.play}}&starttime={{content.startAt}}\" frameborder=\"0\" allowfullscreen><\/iframe>\r\n\t\t<\/div>\r\n\t<\/div>\r\n<\/div>";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('youku', {
	name: 'Youku',
	element: {
		minSize: {width: 100, height: 56},
		defaultSize: {width: 420, height: 236},
		resizable: true,
		supportsFullWidth: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Youku video URL'),
						helpText: __('Copy full Youku video URL') + ' <br /><div style="display: inline-block; max-width: 100%; word-break: break-all;">(http://v.youku.com/v_show/id_XMTYzOTI2OTE4MA==.html...)</div>'},
					{type: 'TextField', id: 'groupId'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'autoplay', label: __('Autoplay')},
					{type: 'VerticalLayout', ignore: true, children: [
						{type: 'Label', text: __('Start at')},
						{type: 'TextField', id: 'startAt', placeholder: '00:00'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, ignore: true, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label',
							text: __('Autoplay'),
							helpText: __('Disable or enable autoplay.')},
						{type: 'RadioBox', id: 'autoplay0', label: __('Enable'), group: 'play'},
						{type: 'RadioBox', id: 'autoplay1', label: __('Disable'), group: 'play'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Video quality settings'),
							helpText: __('Allows to preset video quality settings.')},
						{type: 'RadioBox', id: 'quality0', label: __('low'), group: 'quality'},
						{type: 'RadioBox', id: 'quality1', label: __('autolow'), group: 'quality'},
						{type: 'RadioBox', id: 'quality2', label: __('autohigh'), group: 'quality'},
						{type: 'RadioBox', id: 'quality3', label: __('Medium'), group: 'quality'},
						{type: 'RadioBox', id: 'quality4', label: __('high'), group: 'quality'},
						{type: 'RadioBox', id: 'quality5', label: __('best'), group: 'quality'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Window Mode settings'),
							helpText: __('Changes settings to window mode.')},
						{type: 'RadioBox', id: 'wmode0', label: __('window'),	   group: 'wmode', helpText: __('Broadest accessibility support.')},
						{type: 'RadioBox', id: 'wmode1', label: __('Transparent'), group: 'wmode',helpText: __('Transparency and alpha blending over HTML elements supported. HTML elements can overlap SWF content. Explicit layering control (all browsers).') },
						{type: 'RadioBox', id: 'wmode2', label: __('opaque'),	group: 'wmode', helpText: __('HTML elements can overlap SWF content. Explicit layering control (all browsers).')},
						{type: 'RadioBox', id: 'wmode3', label: __('direct'),	group: 'wmode', helpText: __('Best performance. Hardware accelerated presentation, including Stage Video and Stage 3D (all browsers).')},
						{type: 'RadioBox', id: 'wmode4', label: __('gpu'),	  group: 'wmode', helpText: __('Additional hardware acceleration on some Internet connected TVs and mobile devices.')}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Video background color'),
							helpText: __('Sets background color while video is loading')},
						{type: 'ColorSelector', id: 'color'}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		fields.groupId.setText(data.content.groupId);
		fields.autoplay.setValue(data.content.play === '1');
//		fields.startAt.setValue(data.content.startAt);
		/* fields.color.setValue(data.content.color);
		fields.autoplay0.setValue(data.content.play === 'true');
		fields.autoplay1.setValue(data.content.play === 'false');

		fields.quality0.setValue(data.content.quality === 'low');
		fields.quality1.setValue(data.content.quality === 'autolow');
		fields.quality2.setValue(data.content.quality === 'autohigh');
		fields.quality3.setValue(data.content.quality === 'medium');
		fields.quality4.setValue(data.content.quality === 'high');
		fields.quality5.setValue(data.content.quality === 'best');

		fields.wmode0.setValue(data.content.wmode === 'window');
		fields.wmode1.setValue(data.content.wmode === 'transparent');
		fields.wmode2.setValue(data.content.wmode === 'opaque');
		fields.wmode3.setValue(data.content.wmode === 'direct');
		fields.wmode4.setValue(data.content.wmode === 'gpu'); */
	},
	applyAction: function (fields, data, elem) {
		data.content.groupId = fields.groupId.getText();
		data.content.play = fields.autoplay.getValue() ? '1' : '0';
//		data.content.startAt = fields.startAt.getValue();
		/* data.content.color = fields.color.getValue().replace('#', '');
		data.content.finalGroupId = this._resolveFinalGroupId(data.content.groupId);

		if (fields.autoplay0.getValue()) data.content.play = 'true';
		if (fields.autoplay1.getValue()) data.content.play = 'false';

		if (fields.quality0.getValue()) data.content.quality = 'low';
		if (fields.quality1.getValue())data.content.quality = 'autolow';
		if (fields.quality2.getValue())data.content.quality = 'autohigh';
		if (fields.quality3.getValue())data.content.quality = 'medium';
		if (fields.quality4.getValue())data.content.quality = 'high';
		if (fields.quality5.getValue())data.content.quality = 'best';

		if (fields.wmode0.getValue())data.content.wmode = 'window';
		if (fields.wmode1.getValue())data.content.wmode = 'transparent';
		if (fields.wmode2.getValue())data.content.wmode = 'opaque';
		if (fields.wmode3.getValue())data.content.wmode = 'direct';
		if (fields.wmode4.getValue())data.content.wmode = 'gpu'; */
	},
	_resolveFinalGroupId: function(groupId) {
		if (/https?:\/\/v.youku.com\/v_show\/id_([A-Za-z0-9=]+)/.test(groupId)
				|| /https?:\/\/player\.youku\.com\/player\.php\/sid\/([A-Za-z0-9=]+)/.test(groupId)
				|| /https?:\/\/player\.youku\.com\/embed\/([A-Za-z0-9=]+)/.test(groupId)) {
			return RegExp.$1;
		}
		return groupId;
	},
	loadAction: function (data) {
		if (!data.content.groupId) data.content.groupId = 'XMTYzOTI2OTE4MA';
//		if (!data.content.startAt) data.content.startAt = '';
		if (!data.content.play) data.content.play = '0';
		/* if (!data.content.quality) data.content.quality = 'high';
		if (!data.content.wmode) data.content.wmode = 'window';
		if (!data.content.color) data.content.color = 'ffffff'; */
		data.content.finalGroupId = this._resolveFinalGroupId(data.content.groupId);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"facebook_comment","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/facebook_comment\/main.png";
PluginWrapper._config.template = "<div class=\"fb_comment_wrap\" style=\"width:100%; height:{{height}}px; overflow-y: auto; overflow-x: hidden;\">\r\n\t<div id=\"fb-root\"><\/div>\r\n\t{{#isPublished}}\r\n\t<script>\r\n\t\t(function (d, s, id) {\r\n\t\t\tvar js, fjs = d.getElementsByTagName(s)[0];\r\n\t\t\tif (d.getElementById(id))\r\n\t\t\t\treturn;\r\n\t\t\tjs = d.createElement(s);\r\n\t\t\tjs.id = id;\r\n\t\t\tjs.async = false;\r\n\t\t\tjs.src = \"\/\/connect.facebook.net\/en_US\/sdk.js#xfbml=1&version=v2.6\";\r\n\t\t\tfjs.parentNode.insertBefore(js, fjs);\r\n\t\t}(document, 'script', 'facebook-jssdk'));\r\n\t<\/script>\r\n\t{{\/isPublished}}\r\n\r\n\t<div class=\"fb-comments\" data-href=\"{{content.pageUrl}}\" data-order-by=\"{{content.order_by}}\" data-colorscheme=\"{{content.colorscheme}}\" data-numposts=\"{{content.postNumber}}\" data-width=\"100%\"><\/div>\r\n<\/div>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('facebook_comment', {
	name: 'Comments',
	element: {
		minSize: {width: 100, height: 100},
		defaultSize: {width: 500, height: 400},
		resizable: true,
		renderOnce: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [7, 5], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Link'), helpText:__('URL address of your link, where this comments box will be post')},
							{type: 'TextField', id: 'pageUrl'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Number of items to show')},
							{type: 'SizeSelector', id: 'postNumber', max:20}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color Scheme'), helpText: __('The color scheme used by the comments plugin')},
							{type: 'DropdownBox', id: 'colorscheme', options: [
								{id: '#light', name: 'light', value: 'light'},
								{id: '#dark', name: 'dark', value: 'dark'}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Comments Sorting'), helpText: __('The order to use when displaying comments')},
							{type: 'DropdownBox', id: 'order_by', options: [
								{id: '#social', name: 'social', value: 'social'},
								{id: '#reverse_time', name: 'reverse_time', value: 'reverse_time'},
								{id: '#time', name: 'time', value: 'time'}
							]}
						]}
					]}
				]}
			]}
		]
	},
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (typeof func === 'function') {
				if (this.scriptReady) {
					func.call(inst);
				} else {
					this.listeners.push({inst: inst, func: func});
				}
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('https://connect.facebook.net/en_US/sdk.js', function() {
					FB.init({
						status     : true,
						xfbml      : true,
						version    : 'v2.6'
					});
					self.scriptReady = true;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst);
					}
				});
			}
		}
	},
	resizeTimeout: null,
	resizeAction: function(data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function () {
				self.resizeTimeout = null;
				self.updateElement();
				elem.children('.fb_comment_wrap').css({height:data.height});
				FB.XFBML.parse(elem.get(0));
			}, 1000);
		}
	},
	openAction: function(fields, data, elem) {
		var itm;
		itm = fields.colorscheme.getItemById('#' + data.content.colorscheme);
		fields.colorscheme.selectItem(itm);
		itm = fields.order_by.getItemById('#' + data.content.order_by);
		fields.order_by.selectItem(itm);
		fields.pageUrl.setText(data.content.pageUrl);
		fields.postNumber.setValue(data.content.postNumber);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		itm = fields.colorscheme.getSelectedItem();
		data.content.colorscheme = itm.getOriginal().value;
		itm = fields.order_by.getSelectedItem();
		data.content.order_by = itm.getOriginal().value;
		data.content.pageUrl = fields.pageUrl.getText();
		data.content.postNumber = fields.postNumber.getValue();
		elem.find('.fb-comments').attr({'data-width':data.width,'data-href':data.content.pageUrl,'data-numposts': data.content.postNumber,'data-colorscheme':data.content.colorscheme, 'data-order-by':data.content.order_by});
	},
	loadAction: function (data) {
		if (!data.content.pageUrl) data.content.pageUrl = 'https://developers.facebook.com/docs/plugins/comments#configurator';
		if (!data.content.postNumber) data.content.postNumber = '5';
		if (!data.content.colorscheme) data.content.colorscheme = 'light';
		if (!data.content.order_by) data.content.order_by = 'social';
	},
	loadedAction: function(data, elem) {
		this.pluginScoped.addListener(this, function() {
		});
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"mollie","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/mollie\/main.png";
PluginWrapper._config.template = "{{#content.store}}\r\n<button type=\"submit\" class=\"btn btn-info\" onclick=\"{{id}}_showModal()\"\r\n\t\ttitle=\"{{content.label}}\"\r\n\t\tstyle=\"width: 150px;\r\n\t\t\t   height: 40px;\r\n\t\t\t   border: solid 1px #000;\r\n\t\t\t   background: #fff;\r\n\t\t\t   padding: 6px 10px;\r\n\t\t\t   color: #000;\r\n\t\t\t   font-size: 18px;\r\n\t\t\t   font-family: Arial,Helvetica,sans-serif;\">{{content.label}}<\/button>\r\n\t\t\t   \r\n<div class=\"modal fade\" id=\"{{id}}_modal\" tabindex=\"-1\" role=\"dialog\">\r\n    <div class=\"modal-dialog\" role=\"document\">\r\n        <div class=\"modal-content\">\r\n            <div class=\"modal-header\">\r\n                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;<\/span><\/button>\r\n                <h4 class=\"modal-title\">Mollie<\/h4>\r\n            <\/div>\r\n            <div class=\"modal-body\">\r\n{{\/content.store}}\r\n\t\t\t\t<form data-gateway-id=\"Mollie\" method=\"POST\" accept-charset=\"utf-8\" target=\"_blank\" style=\"width: 100%; height: 100%;\">\r\n\t\t\t\t\t{{#content.store}}\r\n\t\t\t\t\t<div class=\"row\">\r\n\t\t\t\t\t\t<div class=\"form-group col-sm-6\">\r\n\t\t\t\t\t\t\t<label>{{content.__t.first_name}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n\t\t\t\t\t\t\t<input class=\"form-control input-sm\" type=\"text\" name=\"StoreModuleBuyer[first_name]\" required \/>\r\n\t\t\t\t\t\t<\/div>\r\n\t\t\t\t\t\t<div class=\"form-group col-sm-6\">\r\n\t\t\t\t\t\t\t<label>{{content.__t.last_name}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n\t\t\t\t\t\t\t<input class=\"form-control input-sm\" type=\"text\" name=\"StoreModuleBuyer[last_name]\" required \/>\r\n\t\t\t\t\t\t<\/div>\r\n\t\t\t\t\t<\/div>\r\n\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t<label>{{content.__t.email}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n\t\t\t\t\t\t<input class=\"form-control input-sm\" type=\"email\" name=\"StoreModuleBuyer[email]\" required \/>\r\n\t\t\t\t\t<\/div>\r\n\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t<label>{{content.__t.address}}<\/label>\r\n\t\t\t\t\t\t<input class=\"form-control input-sm\" type=\"text\" name=\"StoreModuleBuyer[address]\" \/>\r\n\t\t\t\t\t<\/div>\r\n\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t<label>{{content.__t.phone}}<\/label>\r\n\t\t\t\t\t\t<input class=\"form-control input-sm\" type=\"text\" name=\"StoreModuleBuyer[phone]\" \/>\r\n\t\t\t\t\t<\/div>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"redirectUrl\" value=\"{returnUrl}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"webhookUrl\" value=\"{callbackUrl}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"orderId\" value=\"{transactionId}\" \/>\r\n\t\t\t\t\t<input type=\"submit\" class=\"hidden\" \/>\r\n\t\t\t\t\t{{\/content.store}}\r\n\t\t\t\t\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"description\" value=\"{{content.description}}\" \/>\r\n\t\t\t\t\t{{^content.store}}\r\n\t\t\t\t\t<input type=\"hidden\" name=\"{{id}}_submit\" value=\"1\" \/>\r\n\t\t\t\t\t<button type=\"submit\" class=\"btn btn-info\"\r\n\t\t\t\t\t\t\ttitle=\"{{content.label}}\"\r\n\t\t\t\t\t\t\tstyle=\"width: 100%; height: 100%;\r\n\t\t\t\t\t\t\t\t   {{#content.borderCss}}{{content.borderCss}}{{\/content.borderCss}}\r\n\t\t\t\t\t\t\t\t   {{#content.background}}background: {{content.background}};{{\/content.background}}\r\n\t\t\t\t\t\t\t\t   padding: 6px 10px;\r\n\t\t\t\t\t\t\t\t   {{#content.fontColor}}color: {{content.fontColor}};{{\/content.fontColor}}\r\n\t\t\t\t\t\t\t\t   {{#content.fontSize}}font-size: {{content.fontSize}}px;{{\/content.fontSize}}\r\n\t\t\t\t\t\t\t\t   {{#content.fontFamily}}font-family: {{content.fontFamily}};{{\/content.fontFamily}}\">{{content.label}}<\/button>\r\n\t\t\t\t\t{{{requireService}}}\r\n\t\t\t\t\t{{\/content.store}}\r\n\t\t\t\t<\/form>\r\n{{#content.store}}\r\n\t\t\t<\/div>\r\n\t\t\t<div class=\"modal-footer\">\r\n                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">{{content.__t.close}}<\/button>\r\n                <button type=\"button\" class=\"btn btn-primary\" onclick=\"{{id}}_submit()\">{{content.__t.pay}}<\/button>\r\n            <\/div>\r\n\t\t<\/div>\r\n\t<\/div>\r\n<\/div>\r\n<script type=\"text\/javascript\">\r\n\tfunction {{id}}_showModal() {\r\n\t\t$('#{{id}}_modal').appendTo(\"body\");\r\n\t\t$('#{{id}}_modal').modal('show');\r\n\t}\r\n\tfunction {{id}}_submit() {\r\n\t\t$('#{{id}}_modal').find('input[type=\"submit\"]').trigger('click');\r\n\t}\r\n<\/script>\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/mollie/main.php';
PluginWrapper._config.active = false;
(function() {
	if (typeof window.mollie_translations === 'undefined') {
		window.mollie_translations = {
			'first_name': __c('First Name'),
			'last_name': __c('Last Name'),
			'email': __c('E-mail'),
			'address': __c('Address'),
			'phone': __c('Phone'),
			'close': __c('Close'),
			'pay': __c('Pay')
		};
	}
})();

ElementRegister.registerPaymentGateway({
    name: 'Mollie',
    id: 'mollie',
	pageUrl: 'https://www.mollie.com/',
    keyField: __('API Key'),
    keyFieldId: 'api_key',
    titleFieldId: 'label',
    nameFieldId: 'description',
    priceFieldId: 'amount',
	globalVars: ['api_key'],
	__t: window.mollie_translations
});
PluginWrapper.registerPlugin('mollie', {
    name: 'Mollie',
    element: {
		minSize: {width: 100, height: 30},
		defaultSize: {width: 160, height: 39},
		resizable: true
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('API Key'), helpText: __('This key you can get in account settings page')},
							{type: 'TextField', id: 'api_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'description'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred') + ', EUR'},
							{type: 'TextField', id: 'amount'}
						]}
					]},
					{type: 'VerticalLayout',css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label')},
							{type: 'TextField', id: 'label'}
						]}
					]},
					{type: 'FlowLayout', spacing: 15, css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'background'}
						]},
						{type: 'VerticalLayout', css: {width: 150}, children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'fontFamily', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'fontSize'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'fontColor', noTransparent: true}
						]}
					]}
				]}
			]}
        ]
    },
    openAction: function (fields, data, elem) {
        fields.description.setText(data.content.description);
        fields.amount.setText(data.content.amount);
        fields.api_key.setText(data.content.api_key);
        fields.label.setText(data.content.label);
		fields.border.setValue(data.content.border);
		fields.background.setValue(data.content.background);
		fields.fontFamily.setValue(data.content.fontFamily);
		fields.fontSize.setValue(data.content.fontSize);
		fields.fontColor.setValue(data.content.fontColor);
    },
    applyAction: function (fields, data, elem) {
        data.content.description = fields.description.getText();
        data.content.amount = fields.amount.getText();
        data.content.api_key = fields.api_key.getText();
        data.content.label = fields.label.getText();
		data.content.border = fields.border.getValue();
		data.content.background = fields.background.getValue();
		data.content.fontFamily = fields.fontFamily.getValue();
		data.content.fontSize = fields.fontSize.getValue();
		data.content.fontColor = fields.fontColor.getValue();
		data.content.borderCss = this.updateBorderCss(data);
    },
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
    loadAction: function (data) {
        if (!data.content.description) data.content.description = ''; // Items description
        if (!data.content.amount) data.content.amount = ''; // 129.99
        if (!data.content.api_key) data.content.api_key = ''; // test_Hptv39GWS46hmAJsjGx5bFJARsAMJb
		if (!data.content.label) data.content.label = 'mollie';
		if (!data.content.border) data.content.border = {color: '#000', style: 'solid', weight: 1};
		if (!data.content.background) data.content.background = '#fff';
		if (!data.content.fontFamily) data.content.fontFamily = 'Roboto Slab';
		if (!data.content.fontSize) data.content.fontSize = '18';
		if (!data.content.fontColor) data.content.fontColor = '#000';
		data.content.borderCss = this.updateBorderCss(data);
    }
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"gestpay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/gestpay\/main.png";
PluginWrapper._config.template = "<form {{#content.store}}action=\"{{#content.demo}}https:\/\/testecomm.sella.it\/pagam\/pagam.aspx{{\/content.demo}}{{^content.demo}}https:\/\/ecomm.sella.it\/pagam\/pagam.aspx{{\/content.demo}}{{\/content.store}}\" method=\"post\" data-gateway-id=\"Gestpay\" style=\"width: 100%; height: 100%;\"{{^content.store}} target=\"_blank\"{{\/content.store}}>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"name\" value=\"{{content.name}}\" \/>\r\n\t<input type=\"hidden\" name=\"price\" value=\"{{content.price}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"hidden\" name=\"transactionId\" value=\"{transactionId}\" \/>\r\n\t<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/gestpay\/gestpay.png\" alt=\"\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<input type=\"hidden\" name=\"{{id}}_submit\" value=\"1\" \/>\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/gestpay\/site\/{{\/isPublished}}gallery_gen\/gestpay\/gestpay.png\" alt=\"Gestpay\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/gestpay/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'Gestpay',
	id: 'gestpay',
	keyFieldId: 'shop',
	keyField2Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [12,12], children: [
		{type: 'TextField', placeholder: __('Shop login'), id: 'key'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key2', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'name',
	priceFieldId: 'price',
	currencyFieldId: 'currency',
	globalVars: ['shop', 'demo'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window.gestpay_settings_dialog().setVisible(true); });
		return btn;
	}
});

(function() {
	var dlg = null;
	window.gestpay_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://www.gestpay.it/" target="_blank">https://www.gestpay.it/</a></p>'
					+ '<p><strong>These parameters must be enabled in Gestpay Back Office:</strong></p>'
					+ '<ul><li>Language</li></ul>'
					+ '<p><strong>URL for positive response</strong> (IT: <em>"URL per risposta positiva"</em>)<strong>:</strong><br />'
					+ '<pre>' + base_url + 'store-return/Gestpay' + '</pre></p>'
					+ '<p><strong>URL for negative response</strong> (IT: <em>"URL per risposta negativa"</em>)<strong>:</strong><br />'
					+ '<pre>' + base_url + 'store-cancel/Gestpay' + '</pre></p>'
					+ '<p><strong>URL Server to Server</strong> (IT: <em>"URL Server to Server"</em>)<strong>:</strong><br />'
					+ '<pre>' + base_url + 'store-callback/Gestpay' + '</pre></p>';
			
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
})();

PluginWrapper.registerPlugin('gestpay', {
	name: 'Gestpay',
	element: {
		minSize: {width: 70, height: 35},
		defaultSize: {width: 130, height: 60},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Shop login'), helpText: __('Shop login code on Gestpay site')},
							{type: 'TextField', id: 'shop'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'name'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred')},
							{type: 'TextField', id: 'price'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label')},
							{type: 'TextField', id: 'button_label'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: '242', name: 'EUR'},
								{id:   '1', name: 'USD'},
								{id: '187', name: 'AED'},
								{id: '109', name: 'AUD'},
								{id: '262', name: 'BGN'},
								{id: '234', name: 'BRL'},
								{id:  '12', name: 'CAD'},
								{id:   '3', name: 'CHF'},
								{id: '144', name: 'CNY'},
								{id: '223', name: 'CZK'},
								{id:   '7', name: 'DKK'},
								{id:   '2', name: 'GBP'},
								{id: '103', name: 'HKD'},
								{id: '229', name: 'HRK'},
								{id: '153', name: 'HUF'},
								{id: '123', name: 'IDR'},
								{id: '203', name: 'ILS'},
								{id:  '31', name: 'INR'},
								{id:  '62', name: 'ISK'},
								{id:  '71', name: 'JPY'},
								{id: '119', name: 'KRW'},
								{id:  '55', name: 'MYR'},
								{id:  '81', name: 'NGN'},
								{id:   '8', name: 'NOK'},
								{id: '113', name: 'NZD'},
								{id:  '66', name: 'PHP'},
								{id:  '26', name: 'PKR'},
								{id: '237', name: 'PLN'},
								{id: '270', name: 'RON'},
								{id: '244', name: 'RUB'},
								{id:  '75', name: 'SAR'},
								{id:   '9', name: 'SEK'},
								{id: '124', name: 'SGD'},
								{id:  '73', name: 'THB'},
								{id: '267', name: 'TRY'},
								{id: '143', name: 'TWD'},
								{id: '241', name: 'UAH'},
								{id: '145', name: 'VND'},
								{id:  '82', name: 'ZAR'}
							]}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'button_border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'button_color'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'font_size'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'label_color', noTransparent: true}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', css: {width: 120}, children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Max logo width')},
							{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Show logo')},
							{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
							{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Mode'), init: function() {
							var link = $('<a>').attr('href', 'javascript:void(0)').text(__('Settings'));
							link.on('click', function() {
								window.gestpay_settings_dialog().setVisible(true);
							});
							var cont = $('<span>').css({fontWeight: 'normal', marginLeft: '4px'});
							cont.append('(');
							cont.append(link);
							cont.append(')');
							this._elem.append(cont);
						}},
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'right'});
						}}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		fields.shop.setText(data.content.shop);
		fields.name.setText(data.content.name);
		fields.price.setText(data.content.price);
		itm = fields.currency.getItemById(data.content.currency);
		fields.currency.selectItem(itm);
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		data.content.shop = fields.shop.getText();
		data.content.name = fields.name.getText();
		data.content.price = fields.price.getText();
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().id;
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.shop) data.content.shop = '';
		if (!data.content.name) data.content.name = '';
		if (!data.content.price) data.content.price = '1';
		if (!data.content.currency) data.content.currency = '242'; // EUR
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#516b85';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#fff';
		if (!data.content.button_border) data.content.button_border = {
			color: '#ccc',
			style: 'none',
			weight: 1,
			css: { border: '1px none #ccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"qiwi","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/qiwi\/main.png";
PluginWrapper._config.template = "<form action=\"http:\/\/w.qiwi.ru\/setInetBill.do\" method=\"GET\">\r\n    <input type=\"hidden\" name=\"from\" value=\"{{content.from}}\" \/>\r\n    <input type=\"hidden\" name=\"summ\" value=\"{{content.summ}}\" \/>\r\n    <input type=\"hidden\" name=\"com\" value=\"{{content.com}}\" \/>\r\n    <input type=\"hidden\" name=\"check_agt\" value=\"false\" \/>\r\n    <button style=\"background:url('https:\/\/corp.qiwi.com\/dam\/jcr:526ba995-d4bb-4f10-bad2-94633d72ee1d') no-repeat; background-size:contain; border: none; width:{{width}}px; height:{{height}}px\" type=\"submit\">\r\n    <\/button>\r\n<\/form>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
    name: __('QIWI'),
    id: 'qiwi',
    keyField: __('Provider identifier'),
    keyFieldId: 'from',
    titleFieldId: 'label',
    nameFieldId: 'com',
    priceFieldId: 'summ'
});
PluginWrapper.registerPlugin('qiwi', {
    name: 'QIWI',
    element: {
        minSize: {width: 115, height: 65},
        defaultSize: {width: 115, height: 65},
        resizable: true
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {children: [{type: 'VerticalLayout', spacing: 15, children: [
                            {type: 'HorizontalLayout', css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Provider identifier'), helpText:__('Your wallet ID from account')},
                                            {type: 'TextField', id: 'from'}
                                        ]}
                                ]},
                            {type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Item Name')},
                                            {type: 'TextField', id: 'com'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Amount')},
                                            {type: 'TextField', id: 'summ'}
                                        ]}
                                ]}
                        ]}
                ]}
        ]
    },
    resizeAction: function (data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function () {
                self.resizeTimeout = null;
                self.updateElement();
            }, 1000);
        }
    },
    openAction: function (fields, data, elem) {
        fields.com.setText(data.content.com);
        fields.summ.setText(data.content.summ);
        fields.from.setText(data.content.from);
    },
    applyAction: function (fields, data, elem) {
        data.content.com = fields.com.getText();
        data.content.summ = fields.summ.getText();
        data.content.from = fields.from.getText();
    },
    loadAction: function (data) {
        if (!data.content.com)
            data.content.com = 'Products';
        if (!data.content.summ)
            data.content.summ = '25.99';
        if (!data.content.from)
            data.content.from = '555';
    }
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"ecwid","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/ecwid\/main.png";
PluginWrapper._config.template = "\r\n<div id=\"{{id}}_widget_cont\" style=\"width: 100%; height: 100%; overflow: auto;\">\r\n<div id=\"{{id}}_widget\"><\/div>\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\" src=\"https:\/\/app.ecwid.com\/script.js?{{#content.storeId}}{{content.storeId}}{{\/content.storeId}}{{^content.storeId}}{{content.demoStoreId}}{{\/content.storeId}}&data_platform=code\" charset=\"utf-8\"><\/script>\r\n<script type=\"text\/javascript\"> {{{content.initCall.out}}} <\/script>\r\n{{\/isPublished}}\r\n<\/div>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;

/* global Ecwid, PluginWrapper */

PluginWrapper.registerPlugin('ecwid', {
	name: 'Ecwid',
	element: {
		minSize: {width: 100, height: 24},
		defaultSize: {width: 750, height: 285},
		renderOnce: true,
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{name: __('Store Info'), children: [
				{type: 'Image', src: 'plugins/ecwid/logo.png', id: 'storeLogo', css: {width: 73, display: 'block', margin: '0 auto'}},
				{type: 'VerticalLayout', id: 'storeIdBlock', css: {textAlign: 'left', marginTop: 15}, children: [
					{type: 'Label', text: __('Store ID'), helpText: __('Login to your Account and at the bottom right of the page you will find your "Store ID".')},
					{type: 'TextField', id: 'storeId'}
				]},
				{type: 'Button', text: __('Manage Store'), id: 'loginBtn', css: {margin: '0 5px'}},
				{type: 'Button', text: __('Create New Store'), id: 'registerBtn', css: {margin: '0 5px'}},
				{type: 'CustomContainer', id: 'liteBlock', init: function(def, fields) {
					this._elem.css({margin: '20px auto 0 auto', width: '75%'})
							.append(fields.loginBtn._elem)
							.append(fields.registerBtn._elem)
							.append(fields.storeIdBlock._elem);
				}},
				
				{type: 'Button', text: __('Manage Store'), id: 'cpOpen'},
				{type: 'Button', text: __('Connect existing account'), id: 'regConnect', buttonStyle: 'link'},
				{type: 'CustomContainer', id: 'storeInfo', init: function() {
					this._label = $('<label>');
					this._disconnect = $('<a href="javascript:void(0)">').text(__('logout'));
					this._storeId = null;
					this.setStoreId = function(storeId) {
						this._storeId = storeId;
						this._label.text((this._storeId ? this._storeId : ''));
						return this;
					};
					this.getStoreId = function() {
						return this._storeId;
					};
					this._elem.append(__('Store') + ': ');
					this._elem.append(this._label);
					this._elem.append('&nbsp;('); this._elem.append(this._disconnect); this._elem.append(')');
				}},
				{type: 'CustomContainer', id: 'buttons', init: function(def, fields) {
					this._elem.css({marginTop: 20})
							.append(fields.storeInfo._elem)
							.append(fields.cpOpen._elem)
							.append($('<div>').css({marginTop: 10}).html('<strong>' + __('OR') + '</strong>'))
							.append(fields.regConnect._elem);
				}},
				{type: 'VerticalLayout', id: 'connectForm', css: {textAlign: 'left', width: '75%', margin: '20px auto 0 auto'}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Store ID'), helpText: __('Login to your Account and at the bottom right of the page you will find your "Store ID".')},
						{type: 'TextField', id: 'conStoreId'}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 10}, children: [
						{type: 'Button', text: '< ' + __('Back'), id: 'regRegister', buttonStyle: 'link'},
						{type: 'VerticalLayout', css: {textAlign: 'right'}, children: [
							{type: 'Button', text: __('Connect Ecwid account'), id: 'conSubmit'}
						]}
					]}
				]},
				{type: 'CustomContainer', init: function(def, fields) {
					var liteMode = (wb_builder.ecwidConfig && typeof(wb_builder.ecwidConfig) === 'object'
							&& wb_builder.ecwidConfig.loginUrl && wb_builder.ecwidConfig.registerUrl);
					var container = $('<div>').css({height: 260, textAlign: 'center'})
						.append($('<div>').css({width: '100%', paddingTop: 35}));
					container.append(fields.storeLogo._elem);
					if (liteMode) {
						fields.buttons._elem.hide();
						fields.connectForm._elem.hide();
						container
								.append(fields.liteBlock._elem);
					} else {
						fields.liteBlock._elem.hide();
						container
								.append(fields.buttons._elem)
								.append(fields.connectForm._elem);
					}
					this._elem.append(container);
				}}
			]},
			{name: __('General'), children: [
				{type: 'VerticalLayout', children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Widget type')},
							{type: 'DropdownBox', id: 'type', options: [
								{id: 'product-browser', name: __('Product Browser')},
								{id: 'horizontal-categories', name: __('Horizontal categories')},
								{id: 'vertical-categories', name: __('Vertical categories')},
								{id: 'mini-cart', name: __('Mini cart')},
								{id: 'search-box', name: __('Search box')}
							]}
						]}
					]}
				]},
				{type: 'VerticalLayout', id: 'settings', css: {marginTop: 15}, children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Grid View settings')},
							{type: 'HorizontalLayout', children: [
								{type: 'Label', text: __('Rows'), css: {paddingTop: '5px'}},
								{type: 'SizeSelector', id: 'gridViewRows'}
							]},
							{type: 'HorizontalLayout', css: {marginTop: 4}, children: [
								{type: 'Label', text: __('Columns'), css: {paddingTop: '5px'}},
								{type: 'SizeSelector', id: 'gridViewCols'}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('List View settings')},
							{type: 'HorizontalLayout', children: [
								{type: 'Label', text: __('Rows'), css: {paddingTop: '5px'}},
								{type: 'SizeSelector', id: 'listViewRows'}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Table View settings')},
							{type: 'HorizontalLayout', children: [
								{type: 'Label', text: __('Rows'), css: {paddingTop: '5px'}},
								{type: 'SizeSelector', id: 'tableViewRows'}
							]}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Default category view')},
							{type: 'DropdownBox', id: 'categoryView', options: [
								{id: 'grid', name: __('Grid view')},
								{id: 'list', name: __('List view')},
								{id: 'table', name: __('Table view')}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Default search view')},
							{type: 'DropdownBox', id: 'searchView', options: [
								{id: 'grid', name: __('Grid view')},
								{id: 'list', name: __('List view')},
								{id: 'table', name: __('Table view')}
							]}
						]}
					]}
				]}
			]}
		]
	},
	
	pluginScoped: {
		demoStoreId: (wb_builder.ecwidConfig && (typeof wb_builder.ecwidConfig === 'object') && wb_builder.ecwidConfig.demoStoreId) ? wb_builder.ecwidConfig.demoStoreId : '11549878',
		loginUrl: (wb_builder.ecwidConfig && (typeof wb_builder.ecwidConfig === 'object') && wb_builder.ecwidConfig.loginUrl) ? wb_builder.ecwidConfig.loginUrl : null,
		registerUrl: (wb_builder.ecwidConfig && (typeof wb_builder.ecwidConfig === 'object') && wb_builder.ecwidConfig.registerUrl) ? wb_builder.ecwidConfig.registerUrl : null,
		isLiteMode: function() { return this.loginUrl && this.registerUrl; },
		cpLastStoreId: null,
		scriptLoaded: false,
		scriptAPILoaded: false,
		scriptReady: false,
		listeners: [],
		widgetLoadingTimeout: null,
		widgetLoadingText: (__('loading...').replace('...', '') + ' ' + ((wb_builder.whiteLabel && (typeof wb_builder.whiteLabel === 'object') && wb_builder.whiteLabel.ecwid) ? __('Store') : 'Ecwid') + '...'),
		addListener: function(inst, func, storeId) {
			if (this.scriptReady) {
				window.xnext_ownerId = parseInt(storeId);
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func, storeId: storeId});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('https://app.ecwid.com/script.js?' + storeId, function() {
					if (window.Ecwid && Ecwid.OnAPILoaded) {
						Ecwid.OnAPILoaded.add(function() {
							self.scriptAPILoaded = true;
						});
					}
					var compleFunc = function() {
						var repeat = false;
						if (typeof window.Ecwid.destroy === 'function'/*  && typeof window.xnextScrollTop === 'function' */) {
							if (self.scriptAPILoaded) {
								self.scriptReady = true;
								for (var i = 0; i < self.listeners.length; i++) {
									window.xnext_ownerId = parseInt(self.listeners[i].storeId);
									try { self.listeners[i].func.call(self.listeners[i].inst); } catch (ex) { console.error(ex); }
								}
							} else {
								repeat = true;
							}
						} else {
							repeat = true;
						}
						if (repeat) {
							setTimeout(function() { compleFunc(); }, 100);
						}
					};
					compleFunc();
				});
			}
		},
		initCallCreate: function(data) {
			var initCall;
			if (data.content.type === 'horizontal-categories') {
				initCall = {func: 'xCategories', args: ['id=' + data.id + '_widget']};
			} else if (data.content.type === 'vertical-categories') {
				initCall = {func: 'xVCategories', args: ['id=' + data.id + '_widget']};
			} else if (data.content.type === 'mini-cart') {
				initCall = {func: 'xMinicart', args: ['layout=attachToCategories', 'id=' + data.id + '_widget']};
			} else if (data.content.type === 'search-box') {
				initCall = {func: 'xSearchPanel', args: ['id=' + data.id + '_widget']};
			} else { // product-browser
				initCall = {func: 'xProductBrowser', args: [
					'categoriesPerRow=' + data.content.gridViewRows,
					'views=grid(' + data.content.gridViewCols + ',' + data.content.gridViewRows + ') list(' + data.content.listViewRows + ') table(' + data.content.tableViewRows + ')',
					'categoryView=' + data.content.categoryView,
					'searchView=' + data.content.searchView,
					'id=' + data.id + '_widget'
				]};
			}
			initCall.out = this.initCallToString(initCall);
			return initCall;
		},
		initCallToString: function(initCall) {
			if (!initCall) return '';
			var i, args = '';
			for (i = 0; i < initCall.args.length; i++) {
				if (i > 0) args += ", ";
				args += "'" + initCall.args[i] + "'";
			}
			return "if (typeof window." + initCall.func + " === 'function') window." + initCall.func + "(" + args + ");";
		},
		cpDialog: null,
		cpDialogTitle: __('Ecwid control panel')
	},
	openAction: function(fields, data, elem) {
		var itm, thisSelf = this;
		itm = fields.type.getItemById(data.content.type);
		fields.type.selectItem(itm);
		fields.gridViewRows.setValue(data.content.gridViewRows);
		fields.gridViewCols.setValue(data.content.gridViewCols);
		fields.listViewRows.setValue(data.content.listViewRows);
		fields.tableViewRows.setValue(data.content.tableViewRows);
		itm = fields.categoryView.getItemById(data.content.categoryView);
		fields.categoryView.selectItem(itm);
		itm = fields.searchView.getItemById(data.content.searchView);
		fields.searchView.selectItem(itm);
		
		if (!fields.eventsIsSet) {
			fields.eventsIsSet = true;
			fields.loginBtn.on('click', function() {
				var wnd = window.open(thisSelf.pluginScoped.loginUrl, 'ecwid_window');
				wnd.focus();
			});
			fields.registerBtn.on('click', function() {
				var wnd = window.open(thisSelf.pluginScoped.registerUrl, 'ecwid_window');
				wnd.focus();
			});
			fields.type.on('change', function() {
				var itm = fields.type.getSelectedItem();
				if (itm.getOriginal().id === 'product-browser') {
					fields.settings.setVisible(true);
				} else {
					fields.settings.setVisible(false);
				}
			});
			fields.cpOpen.on('click', function() {
				if (thisSelf.pluginScoped.loginUrl) {
					thisSelf.openCP(null, thisSelf.pluginScoped.loginUrl);
				} else {
					var storeId = fields.storeInfo.getStoreId();
					if (!storeId) {
						fields.cpOpen.setLoading(true);
						$.get(wb_builder.baseUrl + '/ecwid/create').done(function(resp) {
							if (resp.storeId) {
								fields.storeInfo.setStoreId(resp.storeId).setVisible(true);
								thisSelf.openCP(resp.storeId);
							} else {
								alert((resp.error ? resp.error : 'Server error (3)'));
							}
							fields.cpOpen.setLoading(false);
						});
					} else {
						thisSelf.openCP(storeId);
					}
				}
			});
			fields.regConnect.on('click', function() {
				fields.buttons.setVisible(false);
				fields.connectForm.setVisible(true);
			});
			fields.regRegister.on('click', function() {
				fields.connectForm.setVisible(false);
				fields.buttons.setVisible(true);
			});
			fields.conSubmit.on('click', function() {
				var storeId = fields.conStoreId.getValue();
				fields.conSubmit.setLoading(true);
				$.post(wb_builder.baseUrl + '/ecwid/connect', {storeId: storeId}, function(resp) {
					fields.conSubmit.setLoading(false);
					if (resp.ok) {
						fields.storeInfo.setStoreId(storeId);
						fields.conStoreId.setValue('');
						fields.connectForm.setVisible(false);
						fields.buttons.setVisible(true);
						fields.storeInfo.setVisible(true);
					} else {
						alert((resp.error ? resp.error : 'Server error (2)'));
					}
				});
			});
			fields.storeInfo._disconnect.on('click', function() {
				$.get(wb_builder.baseUrl + '/ecwid/disconnect', function(resp) {
					if (resp.ok) {
						fields.storeInfo.setStoreId(null).setVisible(false);
					} else {
						alert((resp.error ? resp.error : 'Error: Disconnect unsuccessful. Please try again.'));
					}
				});
			});
			if (wb_builder.whiteLabel && (typeof wb_builder.whiteLabel === 'object') && wb_builder.whiteLabel.ecwid) {
				if (wb_builder.whiteLabel.logo) {
					fields.storeLogo.setValue(wb_builder.whiteLabel.logo);
				} else {
					fields.storeLogo.setVisible(false);
				}
				this.pluginScoped.cpDialogTitle = __("Store's control panel");
			}
			fields.connectForm.setVisible(false);
			fields.storeInfo.setVisible(false);
		}
		
		fields.storeId.setValue(data.content.storeId);
		if (data.content.storeId) {
			fields.storeInfo.setStoreId(data.content.storeId).setVisible(true);
		} else {
			fields.storeInfo.setStoreId('').setVisible(false);
		}
		fields.type.trigger('change');
	},
	openCP: function(storeId, loginUrl) {
		if (!this.pluginScoped.cpDialog) {
			this.pluginScoped.cpDialog = new WB_Dialog(this.pluginScoped.cpDialogTitle);
			this.pluginScoped.cpDialog.setFooterVisible(false);
			this.pluginScoped.cpDialog.setNoScroll(true);
			this.pluginScoped.cpDialog.setContentSource = function(src) {
				if (!this.contentSourceIframe) {
					this.contentSourceIframe = $('<iframe>').css({
						display: 'block',
						border: 'none',
						background: 'white',
						padding: '0',
						margin: '0',
						width: '100%',
						height: '100%'
					});
					this.setContent(this.contentSourceIframe);
				}
				this.contentSourceIframe.attr({src: src});
			};
		}
		var w = $(window).width(), h = $(window).height();
		this.pluginScoped.cpDialog.setSize(w - 60, h - 60);
		this.pluginScoped.cpDialog.dialog.css({top: '30px'});
		this.pluginScoped.cpDialog.setMaxBodyHeight(h - 139);
		this.pluginScoped.cpDialog.setMinBodyHeight(h - 139);
		
		if (storeId) {
			storeId = storeId ? parseInt(storeId) : null;
			if (!storeId) return;
			if (this.pluginScoped.cpLastStoreId !== storeId) {
				this.pluginScoped.cpDialog.setContentSource(wb_builder.baseUrl + 'ecwid/cp/?storeId=' + storeId);
			}
			this.pluginScoped.cpLastStoreId = storeId;
		} else if (loginUrl) {
			this.pluginScoped.cpLastStoreId = null;
			this.pluginScoped.cpDialog.setContentSource(loginUrl);
		}
		this.pluginScoped.cpDialog.contentSourceIframe.css({height: (h - 139 - 30)});
		this.pluginScoped.cpDialog.setVisible(true);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		if (this.pluginScoped.isLiteMode()) {
			data.content.storeId = fields.storeId.getValue();
			if (!/^\d+$/.test(data.content.storeId)) data.content.storeId = null;
		} else {
			var storeId = fields.storeInfo.getStoreId();
			if (storeId) data.content.storeId = storeId;
		}
		itm = fields.type.getSelectedItem();
		data.content.type = itm.getOriginal().id;
		data.content.gridViewRows = fields.gridViewRows.getValue();
		data.content.gridViewCols = fields.gridViewCols.getValue();
		data.content.listViewRows = fields.listViewRows.getValue();
		data.content.tableViewRows = fields.tableViewRows.getValue();
		itm = fields.categoryView.getSelectedItem();
		data.content.categoryView = itm.getOriginal().id;
		itm = fields.searchView.getSelectedItem();
		data.content.searchView = itm.getOriginal().id;
		data.content.initCall = this.pluginScoped.initCallCreate(data);
		
		var self = this;
		this.pluginScoped.addListener(this, function() {
			self.builderUpdateElement(data, elem);
		}, (data.content.storeId ? data.content.storeId : this.pluginScoped.demoStoreId));
	},
	loadAction: function(data) {
		data.content.demoStoreId = this.pluginScoped.demoStoreId;
		if (!data.content.storeId) data.content.storeId = '';
		if (!data.content.type) data.content.type = this.canAddProductBrowserWidget(data) ? 'product-browser' : 'mini-cart';
		if (!data.content.gridViewRows) data.content.gridViewRows = 3;
		if (!data.content.gridViewCols) data.content.gridViewCols = 3;
		if (!data.content.listViewRows) data.content.listViewRows = 10;
		if (!data.content.tableViewRows) data.content.tableViewRows = 20;
		if (!data.content.categoryView) data.content.categoryView = 'grid';
		if (!data.content.searchView) data.content.searchView = 'list';
		if (!data.content.initCall || !(typeof data.content.initCall === 'object')) {
			data.content.initCall = {out: ''};
		}
	},
	canAddProductBrowserWidget: function(data) {
		var elems = wb_builder.bodyInstance.getContentElements();
		for (var i in elems) {
			if (elems[i].className === 'ecwid' && elems[i].id !== data.id && (typeof elems[i]._data === 'object')
					&& (typeof elems[i]._data.content === 'object') && elems[i]._data.content.type === 'product-browser') {
				return false;
			}
		}
		return true;
	},
	loadedAction: function(data, elem) {
		var self = this, isNew = (!data.content.storeId);
		window.ecwid_script_defer = true; // hack to avoid document.write(...) usage
		window.ecwid_dynamic_widgets = true;
		data.content.initCall = this.pluginScoped.initCallCreate(data);
		this.loadStoreId(data, function(storeId) {
			var initStoreId = storeId ? storeId : data.content.demoStoreId;
			this.pluginScoped.addListener(self, function() {
				var firstLoad = true;
				Ecwid.OnPageLoaded.add(function() {
					if (isNew && firstLoad) {
						if (data.content.type === 'product-browser') {
							firstLoad = false;
							var h = $('#' + data.id + '_widget').height();
							if (h > 20) self.setSize(null, h);
						} else if (data.content.type === 'mini-cart') {
							self.setSize(165, 165);
						}
					}
				});
				self.builderUpdateElement(data, elem);
			}, initStoreId);
		});
		elem.find('#' + data.id + '_widget').text(this.pluginScoped.widgetLoadingText);
	},
	showInfoBox: function(data, elem, text) {
		elem.find('.alert-ecwid-info').remove();
		var info = $('<div class="alert alert-info">').text((text ? text : __('You can insert only one store on each page.'))).css({
			padding: '10px 15px',
			position: 'absolute',
			top: 0, left: 0,
			width: '100%', height: '100%'
		});
		elem.find('#' + data.id + '_widget').empty().append(info);
	},
	
	loadStoreId: function(data, callback) {
		var thisCallback = (typeof callback === 'function') ? callback : function() {};
		if (data.content.storeId) {
			thisCallback.call(this, data.content.storeId);
		} else {
			var self = this;
			$.get(wb_builder.baseUrl + '/ecwid/info').done(function(resp) {
				thisCallback.call(self, resp.storeId);
			});
		}
	},
	builderUpdateElement: function(data, elem) {
		if (data.content.type === 'product-browser') {
			if (this.canAddProductBrowserWidget(data)) {
				var self = this;
				setTimeout(function() {
					if (self.pluginScoped.scriptReady) {
						if ($('#' + data.id + '_widget').length) { // prevent ecwid widget overwrite builder html
							Ecwid.destroy();
							if (typeof window[data.content.initCall.func] === 'function')
								window[data.content.initCall.func].apply(null, data.content.initCall.args);
						}
					}
				}, 100);
			} else {
				this.showInfoBox(data, elem);
				this.setSize(200, 100);
			}
		} else {
			this.showInfoBox(data, elem, __('There will be widget of type "%s"').replace('%s', data.content.type));
		}
	},
	resizeAction: function(data, elem) {
		elem.find('#' + data.id + '_widget_cont').eq(0).css({width: data.width, height: data.height});
	},
	resizeStopAction: function(data, elem) {
		this.builderUpdateElement(data, elem);
	},
	switchModeAction: function(data, elem) {
		this.builderUpdateElement(data, elem);
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"payumoney","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/payumoney\/main.png";
PluginWrapper._config.template = "<form method=\"post\" action=\"https:\/\/secure.payu.in\/_payment\" data-gateway-id=\"Payumoney\"{{^content.store}} target=\"_blank\"{{\/content.store}}>\r\n\t<input type=\"hidden\" name=\"key\" value=\"{{content.key}}\" \/>\r\n\t<input type=\"hidden\" name=\"productinfo\" value=\"{{content.productinfo}}\" \/>\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"txnid\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"surl\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"furl\" value=\"{cancelUrl}\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<input type=\"hidden\" name=\"service_provider\" value=\"payu_paisa\" \/>\r\n\t<button type=\"submit\"\r\n\t\t\tstyle=\"background: url({{^isPublished}}plugins\/payumoney\/site\/{{\/isPublished}}gallery_gen\/payumoney\/payumoney.png) center center no-repeat;\r\n\t\t\t\t   background-size: contain;\r\n\t\t\t\t   vertical-align: middle;\r\n\t\t\t       border: none;\r\n\t\t\t       width: {{#width}}{{width}}px;{{\/width}}{{^width}}118px;{{\/width}}\r\n\t\t\t       height: {{#height}}{{height}}px;{{\/height}}{{^width}}30px;{{\/width}}\"><\/button>\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/payumoney/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'PayUmoney',
	id: 'payumoney',
	pageUrl: 'https://www.payumoney.com/',
	keyField: __('Key'),
	keyFieldId: 'key',
	keyField2: __('Salt'),
	keyField2Id: 'salt',
	titleFieldId: 'label',
	nameFieldId: 'productinfo',
	priceFieldId: 'amount',
	globalVars: ['key', 'salt']
});
PluginWrapper.registerPlugin('payumoney', {
	name: 'PayUmoney',
	element: {
		minSize: {width: 118, height: 30},
		defaultSize: {width: 192, height: 49},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [9, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'productinfo'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred") + ', INR'},
							{type: 'TextField', id: 'amount'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Key'), helpText: __("Unique merchant key provided by PayUmoney")},
							{type: 'TextField', id: 'key'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Salt'), helpText: __("Merchant salt as provided by PayUmoney")},
							{type: 'TextField', id: 'salt'}
						]}
					]}
				]}
			]}
		]
	},
	resizeAction: function (data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function () {
				self.resizeTimeout = null;
				self.updateElement();
			}, 1000);
		}
	},
	openAction: function (fields, data, elem) {
		fields.productinfo.setText(data.content.productinfo);
		fields.amount.setText(data.content.amount);
		fields.key.setText(data.content.key);
		fields.salt.setText(data.content.salt);
	},
	applyAction: function (fields, data, elem) {
		data.content.productinfo = fields.productinfo.getText();
		data.content.amount = fields.amount.getText();
		data.content.key = fields.key.getText();
		data.content.salt = fields.salt.getText();
	},
	loadAction: function (data) {
		if (!data.content.productinfo)
			data.content.productinfo = '';
		if (!data.content.amount)
			data.content.amount = '1';
		if (!data.content.key)
			data.content.key = '';
		if (!data.content.salt)
			data.content.salt = '';
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"2checkout","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/2checkout\/main.png";
PluginWrapper._config.template = "<form action=\"https:\/\/{{#content.demo}}sandbox{{\/content.demo}}{{^content.demo}}www{{\/content.demo}}.2checkout.com\/checkout\/purchase\" method=\"post\" data-gateway-id=\"2checkout\" style=\"width: 100%; height: 100%;\"{{^content.store}} target=\"_blank\"{{\/content.store}}>\r\n\t<input type=\"hidden\" name=\"sid\" value=\"{{content.sid}}\" \/>\r\n\t<input type=\"hidden\" name=\"mode\" value=\"2CO\" \/>\r\n\t<input type=\"hidden\" name=\"li_0_type\" value=\"product\" \/>\r\n\t<input type=\"hidden\" name=\"li_0_name\" value=\"{{content.name}}\" \/>\r\n\t<input type=\"hidden\" name=\"li_0_price\" value=\"{{content.price}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency_code\" value=\"{{content.currency}}\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"merchant_order_id\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"x_receipt_link_url\" value=\"{callbackUrl}\" \/>\r\n\t<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/2checkout\/2checkout3.png\" alt=\"\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/2checkout\/site\/{{\/isPublished}}gallery_gen\/2checkout\/{{content.button_type}}.png\" alt=\"\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/2checkout/main.php';
PluginWrapper._config.active = true;
ElementRegister.registerPaymentGateway({
	name: '2Checkout',
	id: '2checkout',
	keyFieldId: 'sid',
	keyField2Id: 'secret_word',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [6,6,12], children: [
		{type: 'TextField', placeholder: 'SID', id: 'key'},
		{type: 'TextField', placeholder: __('Secret word'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'name',
	priceFieldId: 'price',
	currencyFieldId: 'currency',
	globalVars: ['secret_word', 'demo'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window._2checkout_settings_dialog().setVisible(true); });
		return btn;
	}
});

(function() {
	var dlg = null;
	window._2checkout_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://www.2checkout.com/" target="_blank">https://www.2checkout.com/</a></p>'
					+ '<p><strong>Approved URL:</strong><br />'
					+ '<pre>' + base_url + 'store-return/2checkout' + '</pre></p>';
			
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
})();

PluginWrapper.registerPlugin('2checkout', {
	name: '2Checkout',
	element: {
		minSize: {width: 70, height: 55},
		defaultSize: {width: 150, height: 60},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: 'SID', helpText: __('Your 2Checkout account number')},
							{type: 'TextField', id: 'sid'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'name'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred')},
							{type: 'TextField', id: 'price'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label')},
							{type: 'TextField', id: 'button_label'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: 'USD', name: 'USD'},
								{id: 'EUR', name: 'EUR'},
								{id: 'AED', name: 'AED'},
								{id: 'AFN', name: 'AFN'},
								{id: 'ALL', name: 'ALL'},
								{id: 'ARS', name: 'ARS'},
								{id: 'AUD', name: 'AUD'},
								{id: 'AZN', name: 'AZN'},
								{id: 'BBD', name: 'BBD'},
								{id: 'BDT', name: 'BDT'},
								{id: 'BGN', name: 'BGN'},
								{id: 'BMD', name: 'BMD'},
								{id: 'BND', name: 'BND'},
								{id: 'BOB', name: 'BOB'},
								{id: 'BRL', name: 'BRL'},
								{id: 'BSD', name: 'BSD'},
								{id: 'BWP', name: 'BWP'},
								{id: 'BZD', name: 'BZD'},
								{id: 'CAD', name: 'CAD'},
								{id: 'CHF', name: 'CHF'},
								{id: 'CLP', name: 'CLP'},
								{id: 'CNY', name: 'CNY'},
								{id: 'COP', name: 'COP'},
								{id: 'CRC', name: 'CRC'},
								{id: 'CZK', name: 'CZK'},
								{id: 'DKK', name: 'DKK'},
								{id: 'DOP', name: 'DOP'},
								{id: 'DZD', name: 'DZD'},
								{id: 'EGP', name: 'EGP'},
								{id: 'FJD', name: 'FJD'},
								{id: 'GBP', name: 'GBP'},
								{id: 'GTQ', name: 'GTQ'},
								{id: 'HKD', name: 'HKD'},
								{id: 'HNL', name: 'HNL'},
								{id: 'HRK', name: 'HRK'},
								{id: 'HUF', name: 'HUF'},
								{id: 'IDR', name: 'IDR'},
								{id: 'ILS', name: 'ILS'},
								{id: 'INR', name: 'INR'},
								{id: 'JMD', name: 'JMD'},
								{id: 'JPY', name: 'JPY'},
								{id: 'KES', name: 'KES'},
								{id: 'KRW', name: 'KRW'},
								{id: 'KZT', name: 'KZT'},
								{id: 'LAK', name: 'LAK'},
								{id: 'LBP', name: 'LBP'},
								{id: 'LKR', name: 'LKR'},
								{id: 'LRD', name: 'LRD'},
								{id: 'MAD', name: 'MAD'},
								{id: 'MMK', name: 'MMK'},
								{id: 'MOP', name: 'MOP'},
								{id: 'MRO', name: 'MRO'},
								{id: 'MUR', name: 'MUR'},
								{id: 'MVR', name: 'MVR'},
								{id: 'MXN', name: 'MXN'},
								{id: 'MYR', name: 'MYR'},
								{id: 'NIO', name: 'NIO'},
								{id: 'NOK', name: 'NOK'},
								{id: 'NPR', name: 'NPR'},
								{id: 'NZD', name: 'NZD'},
								{id: 'PEN', name: 'PEN'},
								{id: 'PGK', name: 'PGK'},
								{id: 'PHP', name: 'PHP'},
								{id: 'PKR', name: 'PKR'},
								{id: 'PLN', name: 'PLN'},
								{id: 'QAR', name: 'QAR'},
								{id: 'RON', name: 'RON'},
								{id: 'RUB', name: 'RUB'},
								{id: 'SAR', name: 'SAR'},
								{id: 'SBD', name: 'SBD'},
								{id: 'SCR', name: 'SCR'},
								{id: 'SEK', name: 'SEK'},
								{id: 'SGD', name: 'SGD'},
								{id: 'SYP', name: 'SYP'},
								{id: 'THB', name: 'THB'},
								{id: 'TOP', name: 'TOP'},
								{id: 'TRY', name: 'TRY'},
								{id: 'TTD', name: 'TTD'},
								{id: 'TWD', name: 'TWD'},
								{id: 'UAH', name: 'UAH'},
								{id: 'VND', name: 'VND'},
								{id: 'VUV', name: 'VUV'},
								{id: 'WST', name: 'WST'},
								{id: 'XCD', name: 'XCD'},
								{id: 'XOF', name: 'XOF'},
								{id: 'YER', name: 'YER'},
								{id: 'ZAR', name: 'ZAR'}
							]}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'button_border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'button_color'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'font_size'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button type')},
							{type: 'DropdownBox', id: 'button_type', options: [
								{id: '2checkout2', name: __('Small')},
								{id: '2checkout3', name: __('Medium')},
								{id: '2checkout1', name: __('Large')}
							]}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'label_color', noTransparent: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Max logo width')},
							{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Show logo')},
							{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
							{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'right'});
						}}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		fields.sid.setText(data.content.sid);
		fields.name.setText(data.content.name);
		fields.price.setText(data.content.price);
		itm = fields.currency.getItemById(data.content.currency);
		fields.currency.selectItem(itm);
		fields.button_label.setText(data.content.button_label);
		itm = fields.button_type.getItemById(data.content.button_type);
		fields.button_type.selectItem(itm);
		fields.button_color.setValue(data.content.button_color);
		fields.font_size.setValue(data.content.font_size);
		fields.font_family.setValue(data.content.font_family);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
		fields.demo.setValue(data.content.demo);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		data.content.sid = fields.sid.getText();
		data.content.name = fields.name.getText();
		data.content.price = fields.price.getText();
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().id;
		data.content.button_label = fields.button_label.getText();
		itm = fields.button_type.getSelectedItem();
		data.content.button_type = itm.getOriginal().id;
		data.content.button_color = fields.button_color.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.demo = fields.demo.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.sid) data.content.sid = ''; // 1303908
		if (!data.content.name) data.content.name = ''; // Products
		if (!data.content.price) data.content.price = '1'; // 25.99
		if (!data.content.currency) data.content.currency = 'USD';
		if (data.content.button_label === undefined) data.content.button_label = ''; // 25.99
		if (!data.content.button_type) data.content.button_type = '2checkout3';
		if (!data.content.button_color) data.content.button_color = 'transparent';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.label_color) data.content.label_color = '#000';
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		if (!data.content.button_border) data.content.button_border = {
			color: '#ccc',
			style: 'none',
			weight: 1,
			css: { border: '1px none #ccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"yandex_maps","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/yandex_maps\/main.png";
PluginWrapper._config.template = "<div class=\"ymaps\" id=\"{{id}}_ymaps\" style=\"width: 100%; height: 100%;\"><\/div>\r\n{{#isPublished}}\r\n\t{{#firstOnPage}}\r\n<script type=\"text\/javascript\">\r\n\twindow.WB_YandexMaps = {\r\n\t\tscriptReady: false,\r\n\t\tymaps: null,\r\n\t\tlisteners: [],\r\n\t\taddListener: function(inst, func) {\r\n\t\t\tif (this.scriptReady) {\r\n\t\t\t\tfunc.call(inst, this.ymaps);\r\n\t\t\t} else {\r\n\t\t\t\tthis.listeners.push({inst: inst, func: func});\r\n\t\t\t}\r\n\t\t},\r\n\t\tready: function(ymaps) {\r\n\t\t\tthis.scriptReady = true;\r\n\t\t\tthis.ymaps = ymaps;\r\n\t\t\tfor (var i = 0; i < this.listeners.length; i++) {\r\n\t\t\t\tthis.listeners[i].func.call(this.listeners[i].inst, ymaps);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\twindow.WB_YandexMaps_script_fn = function(ymaps) { window.WB_YandexMaps.ready(ymaps); };\r\n<\/script>\r\n{{{requireService}}}\r\n\t{{\/firstOnPage}}\r\n<script type=\"text\/javascript\">\r\n\twindow.WB_YandexMaps.addListener(window, function(ymaps) {\r\n\t\tvar ll = [{{#content.strll}}{{content.strll}}{{\/content.strll}}{{^content.strll}}{{#content.ll}}{{.}},{{\/content.ll}}0{{\/content.strll}}], zoom = {{content.zoomLevel}}, type = '{{content.type}}';\r\n\t\tvar map = new ymaps.Map('{{id}}_ymaps', { center: ll, zoom: zoom });\r\n\t\tif (type) map.setType(type);\r\n\t\tvar marker = new ymaps.Placemark(ll, {});\r\n\t\tmap.geoObjects.add(marker);\r\n\t});\r\n<\/script>\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/yandex_maps/main.php';
PluginWrapper._config.active = true;

PluginWrapper.registerPlugin('yandex_maps', {
	name: __('Yandex Maps'),
	noButton: true,
	element: {
		minSize: {width: 100, height: 100},
		defaultSize: {width: 602, height: 327},
		resizable: true,
		renderOnce: true,
		supportsFullWidth: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', columnWeights: [8, 4], children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Coordinates or address'), helpText: __('Location address or coordinates')},
						{type: 'TextField', id: 'address'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: 'Zoom level', helpText: __('ex. 4')},
						{type: 'SizeSelector', id: 'zoomLevel'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Drag marker to set your location')},
					{type: 'CustomContainer', id: 'mapElem', css: {width: '100%', height: 220, border: '1px solid #cccccc', backgroundColor: '#ebebeb'}}
				]}
			]}
		]
	},
	
	pluginScoped: {
		apiKey: (wb_builder.mapsConfig && (typeof wb_builder.mapsConfig === 'object') && wb_builder.mapsConfig.yandexMapsApiKey) ? wb_builder.mapsConfig.yandexMapsApiKey : null,
		scriptLoaded: false,
		scriptReady: false,
		ymaps: null,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst, this.ymaps);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				window.WB_YandexMaps_script_fn = function(ymaps) {
					self.scriptReady = true;
					self.ymaps = ymaps;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst, ymaps);
					}
				};
				$.getScript('https://api-maps.yandex.ru/2.1/?' + (this.apiKey ? 'apikey=' + this.apiKey + '&' : '') + 'lang=en_US&onload=WB_YandexMaps_script_fn&lang=ru_RU');
			}
		},
		handleAddress: function(address, func) {
			if (!this.ymaps) return;
			if (('' + address).match(/[0-9\.]+[\ ]*,[\ ]*[0-9\.]+/i)) {
				var parts = ('' + address).split(',');
				if (typeof func === 'function') func.call(this, [parseFloat(parts[0]), parseFloat(parts[1])]);
			} else {
				var self = this, selfFunc = func, geoc = this.ymaps.geocode(address);
				geoc.then(function(res) {
					if (typeof selfFunc === 'function') selfFunc.call(self, res.geoObjects.get(0).geometry.getCoordinates());
				}, function(err) {});
			}
		}
	},
	map: null,
	mapMarker: null,
	mapElem: null,
	
	resizeAction: function(data, elem) {
		if (this.mapElem) this.mapElem.css({width: data.width, height: data.height});
		if (this.map) this.map.container.fitToViewport();
	},
	
	openAction: function(fields, data, elem) {
		fields.address.setText(data.content.address);
		fields.zoomLevel.setValue(data.content.zoomLevel);
		fields.type = data.content.type;
		var self = this;
		if (!fields.map) {
			fields.address.on('change', function() {
				self.pluginScoped.handleAddress(fields.address.getText(), function(ll) {
					fields.map.setCenter(ll);
					fields.mapMarker.geometry.setCoordinates(ll);
				});
			});
			fields.address.on('keydown', function(e) {
				if (e.keyCode === 13) {
					self.pluginScoped.handleAddress(fields.address.getText(), function(ll) {
						fields.map.setCenter(ll);
						fields.mapMarker.geometry.setCoordinates(ll);
					});
				}
			});
			fields.zoomLevel.on('change', function() {
				if (fields.map) fields.map.setZoom(fields.zoomLevel.getValue());
			});
			this.pluginScoped.addListener(this, function(ymaps) {
				//fields.mapElem.css({width: fields.mapElem.getElem().outerWidth()});
				fields.map = new ymaps.Map(fields.mapElem.getElem().get(0), {
					center: data.content.ll,
					zoom: data.content.zoomLevel,
					controls: ['searchControl', 'typeSelector', 'zoomControl']
				});
				fields.map.events.add('boundschange', function(e) {
					fields.zoomLevel.setValue(e.get('newZoom'));
				});
				fields.map.events.add('typechange', function() {
					fields.type = fields.map.getType();
				});
				if (!fields.type) {
					fields.type = fields.map.getType();
				} else {
					fields.map.setType(fields.type);
				}
				fields.map.setZoom(data.content.zoomLevel);
				fields.mapMarker = new ymaps.Placemark(data.content.ll, {}, {draggable: true});
				fields.mapMarker.events.add('dragend', function() {
					var p = fields.mapMarker.geometry.getCoordinates();
					fields.address.setText(p[0] + ', ' + p[1]);
				});
				fields.map.geoObjects.add(fields.mapMarker);
				var searchControl = fields.map.controls.get(0);
				searchControl.events.add('resultselect', function() {
					if (searchControl.getResultsCount() > 0) {
						fields.address.setText(searchControl.getRequestString());
						var results = searchControl.getResultsArray();
						fields.mapMarker.geometry.setCoordinates(results[searchControl.getSelectedIndex()].geometry.getCoordinates());
					}
				});
				searchControl.events.add('load', function() {
					
				});
			});
		} else {
			if (data.content.type) fields.map.setType(data.content.type);
			fields.map.setZoom(data.content.zoomLevel);
			fields.map.setCenter(data.content.ll);
			fields.mapMarker.geometry.setCoordinates(data.content.ll);
		}
	},
	applyAction: function(fields, data, elem) {
		data.content.address = fields.address.getText();
		data.content.zoomLevel = fields.zoomLevel.getValue();
		data.content.type = fields.type;
		if (data.content.type) this.map.setType(data.content.type);
		if (this.map) this.map.setZoom(data.content.zoomLevel);
		var self = this;
		this.pluginScoped.handleAddress(data.content.address, function(ll) {
			data.content.ll = ll;
			data.content.strll = data.content.ll.join(',');
			self.map.setCenter(data.content.ll);
			self.mapMarker.geometry.setCoordinates(data.content.ll);
		});
	},
	loadAction: function(data) {
		if (!data.content.address) data.content.address = '55.76, 37.64';
		if (!data.content.ll) data.content.ll = [55.76, 37.64];
		if (!data.content.zoomLevel) data.content.zoomLevel = 12;
		data.content.strll = data.content.ll.join(',');
		data.content.apiKey = this.pluginScoped.apiKey;
	},
	loadedAction: function(data, elem) {
		this.mapElem = elem.find('.ymaps');
		var self = this;
		this.pluginScoped.addListener(this, function(ymaps) {
			self.map = new ymaps.Map(self.mapElem.get(0), {
				center: data.content.ll,
				zoom: data.content.zoomLevel
			});
			if (data.content.type) self.map.setType(data.content.type);
			self.mapMarker = new ymaps.Placemark(data.content.ll, {});
			self.map.geoObjects.add(self.mapMarker);
		});
	},
	saveAction: function(data, elem) {
		// TODO: save data
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"vimeo","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/vimeo\/main.png";
PluginWrapper._config.template = "<iframe id=\"{{id}}_vimeo\" src=\"https:\/\/player.vimeo.com\/video\/{{content.groupId}}?portrait={{content.portrait}}&title={{content.title}}&autoplay={{content.autoplay}}&color={{content.color}}\" width=\"100%\" height=\"100%\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen><\/iframe>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('vimeo', {
	name: 'Vimeo',
	element: {
		minSize: {width: 100, height: 100},
		defaultSize: {width: 480, height: 300},
		resizable: true,
		supportsFullWidth: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Vimeo ID or URL'),
						helpText: __('Vimeo video id or url with format https://vimeo.com/{video_id}')
					},
					{type: 'TextField', id: 'groupId'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Portrait'), helpText: __('Show the user’s portrait on the video')},
						{type: 'RadioBox', id: 'portrait0', label: __('Yes'), group: 'portrait'},
						{type: 'RadioBox', id: 'portrait1', label: __('No'), group: 'portrait'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Title'), helpText: __('Show the title on the video.')},
						{type: 'RadioBox', id: 'title0', label: __('Yes'), group: 'title'},
						{type: 'RadioBox', id: 'title1', label: __('No'), group: 'title'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Autoplay'), helpText: __('Play the video automatically on load.')},
						{type: 'RadioBox', id: 'autoplay0', label: __('Yes'), group: 'autoplay'},
						{type: 'RadioBox', id: 'autoplay1', label: __('No'), group: 'autoplay'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color'), helpText: __('Specify the color of the video controls.')},
						{type: 'ColorSelector', id: 'color'}
					]}
				]}
			]}
		]
	},
	resizeTimeout: null,
	resizeAction: function(data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function () {
				self.resizeTimeout = null;
				self.updateElement();
			}, 1000);
		}
	},
	openAction: function(fields, data, elem) {
		fields.groupId.setText(data.content.groupId);
		fields.portrait0.setValue(data.content.portrait === '1');
		fields.portrait1.setValue(data.content.portrait === '0');

		fields.title0.setValue(data.content.title === '1');
		fields.title1.setValue(data.content.title === '0');

		fields.autoplay0.setValue(data.content.autoplay === '1');
		fields.autoplay1.setValue(data.content.autoplay === '0');

		fields.color.setValue(data.content.color);

		fields.groupId.on('change', function() {
			var url = fields.groupId.getText();
			var regExp = /https:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;
			var match = url.match(regExp);
			if (match) {
				fields.groupId.setText(match[2]);
			}
		});
	},
	applyAction: function(fields, data, elem) {
		if (fields.portrait0.getValue()) data.content.portrait = '1';
		if (fields.portrait1.getValue()) data.content.portrait = '0';

		if (fields.title0.getValue()) data.content.title = '1';
		if (fields.title1.getValue()) data.content.title = '0';

		if (fields.autoplay0.getValue()) data.content.autoplay = '1';
		if (fields.autoplay1.getValue()) data.content.autoplay = '0';

		data.content.color = fields.color.getValue().replace('#', '');
		data.content.groupId = fields.groupId.getText();
	},
	loadAction: function (data) {
		if (!data.content.groupId) data.content.groupId = '7976699';
		if (!data.content.portrait) data.content.portrait = '1';
		if (!data.content.title) data.content.title = '1';
		if (!data.content.autoplay) data.content.autoplay = '0';
		if (!data.content.color) data.content.color = '#00adef';
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"baokim","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/baokim\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Baokim\"{{^content.store}} target=\"_blank\"{{\/content.store}} action=\"https:\/\/www.baokim.vn\/payment\/product\/version11\" method=\"get\">\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<input type=\"hidden\" name=\"business\" value=\"{{content.business}}\">\r\n\t<input type=\"hidden\" name=\"product_name\" value=\"{{content.product_name}}\">\r\n\t<input type=\"hidden\" name=\"product_price\" value=\"{{content.product_price}}\">\r\n\t<input type=\"hidden\" name=\"total_amount\" value=\"{{content.product_price}}\">\r\n\t<input type=\"hidden\" name=\"product_quantity\" value=\"1\">\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"order_id\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"url_success\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"url_cancel\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"image\" src=\"http:\/\/www.baokim.vn\/developers\/uploads\/baokim_btn\/muahang-l.png\" alt=\"Baokim Checkout\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<input type=\"image\" src=\"http:\/\/www.baokim.vn\/developers\/uploads\/baokim_btn\/{{content.button_type}}.png\" alt=\"Baokim Checkout\" \/>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/baokim/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'BaoKim',
	id: 'baokim',
	pageUrl: 'https://www.baokim.vn/',
	keyField: __('Email'),
	keyFieldId: 'business',
	titleFieldId: 'label',
	nameFieldId: 'product_name',
	priceFieldId: 'product_price'
});

(function() {
	if (typeof window.baokim_translations === 'undefined') {
		window.baokim_translations = {
			'Mua hang - small': 'Nút Mua hàng (nút nhỏ)',
			'Mua hang - medium': 'Nút Mua hàng (nút trung bình)',
			'Mua hang - large': 'Nút Mua hàng (Nút lớn)',
			'Tra tien - small': 'Nút Trả tiền (nút nhỏ)',
			'Tra tien - medium': 'Nút Trả tiền (nút trung bình)',
			'Tra tien - large': 'Nút trả tiền (Nút lớn)',
			'Thank toan - small': 'Nút thanh toán (nút nhỏ)',
			'Thank toan - medium': 'Nút thanh toán (nút trung bình)',
			'Thank toan - large': 'Nút thanh toán (nút lớn)',
			'Thank toan an toan - small': 'Nút thanh toán an toàn (nút nhỏ)',
			'Thank toan an toan - medium': 'Nút thanh toán an toàn (nút trung bình)',
			'Thank toan an toan - large': 'Nút thanh toán an toàn (nút lớn)',
			'Mua hang thoa thuan - small': 'Nút Mua hàng theo thoả thuận (nút nhỏ)',
			'Mua hang thoa thuan - medium': 'Nút Mua hàng theo thoả thuận (nút trung bình)',
			'Mua hang thoa thuan - large': 'Nút Mua hàng theo thoả thuận (nút lớn)',
			'Thanh toan thoa thuan - small': 'Nút Thanh toán theo thoả thuận (nút nhỏ)',
			'Thanh toan thoa thuan - medium': 'Nút Thanh toán theo thoả thuận (nút trung bình)',
			'Thanh toan thoa thuan - large': 'Nút Thanh toán theo thoả thuận (nút lớn)',
			'Buy now - small': 'Buy now (nút nhỏ)',
			'Buy now - medium': 'Buy now (nút trung bình)',
			'Buy now - large': 'Buy now (Nút lớn)',
			'Pay now - small': 'Pay now (nút nhỏ)',
			'Pay now - medium': 'Pay now (nút trung bình)',
			'Pay now - large': 'Pay now (Nút lớn)'
		};
		window.baokim_translate = function(key) {
			return (wb_builder.locale === 'vi_VN' && (key in window.baokim_translations) && window.baokim_translations[key]) ? window.baokim_translations[key] : key;
		};
	}
})();

PluginWrapper.registerPlugin('baokim', {
	name: 'BaoKim',
	element: {
		minSize: {width: 95, height: 30},
		defaultSize: {width: 130, height: 55},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{
                children: [{type: 'VerticalLayout', spacing: 15, children: [
						{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Email'), helpText:__("Email of account payer submitted to BaoKim (%s)").replace('%s', '<a href="http://baokim.vn" target="_blank">baokim.vn</a>')},
							{type: 'TextField', id: 'business'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button type')},
							{type: 'DropdownBox', id: 'button_type', options: [
								{id: '#muahang-s', name: baokim_translate('Mua hang - small'), value: 'muahang-s'},
								{id: '#muahang-m', name: baokim_translate('Mua hang - medium'), value: 'muahang-m'},
								{id: '#muahang-l', name: baokim_translate('Mua hang - large'), value: 'muahang-l'},
								{id: '#tratien-s', name: baokim_translate('Tra tien - small'), value: 'tratien-s'},
								{id: '#tratien-m', name: baokim_translate('Tra tien - medium'), value: 'tratien-m'},
								{id: '#tratien-l', name: baokim_translate('Tra tien - large'), value: 'tratien-l'},
								{id: '#thanhtoan-s', name: baokim_translate('Thank toan - small'), value: 'thanhtoan-s'},
								{id: '#thanhtoan-m', name: baokim_translate('Thank toan - medium'), value: 'thanhtoan-m'},
								{id: '#thanhtoan-l', name: baokim_translate('Thank toan - large'), value: 'thanhtoan-l'},
								{id: '#thanhtoanantoan-s', name: baokim_translate('Thank toan an toan - small'), value: 'thanhtoanantoan-s'},
								{id: '#thanhtoanantoan-m', name: baokim_translate('Thank toan an toan - medium'), value: 'thanhtoanantoan-m'},
								{id: '#thanhtoanantoan-l', name: baokim_translate('Thank toan an toan - large'), value: 'thanhtoanantoan-l'},
								{id: '#muahangthoathuan-s', name: baokim_translate('Mua hang thoa thuan - small'), value: 'muahangthoathuan-s'},
								{id: '#muahangthoathuan-m', name: baokim_translate('Mua hang thoa thuan - medium'), value: 'muahangthoathuan-m'},
								{id: '#muahangthoathuan-l', name: baokim_translate('Mua hang thoa thuan - large'), value: 'muahangthoathuan-l'},
								{id: '#thanhtoanthoathuan-s', name: baokim_translate('Thanh toan thoa thuan - small'), value: 'thanhtoanthoathuan-s'},
								{id: '#thanhtoanthoathuan-m', name: baokim_translate('Thanh toan thoa thuan - medium'), value: 'thanhtoanthoathuan-m'},
								{id: '#thanhtoanthoathuan-l', name: baokim_translate('Thanh toan thoa thuan - large'), value: 'thanhtoanthoathuan-l'},
								{id: '#buynow-s', name: baokim_translate('Buy now - small'), value: 'buynow-s'},
								{id: '#buynow-m', name: baokim_translate('Buy now - medium'), value: 'buynow-m'},
								{id: '#buynow-l', name: baokim_translate('Buy now - large'), value: 'buynow-l'},
								{id: '#paynow-s', name: baokim_translate('Pay now - small'), value: 'paynow-s'},
								{id: '#paynow-m', name: baokim_translate('Pay now - medium'), value: 'paynow-m'},
								{id: '#paynow-l', name: baokim_translate('Pay now - large'), value: 'paynow-l'}
							]}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'product_name'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred") + ', ' + __('VND')},
							{type: 'TextField', id: 'product_price'}
						]}
					]}
				]}
			]}
		]
	},
	resizeAction: function(data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function() {
				self.resizeTimeout = null;
				self.updateElement();
			}, 1000);
		}
	},
	openAction: function(fields, data, elem) {
		fields.product_name.setText(data.content.product_name);
		fields.business.setText(data.content.business);
		fields.product_price.setText(data.content.product_price);
		var itm = fields.button_type.getItemById('#' + data.content.button_type);
		fields.button_type.selectItem(itm);
	},
	applyAction: function(fields, data, elem) {
		data.content.product_name = fields.product_name.getText();
		data.content.business = fields.business.getText();
		data.content.product_price = fields.product_price.getText();
		var itm = fields.button_type.getSelectedItem();
		data.content.button_type = itm.getOriginal().value;
		if (data.content.button_type == 'muahang-s' ||
			data.content.button_type == 'tratien-s' ||
			data.content.button_type == 'thanhtoan-s' ||
			data.content.button_type == 'buynow-s' ||
			data.content.button_type == 'paynow-s') this.setSize(95, 30);

		if (data.content.button_type == 'muahang-m' ||
			data.content.button_type == 'tratien-m' ||
			data.content.button_type == 'thanhtoan-m' ||
			data.content.button_type == 'buynow-m' ||
			data.content.button_type == 'paynow-m') this.setSize(130, 35);

		if (data.content.button_type == 'muahang-l' ||
			data.content.button_type == 'tratien-l' ||
			data.content.button_type == 'thanhtoan-l' ||
			data.content.button_type == 'buynow-l' ||
			data.content.button_type == 'paynow-l') this.setSize(130, 55);

		if (data.content.button_type == 'muahangthoathuan-s' ||
			data.content.button_type == 'thanhtoanthoathuan-s') this.setSize(165, 30);

		if (data.content.button_type == 'thanhtoanantoan-s') this.setSize(165, 40);
		if (data.content.button_type == 'thanhtoanantoan-l') this.setSize(170, 65);
		if (data.content.button_type == 'thanhtoanthoathuan-m') this.setSize(185, 40);
		if (data.content.button_type == 'thanhtoanantoan-m') this.setSize(185, 50);
		if (data.content.button_type == 'muahangthoathuan-m') this.setSize(190, 40);

		if (data.content.button_type == 'muahangthoathuan-l' ||
			data.content.button_type == 'thanhtoanthoathuan-l') this.setSize(190, 70);
	},
	loadAction: function (data) {
		if (!data.content.product_name) data.content.product_name = ''; // Products
		if (!data.content.business) data.content.business = ''; // 1@bk.vn
		if (!data.content.product_price) data.content.product_price = '10000'; // 1199
		if (!data.content.button_type) data.content.button_type = 'muahang-l';
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"baidu_maps","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/baidu_maps\/main.png";
PluginWrapper._config.template = "<script type=\"text\/javascript\" src=\"http:\/\/api.map.baidu.com\/getscript?v=2.0&amp;ak=cfa0fgLRZZjvHugmDo51EPtUHgW0buAG&amp;services=&amp;t=20160801150053\"><\/script>\r\n<div id=\"allmap_{{id}}\" style=\"width: 100%; height: 100%; overflow: hidden; margin: 0;\"><\/div>\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\tvar getMap = function() {\r\n\t\t\tvar map = new BMap.Map(\"allmap_{{id}}\");\r\n\t\t\tmap.centerAndZoom(new BMap.Point({{content.coords}}), 11);\r\n\t\t\tvar point = new BMap.Point({{content.coords}});\r\n\r\n\t\t\tmap.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_SMALL}));\r\n\r\n\t\t\tmap.addControl(new BMap.MapTypeControl());\r\n\t\t\tmap.enableScrollWheelZoom(true);\r\n\t\t\tmap.centerAndZoom(point, {{content.zoom}});\r\n\t\t\t{{#content.marker}}\r\n\t\t\tvar marker = new BMap.Marker(point);\r\n\t\t\tmap.addOverlay(marker);\r\n\t\t\t{{\/content.marker}}\r\n\t\t\t{{#content.animate}}marker.setAnimation(BMAP_ANIMATION_BOUNCE);{{\/content.animate}}\r\n\t\t},\r\n\t\ttwait = function() {\r\n\t\t\tif (typeof window.BMap == 'object') {\r\n\t\t\t\tgetMap();\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tsetTimeout(twait, 100);\r\n\t\t};\r\n\t\ttwait();\r\n\t})();\r\n<\/script>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('baidu_maps', {
	name: __('Baidu Maps'),
	element: {
		minSize: {width: 100, height: 100},
		defaultSize: {width: 602, height: 327},
		resizable: true,
		supportsFullWidth: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Baidu Maps API key'), helpText: __('Get Baidu Maps API key from http://lbsyun.baidu.com/apiconsole/key?application=key')},
					{type: 'TextField', id: 'groupId'}
				]},
				{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Coordinates')},
						{type: 'TextField', id: 'coords', change: function() {
							var val = this.getValue();
							var parts = val.split(',');
							for (var i=0; i < parts.length; i++) {
								parts[i] = parts[i].replace(/^.*?(\-?\d+(?:[\.,]\d+)?).*$/, '$1').replace(',', '.');
							}
							this.setValue(parts.join(', '));
						}}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Zoom level'), helpText: __('ex. 4')},
						{type: 'SizeSelector', id: 'zoom'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CustomContainer', id: 'map', init: function() {
						var map,
							_animate = false,
							_marker = true,
							_coords = [116.404, 39.915],
							_zoom = 15,
							_markerElem,
							_point,
							_fields;
							
						this.setZoom = function(zoom) {
							_zoom = zoom;
							map.centerAndZoom(new BMap.Point(_coords[0], _coords[1]), _zoom);
						};
						this.setCoords = function(coords) {
							_coords = coords.split(',').map(function(crd) {
								return parseFloat($.trim(crd));
							});
							_point = new BMap.Point(_coords[0], _coords[1]);
							map.centerAndZoom(_point, _zoom);
							this.setMarker(_marker);
						};
						this.setMarker = function(marker) {
							_marker = marker;
							if (_markerElem) map.removeOverlay(_markerElem);
							if (_marker) {
								_markerElem = new BMap.Marker(_point);
								_markerElem.enableDragging();
								_markerElem.addEventListener('dragend', function() {
									_coords = [
										_markerElem.getPosition().lng,
										_markerElem.getPosition().lat
									];
									_point = new BMap.Point(_coords[0], _coords[1]);
									map.centerAndZoom(_point, _zoom);
									_fields.coords.setText(_coords.join(', '));
								});
								map.addOverlay(_markerElem);
								this.setAnimate(_animate);
							} else {
								_markerElem = null;
							}
						};
						this.setAnimate = function(animate) {
							_animate = animate;
							if (_markerElem) _markerElem.setAnimation(_animate ? BMAP_ANIMATION_BOUNCE : null);
						};
						this.initOnView = function(elemId, fields) {
							var self = this;
							_fields = fields;
							this._elem.empty();
							this._elem.attr('id', 'demomap_' + elemId);
							map = new BMap.Map('demomap_' + elemId);
							map.enableScrollWheelZoom(true);
							map.addEventListener('zoomend', function() {
								_zoom = map.getZoom();
								_fields.zoom.setValue(_zoom);
							});
						};
					}, css: {width: '100%', height: 234, position: 'relative', border: '1px solid #aaaaaa', backgroundColor: '#ebebeb'}}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show marker')},
						{type: 'RadioBox', id: 'marker0', label: __('Enable'), group: 'marker'},
						{type: 'RadioBox', id: 'marker1', label: __('Disable'), group: 'marker'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Animate marker')},
						{type: 'RadioBox', id: 'animate0', label: __('Enable'), group: 'animate'},
						{type: 'RadioBox', id: 'animate1', label: __('Disable'), group: 'animate'}
					]}
				]}
			]}
		]
	},
	
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('http://api.map.baidu.com/getscript?v=2.0&ak=cfa0fgLRZZjvHugmDo51EPtUHgW0buAG&services=&t=20160801150053', function() {
					var twait = function() {
						var wnd = window;
						if (typeof wnd.BMap == 'object') {
							self.scriptReady = true;
							for (var i = 0; i < self.listeners.length; i++) {
								self.listeners[i].func.call(self.listeners[i].inst);
							}
							return;
						}
						setTimeout(twait, 100);
					};
					twait();
				});
			}
		}
	},

	openAction: function (fields, data, elem) {
		fields.groupId.setText(data.content.groupId);
		fields.coords.setText(data.content.coords);
		fields.zoom.setValue(data.content.zoom);
		
		fields.marker0.setValue(data.content.marker);
		fields.marker1.setValue(!data.content.marker);
		fields.animate0.setValue(data.content.animate);
		fields.animate1.setValue(!data.content.animate);
		
		this.pluginScoped.addListener(this, function() {
			setTimeout(function() {
				fields.map.initOnView(data.id, fields);
				fields.map.setCoords(fields.coords.getText());
				fields.map.setZoom(fields.zoom.getValue());
				fields.map.setMarker(fields.marker0.getValue());
				fields.map.setAnimate(fields.animate0.getValue());
				
				fields.coords.on('change', function() {
					fields.map.setCoords(fields.coords.getText());
				});
				fields.zoom.on('change', function() {
					fields.map.setZoom(fields.zoom.getValue());
				});
				fields.marker0.on('change', function() {
					fields.map.setMarker(true);
				});
				fields.marker1.on('change', function() {
					fields.map.setMarker(false);
				});
				fields.animate0.on('change', function() {
					fields.map.setAnimate(true);
				});
				fields.animate1.on('change', function() {
					fields.map.setAnimate(false);
				});
			}, 500);
		});
	},

	applyAction: function (fields, data, elem) {
		data.content.groupId = fields.groupId.getText();
		data.content.coords = fields.coords.getText();
		data.content.zoom = fields.zoom.getValue();
		this.fixCoords(data);

		data.content.marker = (fields.marker0.getValue());
		data.content.animate = (fields.animate0.getValue());
	},

	loadAction: function (data) {
		if (!data.content.groupId) data.content.groupId = '';
		if (!data.content.marker) data.content.marker = true;
		if (!data.content.zoom) data.content.zoom = '15';
		if (!data.content.animate) data.content.animate = false;
		if (!data.content.coords) data.content.coords = '116.404, 39.915';
		this.fixCoords(data);

		this.pluginScoped.addListener(this, function() {});
	},

	fixCoords: function(data) {
		if (data.content.coords) {
			var val = '' + data.content.coords;
			var parts = val.split(',');
			for (var i=0; i < parts.length; i++) {
				parts[i] = parts[i].replace(/^.*?(\-?\d+(?:[\.,]\d+)?).*$/, '$1').replace(',', '.');
			}
			data.content.coords = parts.join(', ');
		}
	},

	fullWidthChangeAction: function(fullWidth, data, elem) {
		this.updateElement();
		this.fixCoords(data);
	}

});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"tawkto","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/tawkto\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n\t<div class=\"wb_caption smaller\">\r\n\t\t<div>\r\n\t\t\t<i class=\"ico-pl-tawkto\"><\/i> <strong>tawk.to<\/strong><br \/>{{content.placeholder}}\r\n\t\t<\/div>\r\n\t<\/div>\r\n{{\/isPublished}}\r\n{{#firstOnPage}}\r\n<!--Start of Tawk.to Script-->\r\n<script type=\"text\/javascript\">\r\n\tvar Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();\r\n\t(function(){\r\n\t\tvar s1=document.createElement(\"script\"),s0=document.getElementsByTagName(\"script\")[0];\r\n\t\ts1.async=true;\r\n\t\ts1.src='https:\/\/embed.tawk.to\/{{content.siteId}}\/default';\r\n\t\ts1.charset='UTF-8';\r\n\t\ts1.setAttribute('crossorigin','*');\r\n\t\ts0.parentNode.insertBefore(s1,s0);\r\n\t})();\r\n<\/script>\r\n<!--End of Tawk.to Script-->\r\n{{\/firstOnPage}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('tawkto', {
    name: 'Tawk.to',
    element: {
        minSize: {
            width: 190,
            height: 70
        },
        defaultSize: {
            width: 190,
            height: 70
        },
        resizable: false,
		supportsFullWidth: false
    },
    propertyDialog: {
        noScroll: true,
        tabs: [{
            name: 'General',
            children: [{
                type: 'VerticalLayout',
                children: [{
                    type: 'Label',
                    text: __('Site ID'),
					helpText: __('Site ID you can found in tawk.to admin dashboard on property settings page')
                }, {
                    type: 'TextField',
                    id: 'siteId'
                }]
            }]
        }]
    },
    resizeTimeout: null,

    resizeAction: function(data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function() {
                self.resizeTimeout = null;
                self.updateElement();
            }, 1000);
        }
    },
    openAction: function(fields, data, elem) {
        fields.siteId.setText(data.content.siteId);
    },
    applyAction: function(fields, data, elem) {
        data.content.siteId = fields.siteId.getText();
    },
    loadAction: function(data) {
		if (!data.content.siteId) data.content.siteId = '';
		data.content.placeholder = __('Double click to change properties');
    }
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"odnoklassniki","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/odnoklassniki\/main.png";
PluginWrapper._config.template = "<div id=\"{{id}}_ok_group_widget\"><\/div>\r\n{{^isPublished}}\r\n<script type=\"text\/javascript\">\r\n\tif (window.OK) window.OK.CONNECT.insertGroupWidget('{{id}}_ok_group_widget', '{{content.groupId}}', '{width:{{width}},height:{{height}}}');\r\n<\/script>\r\n{{\/isPublished}}\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\">\r\n\t\/\/ -- {{#firstOnPage}}\r\n\twindow.wb_ok_group_widget = {\r\n\t\tscriptLoaded: false,\r\n\t\tscriptReady: false,\r\n\t\tlisteners: [],\r\n\t\taddListener: function(inst, func) {\r\n\t\t\tif (this.scriptReady) {\r\n\t\t\t\tfunc.call(inst);\r\n\t\t\t} else {\r\n\t\t\t\tthis.listeners.push({inst: inst, func: func});\r\n\t\t\t}\r\n\t\t\tif (!this.scriptLoaded) {\r\n\t\t\t\tthis.scriptLoaded = true;\r\n\t\t\t\tvar self = this;\r\n\t\t\t\t$.getScript('https:\/\/connect.ok.ru\/connect.js', function() {\r\n\t\t\t\t\tself.scriptReady = true;\r\n\t\t\t\t\tfor (var i = 0; i < self.listeners.length; i++) {\r\n\t\t\t\t\t\tself.listeners[i].func.call(self.listeners[i].inst);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\t\/\/ -- {{\/firstOnPage}}\r\n\twindow.wb_ok_group_widget.addListener(this, function() {\r\n\t\tOK.CONNECT.insertGroupWidget('{{id}}_ok_group_widget', '{{content.groupId}}', '{width:{{width}},height:{{height}}}');\r\n\t});\r\n<\/script>\r\n{{\/isPublished}}\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;

PluginWrapper.registerPlugin('odnoklassniki', {
	name: 'OK',
	element: {
		minSize: {width: 100, height: 100},
		defaultSize: {width: 200, height: 285},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{name: 'General', children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Group ID'), helpText: __('Open your group (as administrator), on left side under group logo in menu select "change settings", then at the bottom of the page you will find "ID of this group on Odnoklassniki".')},
					{type: 'TextField', id: 'groupId', change: function(fields) {
						fields.__self.notifyHelpSystemPlayer('prop-groupId-change');
					}}
				]}
			]}
		]
	},
	
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('https://connect.ok.ru/connect.js', function() {
					self.scriptReady = true;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst);
					}
				});
			}
		}
	},
	resizeTimeout: null,
	
	resizeAction: function(data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function() { self.resizeTimeout = null; self.updateElement(); }, 2000);
		}
	},
	openAction: function(fields, data, elem) {
		fields.__self = this;
		fields.groupId.setText(data.content.groupId);
	},
	applyAction: function(fields, data, elem) {
		data.content.groupId = fields.groupId.getText();
	},
	loadAction: function(data) {
		if (!data.content.groupId) data.content.groupId = '50582132228315';
	},
	loadedAction: function(data, elem) {
		this.pluginScoped.addListener(this, function() {
			window.OK.CONNECT.insertGroupWidget(data.id + '_ok_group_widget', data.content.groupId, '{width:' + data.width + ',height:' + data.height + '}');
		});
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"robokassa","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/robokassa\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Robokassa\" method=\"post\" action=\"https:\/\/auth.robokassa.ru\/Merchant\/Index.aspx\"{{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"MerchantLogin\" value=\"{{content.merch_id}}\" \/>\r\n\t<input type=\"hidden\" name=\"OutSum\" value=\"{{content.amount}}\" data-fixed-decimal=\"2\" \/>\r\n\t<input type=\"hidden\" name=\"InvDesc\" value=\"{{content.description}}\" \/>\r\n\t{{#content.demo}}\r\n\t<input type=\"hidden\" name=\"IsTest\" value=\"1\" \/>\r\n\t{{\/content.demo}}\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"InvId\" value=\"{transactionId}\" \/>\r\n\t<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 140px; height: 40px;\">\r\n\t\t<img src=\"gallery_gen\/robokassa\/robokassa.png\" alt=\"Robokassa\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/robokassa\/site\/{{\/isPublished}}gallery_gen\/robokassa\/robokassa.png\" alt=\"Robokassa\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/robokassa/main.php';
PluginWrapper._config.active = false;

(function() {
	var dlg = null;
	window._robokassa_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://www.robokassa.ru/" target="_blank">https://www.robokassa.ru/</a></p>'
					+ '<p><strong>Result URL:</strong><br />'
					+ '<pre>' + base_url + 'store-callback/Robokassa' + '</pre></p>'
					+ '<p><strong>Success URL:</strong><br />'
					+ '<pre>' + base_url + 'store-return/Robokassa' + '</pre></p>'
					+ '<p><strong>Fail URL:</strong><br />'
					+ '<pre>' + base_url + 'store-cancel/Robokassa' + '</pre></p>';
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
	if (typeof window.robokassa_translations === 'undefined') {
		window.robokassa_translations = {
			'first_name': __c('First Name'),
			'last_name': __c('Last Name'),
			'email': __c('E-mail'),
			'address': __c('Address'),
			'phone': __c('Phone'),
			'close': __c('Close'),
			'pay': __c('Pay')
		};
	}
})();

ElementRegister.registerPaymentGateway({
	name: 'Robokassa',
	id: 'robokassa',
	keyFieldId: 'merch_id',
	keyField2Id: 'merch_pass1',
	keyField3Id: 'merch_pass2',
	keyField4Id: 'hash_type',
	keyField5Id: 'demo',
	keyFieldDef: {type: 'VerticalLayout', children: [
		{type: 'HorizontalLayout', noPadding: true, columnWeights: [12,6,6,4], children: [
			{type: 'TextField', placeholder: __('Store identifier'), id: 'key'},
			{type: 'TextField', placeholder: __('Password') + ' 1', id: 'key2', css: {marginTop: 5}},
			{type: 'TextField', placeholder: __('Password') + ' 2', id: 'key3', css: {marginTop: 5}},
			{type: 'DropdownBox', id: 'key4', css: {marginTop: 5}, options: [
				{id: 'MD5', name: 'MD5'},
				{id: 'RIPEMD160', name: 'RIPEMD160'},
				{id: 'SHA1', name: 'SHA1'},
				{id: 'SHA256', name: 'SHA256'},
				{id: 'SHA384', name: 'SHA384'},
				{id: 'SHA512', name: 'SHA512'}
			]}
		]},
		{type: 'CheckBox', label: __('Test mode'), id: 'key5', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['merch_id', 'merch_pass1', 'merch_pass2', 'hash_type', 'demo'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window._robokassa_settings_dialog().setVisible(true); });
		return btn;
	},
	__t: window.robokassa_translations
});

PluginWrapper.registerPlugin('robokassa', {
	name: 'Robokassa',
	element: {
		minSize: {width: 60, height: 20},
		defaultSize: {width: 130, height: 50},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{name: 'General', children: [
				{type: 'HorizontalLayout', children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Store identifer'), helpText: __('Shop identifer from Technical preferences')},
						{type: 'TextField', id: 'merch_id'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Password') + ' 1', helpText: __('Password from Technical preferences')},
						{type: 'TextField', id: 'merch_pass1'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Password') + ' 2', helpText: __('Password from Technical preferences')},
						{type: 'TextField', id: 'merch_pass2'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'description'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred') + ', RUB'},
						{type: 'TextField', id: 'amount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Hash type'), helpText: __('Hash calculation algorithm from Technical preferences')},
						{type: 'DropdownBox', id: 'hashtype', options: [
							{id: 'MD5', name: 'MD5'},
							{id: 'RIPEMD160', name: 'RIPEMD160'},
							{id: 'SHA1', name: 'SHA1'},
							{id: 'SHA256', name: 'SHA256'},
							{id: 'SHA384', name: 'SHA384'},
							{id: 'SHA512', name: 'SHA512'}
						]}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [8, 4], columnWeightsSmall: [8, 4], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Button Label')},
						{type: 'TextField', id: 'button_label'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'currency', options: [
							{id: 'RUB', name: 'RUB'},
							{id: 'KZT', name: 'KZT'},
							{id: 'EUR', name: 'EUR'},
							{id: 'USD', name: 'USD'}
						]}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
					}}
				]}
			]
		}]
	},
	openAction: function(fields, data, elem) {
		var itm;
		fields.merch_id.setText(data.content.merch_id);
		fields.merch_pass1.setText(data.content.merch_pass1);
		fields.merch_pass2.setText(data.content.merch_pass2);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		itm = fields.hashtype.getItemById(data.content.hashtype);
		fields.hashtype.selectItem(itm);
		itm = fields.currency.getItemById(data.content.currency);
		fields.currency.selectItem(itm);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		data.content.merch_id = fields.merch_id.getText();
		data.content.merch_pass1 = fields.merch_pass1.getText();
		data.content.merch_pass2 = fields.merch_pass2.getText();
		data.content.description = fields.description.getText();
		data.content.amount = (itm = fields.amount.getText()) ? parseFloat(itm.replace(',', '.')).toFixed(2) : '0.00';
		itm = fields.hashtype.getSelectedItem();
		data.content.hashtype = itm.getOriginal().id;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().id;
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function(data) {
		if (!data.content.merch_id) data.content.merch_id = '';
		if (!data.content.merch_pass1) data.content.merch_pass1 = '';
		if (!data.content.merch_pass2) data.content.merch_pass2 = '';
		if (!data.content.description) data.content.description = '';
		if (!data.content.amount) data.content.amount = '1.00';
		if (!data.content.hashtype) data.content.hashtype = 'MD5';
		if (!data.content.currency) data.content.currency = 'RUB';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#e8edf1';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#48668c';
		if (!data.content.button_border) data.content.button_border = {
			color: '#beccd5',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #beccd5' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 100;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"paytr","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/paytr\/main.png";
PluginWrapper._config.template = "<script src=\"https:\/\/www.paytr.com\/js\/iframeResizer.min.js\"><\/script>\r\n<iframe src=\"https:\/\/www.paytr.com\/odeme\/guvenli\/{{content.token}}\" id=\"paytriframe\" frameborder=\"0\" scrolling=\"no\" style=\"width: 100%;\"><\/iframe>\r\n<!--<script>iFrameResize({},'#paytriframe');<\/script>-->";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
    name: __('PayTR'),
    id: 'paytr',
    keyField: __('Merchant ID'),
    keyFieldId: 'merchant_id',
    keyField2: __('Merchant Key'),
    keyField2Id: 'merchant_key',
    keyField3: __('Merchant Salt'),
    keyField3Id: 'merchant_salt',
    titleFieldId: 'label',
    nameFieldId: 'user_basket',
    priceFieldId: 'payment_amount'
});
PluginWrapper.registerPlugin('paytr', {
    name: 'PayTR',
    element: {
        minSize: {width: 208, height: 50},
        defaultSize: {width: 208, height: 50},
        resizable: false
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {children: [{type: 'VerticalLayout', spacing: 15, children: [
                            {type: 'HorizontalLayout', columnWeights: [4, 4, 4], css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Merchant ID'), helpText: __('Your Merchant ID provided by PayTR')},
                                            {type: 'TextField', id: 'merchant_id'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Merchant Key'), helpText: __('Your Merchant Key provided by PayTR')},
                                            {type: 'TextField', id: 'merchant_key'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Merchant Salt'), helpText: __('Your Merchant Salt provided by PayTR')},
                                            {type: 'TextField', id: 'merchant_salt'}
                                        ]}
                                ]},
                            {type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Item Name')},
                                            {type: 'TextField', id: 'user_basket'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Amount')},
                                            {type: 'TextField', id: 'payment_amount'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Currency')},
                                            {type: 'DropdownBox', id: 'currency', options: [
                                                    {id: '#TL', name: 'TL', value: 'TL'},
                                                    {id: '#EUR', name: 'EUR', value: 'EUR'},
                                                    {id: '#USD', name: 'USD', value: 'USD'}
                                                ]}
                                        ]}
                                ]}
                        ]}
            ]}
        ]
    },
    resizeAction: function (data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function () {
                self.resizeTimeout = null;
                self.updateElement();
            }, 1000);
        }
    },
    openAction: function (fields, data, elem) {
        var itm;
        itm = fields.currency.getItemById('#' + data.content.currency);
        fields.currency.selectItem(itm);
        fields.user_basket.setText(data.content.user_basket);
        fields.payment_amount.setText(data.content.payment_amount);
        fields.merchant_id.setText(data.content.merchant_id);
        fields.merchant_key.setText(data.content.merchant_key);
        fields.merchant_salt.setText(data.content.merchant_salt);
    },
    applyAction: function (fields, data, elem) {
        var itm;
        itm = fields.currency.getSelectedItem();
        data.content.currency = itm.getOriginal().value;
        data.content.user_basket = fields.user_basket.getText();
        data.content.paymemt_amount = fields.payment_amount.getText();
        data.content.merchant_id = fields.merchant_id.getText();
        data.content.merchant_key = fields.merchant_key.getText();
        data.content.merchant_salt = fields.merchant_salt.getText();
    },
    loadAction: function (data) {
        if (!data.content.user_basket)
            data.content.user_basket = 'Items description';
        if (!data.content.payment_amount)
            data.content.payment_amount = '129.99';
        if (!data.content.currency)
            data.content.currency = 'TL';
        if (!data.content.merchant_id)
            data.content.merchant_id = 'XXXXXX';
        if (!data.content.merchant_key)
            data.content.merchant_key = 'YYYYYYYYYYYYYY';
        if (!data.content.merchant_salt)
            data.content.merchant_salt = 'ZZZZZZZZZZZZZZ';

    }
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"payu","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/payu\/main.png";
PluginWrapper._config.template = "<form method=\"post\" action=\"https:\/\/secure.payu.com\/api\/v2_1\/orders\"{{^content.store}} target=\"_blank\"{{\/content.store}} data-gateway-id=\"Payu\">\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"merchantPosId\" value=\"{{content.merchantPosId}}\" \/>\r\n\t<input type=\"hidden\" name=\"currencyCode\" value=\"{{content.currencyCode}}\" \/>\r\n\t<input type=\"hidden\" name=\"description\" value=\"{{content.productName}}\" \/>\r\n\t<input type=\"hidden\" name=\"products[0].name\" value=\"{{content.productName}}\" \/>\r\n\t<input type=\"hidden\" name=\"products[0].unitPrice\" value=\"{{content.productPrice}}\" data-fixed-decimal=\"0\" data-multiplier=\"100\" \/>\r\n\t<input type=\"hidden\" name=\"products[0].quantity\" value=\"1\" \/>\r\n\t<input type=\"hidden\" name=\"totalAmount\" value=\"{{content.productPrice}}\" data-fixed-decimal=\"0\" data-multiplier=\"100\" \/>\r\n\t<input type=\"hidden\" name=\"extOrderId\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"notifyUrl\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"continueUrl\" value=\"{returnUrl}\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<button type=\"submit\"\r\n\t\t\tstyle=\"background: url({{^isPublished}}plugins\/payu\/site\/{{\/isPublished}}gallery_gen\/payu\/payu.png) center center no-repeat;\r\n\t\t\t\t   background-size: contain;\r\n\t\t\t\t   vertical-align: middle;\r\n\t\t\t       border: none;\r\n\t\t\t       width: {{#width}}{{width}}px;{{\/width}}{{^width}}210px;{{\/width}}\r\n\t\t\t       height: {{#height}}{{height}}px;{{\/height}}{{^width}}36px;{{\/width}}\"><\/button>\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/payu/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'PayU',
	id: 'payu',
	pageUrl: 'https://corporate.payu.com/',
	keyField: __('POS identifier'),
	keyFieldId: 'merchantPosId',
	keyField2: __('Private Key'),
	keyField2Id: 'privateKey',
	titleFieldId: 'label',
	nameFieldId: 'productName,description',
	priceFieldId: 'productPrice,totalAmount',
	currencyFieldId: 'currencyCode',
	globalVars: ['merchantPosId', 'privateKey']
});
PluginWrapper.registerPlugin('payu', {
	name: 'PayU',
	element: {
		minSize: {width: 174, height: 30},
		defaultSize: {width: 289, height: 50},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'productName'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currencyCode', options: [
								{id: '#AED', name: 'AED', value: 'AED'},
								{id: '#ALL', name: 'ALL', value: 'ALL'},
								{id: '#AMD', name: 'AMD', value: 'AMD'},
								{id: '#ARS', name: 'ARS', value: 'ARS'},
								{id: '#AUD', name: 'AUD', value: 'AUD'},
								{id: '#AZN', name: 'AZN', value: 'AZN'},
								{id: '#BAM', name: 'BAM', value: 'BAM'},
								{id: '#BDT', name: 'BDT', value: 'BDT'},
								{id: '#BGN', name: 'BGN', value: 'BGN'},
								{id: '#BHD', name: 'BHD', value: 'BHD'},
								{id: '#BOB', name: 'BOB', value: 'BOB'},
								{id: '#BRL', name: 'BRL', value: 'BRL'},
								{id: '#BYN', name: 'BYN', value: 'BYN'},
								{id: '#CAD', name: 'CAD', value: 'CAD'},
								{id: '#CHF', name: 'CHF', value: 'CHF'},
								{id: '#CLP', name: 'CLP', value: 'CLP'},
								{id: '#CNY', name: 'CNY', value: 'CNY'},
								{id: '#COP', name: 'COP', value: 'COP'},
								{id: '#CRC', name: 'CRC', value: 'CRC'},
								{id: '#CVE', name: 'CVE', value: 'CVE'},
								{id: '#CZK', name: 'CZK', value: 'CZK'},
								{id: '#DKK', name: 'DKK', value: 'DKK'},
								{id: '#DOP', name: 'DOP', value: 'DOP'},
								{id: '#DZD', name: 'DZD', value: 'DZD'},
								{id: '#EGP', name: 'EGP', value: 'EGP'},
								{id: '#ETB', name: 'ETB', value: 'ETB'},
								{id: '#EUR', name: 'EUR', value: 'EUR'},
								{id: '#GBP', name: 'GBP', value: 'GBP'},
								{id: '#GEL', name: 'GEL', value: 'GEL'},
								{id: '#GNF', name: 'GNF', value: 'GNF'},
								{id: '#GTQ', name: 'GTQ', value: 'GTQ'},
								{id: '#HKD', name: 'HKD', value: 'HKD'},
								{id: '#HNL', name: 'HNL', value: 'HNL'},
								{id: '#HRK', name: 'HRK', value: 'HRK'},
								{id: '#HUF', name: 'HUF', value: 'HUF'},
								{id: '#IDR', name: 'IDR', value: 'IDR'},
								{id: '#ILS', name: 'ILS', value: 'ILS'},
								{id: '#INR', name: 'INR', value: 'INR'},
								{id: '#IQD', name: 'IQD', value: 'IQD'},
								{id: '#IRR', name: 'IRR', value: 'IRR'},
								{id: '#ISK', name: 'ISK', value: 'ISK'},
								{id: '#JOD', name: 'JOD', value: 'JOD'},
								{id: '#JPY', name: 'JPY', value: 'JPY'},
								{id: '#KES', name: 'KES', value: 'KES'},
								{id: '#KGS', name: 'KGS', value: 'KGS'},
								{id: '#KRW', name: 'KRW', value: 'KRW'},
								{id: '#KWD', name: 'KWD', value: 'KWD'},
								{id: '#KZT', name: 'KZT', value: 'KZT'},
								{id: '#LBP', name: 'LBP', value: 'LBP'},
								{id: '#LKR', name: 'LKR', value: 'LKR'},
								{id: '#MAD', name: 'MAD', value: 'MAD'},
								{id: '#MDL', name: 'MDL', value: 'MDL'},
								{id: '#MGA', name: 'MGA', value: 'MGA'},
								{id: '#MKD', name: 'MKD', value: 'MKD'},
								{id: '#MNT', name: 'MNT', value: 'MNT'},
								{id: '#MXN', name: 'MXN', value: 'MXN'},
								{id: '#MYR', name: 'MYR', value: 'MYR'},
								{id: '#MZN', name: 'MZN', value: 'MZN'},
								{id: '#NGN', name: 'NGN', value: 'NGN'},
								{id: '#NIO', name: 'NIO', value: 'NIO'},
								{id: '#NOK', name: 'NOK', value: 'NOK'},
								{id: '#NZD', name: 'NZD', value: 'NZD'},
								{id: '#OMR', name: 'OMR', value: 'OMR'},
								{id: '#PEN', name: 'PEN', value: 'PEN'},
								{id: '#PHP', name: 'PHP', value: 'PHP'},
								{id: '#PKR', name: 'PKR', value: 'PKR'},
								{id: '#PLN', name: 'PLN', value: 'PLN'},
								{id: '#PYG', name: 'PYG', value: 'PYG'},
								{id: '#QAR', name: 'QAR', value: 'QAR'},
								{id: '#RON', name: 'RON', value: 'RON'},
								{id: '#RSD', name: 'RSD', value: 'RSD'},
								{id: '#RUB', name: 'RUB', value: 'RUB'},
								{id: '#SAR', name: 'SAR', value: 'SAR'},
								{id: '#SEK', name: 'SEK', value: 'SEK'},
								{id: '#SGD', name: 'SGD', value: 'SGD'},
								{id: '#SYP', name: 'SYP', value: 'SYP'},
								{id: '#THB', name: 'THB', value: 'THB'},
								{id: '#TJS', name: 'TJS', value: 'TJS'},
								{id: '#TND', name: 'TND', value: 'TND'},
								{id: '#TRY', name: 'TRY', value: 'TRY'},
								{id: '#TWD', name: 'TWD', value: 'TWD'},
								{id: '#TZS', name: 'TZS', value: 'TZS'},
								{id: '#UAH', name: 'UAH', value: 'UAH'},
								{id: '#UGX', name: 'UGX', value: 'UGX'},
								{id: '#USD', name: 'USD', value: 'USD'},
								{id: '#UYU', name: 'UYU', value: 'UYU'},
								{id: '#UZS', name: 'UZS', value: 'UZS'},
								{id: '#VEF', name: 'VEF', value: 'VEF'},
								{id: '#VND', name: 'VND', value: 'VND'},
								{id: '#XAF', name: 'XAF', value: 'XAF'},
								{id: '#XOF', name: 'XOF', value: 'XOF'},
								{id: '#YER', name: 'YER', value: 'YER'},
								{id: '#ZAR', name: 'ZAR', value: 'ZAR'}
							]}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred")},
							{type: 'TextField', id: 'productPrice'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('POS identifier'), helpText: __("POS identifier provided by PayU")},
							{type: 'TextField', id: 'merchantPosId'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Private Key'), helpText: __("Available in PayU Panel Manager as Second key (MD5)")},
							{type: 'TextField', id: 'privateKey'}
						]}
					]}
				]}
			]}
		]
	},
	resizeAction: function (data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function () {
				self.resizeTimeout = null;
				self.updateElement();
			}, 1000);
		}
	},
	openAction: function (fields, data, elem) {
		var itm;
		fields.productName.setText(data.content.productName);
		fields.productPrice.setText(data.content.productPrice);
		itm = fields.currencyCode.getItemById('#' + data.content.currencyCode);
		fields.currencyCode.selectItem(itm);
		fields.merchantPosId.setText(data.content.merchantPosId);
		fields.privateKey.setText(data.content.privateKey);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		data.content.productName = fields.productName.getText();
		data.content.productPrice = fields.productPrice.getText();
		itm = fields.currencyCode.getSelectedItem();
		data.content.currencyCode = itm.getOriginal().value;
		data.content.merchantPosId = fields.merchantPosId.getText();
		data.content.privateKey  = fields.privateKey .getText();
	},
	loadAction: function (data) {
		if (!data.content.productName)
			data.content.productName = '';
		if (!data.content.productPrice)
			data.content.productPrice = '1';
		if (!data.content.currencyCode)
			data.content.currencyCode = 'USD';
		if (!data.content.merchantPosId)
			data.content.merchantPosId = '';
		if (!data.content.privateKey)
			data.content.privateKey = '';
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"qiwi_kz","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/qiwi_kz\/main.png";
PluginWrapper._config.template = "{{#content.store}}\r\n<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\" onclick=\"{{id}}_showModal()\">\r\n\t<img src=\"gallery_gen\/qiwi_kz\/qiwi_kz.svg\" alt=\"Qiwi.kz\" style=\"width: auto; max-width: 100%;\" \/>\r\n<\/button>\r\n{{\/content.store}}\r\n{{^content.store}}\r\n<button type=\"submit\" class=\"btn btn-default btn-sm\" onclick=\"{{id}}_showModal()\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/qiwi_kz\/site\/{{\/isPublished}}gallery_gen\/qiwi_kz\/qiwi_kz.svg\" alt=\"Qiwi.kz\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n<\/button>\r\n{{\/content.store}}\r\n\r\n<div class=\"modal fade\" id=\"{{id}}_modal\" tabindex=\"-1\" role=\"dialog\">\r\n    <div class=\"modal-dialog\" role=\"document\">\r\n        <div class=\"modal-content\">\r\n            <div class=\"modal-header\">\r\n                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;<\/span><\/button>\r\n                <h4 class=\"modal-title\">Qiwi.kz<\/h4>\r\n            <\/div>\r\n            <div class=\"modal-body\">\r\n\t\t\t\t<form data-gateway-id=\"QiwiKz\" id=\"{{id}}_form\" action=\"https:\/\/bill.qiwi.com\/order\/external\/main.action\" method=\"get\" style=\"width: 100%; height: 100%;\">\r\n\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t<label>{{content.__t.Phone}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n\t\t\t\t\t\t<input class=\"form-control input-sm\" type=\"text\" name=\"phone\" placeholder=\"{{content.__t.Example}}: +7 700 1234567\" required \/>\r\n\t\t\t\t\t<\/div>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"ccy\" value=\"{{content.currency}}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"comment\" value=\"{{content.name}}\" \/>\r\n\t\t\t\t\t<input type=\"submit\" class=\"hidden\" \/>\r\n\t\t\t\t\t{{{requireService}}}\r\n\t\t\t\t\t{{#content.store}}\r\n\t\t\t\t\t<input type=\"hidden\" name=\"successUrl\" value=\"{returnUrl}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"failUrl\" value=\"{cancelUrl}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"transactionId\" value=\"{transactionId}\" \/>\r\n\t\t\t\t\t{{\/content.store}}\r\n\t\t\t\t<\/form>\r\n\t\t\t<\/div>\r\n\t\t\t<div class=\"modal-footer\">\r\n                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">{{content.__t.Close}}<\/button>\r\n                <button type=\"button\" class=\"btn btn-primary\" id=\"{{id}}_pay_btn\">{{content.__t.Pay}}<\/button>\r\n            <\/div>\r\n\t\t<\/div>\r\n\t<\/div>\r\n<\/div>\r\n\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\tvar modalAppendToBody = false;\r\n\t\twindow.{{id}}_showModal = function() {\r\n\t\t\tif (!modalAppendToBody) {\r\n\t\t\t\t$('#{{id}}_modal').appendTo('body');\r\n\t\t\t\tmodalAppendToBody = true;\r\n\t\t\t}\r\n\t\t\t$('#{{id}}_modal').modal('show');\r\n\t\t};\r\n\t\t$('#{{id}}_pay_btn').on('click', function() {\r\n\t\t\t$(this).attr('disabled', 'disabled');\r\n\t\t\t$('#{{id}}_modal').find('input[type=\"submit\"]').trigger('click');\r\n\t\t});\r\n\t\t$('#{{id}}_modal').on('show.bs.modal', function() {\r\n\t\t\t$('#{{id}}_pay_btn').removeAttr('disabled');\r\n\t\t});\r\n\t})();\r\n<\/script>\r\n{{\/isPublished}}\r\n";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/qiwi_kz/main.php';
PluginWrapper._config.active = false;
(function() {
	if (typeof window.qiwikz_translations === 'undefined') {
		window.qiwikz_translations = {
			'Phone': __c('Phone'),
			'Pay': __c('Pay'),
			'Close': __c('Close'),
			'Example': __c('Example')
		};
	}
})();

ElementRegister.registerPaymentGateway({
	name: 'QIWI.kz',
	id: 'qiwi_kz',
	pageUrl: 'https://qiwi.kz/',
	keyFieldId: 'api_id',
	keyField2Id: 'api_password',
	keyField3Id: 'prv_id',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, children: [
		{type: 'TextField', placeholder: 'API ID', id: 'key'},
		{type: 'TextField', placeholder: __('API Password'), id: 'key2'},
		{type: 'TextField', placeholder: __('Provider ID'), id: 'key3'}
	]},
	titleFieldId: 'label',
	nameFieldId: 'name',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['api_id', 'api_password', 'prv_id'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window.qiwi_settings_dialog().setVisible(true); });
		return btn;
	},
	__t: window.qiwikz_translations
});

(function() {
	var dlg = null;
	window.qiwi_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://qiwi.kz/" target="_blank">https://qiwi.kz/</a></p>'
					+ '<p><strong>Callback URL:</strong><br />'
					+ '<pre>' + base_url + 'store-callback/Qiwi' + '</pre></p>';
			
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
})();

PluginWrapper.registerPlugin('qiwi_kz', {
	name: 'QIWI.kz',
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 120, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: 'API ID', helpText: __('Provider ID in API Visa QIWI Wallet')},
							{type: 'TextField', id: 'api_id'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('API Password'), helpText: __('Provider password in API Visa QIWI Wallet')},
							{type: 'TextField', id: 'api_password'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Provider ID'), helpText: __('Provider numeric ID in QIWI')},
							{type: 'TextField', id: 'prv_id'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'name'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred') + ', KZT'},
							{type: 'TextField', id: 'amount'}
						]}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Rounded corners')},
					{type: 'RoundCornersSelector', id: 'border_radius'}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		fields.api_id.setText(data.content.api_id);
		fields.api_password.setText(data.content.api_password);
		fields.prv_id.setText(data.content.prv_id);
		fields.amount.setText(data.content.amount);
		fields.name.setText(data.content.name);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
//		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
		fields.border_radius.setValue(data.content.border_radius);
	},
	applyAction: function (fields, data, elem) {
		data.content.api_id = fields.api_id.getText();
		data.content.api_password = fields.api_password.getText();
		data.content.prv_id = fields.prv_id.getText();
		data.content.name = fields.name.getText();
		data.content.amount = fields.amount.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.border_radius = fields.border_radius.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		var borderRadiusCss = '';
		var borderRadius = data.content.border_radius;
		if (borderRadius && borderRadius.css !== undefined) {
			for (var selector in borderRadius.css) {
				borderRadiusCss += selector + ': ' + borderRadius.css[selector] + ';';
			}
		}
		return borderCss + borderRadiusCss;
	},
	loadAction: function (data) {
		data.content.__t = window.qiwikz_translations;
		data.content.__globalVars = ['api_id', 'api_password', 'prv_id'];
		if (!data.content.api_id) data.content.api_id = '';
		if (!data.content.api_password) data.content.api_password = '';
		if (!data.content.prv_id) data.content.prv_id = '';
		if (!data.content.name) data.content.name = '';
		if (!data.content.amount) data.content.summ = '1';
		if (!data.content.currency) data.content.currency = 'KZT';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#fff';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#757575';
		if (!data.content.button_border) data.content.button_border = {
			color: '#757575',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #757575' }
		};
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		if (!data.content.border_radius) data.content.border_radius = {
			lt: 0, rt: 0, rb: 0, lb: 0,
			css: { 
				"border-radius"			: "0",
				"-webkit-border-radius"	: "0", 
				"-moz-border-radius"	: "0"
			}
		};
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"webmoney_button","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/webmoney_button\/main.png";
PluginWrapper._config.template = "<form method=\"post\" action=\"https:\/\/merchant.wmtransfer.com\/lmi\/payment.asp\" data-gateway-id=\"Webmoney\"{{^content.store}} target=\"_blank\"{{\/content.store}}>\r\n\t<input name=\"LMI_PAYMENT_AMOUNT\" value=\"{{content.amount}}\" type=\"hidden\" \/>\r\n\t<input name=\"LMI_PAYEE_PURSE\" value=\"{{content.purseId}}\" type=\"hidden\" \/>\r\n\t{{#content.store}}\r\n\t<input name=\"LMI_PAYMENT_DESC_BASE64\" value=\"{{content.description}}\" type=\"hidden\" \/>\r\n\t<input type=\"hidden\" name=\"LMI_RESULT_URL\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"LMI_SUCCESS_URL\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"LMI_FAIL_URL\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"TRANSACTION_ID\" value=\"{transactionId}\" \/>\r\n\t<input value=\"{{content.title}}\" type=\"submit\" class=\"wmbtn\"\r\n\t\t   style=\"height: 36px;\r\n\t\t\t\t  border: solid 1px #538ec1;\r\n\t\t\t\t  background: #a4cef4;\r\n\t\t\t\t  padding: 6px 18px;\r\n\t\t\t\t  color: #ffffff;\r\n\t\t\t\t  font-size: 12px;\r\n\t\t\t\t  font-family: Arial,Helvetica,sans-serif;\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<input value=\"{{content.title}}\" type=\"submit\" class=\"wmbtn\"\r\n\t\t   style=\"width: {{width}}px;\r\n\t\t\t\t  height: {{height}}px;\r\n\t\t\t\t  border: {{content.border.css.border}};\r\n\t\t\t\t  background: {{content.background}};\r\n\t\t\t\t  padding: 6px 10px;\r\n\t\t\t\t  color: {{content.fontColor}};\r\n\t\t\t\t  font-size: {{content.fontSize}}px;\r\n\t\t\t\t  font-family: {{content.fontFamily}};\" \/>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/webmoney_button/main.php';
PluginWrapper._config.active = true;
(function() {
	var dlg = null;
	window.webmoney_button_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://www.wmtransfer.com/" target="_blank">https://www.wmtransfer.com/</a></p>'
					+ '<p><strong>Result URL:</strong><br />'
					+ '<pre>' + base_url + '0/store-callback/Webmoneybutton' + '</pre></p>'
					+ '<p><strong>Success URL:</strong><br />'
					+ '<pre>' + base_url + '0/store-return/Webmoneybutton' + '</pre></p>'
					+ '<p><strong>Fail URL:</strong><br />'
					+ '<pre>' + base_url + '0/store-cancel/Webmoneybutton' + '</pre></p>';
			
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
})();

ElementRegister.registerPaymentGateway({
	name: 'WebMoney',
	id: 'webmoney_button',
	keyField: __('Purse ID'),
	keyFieldId: 'purseId',
	titleFieldId: 'title',
	nameFieldId: 'description|base64',
	priceFieldId: 'amount',
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window.webmoney_button_settings_dialog().setVisible(true); });
		return btn;
	}
});
PluginWrapper.registerPlugin('webmoney_button', {
	name: __('WM Button'),
	element: {
		minSize: {width: 25, height: 25},
		defaultSize: {width: 125, height: 36},
		resizable: true
	},
	propertyDialog: {
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Purse ID')},
							{type: 'TextField', id: 'purseId'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label'), helpText: __('Label name on submit button')},
							{type: 'TextField', id: 'title'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [9, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
							{type: 'TextField', id: 'description'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('In WM units defined by purse')},
							{type: 'TextField', id: 'amount'}
						]}
					]},
					{type: 'FlowLayout', spacing: 14, css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'background'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Font family')},
							{type: 'FontFamilySelector', id: 'fontFamily'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Font size')},
							{type: 'SizeSelector', id: 'fontSize'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Font color')},
							{type: 'ColorSelector', id: 'fontColor', noTransparent: true}
						]}
					]}
				]}
			]}
		]
	},
	resizeAction: function(data, elem) {
		elem.find('.wmbtn').eq(0).css({width: data.width, height: data.height});
	},
	openAction: function(fields, data, elem) {
		fields.purseId.setText(data.content.purseId);
		fields.amount.setText(data.content.amount);
		fields.description.setText(data.content.description);
		fields.title.setText(data.content.title);
		fields.border.setValue(data.content.border);
		fields.background.setValue(data.content.background);
		fields.fontFamily.setValue(data.content.fontFamily);
		fields.fontSize.setValue(data.content.fontSize);
		fields.fontColor.setValue(data.content.fontColor);
	},
	applyAction: function(fields, data, elem) {
		data.content.purseId = fields.purseId.getText();
		data.content.amount = parseFloat(fields.amount.getText().replace(',', '.'));
		if (isNaN(data.content.amount)) data.content.amount = 1.0;
		data.content.description = fields.description.getText();
		data.content.title = fields.title.getText();
		data.content.border = fields.border.getValue();
		data.content.background = fields.background.getValue();
		data.content.fontFamily = fields.fontFamily.getValue();
		data.content.fontSize = fields.fontSize.getValue();
		data.content.fontColor = fields.fontColor.getValue();
	},
	loadAction: function(data) {
		if (!data.content.purseId) data.content.purseId = '';
		if (!data.content.amount) data.content.amount = 1.0;
		if (!data.content.description) data.content.description = __('Donation to charitable fund');
		if (!data.content.title) data.content.title = __('pay 1.00 WMZ');
		if (!data.content.border) data.content.border = {
			color: '#538ec1',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #538ec1' }
		};
		if (!data.content.background) data.content.background = '#a4cef4';
		if (!data.content.fontFamily) data.content.fontFamily = 'Arial,Helvetica,sans-serif';
		if (!data.content.fontSize) data.content.fontSize = '12';
		if (!data.content.fontColor) data.content.fontColor = '#ffffff';
	}

});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"olark","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/olark\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n\t<div class=\"wb_caption smaller\">\r\n\t\t<div>\r\n\t\t\t<i class=\"ico-pl-olark\"><\/i> <strong>Olark<\/strong><br \/>{{content.placeholder}}\r\n\t\t<\/div>\r\n\t<\/div>\r\n{{\/isPublished}}\r\n{{#firstOnPage}}\r\n<script data-cfasync=\"false\" type='text\/javascript'>\/*<![CDATA[*\/window.olark||(function(c){var f=window,d=document,l=f.location.protocol==\"https:\"?\"https:\":\"http:\",z=c.name,r=\"load\";var nt=function(){\r\nf[z]=function(){\r\n(a.s=a.s||[]).push(arguments)};var a=f[z]._={\r\n},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){\r\nf[z](\"call\",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={\r\n0:+new Date};a.P=function(u){\r\na.p[u]=new Date-a.p[0]};function s(){\r\na.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent(\"on\"+r,s);var ld=function(){function p(hd){\r\nhd=\"head\";return[\"<\",hd,\"><\/\",hd,\"><\",i,' onl' + 'oad=\"var d=',g,\";d.getElementsByTagName('head')[0].\",j,\"(d.\",h,\"('script')).\",k,\"='\",l,\"\/\/\",a.l,\"'\",'\"',\"><\/\",i,\">\"].join(\"\")}var i=\"body\",m=d[i];if(!m){\r\nreturn setTimeout(ld,100)}a.P(1);var j=\"appendChild\",h=\"createElement\",k=\"src\",n=d[h](\"div\"),v=n[j](d[h](z)),b=d[h](\"iframe\"),g=\"document\",e=\"domain\",o;n.style.display=\"none\";m.insertBefore(n,m.firstChild).id=z;b.frameBorder=\"0\";b.id=z+\"-loader\";if(\/MSIE[ ]+6\/.test(navigator.userAgent)){\r\nb.src=\"javascript:false\"}b.allowTransparency=\"true\";v[j](b);try{\r\nb.contentWindow[g].open()}catch(w){\r\nc[e]=d[e];o=\"javascript:var d=\"+g+\".open();d.domain='\"+d.domain+\"';\";b[k]=o+\"void(0);\"}try{\r\nvar t=b.contentWindow[g];t.write(p());t.close()}catch(x){\r\nb[k]=o+'d.write(\"'+p().replace(\/\"\/g,String.fromCharCode(92)+'\"')+'\");d.close();'}a.P(2)};ld()};nt()})({\r\nloader: \"static.olark.com\/jsclient\/loader0.js\",name:\"olark\",methods:[\"configure\",\"extend\",\"declare\",\"identify\"]});\r\n\/* custom configuration goes here (www.olark.com\/documentation) *\/\r\nolark.identify('{{content.groupId}}');\/*]]>*\/<\/script><noscript><a href=\"https:\/\/www.olark.com\/site\/{{content.groupId}}\/contact\" title=\"Contact us\" target=\"_blank\">Questions? Feedback?<\/a> powered by <a href=\"http:\/\/www.olark.com?welcome\" title=\"Olark live chat software\">Olark live chat software<\/a><\/noscript>\r\n{{\/firstOnPage}}\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('olark', {
    name: 'Olark',
    element: {
        minSize: {
            width: 190,
            height: 70
        },
        defaultSize: {
            width: 190,
            height: 70
        },
        resizable: false,
		supportsFullWidth: false
    },
    propertyDialog: {
        noScroll: true,
        tabs: [{
            name: 'General',
            children: [{
                type: 'VerticalLayout',
                children: [{
                    type: 'Label',
                    text: __('Site ID')
                }, {
                    type: 'TextField',
                    id: 'groupId'
                }]
            }]
        }]
    },
    resizeTimeout: null,

    resizeAction: function(data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function() {
                self.resizeTimeout = null;
                self.updateElement();
            }, 1000);
        }
    },
    openAction: function(fields, data, elem) {
        fields.groupId.setText(data.content.groupId);
    },
    applyAction: function(fields, data, elem) {
        data.content.groupId = fields.groupId.getText();
    },
    loadAction: function(data) {
        if (!data.content.groupId) data.content.groupId = '';
		data.content.placeholder = __('Double click to change properties');
    }
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"yandex_kassa","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/yandex_kassa\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"YandexKassa\" action=\"https:\/\/{{#content.demo}}demo{{\/content.demo}}money.yandex.ru\/eshop.xml\" method=\"post\"{{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input name=\"shopId\" value=\"{{content.shopId}}\" type=\"hidden\" \/>\r\n\t<input name=\"scid\" value=\"{{content.scid}}\" type=\"hidden\" \/>\r\n\t<input name=\"sum\" value=\"{{content.sum}}\" type=\"hidden\" \/>\r\n\t<input name=\"orderDetails\" value=\"{{content.orderDetails}}\" type=\"hidden\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"shopSuccessUrl\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"shopFailUrl\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"orderNumber\" value=\"{transactionId}\" \/>\r\n\t<button style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/yandex_kassa\/logo-color.svg\" alt=\"Yandex Kassa\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/yandex_kassa\/site\/{{\/isPublished}}gallery_gen\/yandex_kassa\/{{content.logo}}\" alt=\"Yandex Kassa\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/yandex_kassa/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: __('Yandex Kassa'),
	id: 'yandex_kassa',
	keyFieldId: 'shopId',
	keyField2Id: 'scid',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [6,6,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Shop ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Scid'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'orderDetails',
	priceFieldId: 'sum',
	globalVars: ['shopId', 'scid', 'demo'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window.yandex_kassa_settings_dialog().setVisible(true); });
		return btn;
	}
});

(function() {
	var dlg = null;
	window.yandex_kassa_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'https://' + wb_builder.siteDomain + '/';
			var note = $('<p><strong>Note.</strong> Your website should support'
					+ ' HTTPS protocol and valid SSL certificate should be installed'
					+ ' in order for Yandex Kassa to work.</p>').append('<br>')
					.append('Also make sure that ')
					.append($('<a href="javascript:void(0)">').text('option').on('click', function() { wb_builder.site.changeProperties(); }))
					.append(' <em>"Publish Site with forced HTTPS"</em> is checked.');
			var html = $('<div>').append('<p><strong>Page URL:</strong> <a href="https://kassa.yandex.ru/" target="_blank">https://kassa.yandex.ru/</a></p>'
					+ '<p><strong>checkURL</strong> (demo and production):<br />'
					+ '<pre>' + base_url + '0/store-verify/YandexKassa' + '</pre></p>'
					+ '<p><strong>paymentAvisoURL</strong> (demo and production):<br />'
					+ '<pre>' + base_url + '0/store-callback/YandexKassa' + '</pre></p>'
					+ '<p><strong>successURL</strong> (demo and production):<br />'
					+ '<pre>' + base_url + '0/store-return/YandexKassa' + '</pre></p>'
					+ '<p><strong>failURL</strong> (demo and production):<br />'
					+ '<pre>' + base_url + '0/store-cancel/YandexKassa' + '</pre></p>');
			html.prepend('<br>').prepend(note);
			
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
})();

PluginWrapper.registerPlugin('yandex_kassa', {
	name: __('Yandex Kassa'),
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 155, height: 65}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Shop ID'), helpText: __('Unique indentificator from Yandex Kassa')},
							{type: 'TextField', id: 'shopId'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Scid'), helpText: __('Unique indentificator from Yandex Kassa')},
							{type: 'TextField', id: 'scid'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'orderDetails'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred") + ', ' + __('RUB')},
							{type: 'TextField', id: 'sum'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Button Label')},
						{type: 'TextField', id: 'button_label'}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'button_border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'button_color'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'font_size'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'label_color', noTransparent: true}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', css: {width: 120}, children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Max logo width')},
							{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Show logo')},
							{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
							{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Logo')},
							{type: 'DropdownBox', id: 'logo', options: [
								{id: 'logo-ya.svg', name: 'yandex-svg'},
								{id: 'logo-black.svg', name: 'yandex-black-svg'},
								{id: 'logo-white.svg', name: 'yandex-white-svg'},
								{id: 'logo-color.svg', name: 'yandex-color-svg'}
							]}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Rounded corners')},
						{type: 'RoundCornersSelector', id: 'border_radius'}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Mode'), init: function() {
								var link = $('<a>').attr('href', 'javascript:void(0)').text(__('Settings'));
								link.on('click', function() {
									window.yandex_kassa_settings_dialog().setVisible(true);
								});
								var cont = $('<span>').css({fontWeight: 'normal', marginLeft: '4px'});
								cont.append('(');
								cont.append(link);
								cont.append(')');
								this._elem.append(cont);
							}},
							{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
								this.getElem().attr('title', __('For testing purpose without real payments'));
								this.getElem().tooltip({placement: 'right'});
							}}
						]}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		fields.shopId.setText(data.content.shopId);
		fields.scid.setText(data.content.scid);
		fields.orderDetails.setText(data.content.orderDetails);
		fields.sum.setText(data.content.sum);
		fields.demo.setValue(data.content.demo);
		itm = fields.logo.getItemById(data.content.logo);
		fields.logo.selectItem(itm);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
		fields.border_radius.setValue(data.content.border_radius);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		data.content.shopId = fields.shopId.getText();
		data.content.scid = fields.scid.getText();
		data.content.orderDetails = fields.orderDetails.getText();
		data.content.sum = fields.sum.getText();
		data.content.demo = fields.demo.getValue();
		itm = fields.logo.getSelectedItem();
		data.content.logo = itm.getOriginal().id;
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.border_radius = fields.border_radius.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		var borderRadiusCss = '';
		var borderRadius = data.content.border_radius;
		if (borderRadius && borderRadius.css !== undefined) {
			for (var selector in borderRadius.css) {
				borderRadiusCss += selector + ': ' + borderRadius.css[selector] + ';';
			}
		}
		return borderCss + borderRadiusCss;
	},
	loadAction: function (data) {
		data.content.__globalVars = ['shopId', 'scid', 'demo'];
		if (!data.content.shopId) data.content.shopId = ''; // 1234
		if (!data.content.scid) data.content.scid = ''; // 4321
		if (!data.content.orderDetails) data.content.orderDetails = ''; // Item description
		if (!data.content.sum) data.content.sum = '1'; // 9.99
		if (data.content.demo === undefined) data.content.demo = true;
		if (!data.content.logo) data.content.logo = 'logo-color.svg';
		
		if (data.content.button_label === undefined) {
			if (data.content.firstLine || data.content.secondLine) {
				data.content.button_label = $.trim([data.content.firstLine, data.content.secondLine].join(' '));
			}
			data.content.button_label = __('Pay with %s').replace('%s', '');
		}
		if (!data.content.button_color) data.content.button_color = '#FFDB4D';
		if (!data.content.font_family) data.content.font_family = "'Open Sans Condensed',Arial,sans-serif";
		if (!data.content.font_size) data.content.font_size = '14';
		if (!data.content.label_color) data.content.label_color = '#000';
		if (!data.content.button_border) data.content.button_border = {
			color: ["#757575", "#757575", "#aaaaaa", "#757575"],
			style: ['none','none','solid','none'],
			weight: [1,1,1,1],
			differ: true,
			css: {
				'border-bottom': "1px solid #aaaaaa",
				'border-left': "1px none #757575",
				'border-right': "1px none #757575",
				'border-top': "1px none #757575"
			}
		};
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 100;
		if (!data.content.border_radius) data.content.border_radius = {
			lt: 4, rt: 4, rb: 4, lb: 4,
			css: { 
				"border-radius"			: "4px",
				"-webkit-border-radius"	: "4px", 
				"-moz-border-radius"	: "4px"
			}
		};
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"vkontakte_community","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/vkontakte_community\/main.png";
PluginWrapper._config.template = "{{#isPublished}}\r\n\t{{#firstOnPage}}\r\n<script type=\"text\/javascript\" src=\"\/\/vk.com\/js\/api\/openapi.js?116\"><\/script>\r\n\t{{\/firstOnPage}}\r\n{{\/isPublished}}\r\n<div id=\"{{id}}_vk_groups\" class=\"vk_groups\"><\/div>\r\n<script type=\"text\/javascript\">\r\n\tif (window.VK) {\r\n\t\ttry {\r\n\t\t\tVK.Widgets.Group('{{id}}_vk_groups', {mode: {{content.mode}}, width: '{{width}}', height: '{{height}}', color1: '{{content.color1}}', color2: '{{content.color2}}', color3: '{{content.color3}}'}, '{{content.profileId}}');\r\n\t\t} catch (error) {\r\n\t\t\tconsole.error('VK Community error: ' + error.message);\r\n\t\t}\r\n\t}\r\n<\/script>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;

PluginWrapper.registerPlugin('vkontakte_community', {
	name: 'VK',
	noButton: true,
	element: {
		minSize: {width: 100, height: 100},
		defaultSize: {width: 220, height: 260},
		resizable: true
	},
	propertyDialog: {
		//size: {width: 500, height: 400},
		noScroll: true,
		tabs: [
			{name: 'General', children: [
				{type: 'VerticalLayout', children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('ID for Page or Group'),
							helpText: __('Note that ID for profile page must be entered with "-" sign at the beginning. Use this page to find your ID: %s').replace('%s', '<a href="https://vk.com/dev/Community" target="_blank">https://vk.com/dev/Community</a>')
						},
						{type: 'TextField', id: 'link', change: function(fields) {
							fields.__self.notifyHelpSystemPlayer('prop-link-change');
							this.setValue(this.getValue().replace(/^.*?(\-*\d+).*$/, '$1'));
						}}
					]},
					{type: 'HorizontalLayout',
						css: {marginTop: 15},
						columnWeights: [5, 7],
						children: [
							{type: 'VerticalLayout', children: [
								{type: 'Label', text: __('Layout')},
								{type: 'RadioBox', id: 'mode0', label: __('Members'), group: 'mode', change: function(fields) {
									fields.__self.notifyHelpSystemPlayer('prop-mode0-change');
								}},
								{type: 'RadioBox', id: 'mode2', label: __('News'), group: 'mode', change: function(fields) {
									fields.__self.notifyHelpSystemPlayer('prop-mode2-change');
								}},
								{type: 'RadioBox', id: 'mode1', label: __('Name only'), group: 'mode', change: function(fields) {
									fields.__self.notifyHelpSystemPlayer('prop-mode1-change');
								}}
							]},
							{type: 'VerticalLayout', children: [
								{type: 'HorizontalLayout', columnWeights: [8, 4], children: [
									{type: 'Label', text: __('Background color')},
									{type: 'ColorSelector', id: 'color1', noTransparent: true, change: function(fields) {
										fields.__self.notifyHelpSystemPlayer('prop-color1-change');
									}}
								]},
								{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 4}, children: [
									{type: 'Label', text: __('Text color')},
									{type: 'ColorSelector', id: 'color2', noTransparent: true, change: function(fields) {
										fields.__self.notifyHelpSystemPlayer('prop-color2-change');
									}}
								]},
								{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 4}, children: [
									{type: 'Label', text: __('Buttons color')},
									{type: 'ColorSelector', id: 'color3', noTransparent: true, change: function(fields) {
										fields.__self.notifyHelpSystemPlayer('prop-color3-change');
									}}
								]}
							]}
						]
					}
				]}
			]}
		]
	},
	
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('http://vk.com/js/api/openapi.js?116', function() {
					self.scriptReady = true;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst);
					}
				});
			}
		},
		handleLink: function(link, func) {
			var selfFunc = func;
			if (('' + link).match(/^([0-9]+|\-[0-9]+)$/i)) {
				if (typeof selfFunc === 'function') selfFunc(link);
			} else {
				$.post('https://vk.com/al_pages.php', {act: 'a_oid_by_link', url: link}, function(oid) {
					if (typeof selfFunc === 'function') selfFunc((oid && oid.match(/^[0-9]+$/)) ? oid : null);
				});
			}
		}
	},
	resizeTimeout: null,
	
	resizeAction: function(data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function() { self.resizeTimeout = null; self.updateElement(); }, 1000);
		}
	},
	openAction: function(fields, data, elem) {
		fields.__self = this;
		fields.link.setText(data.content.profileId);
		fields.mode0.setValue(data.content.mode === 0);
		fields.mode1.setValue(data.content.mode === 1);
		fields.mode2.setValue(data.content.mode === 2);
		fields.color1.setValue(data.content.color1);
		fields.color2.setValue(data.content.color2);
		fields.color3.setValue(data.content.color3);
	},
	applyAction: function(fields, data, elem) {
		data.content.profileId = fields.link.getText();
		if (fields.mode0.getValue()) data.content.mode = 0;
		if (fields.mode1.getValue()) data.content.mode = 1;
		if (fields.mode2.getValue()) data.content.mode = 2;
		data.content.color1 = fields.color1.getValue().substring(1);
		data.content.color2 = fields.color2.getValue().substring(1);
		data.content.color3 = fields.color3.getValue().substring(1);
	},
	loadAction: function(data) {
		if (!data.content.mode) data.content.mode = 0;
		if (!data.content.color1) data.content.color1 = 'ffffff';
		if (!data.content.color2) data.content.color2 = '2B587A';
		if (!data.content.color3) data.content.color3 = '5B7FA6';
		if (!data.content.profileId) data.content.profileId = 20003922;
		data.content.profileId = ('' + data.content.profileId).replace(/^.*?(\-*\d+).*$/, '$1');
	},
	loadedAction: function(data, elem) {
		this.pluginScoped.addListener(this, function() {
			window.VK.Widgets.Group(data.id + '_vk_groups', {mode: data.content.mode, width: data.width, height: data.height, color1: data.content.color1, color2: data.content.color2, color3: data.content.color3}, data.content.profileId);
		});
	},
	saveAction: function(data, elem) {
		// TODO: save data
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"twitter","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/twitter\/main.png";
PluginWrapper._config.template = "<a class=\"twitter-timeline\" data-theme=\"{{content.theme}}\" data-width=\"{{width}}\" data-link-color=\"{{content.linkColor}}\" data-height=\"{{height}}\" href=\"{{content.url}}\">Twitter<\/a> <script async src=\"\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
PluginWrapper.registerPlugin('twitter', {
    name: 'Twitter',
    element: {
        minSize: {width: 250, height: 100},
        defaultSize: {width: 400, height: 480},
        resizable: true
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {children: [
                    {type: 'VerticalLayout', children: [
                            {type: 'Label', text: __('Twitter Url for embed'),
                                helpText: __('Please type collection, profile, list or likes timeline url')
                            },
                            {type: 'TextField', id: 'url'}
                        ]},
                    {type: 'HorizontalLayout', columnWeights: [3, 3], css: {marginTop: 15}, children: [
                            {type: 'VerticalLayout', children: [
                                    {type: 'Label', text: __('Theme')},
                                    {type: 'RadioBox', id: 'light', label: __('Light'), group: 'theme'},
                                    {type: 'RadioBox', id: 'dark', label: __('Dark'), group: 'theme'}
                                ]},
                            {type: 'VerticalLayout', children: [
                                    {type: 'Label', text: __('Default link color')},
                                    {type: 'ColorSelector', id: 'linkColor', noTransparent: true}
                                ]}
                        ]}
                ]}
        ]
    },
    pluginScoped: {
        scriptLoaded: false,
        scriptReady: false,
        listeners: []
    },
    resizeTimeout: null,
    resizeAction: function (data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function () {
                self.resizeTimeout = null;
                self.updateElement();
            }, 2000);
        }
    },
    openAction: function (fields, data, elem) {
        fields.url.setText(data.content.url);
        fields.light.setValue(data.content.theme === 'light');
        fields.dark.setValue(data.content.theme === 'dark');
        fields.linkColor.setValue(data.content.linkColor);
    },
    applyAction: function (fields, data, elem) {
        data.content.url = fields.url.getText();
        data.content.linkColor = fields.linkColor.getValue();
        if (fields.light.getValue())
            data.content.theme = 'light';
        if (fields.dark.getValue())
            data.content.theme = 'dark';
    },
    loadAction: function (data) {
        if (!data.content.linkColor)
            data.content.linkColor = '#1b95e0';
        if (!data.content.theme)
            data.content.theme = 'light';
        if (!data.content.url)
            data.content.url = 'https://twitter.com/sitepro_builder';

    }
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"dragonpay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/dragonpay\/main.png";
PluginWrapper._config.template = "{{#content.store}}\r\n<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 140px; height: 50px;\" onclick=\"{{id}}_showModal()\">\r\n\t<img src=\"gallery_gen\/dragonpay\/dragonpay.png\" alt=\"Dragonpay\" style=\"width: auto; max-width: 100%;\" \/>\r\n<\/button>\r\n{{\/content.store}}\r\n{{^content.store}}\r\n<button class=\"btn btn-default btn-sm\" onclick=\"{{id}}_showModal()\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/dragonpay\/site\/{{\/isPublished}}gallery_gen\/dragonpay\/dragonpay.png\" alt=\"Dragonpay\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n<\/button>\r\n{{\/content.store}}\r\n\r\n<div class=\"modal fade\" id=\"{{id}}_modal\" tabindex=\"-1\" role=\"dialog\">\r\n    <div class=\"modal-dialog\" role=\"document\">\r\n        <div class=\"modal-content\">\r\n            <div class=\"modal-header\">\r\n                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;<\/span><\/button>\r\n                <h4 class=\"modal-title\">Dragonpay<\/h4>\r\n            <\/div>\r\n            <div class=\"modal-body\">\r\n\t\t\t\t<form data-gateway-id=\"Dragonpay\" id=\"{{id}}_form\" action=\"{{#content.demo}}http:\/\/test.dragonpay.ph\/Pay.aspx{{\/content.demo}}{{^content.demo}}https:\/\/gw.dragonpay.ph\/Pay.aspx{{\/content.demo}}\" method=\"get\" style=\"width: 100%; height: 100%;\">\r\n\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t<label>{{content.__t.email}} <span style=\"color: #c00;\">*<\/span><\/label>\r\n\t\t\t\t\t\t<input class=\"form-control input-sm\" type=\"email\" name=\"email\" required \/>\r\n\t\t\t\t\t<\/div>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"merchantid\" value=\"{{content.merchant_id}}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" data-fixed-decimal=\"2\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"ccy\" value=\"{{content.currency}}\" \/>\r\n\t\t\t\t\t<input type=\"hidden\" name=\"description\" value=\"{{content.description}}\" \/>\r\n\t\t\t\t\t<input type=\"submit\" class=\"hidden\" \/>\r\n\t\t\t\t\t{{{requireService}}}\r\n\t\t\t\t\t{{#content.store}}\r\n\t\t\t\t\t<input type=\"hidden\" name=\"txnid\" value=\"{transactionId}\" \/>\r\n\t\t\t\t\t{{\/content.store}}\r\n\t\t\t\t<\/form>\r\n\t\t\t<\/div>\r\n\t\t\t<div class=\"modal-footer\">\r\n                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">{{content.__t.close}}<\/button>\r\n                <button type=\"button\" class=\"btn btn-primary\" id=\"{{id}}_pay_btn\">{{content.__t.pay}}<\/button>\r\n            <\/div>\r\n\t\t<\/div>\r\n\t<\/div>\r\n<\/div>\r\n\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\tvar modalAppendToBody = false;\r\n\t\twindow.{{id}}_showModal = function() {\r\n\t\t\tif (!modalAppendToBody) {\r\n\t\t\t\t$('#{{id}}_modal').appendTo('body');\r\n\t\t\t\tmodalAppendToBody = true;\r\n\t\t\t}\r\n\t\t\t$('#{{id}}_modal').modal('show');\r\n\t\t};\r\n\t\t$('#{{id}}_pay_btn').on('click', function() {\r\n\t\t\t$(this).attr('disabled', 'disabled');\r\n\t\t\t$('#{{id}}_modal').find('input[type=\"submit\"]').trigger('click');\r\n\t\t});\r\n\t\t$('#{{id}}_modal').on('show.bs.modal', function() {\r\n\t\t\t$('#{{id}}_pay_btn').removeAttr('disabled');\r\n\t\t});\r\n\t})();\r\n<\/script>\r\n{{\/isPublished}}\r\n";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/dragonpay/main.php';
PluginWrapper._config.active = false;
(function() {
	var dlg = null;
	window._dragonpay_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://www.dragonpay.ph" target="_blank">https://www.dragonpay.ph</a></p>'
					+ '<p><strong>Postback URL:</strong><br />'
					+ '<pre>' + base_url + 'store-callback/Dragonpay' + '</pre></p>'
					+ '<p><strong>Return URL:</strong><br />'
					+ '<pre>' + base_url + 'store-return/Dragonpay' + '</pre></p>';
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
	if (typeof window.dragonpay_translations === 'undefined') {
		window.dragonpay_translations = {
			'email': __c('E-mail'),
			'pay': __c('Pay'),
			'close': __c('Close')
		};
	}
})();

ElementRegister.registerPaymentGateway({
	name: 'Dragonpay',
	id: 'dragonpay',
	keyFieldId: 'merchant_id',
	keyField2Id: 'secret_key',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [6,6,12], children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Secret Key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['merchant_id', 'secret_key', 'demo'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window._dragonpay_settings_dialog().setVisible(true); });
		return btn;
	},
	__t: window.dragonpay_translations
});
PluginWrapper.registerPlugin('dragonpay', {
	name: 'Dragonpay',
	element: {
		minSize: {width: 60, height: 20},
		defaultSize: {width: 140, height: 70},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Merchant ID')},
							{type: 'TextField', id: 'merchant_id'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Secret Key')},
							{type: 'TextField', id: 'secret_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'description'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount')},
							{type: 'TextField', id: 'amount'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: '#PHP', name: 'PHP', value: 'PHP'},
								{id: '#USD', name: 'USD', value: 'USD'},
								{id: '#CAD', name: 'CAD', value: 'CAD'}
							]}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Button Label')},
						{type: 'TextField', id: 'button_label'}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'button_border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'button_color'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'font_size'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'label_color', noTransparent: true}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', css: {width: 120}, children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Max logo width')},
							{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Show logo')},
							{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
							{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'right'});
						}}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.merchant_id.setText(data.content.merchant_id);
		fields.secret_key.setText(data.content.secret_key);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.merchant_id = fields.merchant_id.getText();
		data.content.secret_key = fields.secret_key.getText();
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		data.content.__t = window.dragonpay_translations;
		if (!data.content.currency) data.content.currency = 'PHP';
		if (!data.content.merchant_id) data.content.merchant_id = '';
		if (!data.content.secret_key) data.content.secret_key = '';
		if (!data.content.amount) data.content.amount = '1';
		if (!data.content.description) data.content.description = '';
		
		if (data.content.button_label === undefined) data.content.button_label = '';
		if (!data.content.button_color) data.content.button_color = '#fafafa';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#555';
		if (!data.content.button_border) data.content.button_border = {
			color: '#000',
			style: 'none',
			weight: 0,
			css: { border: '0px none #000' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 120;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"zopim","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/zopim\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n\t<div class=\"wb_caption smaller\">\r\n\t\t<div>\r\n\t\t\t<i class=\"ico-pl-zopim\"><\/i> <strong>Zopim<\/strong><br \/>{{content.placeholder}}\r\n\t\t<\/div>\r\n\t<\/div>\r\n{{\/isPublished}}\r\n{{#firstOnPage}}\r\n<script type=\"text\/javascript\">\r\nwindow.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=\r\nd.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.\r\n_.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute(\"charset\",\"utf-8\");\r\n$.src=\"\/\/v2.zopim.com\/?{{content.groupId}}\";z.t=+new Date;$.\r\ntype=\"text\/javascript\";e.parentNode.insertBefore($,e)})(document,\"script\");\r\n<\/script>\r\n{{\/firstOnPage}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('zopim', {
    name: 'Zopim',
    element: {
        minSize: {
            width: 190,
            height: 70
        },
        defaultSize: {
            width: 190,
            height: 70
        },
        resizable: false,
		supportsFullWidth: false
    },
    propertyDialog: {
        noScroll: true,
        tabs: [{
            name: 'General',
            children: [{
                type: 'VerticalLayout',
                children: [{
                    type: 'Label',
                    text: __('Zopim SRC ID'),
					helpText: __('SRC ID from widget code "/v2.zopim.com/?SRC_ID" provided by Zopim')
                }, {
                    type: 'TextField',
                    id: 'groupId'
                }]
            }]
        }]
    },
    resizeTimeout: null,

    resizeAction: function(data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function() {
                self.resizeTimeout = null;
                self.updateElement();
            }, 1000);
        }
    },
    openAction: function(fields, data, elem) {
        fields.groupId.setText(data.content.groupId);
    },
    applyAction: function(fields, data, elem) {
        data.content.groupId = fields.groupId.getText();
		if (data.content.groupId.indexOf('//v2.zopim.com/?') > -1) {
			var m = data.content.groupId.match(/\/\/v2\.zopim\.com\/\?(\w+)['"]/i);
			data.content.groupId = ((1 in m) && m[1]) ? m[1] : '';
		}
    },
    loadAction: function(data) {
		if (!data.content.groupId) data.content.groupId = '';
		data.content.placeholder = __('Double click to change properties');
    }
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"easypay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/easypay\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Easypay\" method=\"post\" action=\"https:\/\/ssl.easypay.by\/weborder\/\"{{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"EP_Sum\" value=\"{{content.sum}}\" \/>\r\n\t<input type=\"hidden\" name=\"EP_MerNo\" value=\"{{content.merno}}\" \/>\r\n\t<input type=\"hidden\" name=\"EP_Expires\" value=\"30\" \/>\r\n\t<input type=\"hidden\" name=\"EP_Comment\" value=\"{{content.ordername}}\" \/>\r\n\t<input type=\"hidden\" name=\"EP_OrderInfo\" value=\"{{content.orderdescription}}\" \/>\r\n\t{{#content.demo}}\r\n\t<input type=\"hidden\" name=\"EP_Debug\" value=\"1\" \/>\r\n\t{{\/content.demo}}\r\n\t<input type=\"hidden\" name=\"EP_Encoding\" value=\"utf-8\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"EP_OrderNo\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"EP_Success_URL\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"EP_Cancel_URL\" value=\"{cancelUrl}\" \/>\r\n\t<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/easypay\/easypay.gif\" alt=\"EasyPay\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/easypay\/site\/{{\/isPublished}}gallery_gen\/easypay\/easypay.gif\" alt=\"EasyPay\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/easypay/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'EasyPay',
	id: 'easypay',
	pageUrl: 'https://ssl.easypay.by/',
	keyFieldId: 'merno',
	keyField2Id: 'webkey',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [6,6,12], children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Web key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'ordername,orderdescription',
	priceFieldId: 'sum',
	globalVars: ['merno', 'webkey']
});
PluginWrapper.registerPlugin('easypay', {
	name: 'EasyPay',
	element: {
		minSize: {width: 60, height: 20},
		defaultSize: {width: 110, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant ID'), helpText:__("Merchant account number in EasyPay")},
						{type: 'TextField', id: 'merno'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Web key'), helpText:__("Personal key from EasyPay")},
						{type: 'TextField', id: 'webkey'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Item Name'), helpText:__("The name of the goods. Cannot contain special symbols")},
						{type: 'TextField', id: 'ordername'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred") + ', ' + __('BYN')},
						{type: 'TextField', id: 'sum'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Description')},
					{type: 'TextField', id: 'orderdescription'}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'bottom'});
					}}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		fields.merno.setText(data.content.merno);
		fields.webkey.setText(data.content.webkey);
		fields.ordername.setText(data.content.ordername);
		fields.orderdescription.setText(data.content.orderdescription);
		fields.sum.setText(data.content.sum);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.label_color.setValue(data.content.label_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		data.content.merno = fields.merno.getText();
		data.content.webkey = fields.webkey.getText();
		data.content.ordername = fields.ordername.getText();
		data.content.orderdescription = fields.orderdescription.getText();
		data.content.sum = fields.sum.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.merno) data.content.merno = '';
		if (!data.content.webkey) data.content.webkey = '';
		if (!data.content.ordername) data.content.ordername = ''; // Donate
		if (!data.content.orderdescription) data.content.orderdescription = ''; // Donate 1 RUB
		if (!data.content.sum) data.content.sum = '1';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#fff';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#000';
		if (!data.content.button_border) data.content.button_border = {
			color: '#ccc',
			style: 'none',
			weight: 1,
			css: { border: '1px none #ccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 100;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"hipay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/hipay\/main.png";
PluginWrapper._config.template = "{{^isPreview}}\r\n{{^isPublished}}\r\n<script>\r\n    $.ajax({\r\n        url: \"{{{serviceUrl}}}\",\r\n        type: \"POST\",\r\n        data: {apiKey: \"{{content.apiKey}}\", apiSecretKey: \"{{content.apiSecretKey}}\", siteId: \"{{content.siteId}}\", productName: \"{{content.productName}}\", amount: \"{{content.amount}}\", currency: \"{{content.currency}}\"},\r\n        success: function (data)\r\n        {\r\n            $('#hipay_{{id}}').html(data);\r\n        }\r\n    });\r\n<\/script>\r\n{{\/isPublished}}\r\n{{\/isPreview}}\r\n{{#content.store}}\r\n<form data-gateway-id=\"Hipay\" method=\"POST\" accept-charset=\"utf-8\">\r\n\t<input type=\"hidden\" name=\"callbackurl\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"orderId\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"productName\" value=\"{{content.productName}}\" \/>\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"image\" src=\"http:\/\/i.imgur.com\/V545yLD.png\"\/>\r\n<\/form>\r\n{{\/content.store}}\r\n{{^content.store}}\r\n<div id=\"hipay_{{id}}\">{{{requireService}}}<\/div>\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
    name: __('HiPay'),
    id: 'hipay',
    keyField: __('API Key'),
    keyFieldId: 'apiKey',
    keyField2: __('API Secret Key'),
    keyField2Id: 'apiSecretKey',
    keyField3: __('Site Merchant ID'),
    keyField3Id: 'siteId',
    titleFieldId: 'label',
    nameFieldId: 'productName',
    priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['apiKey', 'apiSecretKey', 'siteId']
});
PluginWrapper.registerPlugin('hipay', {
    name: 'HiPay',
    element: {
        minSize: {width: 162, height: 56},
        defaultSize: {width: 162, height: 56},
        resizable: false
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {children: [{type: 'VerticalLayout', spacing: 15, children: [
                            {type: 'HorizontalLayout', columnWeights: [4, 4], css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('API Key')},
                                            {type: 'TextField', id: 'apiKey'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('API Secret Key')},
                                            {type: 'TextField', id: 'apiSecretKey'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Site Merchant ID')},
                                            {type: 'TextField', id: 'siteId'}
                                        ]}
                                ]},
                            {type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Item Name'), helpText: __('Title of what you are paying for')},
                                            {type: 'TextField', id: 'productName'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Amount')},
                                            {type: 'TextField', id: 'amount'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Currency')},
                                            {type: 'DropdownBox', id: 'currency', options: [
                                                    {id: '#EUR', name: 'EUR', value: 'EUR'},
                                                    {id: '#USD', name: 'USD', value: 'USD'}
                                                ]}
                                        ]}
                                ]}
                        ]}
                ]}
        ]
    },
    resizeAction: function (data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function () {
                self.resizeTimeout = null;
                self.updateElement();
            }, 1000);
        }
    },
    openAction: function (fields, data, elem) {
        fields.apiKey.setText(data.content.apiKey);
        fields.apiSecretKey.setText(data.content.apiSecretKey);
        fields.productName.setText(data.content.productName);
        fields.amount.setText(data.content.amount);
        fields.siteId.setText(data.content.siteId);

        var itm;
        itm = fields.currency.getItemById('#' + data.content.currency);
        fields.currency.selectItem(itm);
    },
    applyAction: function (fields, data, elem) {
        data.content.apiKey = fields.apiKey.getText();
        data.content.apiSecretKey = fields.apiSecretKey.getText();
        data.content.productName = fields.productName.getText();
        data.content.amount = fields.amount.getText();
        data.content.siteId = fields.siteId.getText();

        var itm;
        itm = fields.currency.getSelectedItem();
        data.content.currency = itm.getOriginal().value;

    },
    loadAction: function (data) {
        if (!data.content.apiKey)
            data.content.apiKey = '5a93f0a8a8c2a9a953029a2e8719ab56';
        if (!data.content.apiSecretKey)
            data.content.apiSecretKey = 'c883cc5dd1d8c5ba793cb6733b5f8804';
        if (!data.content.siteId)
            data.content.siteId = '123456';
        if (!data.content.productName)
            data.content.productName = 'Title of what you are paying for';
        if (!data.content.amount)
            data.content.amount = '10.20';
        if (!data.content.currency)
            data.content.currency = 'EUR';
        data.serviceUrl = this.serviceUrl;

    }
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"effect","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/effect\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n\t<div class=\"wb_caption smaller\">\r\n\t\t<div>\r\n\t\t\t<i class=\"ico-pl-effect\"><\/i> <strong>Effect<\/strong><br \/>{{content.placeholder}}\r\n\t\t<\/div>\r\n\t<\/div>\r\n{{\/isPublished}}\r\n{{#firstOnPage}}\r\n\t<script type=\"text\/javascript\" src=\"\/\/effect.com\/widget\"><\/script>\r\n{{\/firstOnPage}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('effect', {
	name: 'Effect',
	element: {
		renderOnce: true,
		resizable: false,
		supportsFullWidth: false,
		minSize: {width: 190, height: 70},
		defaultSize: { width: 190, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{general: true, options: false, children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('To start receiving messages from clients please finish plugin setup.')}
				]},
				{type: 'VerticalLayout', css: {marginTop: 5}, children: [
					{type: 'Button', text: __('Finish setup'), buttonStyle: 'success', click: function() {
						var win = window.open('https://effect.com?r=6isnvi', '_blank');
						win.focus();
					}}
				]}
			]}
		]
	},
	loadAction: function(data) {
		data.content.placeholder = __('Double click to change properties');
//		data.content.placeholder = 'Effect.com ' + __('Settings').toLowerCase();
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"mercado","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/mercado\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Mercado\" method=\"POST\" accept-charset=\"utf-8\"{{^content.store}} target=\"_blank\"{{\/content.store}}>\r\n\t<input type=\"hidden\" name=\"mercado_submit\" value=\"1\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"returnUrl\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"cancelUrl\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"callbackUrl\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"orderId\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.unitPrice}}\" \/>\r\n\t<input type=\"hidden\" name=\"title\" value=\"{{content.title}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currencyId}}\" \/>\r\n\t{{\/content.store}}\r\n\t<button type=\"submit\"\r\n\t\t\tstyle=\"background: url({{^isPublished}}plugins\/mercado\/site\/{{\/isPublished}}gallery_gen\/mercado\/mercado.gif) center center no-repeat;\r\n\t\t\t\t   background-size: contain;\r\n\t\t\t\t   vertical-align: middle;\r\n\t\t\t       border: none;\r\n\t\t\t       width: {{#width}}{{width}}px;{{\/width}}{{^width}}140px;{{\/width}}\r\n\t\t\t       height: {{#height}}{{height}}px;{{\/height}}{{^width}}30px;{{\/width}}\"><\/button>\r\n<\/form>\r\n{{^content.store}}\r\n{{{requireService}}}\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/mercado/main.php';
PluginWrapper._config.active = true;
ElementRegister.registerPaymentGateway({
	name: 'MercadoPago',
	id: 'mercado',
	pageUrl: 'https://www.mercadopago.com/',
	keyField: __('Client ID'),
	keyFieldId: 'clientId',
	keyField2: __('Secret ID'),
	keyField2Id: 'secretId',
	titleFieldId: 'label',
	nameFieldId: 'title',
	priceFieldId: 'unitPrice',
	currencyFieldId: 'currencyId',
	globalVars: ['clientId', 'secretId']
});
PluginWrapper.registerPlugin('mercado', {
	name: 'MercadoPago',
	element: {
		minSize: {width: 50, height: 10},
		defaultSize: {width: 120, height: 25},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Client ID')},
							{type: 'TextField', id: 'clientId'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Secret ID')},
							{type: 'TextField', id: 'secretId'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name'), helpText: __('The name of the goods. Cannot contain special symbols')},
							{type: 'TextField', id: 'title'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount')},
							{type: 'TextField', id: 'unitPrice'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currencyId', options: [
								{id: '#ARS', name: 'ARS', value: 'ARS'},
								{id: '#BRL', name: 'BRL', value: 'BRL'},
								{id: '#VEF', name: 'VEF', value: 'VEF'},
								{id: '#CLP', name: 'CLP', value: 'CLP'},
								{id: '#MXN', name: 'MXN', value: 'MXN'},
								{id: '#COP', name: 'COP', value: 'COP'},
								{id: '#PEN', name: 'PEN', value: 'PEN'},
								{id: '#UYU', name: 'UYU', value: 'UYU'}
								// {id: '#USD', name: 'USD', value: 'USD'}
							]}
						]}
					]}
				]}
			]}
		]
	},
	resizeAction: function (data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function () {
				self.resizeTimeout = null;
				self.updateElement();
			}, 1000);
		}
	},
	openAction: function (fields, data, elem) {
		fields.clientId.setText(data.content.clientId);
		fields.secretId.setText(data.content.secretId);
		fields.title.setText(data.content.title);
		fields.unitPrice.setText(data.content.unitPrice);
		var itm;
		itm = fields.currencyId.getItemById('#' + data.content.currencyId);
		fields.currencyId.selectItem(itm);
	},
	applyAction: function (fields, data, elem) {
		data.content.clientId = fields.clientId.getText();
		data.content.secretId = fields.secretId.getText();
		data.content.title = fields.title.getText();
		data.content.unitPrice = fields.unitPrice.getText();
		var itm;
		itm = fields.currencyId.getSelectedItem();
		data.content.currencyId = itm.getOriginal().value;
	},
	loadAction: function (data) {
		if (!data.content.clientId) data.content.clientId = ''; // 7053461069604856
		if (!data.content.secretId) data.content.secretId = ''; // snhsL9y7Geq0nOqmM3PtEf79QkzRLLvy
		if (!data.content.title) data.content.title = ''; // Title of what you are paying for
		if (!data.content.unitPrice) data.content.unitPrice = '1'; // 10.20
		if (!data.content.currencyId) data.content.currencyId = 'ARS';
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"cash_on_delivery","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/cash_on_delivery\/main.png";
PluginWrapper._config.template = "{{%FILTERS}}\r\n<form data-gateway-id=\"CashOnDelivery\" action=\"\" method=\"post\" style=\"width: 100%; height: 100%;\" id=\"{{id}}_cash_on_delivery_form\" onsubmit=\"return false;\">\r\n\t<input type=\"hidden\" name=\"invoiceUrl\" value=\"\" \/>\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t{{#content.store}}\r\n\t<button class=\"btn btn-default btn-raised\" style=\"vertical-align: middle; font-weight: bold;\"><i class=\"fa fa-money\"><\/i> {{content.__t.label}}<\/button>\r\n\t{{\/content.store}}\r\n<\/form>\r\n\r\n{{#content.store}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\t$('#{{id}}_cash_on_delivery_form').on('beforesend', function(e, checkoutData) {\r\n\t\t\te.preventDefault();\r\n\t\t\t$('#{{id}}_cash_on_delivery_invoice_link').attr(\"href\", checkoutData.orderData.invoiceUrl);\r\n\t\t\t$('#{{id}}_cash_on_delivery_modal')\r\n\t\t\t\t.appendTo(\"body\")\r\n\t\t\t\t.modal({\r\n\t\t\t\t\tbackdrop: 'static',\r\n\t\t\t\t\tkeyboard: false\r\n\t\t\t\t})\r\n\t\t\t\t.on('hide.bs.modal', function() {\r\n\t\t\t\t\twindow.location.href = checkoutData.backUrl;\r\n\t\t\t\t})\r\n\t\t\t;\r\n\t\t\treturn false;\r\n\t\t});\r\n\t})();\r\n<\/script>\r\n<div class=\"modal fade\" id=\"{{id}}_cash_on_delivery_modal\" tabindex=\"-1\" role=\"dialog\">\r\n    <div class=\"modal-dialog\" role=\"document\">\r\n        <div class=\"modal-content\">\r\n            <div class=\"modal-header\">\r\n                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;<\/span><\/button>\r\n                <h4 class=\"modal-title\">{{content.__t.label}}<\/h4>\r\n            <\/div>\r\n            <div class=\"modal-body\">\r\n\t\t\t\t{{{content.info | i18n}}}\r\n\t\t\t\t<div>\r\n\t\t\t\t\t<a id=\"{{id}}_cash_on_delivery_invoice_link\" href=\"javascript:void(0)\" target=\"_blank\" class=\"btn btn-success\"><i class=\"fa fa-file-pdf-o\"><\/i> {{content.__t.download_invoice}}<\/a>\r\n\t\t\t\t<\/div>\r\n\t\t\t<\/div>\r\n\t\t\t<div class=\"modal-footer\">\r\n                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">{{content.__t.close}}<\/button>\r\n            <\/div>\r\n\t\t<\/div>\r\n\t<\/div>\r\n<\/div>\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/cash_on_delivery/main.php';
PluginWrapper._config.active = true;
(function() {
	if (typeof window.cash_on_delivery_translations === 'undefined') {
		window.cash_on_delivery_translations = {
			'download_invoice': __c('Download invoice'),
			'label': __c('Cash on Delivery'),
			'close': __c('Close')
		};
	}
})();

var updateCashOnDeliveryWarning = function(list, store) {
	var _this = this;
	setTimeout(function() {
		var text = '';
		if( _this.enabler.getValue() ) {
			var cartPropertiesFields = list.getUiFields();
			if( !cartPropertiesFields.billingShippingRequired.getValue() )
				text += '<li>' + __('"%s" checkbox must also be checked to enable this gateway.').replace("%s", __('Require Billing/Shipping Information')) + '</li>';
			if( !cartPropertiesFields.companyInfo.getValue() || cartPropertiesFields.companyInfo.getValue() === "" )
				text += '<li>' + __('Seller details are required to create invoices.') + '</li>';
			if( !cartPropertiesFields.invoiceDocumentNumberFormat.getValue() || cartPropertiesFields.invoiceDocumentNumberFormat.getValue() === "" )
				text += '<li>' + __('Invoice document number format is required to create invoices.') + '</li>';
			if( !store.contactForm.content.email || !store.contactForm.content.emailFrom  || store.contactForm.content.emailFrom === "" || store.contactForm.content.email === "" )
				text += '<li>' + __('To send order confirmations recipient and sender emails must be entered in store contact form email settings.') + '</li>';
		}
		if( text === '' )
			_this.cashOnDeliveryWarnings.setContent('');
		else
			_this.cashOnDeliveryWarnings.setContent('<div class="alert alert-warning" style="margin: 5px 0 0;"><ul style="padding: 0 0 0 15px;">' + text + '</ul></div>');
	}, 0);
};

ElementRegister.registerPaymentGateway({
	name: __('Cash on Delivery'),
	id: 'cash_on_delivery',
	priority: 2,
	forceActive: PluginWrapper._config.active,
	pageUrl: null,
	keyFieldId: 'info',
	keyFieldDefaultValue: '<p>' + __("Your order was successfully placed.") + '<br />' + __("You will be contacted shortly about your order confirmation.") + '</p>',
	keyFieldDef: {type: 'VerticalLayout', children: [
		{type: 'HorizontalLayout', columnWeights: [12, 12], noPadding: true, children: [
			{type: 'Label', text: __('Information to display when order is placed')},
			{type: 'WYSIWYGControl', id: 'key', css: {height: 100}, forcePasteAsPlainText: true}
		]},
		{type: 'CustomContainer', id: 'cashOnDeliveryWarnings'}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['info'],
	__t: window.cash_on_delivery_translations,
	onInit: function(list, store) {
		var _this = this;
		var cartPropertiesFields = list.getUiFields();
		cartPropertiesFields.billingShippingRequired.on("change", function() {
			updateCashOnDeliveryWarning.call(_this, list, store);
		});
		cartPropertiesFields.companyInfo.on("change", function() {
			updateCashOnDeliveryWarning.call(_this, list, store);
		});
		cartPropertiesFields.invoiceDocumentNumberFormat.on("change", function() {
			updateCashOnDeliveryWarning.call(_this, list, store);
		});
		cartPropertiesFields.invoiceDocumentNumberSeries.on("change", function() {
			updateCashOnDeliveryWarning.call(_this, list, store);
		});
		cartPropertiesFields.invoiceDocumentNumberLength.on("change", function() {
			updateCashOnDeliveryWarning.call(_this, list, store);
		});
	},
	onEnable: updateCashOnDeliveryWarning,
	onDisable: updateCashOnDeliveryWarning
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"bepaid","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/bepaid\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Bepaid\" method=\"POST\" accept-charset=\"utf-8\" {{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"redirectUrl\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"cancelUrl\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"webhookUrl\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"orderId\" value=\"{transactionId}\" \/>\r\n\t<button type=\"submit\" class=\"btn btn-info\"\r\n  \t\ttitle=\"{{content.label}}\"\r\n  \t\tstyle=\"width: 150px;\r\n  \t\t\t   height: 40px;\r\n  \t\t\t   border: 0 solid #000;\r\n  \t\t\t   background: #e37125;\r\n  \t\t\t   padding: 6px 10px;\r\n  \t\t\t   color: #fff;\r\n  \t\t\t   font-size: 18px;\r\n  \t\t\t   font-family: Arial,Helvetica,sans-serif;\">{{content.label}}<\/button>\r\n\r\n\t{{\/content.store}}\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"hidden\" name=\"description\" value=\"{{content.description}}\" \/>\r\n\t{{^content.store}}\r\n\t<input type=\"hidden\" name=\"{{id}}_submit\" value=\"1\" \/>\r\n\t<button type=\"submit\" class=\"btn btn-info\"\r\n\t\t\ttitle=\"{{content.button_label}}\"\r\n\t\t\tstyle=\"width: 100%; height: 100%;\r\n\t\t\t\t   {{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\r\n\t\t\t\t   background-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t\t   padding: 6px 10px;\r\n\t\t\t\t   color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\r\n\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\">\r\n\t\t   <strong>{{content.button_label}}<\/strong><\/button>\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n<\/form>\r\n";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/bepaid/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'bePaid',
	id: 'bepaid',
	pageUrl: 'https://bepaid.by/',
	keyFieldId: 'shop_id',
	keyField2Id: 'shop_key',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [6,6,12], children: [
		{type: 'TextField', placeholder: __('Shop ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Secret Key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['shop_id', 'shop_key', 'demo']
});

PluginWrapper.registerPlugin('bepaid', {
	name: 'bePaid',
	element: {
		minSize: {width: 162, height: 56},
		defaultSize: {width: 162, height: 56},
		resizable: false
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', spacing: 15, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Shop ID')},
						{type: 'TextField', id: 'shop_id'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Secret Key')},
						{type: 'TextField', id: 'shop_key'}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [6, 3, 3], columnWeightsSmall: [6, 3, 3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Item Name'), helpText:__('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'orderdescription'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred")},
						{type: 'TextField', id: 'amount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'currency', options: [
							{id: '#RUB', name: 'RUB', value: 'RUB'},
							{id: '#USD', name: 'USD', value: 'USD'},
							{id: '#EUR', name: 'EUR', value: 'EUR'},
							{id: '#BYN', name: 'BYN', value: 'BYN'},
							{id: '#AMD', name: 'AMD', value: 'AMD'},
							{id: '#AUD', name: 'AUD', value: 'AUD'},
							{id: '#AZN', name: 'AZN', value: 'AZN'},
							{id: '#BGN', name: 'BGN', value: 'BGN'},
							{id: '#BRL', name: 'BRL', value: 'BRL'},
							{id: '#CAD', name: 'CAD', value: 'CAD'},
							{id: '#CHF', name: 'CHF', value: 'CHF'},
							{id: '#CNY', name: 'CNY', value: 'CNY'},
							{id: '#CZK', name: 'CZK', value: 'CZK'},
							{id: '#DKK', name: 'DKK', value: 'DKK'},
							{id: '#GBP', name: 'GBP', value: 'GBP'},
							{id: '#HUF', name: 'HUF', value: 'HUF'},
							{id: '#INR', name: 'INR', value: 'INR'},
							{id: '#JPY', name: 'JPY', value: 'JPY'},
							{id: '#KGS', name: 'KGS', value: 'KGS'},
							{id: '#KRW', name: 'KRW', value: 'KRW'},
							{id: '#KZT', name: 'KZT', value: 'KZT'},
							{id: '#MDL', name: 'MDL', value: 'MDL'},
							{id: '#NOK', name: 'NOK', value: 'NOK'},
							{id: '#PLN', name: 'PLN', value: 'PLN'},
							{id: '#RON', name: 'RON', value: 'RON'},
							{id: '#SEK', name: 'SEK', value: 'SEK'},
							{id: '#SGD', name: 'SGD', value: 'SGD'},
							{id: '#TJS', name: 'TJS', value: 'TJS'},
							{id: '#TMT', name: 'TMT', value: 'TMT'},
							{id: '#TRY', name: 'TRY', value: 'TRY'},
							{id: '#UAH', name: 'UAH', value: 'UAH'},
							{id: '#UZS', name: 'UZS', value: 'UZS'},
							{id: '#ZAR', name: 'ZAR', value: 'ZAR'}
						]}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'bottom'});
					}}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		fields.shop_id.setText(data.content.shop_id);
		fields.shop_key.setText(data.content.shop_key);
		fields.orderdescription.setText(data.content.orderdescription);
		fields.amount.setText(data.content.amount);

		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);

		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
	},
	applyAction: function(fields, data, elem) {
		data.content.shop_id = fields.shop_id.getText();
		data.content.shop_key = fields.shop_key.getText();
		data.content.orderdescription = fields.orderdescription.getText();
		data.content.amount = fields.amount.getText();
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;

		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.shop_id) data.content.shop_id = ''; // 4225
		if (!data.content.shop_key) data.content.shop_key = ''; // 3834fbef1fe6ea024ef77f5c79ec7ff1ba710ea6241c08c2f341afda8af4c1c4
		if (!data.content.ordername) data.content.orderdescription = '';
		if (!data.content.amount) data.content.amount = '1';
		if (!data.content.currency) data.content.currency = 'BYN';

		if (!data.content.button_label) data.content.button_label = __('Proceed to payment');
		if (!data.content.button_color) data.content.button_color = '#e37125';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#fff';
		if (!data.content.button_border) data.content.button_border = {
			color: '#ccc',
			style: 'none',
			weight: 1,
			css: { border: '1px none #ccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"gplus_like","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/gplus_like\/main.png";
PluginWrapper._config.template = "<div id=\"{{id}}_gp_plus_one\"><\/div>\r\n{{#isPublished}}\r\n<script type=\"text\/javascript\">\r\n\twindow.___gcfg = {parsetags: 'explicit'};\r\n<\/script>\r\n<script src=\"https:\/\/apis.google.com\/js\/platform.js\" type=\"text\/javascript\"><\/script>\r\n{{\/isPublished}}\r\n<script type=\"text\/javascript\">\r\n\tif (window.gapi) {\r\n\t\twindow.gapi.plusone.render('{{id}}_gp_plus_one', {\r\n\t\t\tsize: '{{content.size}}',\r\n\t\t\tannotation: '{{content.annotation}}',\r\n\t\t\twidth: '{{width}}'\r\n\t\t});\r\n\t}\r\n<\/script>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
PluginWrapper.registerPlugin('gplus_like', {
	name: 'G+',
	noButton: true,
	element: {
		minSize: {width: 24, height: 20},
		defaultSize: {width: 300, height: 24},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},								
						{type: 'RadioBox', id: 'sizeSmall', label: __('Small'), group: 'size'},
						{type: 'RadioBox', id: 'sizeMedium', label: __('Medium'), group: 'size'},
						{type: 'RadioBox', id: 'sizeStandard', label: __('Standard'), group: 'size'},
						{type: 'RadioBox', id: 'sizeTall', label: __('Tall'), group: 'size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Annotation')},								
						{type: 'RadioBox', id: 'annInline', label: __('Inline'), group: 'ann'},
						{type: 'RadioBox', id: 'annBubble', label: __('Buble'), group: 'ann'},
						{type: 'RadioBox', id: 'annNone', label: __('None'), group: 'ann'}
					]}
				]}
			]}
		]
	},
	
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		addListener: function(inst, func) {
			if (this.scriptReady) {
				func.call(inst);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('https://apis.google.com/js/platform.js', function() {
					self.scriptReady = true;
					for (var i = 0; i < self.listeners.length; i++) {
						self.listeners[i].func.call(self.listeners[i].inst);
					}
				});
			}
		}
	},
	resizeTimeout: null,

	resizeAction: function(data, elem) {
		if (data.content.annotation !== 'inline') return;
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function() {
				self.resizeTimeout = null;
				self.updateElement();
			}, 2000);
		}
	},
	openAction: function(fields, data, elem) {
		fields.sizeSmall.setValue(data.content.size === 'small');
		fields.sizeMedium.setValue(data.content.size === 'medium');
		fields.sizeStandard.setValue(data.content.size === 'standard');
		fields.sizeTall.setValue(data.content.size === 'tall');
		
		fields.annInline.setValue(data.content.annotation === 'inline');
		fields.annBubble.setValue(data.content.annotation === 'bubble');
		fields.annNone.setValue(data.content.annotation === 'none');
	},
	applyAction: function(fields, data, elem) {
		if (fields.sizeSmall.getValue()) data.content.size = 'small';
		if (fields.sizeMedium.getValue()) data.content.size = 'medium';
		if (fields.sizeStandard.getValue()) data.content.size = 'standard';
		if (fields.sizeTall.getValue()) data.content.size = 'tall';
		
		if (fields.annInline.getValue()) data.content.annotation = 'inline';
		if (fields.annBubble.getValue()) data.content.annotation = 'bubble';
		if (fields.annNone.getValue()) data.content.annotation = 'none';
		var w = null, h = 24;
		if (data.content.size === 'small') {
			if (data.content.annotation === 'none') w = 24;
			if (data.content.annotation === 'bubble') w = 70;
			h = 15;
		} else if (data.content.size === 'medium') {
			if (data.content.annotation === 'none') w = 32;
			if (data.content.annotation === 'bubble') w = 90;
			h = 20;
		} else if (data.content.size === 'standard') {
			if (data.content.annotation === 'none') w = 38;
			if (data.content.annotation === 'bubble') w = 106;
			h = 24;
		} else if (data.content.size === 'tall') {	
			if (data.content.annotation === 'inline') {
				w = null; h = 20;
			} else {
				w = 50;
			}
			if (data.content.annotation === 'none') h = 20;
			if (data.content.annotation === 'bubble') h = 60;
		}
		this.setSize(w, h);
	},
	loadAction: function(data) {
		if (!data.content.size) data.content.size = 'standard';
		if (!data.content.annotation) data.content.annotation = 'inline';
	},
	loadedAction: function(data, elem) {
		window.___gcfg = {parsetags: 'explicit'};
		this.pluginScoped.addListener(this, function() {
			window.gapi.plusone.render(data.id + '_gp_plus_one', {
				size: data.content.size,
				annotation: data.content.annotation,
				width: data.width
			});
		});		
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"webmoney_widget","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/webmoney_widget\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n<div class=\"alert alert-warning\">{{tr.preview_not_available}}<\/div>\r\n{{\/isPublished}}\r\n{{#isPublished}}\r\n<script id=\"wm-script\" type=\"text\/javascript\"\r\n\t\tsrc=\"\/\/merchant.webmoney.ru\/conf\/lib\/wm-simple-x20.min.js?lang=en&amp;wmid={{content.wmId}}&amp;purse={{content.purseId}}&amp;key={{content.key}}&amp;amount={{content.amount}}&amp;desc={{content.descriptionUrlEnc}}\"><\/script>\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;

PluginWrapper.registerPlugin('webmoney_widget', {
	name: __('WM Widget'),
	element: {
		minSize: {width: 25, height: 25},
		defaultSize: {width: 450, height: 224},
		resizable: false
	},
	propertyDialog: {
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'HorizontalLayout', children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('WebMoney ID')},
							{type: 'TextField', id: 'wmId'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Purse ID')},
							{type: 'TextField', id: 'purseId'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Key'), helpText: __('"Secret Key X20" field from your purse settings page'/* ctx: Option name in WM Widget plugin properties */)},
							{type: 'TextField', id: 'key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [9, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Description')},
							{type: 'TextField', id: 'description'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount'), helpText: __('In WM units defined by purse')},
							{type: 'TextField', id: 'amount'}
						]}
					]}
				]}
			]}
		]
	},
	
	pluginScoped: {
		urlEncode: function (str) {
			//       discuss at: http://phpjs.org/functions/urlencode/
			//      original by: Philip Peterson
			//      improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			//      improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			//      improved by: Brett Zamir (http://brett-zamir.me)
			//      improved by: Lars Fischer
			//         input by: AJ
			//         input by: travc
			//         input by: Brett Zamir (http://brett-zamir.me)
			//         input by: Ratheous
			//      bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			//      bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			//      bugfixed by: Joris
			// reimplemented by: Brett Zamir (http://brett-zamir.me)
			// reimplemented by: Brett Zamir (http://brett-zamir.me)

			str = (str + '').toString();
			return window.encodeURIComponent(str)
					.replace(/!/g, '%21')
					.replace(/'/g, '%27')
					.replace(/\(/g, '%28')
					.replace(/\)/g, '%29')
					.replace(/\*/g, '%2A')
					.replace(/%20/g, '+');
		}
	},
	
	resizeAction: function(data, elem) {
		elem.find('.wmbtn').eq(0).css({width: data.width, height: data.height});
	},
	openAction: function(fields, data, elem) {
		fields.wmId.setText(data.content.wmId);
		fields.purseId.setText(data.content.purseId);
		fields.key.setText(data.content.key);
		fields.amount.setText(data.content.amount);
		fields.description.setText(data.content.description);
	},
	applyAction: function(fields, data, elem) {
		data.content.wmId = fields.wmId.getText();
		data.content.purseId = fields.purseId.getText();
		data.content.key = fields.key.getText();
		data.content.amount = parseFloat(fields.amount.getText().replace(',', '.'));
		if (isNaN(data.content.amount)) data.content.amount = 1.0;
		data.content.description = fields.description.getText();
		data.content.descriptionUrlEnc = this.pluginScoped.urlEncode(data.content.description);
	},
	loadAction: function(data) {
		if (!data.content.wmId) data.content.wmId = '';
		if (!data.content.purseId) data.content.purseId = '';
		if (!data.content.key) data.content.key = '';
		if (!data.content.amount) data.content.amount = 1.0;
		if (!data.content.description) data.content.description = __('Donation to charitable fund');
		if (!data.content.descriptionUrlEnc) data.content.descriptionUrlEnc = this.pluginScoped.urlEncode(data.content.description);
		data.tr = {preview_not_available: __('Preview not available')};
	}
	
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"epsilon","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/epsilon\/main.png";
PluginWrapper._config.template = "{{#content.store}}\r\n<button id=\"{{id}}_button\" style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t<img src=\"gallery_gen\/epsilon\/epsilon.png\" alt=\"Epsilon\" style=\"width: auto; max-width: 100%;\" \/>\r\n<\/button>\r\n{{\/content.store}}\r\n{{^content.store}}\r\n<button class=\"btn btn-default btn-sm\" id=\"{{id}}_button\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/epsilon\/site\/{{\/isPublished}}gallery_gen\/epsilon\/epsilon.png\" alt=\"Epsilon\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n<\/button>\r\n{{\/content.store}}\r\n{{#isPublished}}\r\n<div id=\"{{id}}_vars\"\r\n\tdata-amount=\"{{content.amount}}\"\r\n\tdata-transactionid=\"{{#content.store}}{transactionId}{{\/content.store}}\"\r\n\tdata-callbackurl=\"{{#content.store}}{callbackUrl}{{\/content.store}}\"\r\n\tdata-returnurl=\"{{#content.store}}{returnUrl}{{\/content.store}}\"><\/div>\r\n{{{requireService}}}\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/epsilon/main.php';
PluginWrapper._config.active = false;
(function() {
	if (typeof window.epsilon_translations === 'undefined') {
		window.epsilon_translations = {
			'Card number': __c('Card number'),
			'Card expiration date': __c('Card expiration date'),
			'Card security code': __c('Card security code'),
			'Month': __c('Month'),
			'Year': __c('Year'),
			'loading...': __c('loading...'),
			'Close': __c('Close'),
			'Pay': __c('Pay'),
			'Error': __c('Error'),
			'Order Details': __c('Order Details'),
			'Product description': __c('Product description'),
			'Complete': __c('Complete'),
			"Field '%s' is required": __c("Field '%s' is required"),
			'An error occured during processing checkout.': __c('An error occured during processing checkout.'),
			'An error occured during card token creation.': __c('An error occured during card token creation.'),
			'Please try again later.': __c('Please try again later.'),
			'Contract code': __c('Contract code'),
			'Amount must be from %s to %s': __c('Amount must be from %s to %s'),
			'Click for more information': __c('Click for more information'),
			'Transaction code': __c('Transaction code'),
			'Payment has been submitted': __c('Payment has been submitted'),
			'Payment has been canceled': __c('Payment has been canceled'),
			'Are you sure you want to proceed?': __c('Are you sure you want to proceed?')
		};
	}
})();

ElementRegister.registerPaymentGateway({
	name: 'Epsilon',
	id: 'epsilon',
	pageUrl: 'https://www.epsilon.jp/',
	keyFieldId: 'contract_code',
	keyField2Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [12,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Contract code'), id: 'key'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key2', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	__t: window.epsilon_translations
});
PluginWrapper.registerPlugin('epsilon', {
	name: 'Epsilon',
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 120, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('Contract code')},
					{type: 'TextField', id: 'contract_code'}
				]},
				{type: 'HorizontalLayout', columnWeights: [9,3], columnWeightsSmall: [9,3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'description'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred') + ', JPY'},
						{type: 'TextField', id: 'amount'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'right'});
					}}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		fields.contract_code.setText(data.content.contract_code);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		data.content.contract_code = fields.contract_code.getText();
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		data.content.__t = window.epsilon_translations;
		if (!data.content.contract_code) data.content.contract_code = '';
		if (!data.content.description) data.content.description = '';
		if (!data.content.amount) data.content.amount = '1';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#fff';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#757575';
		if (!data.content.button_border) data.content.button_border = {
			color: '#757575',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #757575' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"linepay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/linepay\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n<img src=\"https:\/\/scdn.line-apps.com\/linepay\/partner\/images\/logo\/linepay_logo_119x39_v3.png\" \/>\r\n{{\/isPublished}}\r\n\r\n{{#content.store}}\r\n<form data-gateway-id=\"Linepay\" method=\"POST\" accept-charset=\"utf-8\">\r\n\t<input type=\"hidden\" name=\"accepturl\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"cancelurl\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"callbackurl\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"orderId\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"productName\" value=\"{{content.productName}}\" \/>\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"image\" src=\"https:\/\/scdn.line-apps.com\/linepay\/partner\/images\/logo\/linepay_logo_119x39_v3.png\"\/>\r\n<\/form>\r\n{{\/content.store}}\r\n\r\n{{^content.store}}\r\n{{{requireService}}}\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
    name: __('LINE Pay'),
    id: 'linepay',
    keyField: __('Channel ID'),
    keyFieldId: 'channelId',
    keyField2: __('Channel Secret Key'),
    keyField2Id: 'channelSecretKey',
    titleFieldId: 'label',
    nameFieldId: 'productName',
    priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['channelId', 'channelSecretKey']
});
PluginWrapper.registerPlugin('linepay', {
    name: 'LINE Pay',
    element: {
        minSize: {width: 130, height: 45},
        defaultSize: {width: 130, height: 45},
        resizable: false,
    },
    propertyDialog: {
        noScroll: true,
        tabs: [
            {children: [{type: 'VerticalLayout', spacing: 15, children: [
                            {type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Channel ID')},
                                            {type: 'TextField', id: 'channelId'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Channel Secret Key')},
                                            {type: 'TextField', id: 'channelSecretKey'}
                                        ]}
                                ]},
                            {type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Item Name'), helpText: __('Title of what you are paying for')},
                                            {type: 'TextField', id: 'productName'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Amount')},
                                            {type: 'TextField', id: 'amount'}
                                        ]},
                                    {type: 'VerticalLayout', children: [
                                            {type: 'Label', text: __('Currency')},
                                            {type: 'DropdownBox', id: 'currency', options: [
                                                    {id: '#USD', name: 'USD', value: 'USD'},
                                                    {id: '#JPY', name: 'JPY', value: 'JPY'},
                                                    {id: '#TWD', name: 'TWD', value: 'TWD'},
                                                    {id: '#THB', name: 'THB', value: 'THB'}
                                                ]}
                                        ]}
                                ]}
                        ]}
                ]}
        ]
    },
    resizeAction: function (data, elem) {
        if (!this.resizeTimeout) {
            var self = this;
            this.resizeTimeout = setTimeout(function () {
                self.resizeTimeout = null;
                self.updateElement();
            }, 1000);
        }
    },
    openAction: function (fields, data, elem) {
        fields.channelId.setText(data.content.channelId);
        fields.channelSecretKey.setText(data.content.channelSecretKey);
        fields.productName.setText(data.content.productName);
        fields.amount.setText(data.content.amount);

        var itm;
        itm = fields.currency.getItemById('#' + data.content.currency);
        fields.currency.selectItem(itm);
    },
    applyAction: function (fields, data, elem) {
        data.content.channelId = fields.channelId.getText();
        data.content.channelSecretKey = fields.channelSecretKey.getText();
        data.content.productName = fields.productName.getText();
        data.content.amount = fields.amount.getText();

        var itm;
        itm = fields.currency.getSelectedItem();
        data.content.currency = itm.getOriginal().value;

    },
    loadAction: function (data) {
        if (!data.content.channelId)
            data.content.channelId = '1509190620';
        if (!data.content.channelSecretKey)
            data.content.channelSecretKey = '148de1543696ebdb7658e47b1eff097f';
        if (!data.content.productName)
            data.content.productName = 'Title of what you are paying for';
        if (!data.content.amount)
            data.content.amount = '9.99';
        if (!data.content.currency)
            data.content.currency = 'JPY';
        data.serviceUrl = this.serviceUrl;

    }
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"instagram","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/instagram\/main.png";
PluginWrapper._config.template = "<style>\r\n#{{id}}_instafeed {\r\n\tlist-style:none;\r\n\tfloat: left;\r\n\tmargin-top: -10px;\r\n\tmargin-left: -50px;\r\n\tmargin-right: -10px;\r\n}\r\n#{{id}}_instafeed li {\r\n\tfloat: left;\r\n\twidth: {{content.imgSize}}px;\r\n\theight: {{content.imgSize}}px;\r\n\tmargin: {{content.imgMargin}}px;\r\n}\r\n.{{id}}_instagram_img {\r\n  width: 100%;\r\n  height: auto;\r\n}\r\n#{{id}}_preloader {\r\n\tfont-size: 28px;\r\n}\r\n#{{id}}_state {\r\n\tfont-size: 16px;\r\n}\r\n<\/style>\r\n<span id=\"{{id}}_preloader\" class=\"fa fa-pulse fa-spinner\"><\/span>\r\n<span id=\"{{id}}_state\"><\/span>\r\n<ul id=\"{{id}}_instafeed\"><\/ul>\r\n<script>\r\n\t{{#content.accessToken}}\r\n\t$.ajax({\r\n\t\turl: 'https:\/\/api.instagram.com\/v1\/users\/self\/media\/recent',\r\n\t\tdataType: 'jsonp',\r\n\t\ttype: 'GET',\r\n\t\tresolution: 'standard_resolution',\r\n\t\tdata: {access_token: '{{content.accessToken}}', count: {{content.images}}},\r\n\t\tsuccess: function(resp) {\r\n\t\t\t$('#{{id}}_preloader').hide();\r\n\t\t\tif (resp.meta && resp.meta.code == 200) {\r\n\t\t\t\tif (resp.data && resp.data.length) {\r\n\t\t\t\t\t$('#{{id}}_state').text('');\r\n\t\t\t\t\tfor (var i in resp.data) {\r\n\t\t\t\t\t\t$('#{{id}}_instafeed').append('<li><a href=\"' + resp.data[i].link + '\" target=\"_blank\"><img src=\"' + resp.data[i].images.standard_resolution.url + '\" class=\"{{id}}_instagram_img\"><\/a><\/li>');\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\t$('#{{id}}_state').text('No images found.');\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\t$('#{{id}}_state').text((resp.meta && resp.meta.code && resp.meta.error_message\r\n\t\t\t\t\t\t? 'Instagram Error (' + resp.meta.code + '): ' + resp.meta.error_message\r\n\t\t\t\t\t\t: 'Error retrieving images.'));\r\n\t\t\t}\r\n\t\t},\r\n\t\terror: function() {\r\n\r\n\t\t}\r\n\t});\r\n\t{{\/content.accessToken}}\r\n<\/script>\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('instagram', {
	name: 'Instagram',
	element: {
		minSize: {width: 140, height: 140},
		defaultSize: {width: 910, height: 600},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'Image', src: 'plugins/instagram/logo.png', id: 'logo', css: {width: 80, display: 'block', margin: '0 auto'}},
				{type: 'VerticalLayout', id: 'container', css: {marginTop: 10, textAlign: 'center'}, children: [
					{type: 'Button', text: __('Connect with Instagram'), id: 'loginButtonIG', enabled: true, css: {marginTop: 10}},
					/*{type: 'Button', text: __('Connect with Facebook'), id: 'loginButtonFB', visible: false, css: {marginTop: 10}},
					{type: 'CheckBox', label: __('I\'m using Instagram Business Account'), id: 'FBCheckBox', change: function(fields) {
							fields.loginButtonFB.setVisible(this.getValue());
							fields.loginButtonIG.setVisible(!this.getValue());
						}, css: {marginTop: 10}},*/
					{type: 'VerticalLayout', id: 'loggedInBlock', children: [
						{type: 'Label', id: 'loginState', css: {fontWeight: 'normal', marginTop: 5}},
						{type: 'Button', text: __('Sign Out'), id: 'logoutButton'}
					]}
				]},
				{type: 'CustomContainer', init: function(def, fields) {
					this._elem.append($('<div>').css({paddingTop: 30}).append(fields.logo._elem))
							.append(fields.container._elem);
				}}
			]},
			{name: __('Settings'), children: [
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Number of items to show')},
						{type: 'SizeSelector', id: 'images', max:20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Image Size')},
						{type: 'SizeSelector', id: 'imgSize', max:640, min:150}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Gallery padding (px)')},
						{type: 'SizeSelector', id: 'imgMargin', min:0}
					]}
				]}
			]}
		]
	},

	pluginScoped: {
		defaultIGAccessToken: '4270477368.65a7c60.0d7657e6b3f447e49058caf1b05d66c7',
		defaultFBAccessToken: '4270477368.8d84514.b5ddb07ee13f40cb89915731e81d0463',
		sessionData: null,

		getSessionData: function(callback, reset, fb) {
			var pl = 'instagram';
			if (fb) pl = 'fb';
			if (typeof(callback) !== 'function') return;
			if (reset) this.sessionData = null;
			if (!this.sessionData) {
				var thisSelf = this;
				$.get(wb_builder.baseUrl + pl + '/get-data', function(resp) {
					if (resp) {
						var obj = {};
						obj.access_token = resp.access_token ? resp.access_token : null;
						obj.access_token_name = (resp.user && resp.user.full_name) ? resp.user.full_name : null;
						obj.error = resp.error ? resp.error : null;
						thisSelf.sessionData = obj;
					}
					callback(thisSelf.sessionData);
				});
			} else {
				callback(this.sessionData);
			}
		},
		waitForAccessToken: function(succClb, errClb, fb) {
			var thisSelf = this;
			this.getSessionData(function(sessData) {
				if (!sessData) {
					setTimeout(function() { thisSelf.waitForAccessToken(succClb, errClb, fb); }, 1000);
				} else if (!sessData.access_token) {
					if (typeof(errClb) === 'function') errClb((sessData.error ? sessData.error : 'Could not retrieve access token'));
				} else {
					if (typeof(succClb) === 'function') succClb(sessData.access_token);
				}
			}, true, fb);
		},
		logout: function(callback, fb) {
			var pl = 'instagram';
			if (fb) pl = 'fb';
			var thisSelf = this;
			$.get(wb_builder.baseUrl + pl +'/logout', function(resp) {
				if (resp && resp.ok) {
					thisSelf.sessionData = null;
					if (typeof(callback) === 'function') callback();
				}	
			});
		}
	},
	openAction: function(fields, data, elem) {
		console.log("open " + data.content.accessToken);
		var thisSelf = this;
		//if (!fields.eventsIsSet) {
			fields.eventsIsSet = true;
			fields.loginButtonIG.on('click', function() {
				data.content.useFB = false;
				fields.loginButtonIG.setLoading(true);
				var w = 760, h = 800,
				left = parseInt((screen.availWidth - w) / 2),
				top = parseInt((screen.availHeight - h) / 2);
				thisSelf.pluginScoped.loginWindow = window.open(wb_builder.baseUrl + 'instagram', 'Instagram', 'width=' + w + ',height=' + h + ',left=' + left + ',top=' + top);

				// if the popup window will close by customer
				var timer = setInterval(function() {
					if(thisSelf.pluginScoped.loginWindow.closed) {
						clearInterval(timer);
						fields.loginButtonIG.setLoading(false);
						// $.get(wb_builder.baseUrl + 'instagram/reset-popup', function(resp) {
						// 	if (resp && resp.ok) {
						// 		thisSelf.sessionData = null;
						// 	}
						// });
					}
				}, 1000);

				thisSelf.pluginScoped.waitForAccessToken(function(token) {
					fields.loginButtonIG.setLoading(false);
					data.content.accessToken = token;
					thisSelf.updateLoginBlock(fields, data);
				}, function(error) {
					fields.loginButtonIG.setLoading(false);
					var thisSelf = this;
					$.get(wb_builder.baseUrl + 'instagram/reset-popup', function(resp) {
						if (resp && resp.ok) {
							thisSelf.sessionData = null;
						}
					});
				}, data.content.useFB);
			});
			/*fields.loginButtonFB.on('click', function() {
				data.content.useFB = true;
				fields.loginButtonFB.setLoading(true);
				var w = 600, h = 600,
					left = parseInt((screen.availWidth - w) / 2),
					top = parseInt((screen.availHeight - h) / 2);
				thisSelf.pluginScoped.loginWindow = window.open(wb_builder.baseUrl + 'fb', 'Facebook Login', 'width=' + w + ',height=' + h + ',left=' + left + ',top=' + top);

				// if the popup window will close by customer
				var timer = setInterval(function() {
					if(thisSelf.pluginScoped.loginWindow.closed) {
						clearInterval(timer);
						fields.loginButtonFB.setLoading(false);
						// $.get(wb_builder.baseUrl + 'fb/reset-popup', function(resp) {
						// 	if (resp && resp.ok) {
						// 		thisSelf.sessionData = null;
						// 	}
						// });
					}
				}, 1000);

				thisSelf.pluginScoped.waitForAccessToken(function(token) {
					fields.loginButtonFB.setLoading(false);
					data.content.accessToken = token;
					thisSelf.updateLoginBlock(fields, data);
				}, function(error) {
					fields.loginButtonFB.setLoading(false);
					alert(error);
				}, data.content.useFB);
			});*/
			fields.logoutButton.on('click', function() {
				fields.logoutButton.setLoading(true);
				thisSelf.pluginScoped.logout(function() {
					fields.logoutButton.setLoading(false);
					data.content.accessToken = null;
					thisSelf.updateLoginBlock(fields, data);
				}, data.content.useFB);
			});
		//}
		this.updateLoginBlock(fields, data);
		fields.images.setValue(data.content.images);
		fields.imgSize.setValue(data.content.imgSize);
		fields.imgMargin.setValue(data.content.imgMargin);
	},
	updateLoginBlock: function(fields, data) {
		this.pluginScoped.getSessionData(function(sessData) {
			if (sessData && sessData.access_token) {
				console.log("update " + sessData.access_token);
				fields.loginButtonIG.setVisible(false);
				//fields.loginButtonFB.setVisible(false);
				//fields.FBCheckBox.setVisible(false);
				if (data.content.useFB) fields.loginState.setHtml('<b>Logged in</b>');
					else fields.loginState.setHtml('Logged in as <strong>' + sessData.access_token_name + '</strong>');

				fields.loggedInBlock.setVisible(true);
			} else {
				fields.loggedInBlock.setVisible(false);
				fields.loginButtonIG.setVisible(true);
				//fields.loginButtonIG.setVisible(!fields.FBCheckBox.getValue());
				//fields.loginButtonFB.setVisible(fields.FBCheckBox.getValue());
				//fields.FBCheckBox.setVisible(true);
			}
		});
	},
	applyAction: function(fields, data, elem) {
		console.log("apply " + data.content.accessToken);
		data.content.images = Math.max(Math.min(fields.images.getValue(), 20), 0);
		data.content.imgSize = Math.max(Math.min(fields.imgSize.getValue(), 640), 150);
		data.content.imgMargin = fields.imgMargin.getValue();
	},
	loadAction: function (data) {
		console.log("load " + data.content.accessToken);
		if (!data.content.images) data.content.images = '6';
		if (!data.content.imgSize) data.content.imgSize = '290';
		if (!data.content.imgMargin) data.content.imgMargin = '10';
		if (!data.content.useFB) data.content.useFB = false;
	},
	loadedAction: function(data, elem) {
		console.log("loaded " + data.content.accessToken);
		var thisSelf = this;
		if (!data.content.accessToken) {
			this.pluginScoped.getSessionData(function(sessData) {
				if (sessData && sessData.access_token) {
					data.content.accessToken = sessData.access_token;
				} else {
					if (!data.content.useFB) data.content.accessToken = thisSelf.pluginScoped.defaultIGAccessToken;
					else data.content.accessToken = thisSelf.pluginScoped.defaultFBAccessToken;
				}
				thisSelf.updateElement();
			}, false, data.content.useFB);
		}
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"paytrail","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/paytrail\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Paytrail\" action=\"https:\/\/payment.paytrail.com\/e2\" method=\"post\" style=\"width: 100%; height: 100%;\">\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"MERCHANT_ID\" value=\"{{content.merchantId}}\" \/>\r\n\t<input type=\"hidden\" name=\"CURRENCY\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"hidden\" name=\"URL_SUCCESS\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"URL_CANCEL\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"ORDER_NUMBER\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"AMOUNT\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"PARAMS_OUT\" value=\"ORDER_NUMBER,PAYMENT_ID,AMOUNT,CURRENCY,PAYMENT_METHOD,TIMESTAMP,STATUS\" \/>\r\n\t<input type=\"hidden\" name=\"ALG\" value=\"1\" \/>\r\n\t<input type=\"hidden\" name=\"URL_NOTIFY\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"ITEM_TITLE[0]\" value=\"{{content.name}}\" \/>\r\n\t<input type=\"hidden\" name=\"ITEM_QUANTITY[0]\" value=\"1\" \/>\r\n\t<input type=\"hidden\" name=\"ITEM_VAT_PERCENT[0]\" value=\"0.00\" \/>\r\n\t<input type=\"hidden\" name=\"ITEM_UNIT_PRICE[0]\" value=\"{{content.amount}}\" \/>\r\n\t<button style=\"background: none; border: none; vertical-align: middle; width: 47px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/paytrail\/paytrail.png\" alt=\"Paytrail\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/paytrail\/site\/{{\/isPublished}}gallery_gen\/paytrail\/paytrail.png\" alt=\"Paytrail\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/paytrail/main.php';
PluginWrapper._config.active = false;

ElementRegister.registerPaymentGateway({
	name: 'Paytrail',
	id: 'paytrail',
	pageUrl: 'https://www.paytrail.com/',
	keyField: __('Merchant ID'),
	keyFieldId: 'merchantId',
	keyField2: __('Secret Key'),
	keyField2Id: 'secretKey',
	titleFieldId: 'label',
	nameFieldId: 'name',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['merchantId', 'secretKey']
});
PluginWrapper.registerPlugin('paytrail', {
	name: 'Paytrail',
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 160, height: 60}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', children: [
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Merchant ID')},
						{type: 'TextField', id: 'merchantId'}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Secret Key')},
						{type: 'TextField', id: 'secretKey'}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [9,3], columnWeightsSmall: [9,3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description')},
						{type: 'TextField', id: 'name'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred') + ', EUR'},
						{type: 'TextField', id: 'amount'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Rounded corners')},
					{type: 'RoundCornersSelector', id: 'border_radius'}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		fields.merchantId.setText(data.content.merchantId);
		fields.secretKey.setText(data.content.secretKey);
		fields.amount.setValue(data.content.amount);
		fields.name.setText(data.content.name);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
		fields.border_radius.setValue(data.content.border_radius);
	},
	applyAction: function (fields, data, elem) {
		data.content.merchantId = fields.merchantId.getText();
		data.content.secretKey = fields.secretKey.getText();
		data.content.amount = fields.amount.getValue();
		data.content.name = fields.name.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.border_radius = fields.border_radius.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		var borderRadiusCss = '';
		var borderRadius = data.content.border_radius;
		if (borderRadius && borderRadius.css !== undefined) {
			for (var selector in borderRadius.css) {
				borderRadiusCss += selector + ': ' + borderRadius.css[selector] + ';';
			}
		}
		return borderCss + borderRadiusCss;
	},
	loadAction: function (data) {
		data.content.__globalVars = ['merchantId', 'secretKey'];
		if (!data.content.merchantId) data.content.merchantId = '';
		if (!data.content.secretKey) data.content.secretKey = '';
		if (!data.content.amount) data.content.amount = '1';
		if (!data.content.currency) data.content.currency = 'EUR';
		if (!data.content.name) data.content.name = '';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#e60094';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '14';
		if (!data.content.label_color) data.content.label_color = '#ffffff';
		if (!data.content.button_border) data.content.button_border = {
			color: '#eeeeee',
			style: 'none',
			weight: 1,
			css: { border: '1px none #eeeeee' }
		};
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 48;
		if (!data.content.border_radius) data.content.border_radius = {
			lt: 0, rt: 0, rb: 0, lb: 0,
			css: { 
				"border-radius"			: "0",
				"-webkit-border-radius"	: "0", 
				"-moz-border-radius"	: "0"
			}
		};
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"platron","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/platron\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Platron\" method=\"post\" action=\"https:\/\/www.platron.ru\/payment.php\"{{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"pg_merchant_id\" value=\"{{content.merchant_id}}\" \/>\r\n\t<input type=\"hidden\" name=\"pg_amount\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"pg_description\" value=\"{{content.description}}\" \/>\r\n\t<input type=\"hidden\" name=\"pg_currency\" value=\"{{content.currency}}\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"pg_result_url\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"pg_success_url\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"pg_success_url_method\" value=\"POST\" \/>\r\n\t<input type=\"hidden\" name=\"pg_failure_url\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"pg_failure_url_method\" value=\"POST\" \/>\r\n\t<input type=\"hidden\" name=\"pg_order_id\" value=\"{transactionId}\" \/>\r\n\t<input type=\"submit\" class=\"hidden\" \/>\r\n\t<button type=\"submit\" style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\" onclick=\"{{id}}_showModal()\">\r\n\t\t<img src=\"gallery_gen\/platron\/platron.svg\" alt=\"Platron\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t<button type=\"submit\" class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/platron\/site\/{{\/isPublished}}gallery_gen\/platron\/platron.svg\" alt=\"Platron\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;

(function() {
	var dlg = null;
	window._platron_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="https://front.platron.ru/" target="_blank">https://front.platron.ru/</a></p>'
					+ '<p><strong>Result URL:</strong><br />'
					+ '<pre>' + base_url + 'store-callback/Platron' + '</pre></p>'
					+ '<p><strong>Success URL:</strong><br />'
					+ '<pre>' + base_url + 'store-return/Platron' + '</pre></p>'
					+ '<p><strong>Failure URL:</strong><br />'
					+ '<pre>' + base_url + 'store-cancel/Platron' + '</pre></p>';
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
	if (typeof window.platron_translations === 'undefined') {
		window.platron_translations = {
			'first_name': __c('First Name'),
			'last_name': __c('Last Name'),
			'email': __c('E-mail'),
			'address': __c('Address'),
			'phone': __c('Phone'),
			'close': __c('Close'),
			'pay': __c('Pay')
		};
	}
})();

ElementRegister.registerPaymentGateway({
	name: 'Platron',
	id: 'platron',
	keyFieldId: 'merchant_id',
	keyField2Id: 'secret_key',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [6,6,12], children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Secret Key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['merchant_id', 'secret_key', 'demo'],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window._platron_settings_dialog().setVisible(true); });
		return btn;
	},
	__t: window.platron_translations
});
PluginWrapper.registerPlugin('platron', {
	name: 'Platron',
	element: {
		minSize: {width: 60, height: 20},
		defaultSize: {width: 160, height: 30},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Merchant ID')},
							{type: 'TextField', id: 'merchant_id'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Secret Key')},
							{type: 'TextField', id: 'secret_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'description'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount')},
							{type: 'TextField', id: 'amount'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: '#RUB', name: 'RUB', value: 'RUB'},
								{id: '#USD', name: 'USD', value: 'USD'},
								{id: '#EUR', name: 'EUR', value: 'EUR'}
							]}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'Label', text: __('Button Label')},
						{type: 'TextField', id: 'button_label'}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Border')},
							{type: 'BorderSelector', id: 'button_border'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Background')},
							{type: 'ColorSelector', id: 'button_color'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Size')},
							{type: 'SizeSelector', id: 'font_size'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Color')},
							{type: 'ColorSelector', id: 'label_color', noTransparent: true}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', css: {width: 120}, children: [
							{type: 'Label', text: __('Font')},
							{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Max logo width')},
							{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Show logo')},
							{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
							{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
						]}
					]},
					{type: 'VerticalLayout', css: {marginTop: 15}, children: [
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'right'});
						}}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.merchant_id.setText(data.content.merchant_id);
		fields.secret_key.setText(data.content.secret_key);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.merchant_id = fields.merchant_id.getText();
		data.content.secret_key = fields.secret_key.getText();
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.currency) data.content.currency = 'RUB';
		if (!data.content.merchant_id) data.content.merchant_id = '';
		if (!data.content.secret_key) data.content.secret_key = '';
		if (!data.content.amount) data.content.amount = '1';
		if (!data.content.description) data.content.description = '';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = 'transparent';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#555';
		if (!data.content.button_border) data.content.button_border = {
			color: '#000',
			style: 'none',
			weight: 1,
			css: { border: '1px none #000' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 80;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"redsys","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/redsys\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n<button class=\"btn btn-default btn-sm\" type=\"submit\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t{{#content.showlogo}}<img src=\"plugins\/redsys\/site\/gallery_gen\/redsys\/redsys.png\" alt=\"Redsys\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n<\/button>\r\n{{\/isPublished}}\r\n{{#isPublished}}\r\n\t{{#content.store}}\r\n\t\t<form action=\"\" data-gateway-id=\"Redsys\" method=\"post\">\r\n\t\t\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" data-multiplier=\"100\" data-fixed-decimal=\"0\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"description\" value=\"{{content.description}}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"transactionId\" value=\"{transactionId}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"callbackUrl\" value=\"{callbackUrl}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"returnUrl\" value=\"{returnUrl}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"cancelUrl\" value=\"{cancelUrl}\" \/>\r\n\t\t\t<button style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t\t\t<img src=\"gallery_gen\/redsys\/redsys.png\" alt=\"Redsys\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t\t\t<\/button>\r\n\t\t<\/form>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/redsys/main.php';
PluginWrapper._config.active = false;

ElementRegister.registerPaymentGateway({
	name: 'Redsys',
	id: 'redsys',
	pageUrl: 'http://www.redsys.es/',
	keyFieldId: 'name',
	keyField2Id: 'terminal',
	keyField3Id: 'merchantCode',
	keyField4Id: 'merchantPassword',
	keyField5Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [9,3,6,6,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Name'), id: 'key'},
		{type: 'TextField', placeholder: __('Terminal'), id: 'key2'},
		{type: 'TextField', placeholder: __('Merchant Code'), id: 'key3', css: {marginTop: 5}},
		{type: 'TextField', placeholder: __('Merchant Password'), id: 'key4', css: {marginTop: 5}},
		{type: 'CheckBox', label: __('Test mode'), id: 'key5', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	__t: window.assist_translations,
	globalVars: ['name', 'merchantCode', 'terminal', 'merchantPassword', 'demo']
});
PluginWrapper.registerPlugin('redsys', {
	name: 'Redsys',
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 120, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', spacing: 15, columnWeights: [9,3], columnWeightsSmall: [9,3], children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Name')},
						{type: 'TextField', id: 'name'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Terminal')},
						{type: 'TextField', id: 'terminal'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant Code')},
						{type: 'TextField', id: 'merchantCode'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant Password')},
						{type: 'TextField', id: 'merchantPassword'}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [6,3,3], columnWeightsSmall: [6,3,3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'description'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred')},
						{type: 'TextField', id: 'amount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'currency', options: [
							{id: '840', name: 'USD'},
							{id: '978', name: 'EUR'},
							{id: '826', name: 'GBP'},
							{id: '032', name: 'ARS'},
							{id: '986', name: 'BRL'},
							{id: '124', name: 'CAD'},
							{id: '756', name: 'CHF'},
							{id: '152', name: 'CLP'},
							{id: '392', name: 'CNY'},
							{id: '170', name: 'COP'},
							{id: '356', name: 'INR'},
							{id: '484', name: 'MXN'},
							{id: '604', name: 'PEN'},
							{id: '949', name: 'TRY'},
							{id: '937', name: 'VEF'}
						]}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'right'});
					}}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		var itm;
		fields.name.setText(data.content.name);
		fields.terminal.setText(data.content.terminal);
		fields.merchantCode.setText(data.content.merchantCode);
		fields.merchantPassword.setText(data.content.merchantPassword);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		itm = fields.currency.getItemById(data.content.currency);
		fields.currency.selectItem(itm);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		data.content.name = fields.name.getText();
		data.content.terminal = fields.terminal.getText();
		data.content.merchantCode = fields.merchantCode.getText();
		data.content.merchantPassword = fields.merchantPassword.getText();
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().id;
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		data.content.__t = window.assist_translations;
		if (!data.content.name) data.content.name = '';
		if (!data.content.terminal) data.content.terminal = '';
		if (!data.content.merchantCode) data.content.merchantCode = '';
		if (!data.content.merchantPassword) data.content.merchantPassword = '';
		if (!data.content.description) data.content.description = '';
		if (!data.content.amount) data.content.amount = '1';
		if (!data.content.currency) data.content.currency = '840';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#fff';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#757575';
		if (!data.content.button_border) data.content.button_border = {
			color: '#757575',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #757575' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"click","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/click\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Click\" action=\"https:\/\/my.click.uz\/pay\/\" method=\"post\"{{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"MERCHANT_ID\" value=\"{{content.merchantId}}\" \/>\r\n\t<input type=\"hidden\" name=\"MERCHANT_SERVICE_ID\" value=\"{{content.merchantServiceId}}\" \/>\r\n\t<input type=\"hidden\" name=\"MERCHANT_TRANS_AMOUNT\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"MERCHANT_TRANS_NOTE\" value=\"{{content.description}}\" \/>\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<input type=\"hidden\" name=\"MERCHANT_TRANS_ID\" value=\"{transactionId}\" \/>\r\n\t{{#content.store}}\r\n\t<button style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/click\/click.png\" alt=\"Click\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<button class=\"btn btn-default btn-sm\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/click\/site\/{{\/isPublished}}gallery_gen\/click\/click.png\" alt=\"Click\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/click/main.php';
PluginWrapper._config.active = false;

ElementRegister.registerPaymentGateway({
	name: 'Click',
	id: 'click',
	keyFieldId: 'merchantId',
	keyField2Id: 'merchantServiceId',
	keyField3Id: 'secretKey',
//	keyField4Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [6,6,12/* ,12 */], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Merchant Service ID'), id: 'key2'},
		{type: 'TextField', placeholder: __('Secret Key'), id: 'key3', css: {marginTop: 5}}/* ,
		{type: 'CheckBox', label: __('Test mode'), id: 'key4', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}} */
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	globalVars: ['merchantId', 'merchantServiceId', 'secretKey'/* , 'demo' */],
	helpText: function() {
		var btn = $('<span class="badge wb_badge_help" style="cursor: pointer;">?</span>');
		btn.on('click', function() { window.click_settings_dialog().setVisible(true); });
		return btn;
	}
});

(function() {
	var dlg = null;
	window.click_settings_dialog = function() {
		if (!dlg) {
			var base_url = 'http://' + wb_builder.siteDomain + '/';
			var html = '<p><strong>Page URL:</strong> <a href="http://click.uz/" target="_blank">http://click.uz/</a></p>'
					+ '<p><strong>Prepare URL:</strong><br />'
					+ '<pre>' + base_url + 'store-verify/Click' + '</pre></p>'
					+ '<p><strong>Complete URL:</strong><br />'
					+ '<pre>' + base_url + 'store-callback/Click' + '</pre></p>';
			
			dlg = new WB_Dialog(__('Settings'));
			dlg.setContent(html);
			dlg.removeAllButtons();
			dlg.addButton(__('Close'), function() {
				dlg.setVisible(false);
			}, false, 'btn-default');
		}
		return dlg;
	};
})();

PluginWrapper.registerPlugin('click', {
	name: 'Click',
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 160, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', spacing: 15, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant ID')},
						{type: 'TextField', id: 'merchantId'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant Service ID')},
						{type: 'TextField', id: 'merchantServiceId'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Secret Key')},
						{type: 'TextField', id: 'secretKey'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'description'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred') + ', UZS'},
						{type: 'TextField', id: 'amount'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', spacing: 15, css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					/*{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Mode'), init: function() {
							var link = $('<a>').attr('href', 'javascript:void(0)').text(__('Settings'));
							link.on('click', function() {
								window.click_settings_dialog().setVisible(true);
							});
							var cont = $('<span>').css({fontWeight: 'normal', marginLeft: '4px'});
							cont.append('(');
							cont.append(link);
							cont.append(')');
							this._elem.append(cont);
						}},
						{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
							this.getElem().attr('title', __('For testing purpose without real payments'));
							this.getElem().tooltip({placement: 'right'});
						}}
					]},*/
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'CustomContainer', css: {marginTop: 15}, init: function() {
					this.getElem().append('(')
							.append($('<a>').text(__('Settings'))
								.attr('href', 'javascript:void(0)')
								.on('click', function() { window.click_settings_dialog().setVisible(true); }))
							.append(')');
				}}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		fields.merchantId.setText(data.content.merchantId);
		fields.merchantServiceId.setText(data.content.merchantServiceId);
		fields.secretKey.setText(data.content.secretKey);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_border.setValue(data.content.button_border);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
//		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		data.content.merchantId = fields.merchantId.getText();
		data.content.merchantServiceId = fields.merchantServiceId.getText();
		data.content.secretKey = fields.secretKey.getText();
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_border = fields.button_border.getValue();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
//		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		data.content.__t = window.assist_translations;
		if (!data.content.merchantId) data.content.merchantId = '';
		if (!data.content.merchantServiceId) data.content.merchantServiceId = '';
		if (!data.content.secretKey) data.content.secretKey = '';
		if (!data.content.description) data.content.description = '';
		if (!data.content.amount) data.content.amount = '1';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_border) data.content.button_border = {
			color: '#ddd',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #ddd' }
		};
		if (!data.content.button_color) data.content.button_color = '#fff';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '14';
		if (!data.content.label_color) data.content.label_color = '#333333';
//		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 75;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"skrill","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/skrill\/main.png";
PluginWrapper._config.template = "<form action=\"{{#content.demo}}https:\/\/www.skrill.com\/app\/test_payment.pl{{\/content.demo}}{{^content.demo}}https:\/\/pay.skrill.com{{\/content.demo}}\" method=\"post\" data-gateway-id=\"Skrill\" {{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"pay_to_email\" value=\"{{content.email}}\"\/>\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\"\/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\"\/>\r\n\t<input type=\"hidden\" name=\"detail1_description\" value=\"{{content.description}}\"\/>\r\n\t<input type=\"hidden\" name=\"detail1_text\" value=\"{{content.text}}\"\/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"status_url\" value=\"{callbackUrl}\"\/>\r\n\t<input type=\"hidden\" name=\"return_url\" value=\"{returnUrl}\"\/>\r\n\t<input type=\"hidden\" name=\"cancel_url\" value=\"{cancelUrl}\"\/>\r\n\t<input type=\"hidden\" name=\"transaction_id\" value=\"{transactionId}\"\/>\r\n\t<input type=\"submit\" class=\"buton\" value=\"{{content.ht_title}}\" title=\"{{content.ht_title}}\"\r\n\t\t   style=\"height: 40px;\r\n\t\t          border: 2px solid #fff;\r\n\t\t          background: #811e68;\r\n\t\t          padding: 6px 18px;\r\n\t\t\t\t  color: #fff;\r\n\t\t\t\t  font-size: 15px;\r\n\t\t\t\t  font-family: Trebuchet MS,sans-serif;\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<input type=\"submit\" class=\"buton\" value=\"{{content.ht_title}}\" title=\"{{content.ht_title}}\"\r\n\t\t   style=\"width: 100%; height: 100%;\r\n\t\t          border: {{content.border.css.border}};\r\n\t\t          background: {{content.background}};\r\n\t\t          padding: 6px 10px;\r\n\t\t\t\t  color: {{content.fontColor}};\r\n\t\t\t\t  font-size: {{content.fontSize}}px;\r\n\t\t\t\t  font-family: {{content.fontFamily}};\" \/>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/skrill/main.php';
PluginWrapper._config.active = true;
ElementRegister.registerPaymentGateway({
	name: 'Skrill',
	id: 'skrill',
	pageUrl: 'https://www.skrill.com/',
	keyFieldId: 'email',
	keyField2Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [12,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Email'), id: 'key'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key2', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'ht_title',
	nameFieldId: 'text,description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['email', 'demo']
});
PluginWrapper.registerPlugin('skrill', {
	name: 'Skrill',
	element: {
		minSize: {width: 100, height: 30},
		defaultSize: {width: 160, height: 40}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Email'), helpText: __('The email address of your Skrill')},
						{type: 'TextField', id: 'email'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Button Label'), helpText: __('Label name on submit button')},
						{type: 'TextField', id: 'ht_title'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
					{type: 'TextField', id: 'description'}
				]},
				{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Detailed text')},
						{type: 'TextField', id: 'text'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred')},
						{type: 'TextField', id: 'amount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'currency', options: [
							{id: '#USD', name: 'USD', value: 'USD'},
							{id: '#EUR', name: 'EUR', value: 'EUR'},
							{id: '#GBP', name: 'GBP', value: 'GBP'},
							{id: '#AED', name: 'AED', value: 'AED'},
							{id: '#AUD', name: 'AUD', value: 'AUD'},
							{id: '#BGN', name: 'BGN', value: 'BGN'},
							{id: '#CAD', name: 'CAD', value: 'CAD'},
							{id: '#CHF', name: 'CHF', value: 'CHF'},
							{id: '#CZK', name: 'CZK', value: 'CZK'},
							{id: '#DKK', name: 'DKK', value: 'DKK'},
							{id: '#HKD', name: 'HKD', value: 'HKD'},
							{id: '#HRK', name: 'HRK', value: 'HRK'},
							{id: '#HUF', name: 'HUF', value: 'HUF'},
							{id: '#ILS', name: 'ILS', value: 'ILS'},
							{id: '#INR', name: 'INR', value: 'INR'},
							{id: '#ISK', name: 'ISK', value: 'ISK'},
							{id: '#JOD', name: 'JOD', value: 'JOD'},
							{id: '#JPY', name: 'JPY', value: 'JPY'},
							{id: '#KRW', name: 'KRW', value: 'KRW'},
							{id: '#MAD', name: 'MAD', value: 'MAD'},
							{id: '#MYR', name: 'MYR', value: 'MYR'},
							{id: '#NOK', name: 'NOK', value: 'NOK'},
							{id: '#NZD', name: 'NZD', value: 'NZD'},
							{id: '#OMR', name: 'OMR', value: 'OMR'},
							{id: '#PLN', name: 'PLN', value: 'PLN'},
							{id: '#QAR', name: 'QAR', value: 'QAR'},
							{id: '#RON', name: 'RON', value: 'RON'},
							{id: '#RSD', name: 'RSD', value: 'RSD'},
							{id: '#SAR', name: 'SAR', value: 'SAR'},
							{id: '#SEK', name: 'SEK', value: 'SEK'},
							{id: '#SGD', name: 'SGD', value: 'SGD'},
							{id: '#SKK', name: 'SKK', value: 'SKK'},
							{id: '#THB', name: 'THB', value: 'THB'},
							{id: '#TND', name: 'TND', value: 'TND'},
							{id: '#TRY', name: 'TRY', value: 'TRY'},
							{id: '#TWD', name: 'TWD', value: 'TWD'},
							{id: '#ZAR', name: 'ZAR', value: 'ZAR'}
						]}
					]}
				]},
				{type: 'FlowLayout', spacing: 15, css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'background'}
					]},
					{type: 'VerticalLayout', css: {width: 150}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'fontFamily', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'fontSize'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'fontColor', noTransparent: true}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'right'});
					}}
				]}
			]}
		]
	},
	resizeAction: function(data, elem) {
		elem.find('.buton').eq(0).css({width: data.width, height: data.height});
	},
	openAction: function(fields, data, elem) {
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.amount.setText(data.content.amount);
		fields.ht_title.setText(data.content.ht_title);
		fields.description.setText(data.content.description);
		fields.text.setText(data.content.text);
		fields.email.setText(data.content.email);
		fields.border.setValue(data.content.border);
		fields.background.setValue(data.content.background);
		fields.fontFamily.setValue(data.content.fontFamily);
		fields.fontSize.setValue(data.content.fontSize);
		fields.fontColor.setValue(data.content.fontColor);
		fields.demo.setValue(data.content.demo);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.amount = fields.amount.getText();
		data.content.ht_title = fields.ht_title.getText();
		data.content.description = fields.description.getText();
		data.content.text = fields.text.getText();
		data.content.email = fields.email.getText();
		data.content.border = fields.border.getValue();
		data.content.background = fields.background.getValue();
		data.content.fontFamily = fields.fontFamily.getValue();
		data.content.fontSize = fields.fontSize.getValue();
		data.content.fontColor = fields.fontColor.getValue();
		data.content.demo = fields.demo.getValue();
	},
	loadAction: function(data) {
		if (!data.content.amount) data.content.amount = '9.99';
		if (!data.content.ht_title) data.content.ht_title = __('Pay %s via Skrill').replace('%s', data.content.amount + ' €');
		if (!data.content.currency) data.content.currency = 'EUR';
		if (!data.content.text) data.content.text = __('Skrill payment text');
		if (!data.content.description) data.content.description = __('Product description');
		if (!data.content.email) data.content.email = '';
		if (!data.content.border) data.content.border = {
			color: '#fff',
			style: 'solid',
			weight: 2,
			css: { border: '2px solid #fff'}
		};
		if (!data.content.background) data.content.background = '#811E68';
		if (!data.content.fontFamily) data.content.fontFamily = 'Trebuchet MS,sans-serif';
		if (!data.content.fontSize) data.content.fontSize = '15';
		if (!data.content.fontColor) data.content.fontColor = '#fff';
		if (data.content.demo === undefined) data.content.demo = false;
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"liqpay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/liqpay\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Liqpay\" method=\"POST\" action=\"https:\/\/www.liqpay.com\/api\/3\/checkout\"{{^content.store}} target=\"_blank\"{{\/content.store}} accept-charset=\"utf-8\" style=\"width: 100%; height: 100%;\">\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"version\" value=\"3\" \/>\r\n\t<input type=\"hidden\" name=\"action\" value=\"pay\" \/>\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t<input type=\"hidden\" name=\"description\" value=\"{{content.description}}\" \/>\r\n\t<input type=\"hidden\" name=\"order_id\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"result_url\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"server_url\" value=\"{callbackUrl}\" \/>\r\n\t<button style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/liqpay\/liqpay-2.png\" alt=\"Liqpay\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^isPublished}}\r\n\t<button class=\"btn btn-default btn-sm\" type=\"submit\" style=\"width: 100%; height: 100%; white-space: normal; overflow: hidden;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/liqpay\/site\/{{\/isPublished}}gallery_gen\/liqpay\/{{content.logo}}\" alt=\"Liqpay\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/isPublished}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/liqpay/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'LiqPay',
	id: 'liqpay',
	pageUrl: 'https://www.liqpay.ua/',
	keyFieldId: 'public_key',
	keyField2Id: 'private_key',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [6,6,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Public Key'), id: 'key'},
		{type: 'TextField', placeholder: __('Private Key'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['public_key', 'private_key', 'demo']
});
PluginWrapper.registerPlugin('liqpay', {
	name: 'LiqPay',
	element: {
		minSize: {width: 50, height: 20},
		defaultSize: {width: 150, height: 70}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', columnWeights: [6, 6], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Public Key'), helpText: __('This key you can get in LiqPay account on shop settings page')},
							{type: 'TextField', id: 'public_key'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Private Key'), helpText: __('This key you can get in LiqPay account on shop settings page')},
							{type: 'TextField', id: 'private_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'description'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount')},
							{type: 'TextField', id: 'amount'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: '#USD', name: 'USD', value: 'USD'},
								{id: '#EUR', name: 'EUR', value: 'EUR'},
								{id: '#RUB', name: 'RUB', value: 'RUB'},
								{id: '#UAH', name: 'UAH', value: 'UAH'},
								{id: '#BYN', name: 'BYN', value: 'BYN'},
								{id: '#KZT', name: 'KZT', value: 'KZT'}
							]}
						]}
					]},
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Logo')},
						{type: 'DropdownBox', id: 'logo', options: [
							{id: 'liqpay-1.png', name: 'liqpay-1'},
							{id: 'liqpay-2.png', name: 'liqpay-2'}
						]}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'right'});
					}}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		fields.public_key.setText(data.content.public_key);
		fields.private_key.setText(data.content.private_key);
		
		itm = fields.logo.getItemById(data.content.logo);
		fields.logo.selectItem(itm);
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		data.content.public_key = fields.public_key.getText();
		data.content.private_key = fields.private_key.getText();
		
		itm = fields.logo.getSelectedItem();
		data.content.logo = itm.getOriginal().id;
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function(data) {
		if (!data.content.description)
			data.content.description = ''; // Items description
		if (!data.content.amount)
			data.content.amount = '1'; // 129.99
		if (!data.content.currency)
			data.content.currency = 'RUB';
		if (!data.content.public_key)
			data.content.public_key = ''; // 12345
		if (!data.content.private_key)
			data.content.private_key = ''; // 54321
		data.content.langCode = this._getBuilderLanguage();
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#fff';
		if (!data.content.font_family) data.content.font_family = "'Roboto Condensed',Arial,sans-serif";
		if (!data.content.font_size) data.content.font_size = '14';
		if (!data.content.label_color) data.content.label_color = '#333333';
		if (!data.content.button_border) data.content.button_border = {
			color: '#cccccc',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #cccccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 130;
		if (!data.content.logo) data.content.logo = 'liqpay-1.png';
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	_getBuilderLanguage: function() {
		var lang;
		return (lang = wb_builder.getLanguageByLocale(wb_builder.locale)) ? lang.code : 'en';
	},
	switchLanguageAction: function(data, elem, langCode) {
		data.content.langCode = ((langCode === 'ru') ? 'ru' : 'en');
		this.updateElement();
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"bing_maps","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/bing_maps\/main.png";
PluginWrapper._config.template = "<div id=\"{{id}}_myMap\" class=\"bingmap\" style=\"position:relative; min-width:200px; height:100%;\"><\/div>\r\n{{#isPublished}}\r\n\t{{#firstOnPage}}\r\n<script type=\"text\/javascript\" src=\"https:\/\/ecn.dev.virtualearth.net\/mapcontrol\/mapcontrol.ashx?v=7.0\"><\/script>\r\n\t{{\/firstOnPage}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\tvar getMap_{{id}} = function() {\r\n\t\t\tMicrosoft.Maps.loadModule('Microsoft.Maps.Themes.BingTheme', { callback: function() {\r\n\t\t\t\tmap_{{id}} = new Microsoft.Maps.Map(document.getElementById('{{id}}_myMap'), { \r\n\t\t\t\t\tcredentials: '{{#isPreview}}{{content.previewKey}}{{\/isPreview}}{{^isPreview}}{{content.apiKey}}{{\/isPreview}}', \r\n\t\t\t\t\tmapTypeId: Microsoft.Maps.MapTypeId.road,\r\n\t\t\t\t\ttheme: new Microsoft.Maps.Themes.BingTheme(),\r\n\t\t\t\t\tzoom: {{content.zoomLevel}},\r\n\t\t\t\t\tcenter: new Microsoft.Maps.Location(Number(\"{{content.loc1}}\").valueOf(), Number(\"{{content.loc2}}\").valueOf())\r\n\t\t\t\t});\r\n\t\t\t\tvar pushpin= new Microsoft.Maps.Pushpin(map_{{id}}.getCenter(), null); \r\n\t\t\t\tpushpin.setLocation(new Microsoft.Maps.Location(Number(\"{{content.loc1}}\").valueOf(), Number(\"{{content.loc2}}\").valueOf()));\r\n\t\t\t\tmap_{{id}}.entities.push(pushpin)\r\n\t\t\t}});\r\n\t\t}\r\n\t\ttwait = function() {\r\n\t\t\tif (window.Microsoft && window.Microsoft.Maps && typeof window.Microsoft.Maps.loadModule === 'function') {\r\n\t\t\t\tgetMap_{{id}}();\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tsetTimeout(twait, 100);\r\n\t\t};\r\n\t\ttwait();\r\n\t})();\r\n<\/script>\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('bing_maps', {
	name: __('Bing Maps'),
	noButton: true,
	element: {
		minSize: {width: 100, height: 100},
		defaultSize: {width: 602, height: 327},
		resizable: true,
		renderOnce: true,
		supportsFullWidth: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', children: [
					{type: 'Label', text: __('API Key'), helpText: __('Get API Key from %s').replace('%s', '<a style="word-break: break-word;" href="https://msdn.microsoft.com/library/ff428642.aspx" target="_blank">https://msdn.microsoft.com/library/ff428642.aspx</a>')},
					{type: 'TextField', id: 'apiKey'}
				]},
				{type: 'HorizontalLayout', columnWeights: [8, 4], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Coordinates or address'), helpText: __('Location address or coordinates')},
						{type: 'TextField', id: 'address'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Zoom level'), helpText: __('ex. 4')},
						{type: 'SizeSelector', id: 'zoomLevel'}
					]}
				]},
				{type: 'Label', text: __('Drag marker to set your location'), css: {marginTop: 15}},
				{type: 'CustomContainer', id: 'mapElem', css: {width: '100%', height: '234px', position: 'relative', border: '1px solid #aaaaaa', backgroundColor: '#ebebeb'}, init: function() { this.getElem().append('<div>'); }}
			]}
		]
	},
	pluginScoped: {
		scriptLoaded: false,
		scriptReady: false,
		listeners: [],
		key: wb_builder.mapsConfig.bingMapsApiKey,
		addListener: function (inst, func) {
			if (this.scriptReady) {
				func.call(inst, this.ymaps);
			} else {
				this.listeners.push({inst: inst, func: func});
			}
			if (!this.scriptLoaded) {
				this.scriptLoaded = true;
				var self = this;
				$.getScript('https://www.bing.com/mapspreview/sdk/mapcontrol?v=7.0', function () {
					var twait = function () {
						var wnd = window;
						if (wnd.Microsoft && wnd.Microsoft.Maps && typeof wnd.Microsoft.Maps.loadModule === 'function') {
							wnd.Microsoft.Maps.loadModule('Microsoft.Maps.Themes.BingTheme', {
								callback: function () {
									self.scriptReady = true;
									for (var i = 0; i < self.listeners.length; i++) {
										self.listeners[i].func.call(self.listeners[i].inst);
									}
								}
							});
							return;
						}
						setTimeout(twait, 100);
					};
					twait();
				});
			}
		},
		setKey: function(key) {
			if (!key || this.key) return;
			this.key = key;
			this.addListener();
		}
	},
	map: null,
	mapElem: null,
	resizeAction: function (data, elem) {
		if (this.mapElem)
			this.mapElem.css({
				width: data.width,
				height: data.height
			});
		if (this.map && this.map.container)
			this.map.container.fitToViewport();
	},
	openAction: function (fields, data, elem) {
		fields.apiKey.setText(data.content.apiKey);
		fields.address.setText(data.content.address);
		fields.zoomLevel.setValue(data.content.zoomLevel);
		var self = this;
		data.content.coord = data.content.address.split(',');
		data.content.loc1 = data.content.coord[0];
		data.content.loc2 = data.content.coord[1];

		$(fields.address.getElem().get(0)).autocomplete({
			source: function (request, response) {
				$.ajax({
					url: 'https://dev.virtualearth.net/REST/v1/Locations',
					dataType: 'jsonp',
					data: {
						key: self.pluginScoped.key,
						q: request.term
					},
					jsonp: 'jsonp',
					success: function (data) {
						var result = data.resourceSets[0];
						if (result) {
							if (result.estimatedTotal > 0) {
								response($.map(result.resources, function (item) {
									return {
										data: item,
										label: item.name + ' (' + item.address.countryRegion + ')',
										value: item.name
									};
								}));
							}
						}
					}
				});
			},
			minLength: 1,
			change: function (event, ui) {
				if (ui.item)
					displaySelectedItem(ui.item.data);
			},
			select: function (event, ui) {
			}
		});

		function displaySelectedItem(item) {
			fields.address.setText(item.point.coordinates[0] + ', ' + item.point.coordinates[1]);
			fields.map.entities.clear();
			fields.map.setView({
				center: new Microsoft.Maps.Location(item.point.coordinates[0], item.point.coordinates[1])
			});
			var pushpinOptions = {
				draggable: true
			};
			var pushpin = new Microsoft.Maps.Pushpin(fields.map.getCenter(), pushpinOptions);
			fields.map.entities.push(pushpin);

		}

		Microsoft.Maps.loadModule('Microsoft.Maps.Themes.BingTheme', {
			callback: function () {
				fields.map = new Microsoft.Maps.Map(fields.mapElem.getElem().children('div').get(0), {
					credentials: self.pluginScoped.key,
					mapTypeId: Microsoft.Maps.MapTypeId.road,
					theme: new Microsoft.Maps.Themes.BingTheme(),
					zoom: (typeof data.content.zoomLevel === "string") ? parseFloat(data.content.zoomLevel) : data.content.zoomLevel,
					center: new Microsoft.Maps.Location(data.content.loc1, data.content.loc2)
				});
				var pushpinOptions = {
					draggable: true
				};
				var pushpin = new Microsoft.Maps.Pushpin(self.map.getCenter(), pushpinOptions);
				pushpin.setLocation(new Microsoft.Maps.Location(data.content.loc1, data.content.loc2));
				Microsoft.Maps.Events.addHandler(pushpin, 'drag', function (e) {
					var loc = e.location || e.entity.getLocation();
					fields.address.setText(loc.latitude + ', ' + loc.longitude);
					data.content.address = loc.latitude + ', ' + loc.longitude;
				});
				fields.map.entities.push(pushpin);
			}
		});

		function LoadSearchModule() {
			Microsoft.Maps.loadModule('Microsoft.Maps.Search', {
				callback: geocodeRequest
			});
		}

		function geocodeRequest() {
			fields.map.addComponent('searchManager', new Microsoft.Maps.Search.SearchManager(fields.map));
			var searchManager = fields.map.getComponent('searchManager');

			var where = data.content.address;
			var userData = {
				name: 'Maps Test User',
				id: 'XYZ'
			};
			var request = {
				where: where,
				count: 5,
				bounds: fields.map.getBounds(),
				callback: onGeocodeSuccess,
				errorCallback: onGeocodeFailed,
				userData: userData
			};
			searchManager.geocode(request);
		}

		function onGeocodeSuccess(result, userData) {
			if (result) {
				fields.map.entities.clear();
				var topResult = result.results && result.results[0];
				if (topResult) {
					var pushpinOptions = {
						draggable: true
					};
					var pushpin = new Microsoft.Maps.Pushpin(topResult.location, pushpinOptions);

					fields.map.setView({
						zoom: (typeof data.content.zoomLevel === "string") ? parseFloat(data.content.zoomLevel) : data.content.zoomLevel,
						center: topResult.location,
						theme: new Microsoft.Maps.Themes.BingTheme()
					});

					var locs = topResult.location;
					fields.address.setText(locs.latitude + ', ' + locs.longitude);
					data.content.address = locs.latitude + ', ' + locs.longitude;
					data.content.coord = data.content.address.split(",");
					data.content.loc1 = data.content.coord[0];
					data.content.loc2 = data.content.coord[1];
					Microsoft.Maps.Events.addHandler(pushpin, 'drag', function (e) {
						var loc = e.location || e.entity.getLocation();
						fields.address.setText(loc.latitude + ', ' + loc.longitude);
						data.content.address = loc.latitude + ', ' + loc.longitude;
					});
					fields.map.entities.push(pushpin);
				}
			}
		}

		function onGeocodeFailed(result, userData) {
			alert('Geocode failed');
		}

		fields.zoomLevel.on('change', function () {
			data.content.zoomLevel = fields.zoomLevel.getValue();
			fields.map.setView({
				zoom: (typeof data.content.zoomLevel === "string") ? parseFloat(data.content.zoomLevel) : data.content.zoomLevel
			});
		});

		fields.address.on('change', function () {
			data.content.address = fields.address.getText();
			data.content.zoomLevel = fields.zoomLevel.getValue();

			if (/[a-zA-Z]/.test(data.content.address)) {
				LoadSearchModule();
			} else {
				data.content.coord = data.content.address.split(",");
				data.content.loc1 = data.content.coord[0];
				data.content.loc2 = data.content.coord[1];
				fields.map.setView({
					center: new Microsoft.Maps.Location(data.content.loc1, data.content.loc2)
				});
				fields.map.entities.clear();
				var pushpinOptions = {draggable: true};
				var pushpin = new Microsoft.Maps.Pushpin(self.map.getCenter(), pushpinOptions);
				pushpin.setLocation(new Microsoft.Maps.Location(data.content.loc1, data.content.loc2));
				Microsoft.Maps.Events.addHandler(pushpin, 'drag', function (e) {
					var loc = e.location || e.entity.getLocation();
					fields.address.setText(loc.latitude + ', ' + loc.longitude);
					data.content.address = loc.latitude + ', ' + loc.longitude;
				});
				fields.map.entities.push(pushpin);
			}

		});

		this.pluginScoped.addListener(this, function () {});

	},
	applyAction: function (fields, data, elem) {
		var wnd = window, pin1;
		data.content.address = fields.address.getText();
		data.content.apiKey = fields.apiKey.getText();
		this.pluginScoped.setKey(data.content.apiKey);
		data.content.zoomLevel = fields.zoomLevel.getValue();
		data.content.coord = data.content.address.split(',');
		if (!this.getIsCorrectCoords(data.content.coord)) {
			this.loadAction(data, true);
		} else {
			data.content.loc1 = data.content.coord[0];
			data.content.loc2 = data.content.coord[1];
		}

		this.map.setView({
			zoom: (typeof data.content.zoomLevel === "string") ? parseFloat(data.content.zoomLevel) : data.content.zoomLevel,
			center: new wnd.Microsoft.Maps.Location(data.content.loc1, data.content.loc2)
		});
		this.map.entities.clear();
		pin1 = new wnd.Microsoft.Maps.Pushpin(this.map.getCenter(), {draggable: false});
		pin1.setLocation(new wnd.Microsoft.Maps.Location(data.content.loc1, data.content.loc2));
		this.map.entities.push(pin1);
	},
	loadAction: function (data, forceApply) {
		if (!forceApply) data.content.previewKey = this.pluginScoped.key;
		if (!data.content.address || forceApply)
			data.content.address = '40.6898193359375, -74.0456314086914';
		if (!data.content.zoomLevel || forceApply)
			data.content.zoomLevel = 16;
		if (!data.content.loc1 || forceApply)
			data.content.loc1 = '40.6898193359375';
		if (!data.content.loc2 || forceApply)
			data.content.loc2 = '-74.0456314086914';
		if (!data.content.apiKey)
			data.content.apiKey = null;
		if (!forceApply) this.pluginScoped.setKey(data.content.apiKey);
	},
	loadedAction: function (data, elem) {
		var self = this;
		if (!this.getIsCorrectCoords(data.content.coord)) {
			this.loadAction(data, true);
		} else {
			data.content.coord = data.content.address.split(",");
			data.content.loc1 = data.content.coord[0];
			data.content.loc2 = data.content.coord[1];
		}

		this.pluginScoped.addListener(this, function () {
			var wnd = window, pushpinOptions, pushpin;
			self.map = new wnd.Microsoft.Maps.Map(elem.children('.bingmap').get(0), {
				credentials: self.pluginScoped.key,
				mapTypeId: wnd.Microsoft.Maps.MapTypeId.road,
				theme: new wnd.Microsoft.Maps.Themes.BingTheme(),
				zoom: (typeof data.content.zoomLevel === "string") ? parseFloat(data.content.zoomLevel) : data.content.zoomLevel,
				center: new wnd.Microsoft.Maps.Location(data.content.loc1, data.content.loc2)
			});
			pushpinOptions = {draggable: true};
			pushpin = new wnd.Microsoft.Maps.Pushpin(self.map.getCenter(), pushpinOptions);
			pushpin.setLocation(new wnd.Microsoft.Maps.Location(data.content.loc1, data.content.loc2));
			self.map.entities.push(pushpin);
		});
	},
	getIsCorrectCoords: function (coord) {
		return !(!coord || coord.length < 2 || isNaN(Number(coord[0])) || isNaN(Number(coord[1])));
	},
	trim: function (str, symbols) {
		var cont = true, a, b, i;
		var symbs = {};
		if (typeof symbols !== 'undefined') {
			symbols = symbols.split('');
		} else {
			symbols = [' '];
		}
		for (i = 0; i < symbols.length; i++) {
			symbs[symbols[i]] = true;
		}
		while (cont) {
			cont = false;
			a = str.substring(0, 1);
			b = str.substring(str.length - 1);
			if (a in symbs) {
				str = str.substring(1);
				cont = true;
			}
			if (b in symbs) {
				str = str.substring(0, str.length - 1);
				cont = true;
			}
		}
		return str;
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"google_calendar","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/google_calendar\/main.png";
PluginWrapper._config.template = "<iframe src=\"https:\/\/calendar.google.com\/calendar\/embed?src={{content.groupId}}&title={{content.calendar_name}}&mode={{content.mode}}&ctz={{content.timezone}}&bgcolor=%23{{content.color}}&wkst={{content.weekday}}&hl={{content.language}}{{content.check1}}{{content.check2}}{{content.check3}}{{content.check4}}{{content.check5}}{{content.check6}}{{content.check7}}\" style=\"{{content.border_style}} \" width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\"><\/iframe>\r\n\r\n";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = true;
PluginWrapper.registerPlugin('google_calendar', {
    name: __('Calendar'),
    element: {
        minSize: {width: 100, height: 100},
        defaultSize: {width: 800, height: 600},
        resizable: true
    },
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', columnWeights: [7, 5], children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Google calendar ID'),
							helpText: __('To find calendar ID, go to calendar settings')
						},
						{type: 'TextField', id: 'groupId'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Calendar name')},
						{type: 'TextField', id: 'calendar_name'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Language')},
						{type: 'DropdownBox', id: 'language', options: [
							{id: '', name: 'Default'},
							{id: 'id', name: 'Bahasa Indonesia'},
							{id: 'ca', name: 'Català'},
							{id: 'cs', name: 'Čeština'},
							{id: 'da', name: 'Dansk'},
							{id: 'de', name: 'Deutsch'},
							{id: 'en_GB', name: 'English (UK)'},
							{id: 'en', name: 'English (US)'},
							{id: 'es', name: 'Español'},
							{id: 'es_419', name: 'Español (Latinoamérica)'},
							{id: 'fil', name: 'Filipino'},
							{id: 'fr', name: 'Français'},
							{id: 'hr', name: 'Hrvatski'},
							{id: 'it', name: 'Italiano'},
							{id: 'lv', name: 'Latviešu'},
							{id: 'lt', name: 'Lietuvių'},
							{id: 'hu', name: 'Magyar'},
							{id: 'nl', name: 'Nederlands'},
							{id: 'no', name: 'Norsk (bokmål)'},
							{id: 'pl', name: 'Polski'},
							{id: 'pt_BR', name: 'Português (Brasil)'},
							{id: 'pt_PT', name: 'Português (Portugal)'},
							{id: 'ro', name: 'Română'},
							{id: 'sk', name: 'Slovenčina'},
							{id: 'sl', name: 'Slovenščina'},
							{id: 'fi', name: 'Suomi'},
							{id: 'sv', name: 'Svenska'},
							{id: 'tr', name: 'Türkçe'},
							{id: 'vi', name: 'Tiếng Việt'},
							{id: 'el', name: 'Ελληνικά'},
							{id: 'ru', name: 'Русский'},
							{id: 'sr', name: 'Српски'},
							{id: 'uk', name: 'Українська'},
							{id: 'bg', name: 'Български'},
							{id: 'iw', name: 'עברית'},
							{id: 'ar', name: 'العربية'},
							{id: 'fa', name: 'فارسی'},
							{id: 'hi', name: 'हिन्दी'},
							{id: 'th', name: 'ภาษาไทย'},
							{id: 'zh_TW', name: '中文（繁體）'},
							{id: 'zh_CN', name: '中文（简体）'},
							{id: 'ja', name: '日本語'},
							{id: 'ko', name: '한국어'}
						]}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Time zone')},
						{type: 'DropdownBox', id: 'timezone', options: [
							{id: '', name: 'Default'},
							{id: 'Pacific/Niue', name: '(GMT-11:00) Niue'},
							{id: 'Pacific/Pago_Pago', name: '(GMT-11:00) Pago Pago'},
							{id: 'Pacific/Honolulu', name: '(GMT-10:00) Honolulu'},
							{id: 'Pacific/Rarotonga', name: '(GMT-10:00) Rarotonga'},
							{id: 'Pacific/Tahiti', name: '(GMT-10:00) Tahiti'},
							{id: 'Pacific/Marquesas', name: '(GMT-09:30) Marquesas'},
							{id: 'America/Anchorage', name: '(GMT-09:00) Anchorage'},
							{id: 'Pacific/Gambier', name: '(GMT-09:00) Gambier'},
							{id: 'America/Los_Angeles', name: '(GMT-08:00) Los Angeles'},
							{id: 'America/Tijuana', name: '(GMT-08:00) Tijuana'},
							{id: 'America/Vancouver', name: '(GMT-08:00) Vancouver'},
							{id: 'America/Whitehorse', name: '(GMT-08:00) Whitehorse'},
							{id: 'Pacific/Pitcairn', name: '(GMT-08:00) Pitcairn'},
							{id: 'America/Dawson_Creek', name: '(GMT-07:00) Dawson Creek'},
							{id: 'America/Denver', name: '(GMT-07:00) Denver'},
							{id: 'America/Edmonton', name: '(GMT-07:00) Edmonton'},
							{id: 'America/Hermosillo', name: '(GMT-07:00) Hermosillo'},
							{id: 'America/Mazatlan', name: '(GMT-07:00) Mazatlan'},
							{id: 'America/Phoenix', name: '(GMT-07:00) Phoenix'},
							{id: 'America/Yellowknife', name: '(GMT-07:00) Yellowknife'},
							{id: 'America/Belize', name: '(GMT-06:00) Belize'},
							{id: 'America/Chicago', name: '(GMT-06:00) Chicago'},
							{id: 'America/Costa_Rica', name: '(GMT-06:00) Costa Rica'},
							{id: 'America/El_Salvador', name: '(GMT-06:00) El Salvador'},
							{id: 'America/Guatemala', name: '(GMT-06:00) Guatemala'},
							{id: 'America/Managua', name: '(GMT-06:00) Managua'},
							{id: 'America/Mexico_City', name: '(GMT-06:00) Mexico City'},
							{id: 'America/Regina', name: '(GMT-06:00) Regina'},
							{id: 'America/Tegucigalpa', name: '(GMT-06:00)Tegucigalpa'},
							{id: 'America/Winnipeg', name: '(GMT-06:00) Winnipeg'},
							{id: 'Pacific/Galapagos', name: '(GMT-06:00) Galapagos'},
							{id: 'America/Bogota', name: '(GMT-05:00) Bogota'},
							{id: 'America/Cancun', name: '(GMT-05:00) Cancun'},
							{id: 'America/Cayman', name: '(GMT-05:00) Cayman'},
							{id: 'America/Guayaquil', name: '(GMT-05:00) Guayaquil'},
							{id: 'America/Havana', name: '(GMT-05:00) Havana'},
							{id: 'America/Iqaluit', name: '(GMT-05:00) Iqaluit'},
							{id: 'America/Jamaica', name: '(GMT-05:00) Jamaica'},
							{id: 'America/Lima', name: '(GMT-05:00) Lima'},
							{id: 'America/Nassau', name: '(GMT-05:00) Nassau'},
							{id: 'America/New_York', name: '(GMT-05:00) New York'},
							{id: 'America/Panama', name: '(GMT-05:00) Panama'},
							{id: 'America/Port-au-Prince', name: '(GMT-05:00) Port au Prince'},
							{id: 'America/Rio_Branco', name: '(GMT-05:00) Rio Branco'},
							{id: 'America/Toronto', name: '(GMT-05:00) Toronto'},
							{id: 'Pacific/Easter', name: '(GMT-05:00) Easter'},
							{id: 'America/Caracas', name: '(GMT-04:30) Caracas'},
							{id: 'America/Asuncion', name: '(GMT-04:00) Asuncion'},
							{id: 'America/Barbados', name: '(GMT-04:00) Barbados'},
							{id: 'America/Boa_Vista', name: '(GMT-04:00) Boa Vista'},
							{id: 'America/Campo_Grande', name: '(GMT-04:00) Campo Grande'},
							{id: 'America/Cuiaba', name: '(GMT-04:00) Cuiaba'},
							{id: 'America/Curacao', name: '(GMT-04:00) Curacao'},
							{id: 'America/Grand_Turk', name: '(GMT-04:00) Grand Turk'},
							{id: 'America/Guyana', name: '(GMT-04:00) Guyana'},
							{id: 'America/Halifax', name: '(GMT-04:00) Halifax'},
							{id: 'America/La_Paz', name: '(GMT-04:00) La Paz'},
							{id: 'America/Manaus', name: '(GMT-04:00) Manaus'},
							{id: 'America/Martinique', name: '(GMT-04:00) Martinique'},
							{id: 'America/Port_of_Spain', name: '(GMT-04:00) Port of Spain'},
							{id: 'America/Porto_Velho', name: '(GMT-04:00) Porto Velho'},
							{id: 'America/Puerto_Rico', name: '(GMT-04:00) Puerto Rico'},
							{id: 'America/Santo_Domingo', name: '(GMT-04:00) Santo Domingo'},
							{id: 'America/Thule', name: '(GMT-04:00) Thule'},
							{id: 'Atlantic/Bermuda', name: '(GMT-04:00) Bermuda'},
							{id: 'America/St_Johns', name: '(GMT-03:30) St Johns'},
							{id: 'America/Araguaina', name: '(GMT-03:00) Araguaina'},
							{id: 'America/Argentina/Buenos_Aires', name: '(GMT-03:00) Buenos Aires'},
							{id: 'America/Bahia', name: '(GMT-03:00) Bahia'},
							{id: 'America/Belem', name: '(GMT-03:00) Belem'},
							{id: 'America/Cayenne', name: '(GMT-03:00) Cayenne'},
							{id: 'America/Fortaleza', name: '(GMT-03:00) Fortaleza'},
							{id: 'America/Godthab', name: '(GMT-03:00) Godthab'},
							{id: 'America/Maceio', name: '(GMT-03:00) Maceio'},
							{id: 'America/Miquelon', name: '(GMT-03:00) Miquelon'},
							{id: 'America/Montevideo', name: '(GMT-03:00) Montevideo'},
							{id: 'America/Paramaribo', name: '(GMT-03:00) Paramaribo'},
							{id: 'America/Recife', name: '(GMT-03:00) Recife'},
							{id: 'America/Santiago', name: '(GMT-03:00) Santiago'},
							{id: 'America/Sao_Paulo', name: '(GMT-03:00) Sao Paulo'},
							{id: 'Antarctica/Palmer', name: '(GMT-03:00) Palmer'},
							{id: 'Antarctica/Rothera', name: '(GMT-03:00) Rothera'},
							{id: 'Atlantic/Stanley', name: '(GMT-03:00) Stanley'},
							{id: 'America/Noronha', name: '(GMT-02:00) Noronha'},
							{id: 'Atlantic/South_Georgia', name: '(GMT-02:00) South Georgia'},
							{id: 'America/Scoresbysund', name: '(GMT-01:00) Scoresbysund'},
							{id: 'Atlantic/Azores', name: '(GMT-01:00) Azores'},
							{id: 'Atlantic/Cape_Verde', name: '(GMT-01:00) Cape Verde'},
							{id: 'Africa/Abidjan', name: '(GMT+00:00) Abidjan'},
							{id: 'Africa/Accra', name: '(GMT+00:00) Accra'},
							{id: 'Africa/Bissau', name: '(GMT+00:00) Bissau'},
							{id: 'Africa/Casablanca', name: '(GMT+00:00) Casablanca'},
							{id: 'Africa/El_Aaiun', name: '(GMT+00:00) El Aaiun'},
							{id: 'Africa/Monrovia', name: '(GMT+00:00) Monrovia'},
							{id: 'America/Danmarkshavn', name: '(GMT+00:00) Danmarkshavn'},
							{id: 'Atlantic/Canary', name: '(GMT+00:00) Canary'},
							{id: 'Atlantic/Faroe', name: '(GMT+00:00) Faroe'},
							{id: 'Atlantic/Reykjavik', name: '(GMT+00:00) Reykjavik'},
							{id: 'Etc/GMT', name: '(GMT+00:00) GMT'},
							{id: 'Europe/Dublin', name: '(GMT+00:00) Dublin'},
							{id: 'Europe/Lisbon', name: '(GMT+00:00) Lisbon'},
							{id: 'Europe/London', name: '(GMT+00:00) London'},
							{id: 'Africa/Algiers', name: '(GMT+01:00) Algiers'},
							{id: 'Africa/Ceuta', name: '(GMT+01:00) Ceuta'},
							{id: 'Africa/Lagos', name: '(GMT+01:00) Lagos'},
							{id: 'Africa/Ndjamena', name: '(GMT+01:00) Ndjamena'},
							{id: 'Africa/Tunis', name: '(GMT+01:00) Tunis'},
							{id: 'Africa/Windhoek', name: '(GMT+01:00) Windhoek'},
							{id: 'Europe/Amsterdam', name: '(GMT+01:00) Amsterdam'},
							{id: 'Europe/Andorra', name: '(GMT+01:00) Andorra'},
							{id: 'Europe/Belgrade', name: '(GMT+01:00) Belgrade'},
							{id: 'Europe/Berlin', name: '(GMT+01:00) Berlin'},
							{id: 'Europe/Brussels', name: '(GMT+01:00) Brussels'},
							{id: 'Europe/Budapest', name: '(GMT+01:00) Budapest'},
							{id: 'Europe/Copenhagen', name: '(GMT+01:00) Copenhagen'},
							{id: 'Europe/Gibraltar', name: '(GMT+01:00) Gibraltar'},
							{id: 'Europe/Luxembourg', name: '(GMT+01:00) Luxembourg'},
							{id: 'Europe/Madrid', name: '(GMT+01:00) Madrid'},
							{id: 'Europe/Malta', name: '(GMT+01:00) Malta'},
							{id: 'Europe/Monaco', name: '(GMT+01:00) Monaco'},
							{id: 'Europe/Oslo', name: '(GMT+01:00) Oslo'},
							{id: 'Europe/Paris', name: '(GMT+01:00) Paris'},
							{id: 'Europe/Prague', name: '(GMT+01:00) Prague'},
							{id: 'Europe/Rome', name: '(GMT+01:00) Rome'},
							{id: 'Europe/Stockholm', name: '(GMT+01:00) Stockholm'},
							{id: 'Europe/Tirane', name: '(GMT+01:00) Tirane'},
							{id: 'Europe/Vienna', name: '(GMT+01:00) Vienna'},
							{id: 'Europe/Warsaw', name: '(GMT+01:00) Warsaw'},
							{id: 'Europe/Zurich', name: '(GMT+01:00) Zurich'},
							{id: 'Africa/Cairo', name: '(GMT+02:00) Cairo'},
							{id: 'Africa/Johannesburg', name: '(GMT+02:00) Johannesburg'},
							{id: 'Africa/Maputo', name: '(GMT+02:00) Maputo'},
							{id: 'Africa/Tripoli', name: '(GMT+02:00) Tripoli'},
							{id: 'Asia/Amman', name: '(GMT+02:00) Amman'},
							{id: 'Asia/Beirut', name: '(GMT+02:00) Beirut'},
							{id: 'Asia/Damascus', name: '(GMT+02:00) Damascus'},
							{id: 'Asia/Gaza', name: '(GMT+02:00) Gaza'},
							{id: 'Asia/Jerusalem', name: '(GMT+02:00) Jerusalem'},
							{id: 'Asia/Nicosia', name: '(GMT+02:00) Nicosia'},
							{id: 'Europe/Athens', name: '(GMT+02:00) Athens'},
							{id: 'Europe/Bucharest', name: '(GMT+02:00) Bucharest'},
							{id: 'Europe/Chisinau', name: '(GMT+02:00) Chisinau'},
							{id: 'Europe/Helsinki', name: '(GMT+02:00) Helsinki'},
							{id: 'Europe/Istanbul', name: '(GMT+02:00) Istanbul'},
							{id: 'Europe/Kaliningrad', name: '(GMT+02:00) Kaliningrad'},
							{id: 'Europe/Kiev', name: '(GMT+02:00) Kiev'},
							{id: 'Europe/Riga', name: '(GMT+02:00) Riga'},
							{id: 'Europe/Sofia', name: '(GMT+02:00) Sofia'},
							{id: 'Europe/Tallinn', name: '(GMT+02:00) Tallinn'},
							{id: 'Europe/Vilnius', name: '(GMT+02:00) Vilnius'},
							{id: 'Africa/Khartoum', name: '(GMT+03:00) Khartoum'},
							{id: 'Africa/Nairobi', name: '(GMT+03:00) Nairobi'},
							{id: 'Antarctica/Syowa', name: '(GMT+03:00) Syowa'},
							{id: 'Asia/Baghdad', name: '(GMT+03:00) Baghdad'},
							{id: 'Asia/Qatar', name: '(GMT+03:00) Qatar'},
							{id: 'Asia/Riyadh', name: '(GMT+03:00) Riyadh'},
							{id: 'Europe/Minsk', name: '(GMT+03:00) Minsk'},
							{id: 'Europe/Moscow', name: '(GMT+03:00) Moscow'},
							{id: 'Asia/Tehran', name: '(GMT+03:30) Tehran'},
							{id: 'Asia/Baku', name: '(GMT+04:00) Baku'},
							{id: 'Asia/Dubai', name: '(GMT+04:00) Dubai'},
							{id: 'Asia/Tbilisi', name: '(GMT+04:00) Tbilisi'},
							{id: 'Asia/Yerevan', name: '(GMT+04:00) Yerevan'},
							{id: 'Europe/Samara', name: '(GMT+04:00) Samara'},
							{id: 'Indian/Mahe', name: '(GMT+04:00) Mahe'},
							{id: 'Indian/Mauritius', name: '(GMT+04:00) Mauritius'},
							{id: 'Indian/Reunion', name: '(GMT+04:00) Reunion'},
							{id: 'Asia/Kabul', name: '(GMT+04:30) Kabul'},
							{id: 'Antarctica/Mawson', name: '(GMT+05:00) Mawson'},
							{id: 'Asia/Aqtau', name: '(GMT+05:00) Aqtau'},
							{id: 'Asia/Aqtobe', name: '(GMT+05:00) Aqtobe'},
							{id: 'Asia/Ashgabat', name: '(GMT+05:00) Ashgabat'},
							{id: 'Asia/Dushanbe', name: '(GMT+05:00) Dushanbe'},
							{id: 'Asia/Karachi', name: '(GMT+05:00) Karachi'},
							{id: 'Asia/Tashkent', name: '(GMT+05:00) Tashkent'},
							{id: 'Asia/Yekaterinburg', name: '(GMT+05:00) Yekaterinburg'},
							{id: 'Indian/Kerguelen', name: '(GMT+05:00) Kerguelen'},
							{id: 'Indian/Maldives', name: '(GMT+05:00) Maldives'},
							{id: 'Asia/Calcutta', name: '(GMT+05:30) Calcutta'},
							{id: 'Asia/Colombo', name: '(GMT+05:30) Colombo'},
							{id: 'Asia/Katmandu', name: '(GMT+05:45) Katmandu'},
							{id: 'Antarctica/Vostok', name: '(GMT+06:00) Vostok'},
							{id: 'Asia/Almaty', name: '(GMT+06:00) Almaty'},
							{id: 'Asia/Bishkek', name: '(GMT+06:00) Bishkek'},
							{id: 'Asia/Dhaka', name: '(GMT+06:00) Dhaka'},
							{id: 'Asia/Omsk', name: '(GMT+06:00) Omsk'},
							{id: 'Asia/Thimphu', name: '(GMT+06:00) Thimphu'},
							{id: 'Indian/Chagos', name: '(GMT+06:00) Chagos'},
							{id: 'Asia/Rangoon', name: '(GMT+06:30) Rangoon'},
							{id: 'Indian/Cocos', name: '(GMT+06:30) Cocos'},
							{id: 'Antarctica/Davis', name: '(GMT+07:00) Davis'},
							{id: 'Asia/Bangkok', name: '(GMT+07:00) Bangkok'},
							{id: 'Asia/Hovd', name: '(GMT+07:00) Hovd'},
							{id: 'Asia/Jakarta', name: '(GMT+07:00) Jakarta'},
							{id: 'Asia/Krasnoyarsk', name: '(GMT+07:00) Krasnoyarsk'},
							{id: 'Asia/Saigon', name: '(GMT+07:00) Saigon'},
							{id: 'Indian/Christmas', name: '(GMT+07:00) Christmas'},
							{id: 'Antarctica/Casey', name: '(GMT+08:00) Casey'},
							{id: 'Asia/Brunei', name: '(GMT+08:00) Brunei'},
							{id: 'Asia/Choibalsan', name: '(GMT+08:00) Choibalsan'},
							{id: 'Asia/Hong_Kong', name: '(GMT+08:00) Hong Kong'},
							{id: 'Asia/Irkutsk', name: '(GMT+08:00) Irkutsk'},
							{id: 'Asia/Kuala_Lumpur', name: '(GMT+08:00) Kuala Lumpur'},
							{id: 'Asia/Macau', name: '(GMT+08:00) Macau'},
							{id: 'Asia/Makassar', name: '(GMT+08:00) Makassar'},
							{id: 'Asia/Manila', name: '(GMT+08:00) Manila'},
							{id: 'Asia/Shanghai', name: '(GMT+08:00) Shanghai'},
							{id: 'Asia/Singapore', name: '(GMT+08:00) Singapore'},
							{id: 'Asia/Taipei', name: '(GMT+08:00) Taipei'},
							{id: 'Asia/Ulaanbaatar', name: '(GMT+08:00) Ulaanbaatar'},
							{id: 'Australia/Perth', name: '(GMT+08:00) Perth'},
							{id: 'Asia/Pyongyang', name: '(GMT+08:30) Pyongyang'},
							{id: 'Asia/Dili', name: '(GMT+09:00) Dili'},
							{id: 'Asia/Jayapura', name: '(GMT+09:00) Jayapura'},
							{id: 'Asia/Seoul', name: '(GMT+09:00) Seoul'},
							{id: 'Asia/Tokyo', name: '(GMT+09:00) Tokyo'},
							{id: 'Asia/Yakutsk', name: '(GMT+09:00) Yakutsk'},
							{id: 'Pacific/Palau', name: '(GMT+09:00) Palau'},
							{id: 'Australia/Adelaide', name: '(GMT+09:30) Adelaide'},
							{id: 'Australia/Darwin', name: '(GMT+09:30) Darwin'},
							{id: 'Antarctica/DumontDUrville', name: '(GMT+10:00) DumontDUrville'},
							{id: 'Asia/Magadan', name: '(GMT+10:00) Magadan'},
							{id: 'Asia/Vladivostok', name: '(GMT+10:00) Vladivostok'},
							{id: 'Australia/Brisbane', name: '(GMT+10:00) Brisbane'},
							{id: 'Australia/Hobart', name: '(GMT+10:00) Hobart'},
							{id: 'Australia/Sydney', name: '(GMT+10:00) Sydney'},
							{id: 'Pacific/Chuuk', name: '(GMT+10:00) Chuuk'},
							{id: 'Pacific/Guam', name: '(GMT+10:00) Guam'},
							{id: 'Pacific/Port_Moresby', name: '(GMT+10:00) Port Moresby'},
							{id: 'Pacific/Efate', name: '(GMT+11:00) Efate'},
							{id: 'Pacific/Guadalcanal', name: '(GMT+11:00) Guadalcanal'},
							{id: 'Pacific/Kosrae', name: '(GMT+11:00) Kosrae'},
							{id: 'Pacific/Norfolk', name: '(GMT+11:00) Norfolk'},
							{id: 'Pacific/Noumea', name: '(GMT+11:00) Noumea'},
							{id: 'Pacific/Pohnpei', name: '(GMT+11:00) Pohnpei'},
							{id: 'Asia/Kamchatka', name: '(GMT+12:00) Kamchatka'},
							{id: 'Pacific/Auckland', name: '(GMT+12:00) Auckland'},
							{id: 'Pacific/Fiji', name: '(GMT+12:00) Fiji'},
							{id: 'Pacific/Funafuti', name: '(GMT+12:00) Funafuti'},
							{id: 'Pacific/Kwajalein', name: '(GMT+12:00) Kwajalein'},
							{id: 'Pacific/Majuro', name: '(GMT+12:00) Majuro'},
							{id: 'Pacific/Nauru', name: '(GMT+12:00) Nauru'},
							{id: 'Pacific/Tarawa', name: '(GMT+12:00) Tarawa'},
							{id: 'Pacific/Wake', name: '(GMT+12:00) Wake'},
							{id: 'Pacific/Wallis', name: '(GMT+12:00) Wallis'},
							{id: 'Pacific/Apia', name: '(GMT+13:00) Apia'},
							{id: 'Pacific/Enderbury', name: '(GMT+13:00) Enderbury'},
							{id: 'Pacific/Fakaofo', name: '(GMT+13:00) Fakaofo'},
							{id: 'Pacific/Tongatapu', name: '(GMT+13:00) Tongatapu'},
							{id: 'Pacific/Kiritimati', name: '(GMT+14:00) Kiritimati'}
						]}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('First day')},
						{type: 'DropdownBox', id: 'weekday', options: [
							{id: '1', name: 'Sunday'},
							{id: '2', name: 'Monday'},
							{id: '7', name: 'Saturday'}
						]}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('View mode')},
						{type: 'RadioBox', id: 'mode0', label: __('Week'), group: 'mode'},
						{type: 'RadioBox', id: 'mode1', label: __('Month'), group: 'mode'},
						{type: 'RadioBox', id: 'mode2', label: __('Agenda'), group: 'mode'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border'), helpText: __('Show border on calendar')},
						{type: 'RadioBox', id: 'border0', label: __('Yes'), group: 'border'},
						{type: 'RadioBox', id: 'border1', label: __('No'), group: 'border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background color')},
						{type: 'ColorSelector', id: 'color'}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'CheckBox', id: 'check1', label: __('Title')},
						{type: 'CheckBox', id: 'check2', label: __('Navigation')},
						{type: 'CheckBox', id: 'check3', label: __('Date')}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'CheckBox', id: 'check4', label: __('Print icon')},
						{type: 'CheckBox', id: 'check5', label: __('Tabs')}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'CheckBox', id: 'check6', label: __('Calendars list')},
						{type: 'CheckBox', id: 'check7', label: __('Time zone')}
					]}
				]}
			]}
		]
	},
	resizeTimeout: null,
	
	resizeAction: function(data, elem) {
		if (!this.resizeTimeout) {
			var self = this;
			this.resizeTimeout = setTimeout(function() {
				self.resizeTimeout = null;
				self.updateElement();
			}, 1000);
		}
	},
	openAction: function(fields, data, elem) {
		var itm;
		itm = fields.timezone.getItemById(data.content.timezone);
		if (!itm) itm = fields.timezone.getItem(0);
		fields.timezone.selectItem(itm);
		itm = fields.language.getItemById(data.content.language);
		if (!itm) itm = fields.language.getItem(0);
		fields.language.selectItem(itm);
		itm = fields.weekday.getItemById(data.content.weekday);
		if (!itm) itm = fields.weekday.getItem(0);
		fields.weekday.selectItem(itm);
		fields.groupId.setText(data.content.groupId);
		fields.calendar_name.setText(data.content.calendar_name);
		fields.border0.setValue(data.content.border === '1');
		fields.border1.setValue(data.content.border === '0');
		
		fields.check1.setValue(data.content.check1 === '');
		fields.check2.setValue(data.content.check2 === '');
		fields.check3.setValue(data.content.check3 === '');
		fields.check4.setValue(data.content.check4 === '');
		fields.check5.setValue(data.content.check5 === '');
		fields.check6.setValue(data.content.check6 === '');
		fields.check7.setValue(data.content.check7 === '');
		
		fields.mode0.setValue(data.content.mode === 'WEEK');
		fields.mode1.setValue(data.content.mode === 'MONTH');
		fields.mode2.setValue(data.content.mode === 'AGENDA');
		
		fields.color.setValue(data.content.color);
	},
	applyAction: function(fields, data, elem) {
		var itm, color;
		itm = fields.timezone.getSelectedItem();
		data.content.timezone = itm.getOriginal().id;
		itm = fields.language.getSelectedItem();
		data.content.language = itm.getOriginal().id;
		itm = fields.weekday.getSelectedItem();
		data.content.weekday = itm.getOriginal().id;
		
		data.content.check1 = fields.check1.getValue() ? '' : '&showTitle=0';
		data.content.check2 = fields.check2.getValue() ? '' : '&showNav=0';
		data.content.check3 = fields.check3.getValue() ? '' : '&showDate=0';
		data.content.check4 = fields.check4.getValue() ? '' : '&showPrint=0';
		data.content.check5 = fields.check5.getValue() ? '' : '&showTabs=0';
		data.content.check6 = fields.check6.getValue() ? '' : '&showCalendars=0';
		data.content.check7 = fields.check7.getValue() ? '' : '&showTz=0';
		
		if (fields.border0.getValue()) {
			data.content.border = '1';
			data.content.border_style = 'border:solid 1px #777';
		}
		if (fields.border1.getValue()) {
			data.content.border = '0';
			data.content.border_style = 'border-width:0';
		}
		if (fields.mode0.getValue()) data.content.mode = 'WEEK';
		if (fields.mode1.getValue()) data.content.mode = 'MONTH';
		if (fields.mode2.getValue()) data.content.mode = 'AGENDA';
		
		color = fields.color.getValue();
		data.content.color = color.replace('#', '');
		
		data.content.groupId = fields.groupId.getText();
		data.content.calendar_name = fields.calendar_name.getText();
	},
	loadAction: function(data) {
		if (!data.content.timezone) data.content.timezone = '';
		if (!data.content.language) data.content.language = '';
		if (!data.content.weekday) data.content.weekday = '2';
		if (!data.content.groupId) data.content.groupId = 'uk__en_gb@holiday.calendar.google.com';
		if (!data.content.calendar_name) data.content.calendar_name = 'Calendar name';
		if (!data.content.border) data.content.border = '0';
		if (!data.content.check1) data.content.check1 = '';
		if (!data.content.check2) data.content.check2 = '';
		if (!data.content.check3) data.content.check3 = '';
		if (!data.content.check4) data.content.check4 = '';
		if (!data.content.check5) data.content.check5 = '';
		if (!data.content.check6) data.content.check6 = '';
		if (!data.content.check7) data.content.check7 = '';
		if (!data.content.mode) data.content.mode = 'MONTH';
		if (!data.content.border_style) data.content.border_style = 'border-width:0';
		if (!data.content.color) data.content.color = '00adef';
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"payfast","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/payfast\/main.png";
PluginWrapper._config.template = "<form action=\"https:\/\/www.payfast.co.za\/eng\/process\" method=\"post\" data-gateway-id=\"Payfast\"{{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"merchant_id\" value=\"{{content.merchantId}}\" \/>\r\n\t<input type=\"hidden\" name=\"merchant_key\" value=\"{{content.merchantKey}}\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"return_url\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"cancel_url\" value=\"{cancelUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"notify_url\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"m_payment_id\" value=\"{transactionId}\" \/>\r\n\t{{\/content.store}}\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"item_name\" value=\"{{content.itemName}}\" \/>\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<button type=\"submit\" class=\"btn-link\" style=\"{{#content.store}}width: 106px; height: 32px;{{\/content.store}}{{^content.store}}width: 100%; height: 100%;{{\/content.store}} border: none; padding: 0; background-image: url(https:\/\/www.payfast.co.za\/storage\/{{#content.button}}{{content.button}}{{\/content.button}}{{^content.button}}buynow-dark{{\/content.button}}.png); background-position: -20px 0;\"><\/button>\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/payfast/main.php';
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: 'PayFast',
	id: 'payfast',
	pageUrl: 'https://www.payfast.co.za/',
	keyFieldId: 'merchantId',
	keyField2Id: 'merchantKey',
	keyField3Id: 'passphrase',
	keyFieldDef: {type: 'HorizontalLayout', noPadding: true, columnWeights: [12,6,6], children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Merchant Key'), id: 'key2', css: {marginTop: 5}},
		{type: 'TextField', placeholder: __('Passphrase'), id: 'key3', css: {marginTop: 5}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'itemName',
	priceFieldId: 'amount',
	globalVars: ['merchantId', 'merchantKey', 'passphrase']
});
PluginWrapper.registerPlugin('payfast', {
	name: 'PayFast',
	element: {
		minSize: {width: 106, height: 32},
		defaultSize: {width: 106, height: 32},
		resizable: false
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Item Name')},
						{type: 'TextField', id: 'itemName'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred") + ', ' + 'ZAR'},
						{type: 'TextField', id: 'amount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Button type')},
						{type: 'DropdownBox', id: 'button', options: [
							{id: '#paynow-dark', name: 'paynow-dark', value: 'paynow-dark'},
							{id: '#paynow-light', name: 'paynow-light', value: 'paynow-light'},
							{id: '#buynow-dark', name: 'buynow-dark', value: 'buynow-dark'},
							{id: '#buynow-light', name: 'buynow-light', value: 'buynow-light'},
							{id: '#donate-dark', name: 'donate-dark', value: 'donate-dark'},
							{id: '#donate-light', name: 'donate-light', value: 'donate-light'}
						]}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant ID')},
						{type: 'TextField', id: 'merchantId'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant Key')},
						{type: 'TextField', id: 'merchantKey'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Passphrase')},
						{type: 'TextField', id: 'passphrase'}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		itm = fields.button.getItemById('#' + data.content.button);
		fields.button.selectItem(itm);
		fields.merchantId.setText(data.content.merchantId);
		fields.merchantKey.setText(data.content.merchantKey);
		fields.passphrase.setText(data.content.passphrase);
		fields.itemName.setText(data.content.itemName);
		fields.amount.setText(data.content.amount);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		itm = fields.button.getSelectedItem();
		data.content.button = itm.getOriginal().value;
		data.content.merchantId = fields.merchantId.getText();
		data.content.merchantKey = fields.merchantKey.getText();
		data.content.passphrase = fields.passphrase.getText();
		data.content.itemName = fields.itemName.getText();
		data.content.amount = fields.amount.getText();
	},
	loadAction: function (data) {
		if (!data.content.merchantId)
			data.content.merchantId = ''; // 10005521
		if (!data.content.merchantKey)
			data.content.merchantKey = ''; // o3mztwvetaxrk
		if (!data.content.passphrase)
			data.content.passphrase = ''; // sitepro4payfast
		if (!data.content.itemName)
			data.content.itemName = ''; // Black Eye Boxing Gloves
		if (!data.content.amount)
			data.content.amount = '1'; // 129.99
		if (!data.content.button)
			data.content.button = 'buynow-dark';
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"assist","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/assist\/main.png";
PluginWrapper._config.template = "<form data-gateway-id=\"Assist\" method=\"post\" action=\"https:\/\/{{#content.demo}}payments.demo.paysecure.ru{{\/content.demo}}{{^content.demo}}{{content.servername}}{{\/content.demo}}\/pay\/order.cfm\"{{^content.store}} target=\"_blank\"{{\/content.store}} style=\"width: 100%; height: 100%;\">\r\n\t<input type=\"hidden\" name=\"Merchant_ID\" value=\"{{content.merchantid}}\">\r\n\t<input type=\"hidden\" name=\"OrderAmount\" value=\"{{content.orderamount}}\">\r\n\t<input type=\"hidden\" name=\"OrderComment\" value=\"{{content.ordercomment}}\">\r\n\t<input type=\"hidden\" name=\"OrderCurrency\" value=\"{{content.ordercurrency}}\">\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"OrderNumber\" value=\"{transactionId}\" \/>\r\n\t<input type=\"hidden\" name=\"URL_RETURN_OK\" value=\"{callbackUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"URL_RETURN_NO\" value=\"{cancelUrl}\" \/>\r\n\t{{\/content.store}}\r\n\t{{{requireService}}}\r\n\t{{#content.store}}\r\n\t<button style=\"background: none; border: none; vertical-align: middle; width: 100px; height: 47px;\">\r\n\t\t<img src=\"gallery_gen\/assist\/assist.png\" alt=\"Assist\" style=\"width: auto; max-width: 100%;\" \/>\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<button class=\"btn btn-default btn-sm\" onclick=\"{{id}}_show_modal()\" style=\"width: 100%; height: 100%; white-space: normal;\r\n\t\t\tbackground-color: {{#content.button_color}}{{content.button_color}}{{\/content.button_color}}{{^content.button_color}}#fff{{\/content.button_color}};\r\n\t\t\t{{#content.buttonBorderCss}}{{content.buttonBorderCss}}{{\/content.buttonBorderCss}}\">\r\n\t\t<strong style=\"color: {{#content.label_color}}{{content.label_color}}{{\/content.label_color}}{{^content.label_color}}#000{{\/content.label_color}};\r\n\t\t\t\t\t   font-family: {{#content.font_family}}{{content.font_family}}{{\/content.font_family}}{{^content.font_family}}Arial{{\/content.font_family}};\r\n\t\t\t\t\t   font-size: {{#content.font_size}}{{content.font_size}}px{{\/content.font_size}}{{^content.font_size}}12px{{\/content.font_size}};\">{{content.button_label}}<\/strong>\r\n\t\t{{#content.showlogo}}<img src=\"{{^isPublished}}plugins\/assist\/site\/{{\/isPublished}}gallery_gen\/assist\/assist.png\" alt=\"Assist\" style=\"width: {{content.logo_width}}px; max-width: 100%;\" \/>{{\/content.showlogo}}\r\n\t<\/button>\r\n\t{{\/content.store}}\r\n<\/form>";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/assist/main.php';
PluginWrapper._config.active = false;

ElementRegister.registerPaymentGateway({
	name: 'Assist',
	id: 'assist',
	pageUrl: 'https://www.assist.ru/',
	keyFieldId: 'merchantid',
	keyField2Id: 'servername',
	keyField3Id: 'demo',
	keyFieldDef: {type: 'HorizontalLayout', columnWeights: [6,6,12], noPadding: true, children: [
		{type: 'TextField', placeholder: __('Merchant ID'), id: 'key'},
		{type: 'TextField', placeholder: __('Server name'), id: 'key2'},
		{type: 'CheckBox', label: __('Test mode'), id: 'key3', css: {padding: 7, marginTop: 5, display: 'inline-block'}, init: function() {
			this.getElem().attr('title', __('For testing purpose without real payments')).tooltip({placement: 'right'});
		}}
	]},
	titleFieldId: 'label',
	nameFieldId: 'ordercomment',
	priceFieldId: 'orderamount',
	currencyFieldId: 'ordercurrency',
	globalVars: ['merchantid', 'servername', 'demo']
});
PluginWrapper.registerPlugin('assist', {
	name: 'Assist',
	element: {
		minSize: {width: 100, height: 35},
		defaultSize: {width: 190, height: 50}
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', spacing: 15, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Merchant ID'), helpText:__("Identifier from Assist")},
						{type: 'TextField', id: 'merchantid'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Server name'), helpText:__("Server name provided by Assist support team")},
						{type: 'TextField', id: 'servername'}
					]}
				]},
				{type: 'HorizontalLayout', columnWeights: [6, 3, 3], columnWeightsSmall: [6, 3, 3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Item Name'), helpText:__('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'ordercomment'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __("Amount to be transferred")},
						{type: 'TextField', id: 'orderamount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'ordercurrency', options: [
							{id: 'RUB', name: 'RUB'},
							{id: 'USD', name: 'USD'},
							{id: 'EUR', name: 'EUR'},
							{id: 'BYN', name: 'BYN'},
							{id: 'AMD', name: 'AMD'},
							{id: 'AUD', name: 'AUD'},
							{id: 'AZN', name: 'AZN'},
							{id: 'BGN', name: 'BGN'},
							{id: 'BRL', name: 'BRL'},
							{id: 'CAD', name: 'CAD'},
							{id: 'CHF', name: 'CHF'},
							{id: 'CNY', name: 'CNY'},
							{id: 'CZK', name: 'CZK'},
							{id: 'DKK', name: 'DKK'},
							{id: 'GBP', name: 'GBP'},
							{id: 'HUF', name: 'HUF'},
							{id: 'INR', name: 'INR'},
							{id: 'JPY', name: 'JPY'},
							{id: 'KGS', name: 'KGS'},
							{id: 'KRW', name: 'KRW'},
							{id: 'KZT', name: 'KZT'},
							{id: 'MDL', name: 'MDL'},
							{id: 'NOK', name: 'NOK'},
							{id: 'PLN', name: 'PLN'},
							{id: 'RON', name: 'RON'},
							{id: 'SEK', name: 'SEK'},
							{id: 'SGD', name: 'SGD'},
							{id: 'TJS', name: 'TJS'},
							{id: 'TMT', name: 'TMT'},
							{id: 'TRY', name: 'TRY'},
							{id: 'UAH', name: 'UAH'},
							{id: 'UZS', name: 'UZS'},
							{id: 'ZAR', name: 'ZAR'}
						]}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'Label', text: __('Button Label')},
					{type: 'TextField', id: 'button_label'}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'button_border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'button_color'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'font_size'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'label_color', noTransparent: true}
					]}
				]},
				{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', css: {width: 120}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'font_family', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Max logo width')},
						{type: 'SizeSelector', id: 'logo_width', max: 180, min: 20}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Show logo')},
						{type: 'RadioBox', id: 'showlogo1', label: __('Yes'), group: 'showlogo'},
						{type: 'RadioBox', id: 'showlogo0', label: __('No'), group: 'showlogo'}
					]}
				]},
				{type: 'VerticalLayout', css: {marginTop: 15}, children: [
					{type: 'CheckBox', id: 'demo', css: {display: 'inline-block'}, label: __('Test mode'), init: function() {
						this.getElem().attr('title', __('For testing purpose without real payments'));
						this.getElem().tooltip({placement: 'bottom'});
					}}
				]}
			]}
		]
	},
	openAction: function(fields, data, elem) {
		var itm;
		fields.merchantid.setText(data.content.merchantid);
		fields.servername.setText(data.content.servername);
		fields.orderamount.setText(data.content.orderamount);
		itm = fields.ordercurrency.getItemById(data.content.ordercurrency);
		fields.ordercurrency.selectItem(itm);
		fields.ordercomment.setText(data.content.ordercomment);
		
		fields.button_label.setText(data.content.button_label);
		fields.button_color.setValue(data.content.button_color);
		fields.font_family.setValue(data.content.font_family);
		fields.font_size.setValue(data.content.font_size);
		fields.label_color.setValue(data.content.label_color);
		fields.button_border.setValue(data.content.button_border);
		fields.demo.setValue(data.content.demo);
		fields.showlogo1.setValue(data.content.showlogo === true);
		fields.showlogo0.setValue(data.content.showlogo === false);
		fields.logo_width.setValue(data.content.logo_width);
	},
	applyAction: function(fields, data, elem) {
		var itm;
		data.content.merchantid = fields.merchantid.getText();
		data.content.servername = fields.servername.getText();
		data.content.orderamount = fields.orderamount.getText();
		itm = fields.ordercurrency.getSelectedItem();
		data.content.ordercurrency = itm.getOriginal().id;
		data.content.ordercomment = fields.ordercomment.getText();
		
		data.content.button_label = fields.button_label.getText();
		data.content.button_color = fields.button_color.getValue();
		data.content.font_family = fields.font_family.getValue();
		data.content.font_size = fields.font_size.getValue();
		data.content.label_color = fields.label_color.getValue();
		data.content.button_border = fields.button_border.getValue();
		data.content.demo = fields.demo.getValue();
		if (fields.showlogo1.getValue()) data.content.showlogo = true;
		if (fields.showlogo0.getValue()) data.content.showlogo = false;
		data.content.logo_width = fields.logo_width.getValue();
		data.content.buttonBorderCss = this.updateBorderCss(data);
	},
	updateBorderCss: function(data) {
		var borderCss = '';
		var border = data.content.button_border;
		if (border.css !== undefined) {
			if (typeof border.css === 'string') {
				borderCss = border.css;
			} else {
				for (var i in border.css) {
					borderCss += i + ': ' + border.css[i] + ';';
				}
			}
		} else {
			borderCss = 'border: ' + border.weight + 'px ' + border.style + ' ' + border.color + ';';
		}
		return borderCss;
	},
	loadAction: function (data) {
		if (!data.content.merchantid) data.content.merchantid = '';
		if (!data.content.servername) data.content.servername = '';
		if (!data.content.orderamount) data.content.orderamount = '1';
		if (!data.content.ordercurrency) data.content.ordercurrency = 'RUB';
		if (!data.content.ordercomment) data.content.ordercomment = 'Donate';
		
		if (data.content.button_label === undefined) data.content.button_label = __('Pay with %s').replace('%s', '');
		if (!data.content.button_color) data.content.button_color = '#ffffff';
		if (!data.content.font_family) data.content.font_family = 'Arial';
		if (!data.content.font_size) data.content.font_size = '12';
		if (!data.content.label_color) data.content.label_color = '#000';
		if (!data.content.button_border) data.content.button_border = {
			color: '#ccc',
			style: 'solid',
			weight: 1,
			css: { border: '1px solid #ccc' }
		};
		if (data.content.demo === undefined) data.content.demo = false;
		if (data.content.showlogo === undefined) data.content.showlogo = true;
		if (!data.content.logo_width) data.content.logo_width = 90;
		data.content.buttonBorderCss = this.updateBorderCss(data);
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"7_connect","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/7_connect\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n<img height=\"38\" src=\"plugins\/7_connect\/site\/gallery_gen\/7_connect\/7_connect.png\" \/>\r\n{{\/isPublished}}\r\n\r\n{{#content.store}}\r\n<form data-gateway-id=\"7Connect\" class=\"{{id}}\" method=\"get\" action=\"https:\/\/pay.7-eleven.com.ph\/transact\">\r\n\t<input type=\"hidden\" name=\"merchantID\" value=\"{{content.merchantID}}\">\r\n\t<input type=\"hidden\" name=\"merchantRef\" value=\"{{content.merchantRef}}\">\r\n\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\">\r\n\t<input type=\"hidden\" name=\"transactionDescription\" value=\"{{content.transactionDescription}}\">\r\n\t<input type=\"hidden\" name=\"token\" value=\"{{content.token}}\">\r\n\t<input type=\"hidden\" name=\"successURL\" value=\"{returnUrl}\" \/>\r\n\t<input type=\"hidden\" name=\"failURL\" value=\"{cancelUrl}\" \/>\r\n\t<button style=\"background:url('gallery_gen\/7_connect\/7_connect.png') no-repeat; background-size:contain; border: none; width:38px; height:38px\" type=\"submit\" value=\"submit\"><\/button>\r\n<\/form>\r\n{{\/content.store}}\r\n\r\n{{^content.store}}\r\n{{{requireService}}}\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = null;
PluginWrapper._config.active = false;
ElementRegister.registerPaymentGateway({
	name: __('7-Connect'),
	id: '7_connect',
	pageUrl: 'https://7-connect.philseven.com/',
	keyField: __('Merchant ID'),
	keyFieldId: 'merchantID',
	keyField2: __('Transaction Key'),
	keyField2Id: 'transactionKey',
	titleFieldId: null,
	nameFieldId: 'transactionDescription',
	priceFieldId: 'amount',
	currencyFieldId: null
});
PluginWrapper.registerPlugin('7_connect', {
	name: __('7-Connect'),
	element: {
		minSize: {width: 38, height: 38},
		defaultSize: {width: 38, height: 38},
		resizable: false
	},
	propertyDialog: {
		noScroll: true,
			tabs: [
				{children: [
					{type: 'VerticalLayout', spacing: 15, children: [
						{type: 'VerticalLayout', children: [
							{
								type: 'Label', text: __('Merchant ID'),
								helpText: __("Merchant's ID as provided by 7-CONNECT")
							},
							{type: 'TextField', id: 'merchantID'}
						]},
						{type: 'VerticalLayout', children: [
							{
								type: 'Label', text: __('Transaction Key'),
								helpText: __("TransactionKey as provided by 7-CONNECT")
							},
							{type: 'TextField', id: 'transactionKey'}
						]},
						{type: 'VerticalLayout', children: [
							{
								type: 'Label', text: __('Merchant Ref'),
								helpText: __("Merchant's Reference Number")
							},
							{type: 'TextField', id: 'merchantRef'}
						]},
						{type: 'VerticalLayout', children: [
							{
								type: 'Label', text: __('Transaction Description'),
								helpText: __("Will be shown in the customer LCD screen and payment instruction page (max of 3000 characters)")
							},
							{type: 'TextField', id: 'transactionDescription'}
						]},
						{type: 'VerticalLayout', children: [
							{
								type: 'Label', text: __('Amount'),
								helpText: __("Amount to be transferred") + ', PHP'
							},
							{type: 'TextField', id: 'amount'}
						]},
					]}
				]}
			]
	},
	openAction: function(fields, data, elem) {
		fields.merchantID.setText(data.content.merchantID);
		fields.merchantRef.setText(data.content.merchantRef);
		fields.amount.setText(data.content.amount);
		fields.transactionKey.setText(data.content.transactionKey);
		fields.transactionDescription.setText(data.content.transactionDescription);
	},
	applyAction: function(fields, data, elem) {
		data.content.transactionKey = fields.transactionKey.getText();
		data.content.merchantID = fields.merchantID.getText();
		data.content.merchantRef = fields.merchantRef.getText();
		data.content.amount = parseFloat(fields.amount.getText()).toFixed(2);
		data.content.transactionDescription = fields.transactionDescription.getText();
	},
	loadAction: function (data) {
		if (!data.content.merchantID) data.content.merchantID = ''; // 7-Eleven
		if (!data.content.merchantRef) data.content.merchantRef = ''; // 51644
		if (!data.content.amount) data.content.amount = '1'; // 49.99
		// if (!data.content.token) data.content.token = '996700bdd155a5d0e6b1398655e51c0c9cc3d90c';
		if (!data.content.transactionKey) data.content.transactionKey = ''; // 628e936f45884030ac1f34bcde9c28efa6ae9c839623b45b8942bd4490e1f05d
		if (!data.content.transactionDescription) data.content.transactionDescription = ''; // Product description
	}
});});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"bank_transfer","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/bank_transfer\/main.png";
PluginWrapper._config.template = "{{%FILTERS}}\r\n<form data-gateway-id=\"BankTransfer\" action=\"\" method=\"post\" style=\"width: 100%; height: 100%;\" id=\"{{id}}_bank_transfer_form\" onsubmit=\"return false;\">\r\n\t<input type=\"hidden\" name=\"invoiceUrl\" value=\"\" \/>\r\n\t{{^content.store}}\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t{{#content.store}}\r\n\t<button class=\"btn btn-default btn-raised\" style=\"vertical-align: middle; font-weight: bold;\"><i class=\"fa fa-bank\"><\/i> {{content.__t.label}}<\/button>\r\n\t{{\/content.store}}\r\n<\/form>\r\n\r\n{{#content.store}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\t$('#{{id}}_bank_transfer_form').on('beforesend', function(e, checkoutData) {\r\n\t\t\te.preventDefault();\r\n\t\t\t$('#{{id}}_bank_transfer_invoice_link').attr(\"href\", checkoutData.orderData.invoiceUrl);\r\n\t\t\t$('#{{id}}_bank_transfer_modal')\r\n\t\t\t\t.appendTo(\"body\")\r\n\t\t\t\t.modal({\r\n\t\t\t\t\tbackdrop: 'static',\r\n\t\t\t\t\tkeyboard: false\r\n\t\t\t\t})\r\n\t\t\t\t.on('hide.bs.modal', function() {\r\n\t\t\t\t\twindow.location.href = checkoutData.backUrl;\r\n\t\t\t\t})\r\n\t\t\t;\r\n\t\t\treturn false;\r\n\t\t});\r\n\t})();\r\n<\/script>\r\n<div class=\"modal fade\" id=\"{{id}}_bank_transfer_modal\" tabindex=\"-1\" role=\"dialog\">\r\n    <div class=\"modal-dialog\" role=\"document\">\r\n        <div class=\"modal-content\">\r\n            <div class=\"modal-header\">\r\n                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;<\/span><\/button>\r\n                <h4 class=\"modal-title\">{{content.__t.label}}<\/h4>\r\n            <\/div>\r\n            <div class=\"modal-body\">\r\n\t\t\t\t{{{content.info | i18n}}}\r\n\t\t\t\t<div>\r\n\t\t\t\t\t<a id=\"{{id}}_bank_transfer_invoice_link\" href=\"javascript:void(0)\" target=\"_blank\" class=\"btn btn-success\"><i class=\"fa fa-file-pdf-o\"><\/i> {{content.__t.download_invoice}}<\/a>\r\n\t\t\t\t<\/div>\r\n\t\t\t<\/div>\r\n\t\t\t<div class=\"modal-footer\">\r\n                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">{{content.__t.close}}<\/button>\r\n            <\/div>\r\n\t\t<\/div>\r\n\t<\/div>\r\n<\/div>\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/bank_transfer/main.php';
PluginWrapper._config.active = true;
(function() {
	if (typeof window.bank_transfer_translations === 'undefined') {
		window.bank_transfer_translations = {
			'download_invoice': __c('Download invoice'),
			'label': __c('Bank Transfer'),
			'close': __c('Close')
		};
	}
})();

var updateBankTransferWarning = function(list, store) {
	var _this = this;
	setTimeout(function() {
		var text = '';
		if( _this.enabler.getValue() ) {
			var cartPropertiesFields = list.getUiFields();
			if( !cartPropertiesFields.billingShippingRequired.getValue() )
				text += '<li>' + __('"%s" checkbox must also be checked to enable this gateway.').replace("%s", __('Require Billing/Shipping Information')) + '</li>';
			if( !cartPropertiesFields.companyInfo.getValue() || cartPropertiesFields.companyInfo.getValue() === "" )
				text += '<li>' + __('Seller details are required to create invoices.') + '</li>';
			if( !cartPropertiesFields.invoiceDocumentNumberFormat.getValue() || cartPropertiesFields.invoiceDocumentNumberFormat.getValue() === "" )
				text += '<li>' + __('Invoice document number format is required to create invoices.') + '</li>';
			if( !store.contactForm.content.email || !store.contactForm.content.emailFrom  || store.contactForm.content.emailFrom === "" || store.contactForm.content.email === "" )
				text += '<li>' + __('To send order confirmations recipient and sender emails must be entered in store contact form email settings.') + '</li>';
		}
		if( text === '' )
			_this.bankTransferWarnings.setContent('');
		else
			_this.bankTransferWarnings.setContent('<div class="alert alert-warning" style="margin: 5px 0 0;"><ul style="padding: 0 0 0 15px;">' + text + '</ul></div>');
	}, 0);
};

ElementRegister.registerPaymentGateway({
	name: __('Bank Transfer'),
	id: 'bank_transfer',
	priority: 2,
	forceActive: PluginWrapper._config.active,
	pageUrl: null,
	keyFieldId: 'info',
	keyFieldDefaultValue: '<p>' + __("Your order was successfully placed.") + '<br />' + __("Please use Seller bank account information in invoice to make a bank transfer for your order.") + '</p>',
	keyFieldDef: {type: 'VerticalLayout', children: [
		{type: 'HorizontalLayout', columnWeights: [12, 12], noPadding: true, children: [
			{type: 'Label', text: __('Information to display when order is placed')},
			{type: 'WYSIWYGControl', id: 'key', css: {height: 100}, forcePasteAsPlainText: true}
		]},
		{type: 'CustomContainer', id: 'bankTransferWarnings'}
	]},
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['info'],
	__t: window.bank_transfer_translations,
	onInit: function(list, store) {
		var _this = this;
		var cartPropertiesFields = list.getUiFields();
		cartPropertiesFields.billingShippingRequired.on("change", function() {
			updateBankTransferWarning.call(_this, list, store);
		});
		cartPropertiesFields.companyInfo.on("change", function() {
			updateBankTransferWarning.call(_this, list, store);
		});
		cartPropertiesFields.invoiceDocumentNumberFormat.on("change", function() {
			updateBankTransferWarning.call(_this, list, store);
		});
		cartPropertiesFields.invoiceDocumentNumberSeries.on("change", function() {
			updateBankTransferWarning.call(_this, list, store);
		});
		cartPropertiesFields.invoiceDocumentNumberLength.on("change", function() {
			updateBankTransferWarning.call(_this, list, store);
		});
	},
	onEnable: updateBankTransferWarning,
	onDisable: updateBankTransferWarning
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"alipay","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/alipay\/main.png";
PluginWrapper._config.template = "<form action=\"https:\/\/mapi.alipay.com\/gateway.do\" method=\"get\"{{^content.store}} target=\"_blank\"{{\/content.store}} data-gateway-id=\"Alipay\"{{#content.store}} data-onload=\"alipay_onload\" data-onsubmit=\"alipay_onsubmit\" data-sc=\"{{content.security_code}}\"{{\/content.store}}>\r\n\t<input type=\"hidden\" name=\"_input_charset\" value=\"utf-8\" \/>\r\n\t<input type=\"hidden\" name=\"apInitiateService_run\" value=\"1\" \/>\r\n\t<input type=\"hidden\" name=\"body\" value=\"{{content.description}}\" \/>\r\n\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"hidden\" name=\"notify_url\" value=\"{callbackUrl}\"\/>\r\n\t<input type=\"hidden\" name=\"out_trade_no\" value=\"{transactionId}\"\/>\r\n\t<input type=\"hidden\" name=\"sign\" value=\"\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<input type=\"hidden\" name=\"notify_url\" value=\"about:blank\"\/>\r\n\t<input type=\"hidden\" name=\"out_trade_no\" value=\"{{content.trade_no}}\"\/>\r\n\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n\t<input type=\"hidden\" name=\"partner\" value=\"{{content.partner}}\" \/>\r\n\t<input type=\"hidden\" name=\"service\" value=\"create_forex_trade\" \/>\r\n\t<input type=\"hidden\" name=\"subject\" value=\"{{content.description}}\" \/>\r\n\t<input type=\"hidden\" name=\"total_fee\" value=\"{{content.amount}}\" \/>\r\n\t<input type=\"hidden\" name=\"sign_type\" value=\"MD5\" \/>\r\n\t{{#content.store}}\r\n\t<input type=\"submit\" class=\"btn btn-info\" value=\"{{content.label}}\"\r\n\t\t   title=\"{{content.label}}\"\r\n\t\t   style=\"height: 40px;\r\n\t\t\t\t  border: 2px solid #fff;\r\n\t\t\t\t  background: #5bc0de;\r\n\t\t\t\t  padding: 6px 18px;\r\n\t\t\t\t  color: #fff;\r\n\t\t\t\t  font-size: 15px;\r\n\t\t\t\t  font-family: Trebuchet MS,sans-serif;\" \/>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t<input type=\"submit\" class=\"btn btn-info\" value=\"{{content.label}}\"\r\n\t\t   title=\"{{content.label}}\"\r\n\t\t   style=\"width: {{width}}px;\r\n\t\t          height: {{height}}px;\r\n\t\t          border: {{content.border.css.border}};\r\n\t\t          background: {{content.background}};\r\n\t\t          padding: 6px 10px;\r\n\t\t          color: {{content.fontColor}};\r\n\t\t          font-size: {{content.fontSize}}px;\r\n\t\t          font-family: {{content.fontFamily}};\" \/>\r\n\t{{\/content.store}}\r\n<\/form>\r\n{{#content.store}}\r\n<script type=\"text\/javascript\">\r\n\t(function() {\r\n\t\tvar alipay_sc = null;\r\n\t\tvar alipay_onsubmit = function(form) {\r\n\t\t\tif (('wb_MD5' in window) && (typeof window.wb_MD5 === 'function') && alipay_sc) {\r\n\t\t\t\tvar elems = form.elements;\r\n\t\t\t\tvar sign = '_input_charset=utf-8&apInitiateService_run=1&body='+ elems['subject'].value + '&currency=' + elems['currency'].value + '&notify_url=' + elems['notify_url'].value + '&out_trade_no=' + elems['out_trade_no'].value + '&partner=' + elems['partner'].value + '&service=create_forex_trade&subject=' + elems['subject'].value + '&total_fee=' + elems['total_fee'].value + alipay_sc;\r\n\t\t\t\t$('input[name=\"sign\"]', $(form)).val(wb_MD5(sign));\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t};\r\n\t\tvar alipay_onload = function(form) {\r\n\t\t\tform = $(form);\r\n\t\t\talipay_sc = form.attr('data-sc');\r\n\t\t\tform.removeAttr('data-sc');\r\n\t\t};\r\n\t\twindow.alipay_onsubmit = alipay_onsubmit;\r\n\t\twindow.alipay_onload = alipay_onload;\r\n\t})();\r\n<\/script>\r\n{{\/content.store}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/alipay/main.php';
PluginWrapper._config.active = true;
ElementRegister.registerPaymentGateway({
	name: __('Alipay'),
	id: 'alipay',
	pageUrl: 'https://global.alipay.com/',
	keyField: __('Partner'),
	keyFieldId: 'partner',
	keyField2: __('Security code'),
	keyField2Id: 'security_code',
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency'
});
PluginWrapper.registerPlugin('alipay', {
	name: __('Alipay'),
	element: {
		minSize: {width: 100, height: 30},
		defaultSize: {width: 160, height: 40},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Product description'), helpText: __('The name of the goods. Cannot contain special symbols')},
						{type: 'TextField', id: 'description'}
					]},

					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Amount'), helpText: __('Amount to be transferred. Range 0.01 ~ 1000000.00')},
						{type: 'TextField', id: 'amount'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Currency')},
						{type: 'DropdownBox', id: 'currency', options: [
							{id: '#GBP', name: 'GBP', value: 'GBP'},
							{id: '#HKD', name: 'HKD', value: 'HKD'},
							{id: '#USD', name: 'USD', value: 'USD'},
							{id: '#CHF', name: 'CHF', value: 'CHF'},
							{id: '#SGD', name: 'SGD', value: 'SGD'},
							{id: '#SEK', name: 'SEK', value: 'SEK'},
							{id: '#DKK', name: 'DKK', value: 'DKK'},
							{id: '#NOK', name: 'NOK', value: 'NOK'},
							{id: '#JPY', name: 'JPY', value: 'JPY'},
							{id: '#CAD', name: 'CAD', value: 'CAD'},
							{id: '#AUD', name: 'AUD', value: 'AUD'},
							{id: '#EUR', name: 'EUR', value: 'EUR'},
							{id: '#NZD', name: 'NZD', value: 'NZD'},
							{id: '#RUB', name: 'RUB', value: 'RUB'},
							{id: '#MOP', name: 'MOP', value: 'MOP'}
						]}
					]}
				]},
				{type: 'HorizontalLayout',css: {marginTop: 15}, columnWeights: [6, 6], children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Partner'), helpText: __('The ID of the partner on the Alipay system')},
						{type: 'TextField', id: 'partner'}
					]},									
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Security code'), helpText: __('Security key on the Alipay system')},
						{type: 'TextField', id: 'security'}
					]},									
				]},
				{type: 'VerticalLayout',css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Button Label'), helpText: __('Label name on submit button')},
						{type: 'TextField', id: 'label'}
					]},									
				]},
				{type: 'FlowLayout', spacing: 15, css: {marginTop: 15}, children: [
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Border')},
						{type: 'BorderSelector', id: 'border'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Background')},
						{type: 'ColorSelector', id: 'background'}
					]},
					{type: 'VerticalLayout', css: {width: 150}, children: [
						{type: 'Label', text: __('Font')},
						{type: 'FontFamilySelector', id: 'fontFamily', noFixedWidth: true}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Size')},
						{type: 'SizeSelector', id: 'fontSize'}
					]},
					{type: 'VerticalLayout', children: [
						{type: 'Label', text: __('Color')},
						{type: 'ColorSelector', id: 'fontColor', noTransparent: true}
					]}
				]}
			]}
		]
	},
	resizeAction: function(data, elem) {
		elem.find('.btn').eq(0).css({width: data.width, height: data.height});
	},
	openAction: function(fields, data, elem) {
		fields.description.setText(data.content.description);
		fields.label.setText(data.content.label);
		fields.security.setText(data.content.security);
		fields.partner.setText(data.content.partner);
		fields.amount.setText(data.content.amount);
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.border.setValue(data.content.border);
		fields.background.setValue(data.content.background);
		fields.fontFamily.setValue(data.content.fontFamily);
		fields.fontSize.setValue(data.content.fontSize);
		fields.fontColor.setValue(data.content.fontColor);
	},
	applyAction: function(fields, data, elem) {
		data.content.description = fields.description.getText();
		data.content.label = fields.label.getText();
		data.content.security = fields.security.getText();
		data.content.partner = fields.partner.getText();
		data.content.amount = fields.amount.getText();
		data.content.trade_no = Date.now();
		var itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.border = fields.border.getValue();
		data.content.background = fields.background.getValue();
		data.content.fontFamily = fields.fontFamily.getValue();
		data.content.fontSize = fields.fontSize.getValue();
		data.content.fontColor = fields.fontColor.getValue();
	},
	loadAction: function(data) {
		if (!data.content.description) data.content.description = __('Product description');
		if (!data.content.label) data.content.label = 'Pay via Alipay';
		if (!data.content.security) data.content.security = '';
		if (!data.content.amount) data.content.amount = '1';
		if (!data.content.trade_no) data.content.trade_no = '';
		if (!data.content.currency) data.content.currency = 'USD';
		if (!data.content.border) data.content.border = {
			color: '#fff',
			style: 'solid',
			weight: 2,
			css: { border: '2px solid #fff' }
		};
		if (!data.content.background) data.content.background = '#5bc0de';
		if (!data.content.fontFamily) data.content.fontFamily = 'Trebuchet MS,sans-serif';
		if (!data.content.fontSize) data.content.fontSize = '15';
		if (!data.content.fontColor) data.content.fontColor = '#fff';
		if (!data.content.partner) data.content.partner = '';
	}
});
});
require(['ElementRegister', 'PluginApi/PluginWrapper'], function(ElementRegister, PluginWrapper) {
    var pluginData = {"id":"stripe","extReferenceId":null};
PluginWrapper._config.icon = "http:\/\/sitepro4.mychrome.pt\/plugins\/stripe\/main.png";
PluginWrapper._config.template = "{{^isPublished}}\r\n<link rel=\"stylesheet\" type=\"text\/css\" href=\"https:\/\/checkout.stripe.com\/v3\/checkout\/button-qpwW2WfkB0oGWVWIASjIOQ.css\" \/>\r\n<button type=\"submit\" class=\"stripe-button-el\" style=\"visibility: visible;\">\r\n\t<span style=\"display: block; min-height: 30px;\">{{#content.label}}{{content.label}}{{\/content.label}}{{^content.label}}Pay with Card{{\/content.label}}<\/span>\r\n<\/button>\r\n{{\/isPublished}}\r\n{{#isPublished}}\r\n\t{{#content.store}}\r\n\t\t<link rel=\"stylesheet\" type=\"text\/css\" href=\"https:\/\/checkout.stripe.com\/v3\/checkout\/button-qpwW2WfkB0oGWVWIASjIOQ.css\" \/>\r\n\t\t<form action=\"\" method=\"post\" data-gateway-id=\"Stripe\" id=\"{{id}}_stripe_form\">\r\n\t\t\t<input type=\"hidden\" name=\"transactionId\" value=\"{transactionId}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"amount\" value=\"{{content.amount}}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"currency\" value=\"{{content.currency}}\" \/>\r\n\t\t\t<input type=\"hidden\" name=\"description\" value=\"{{content.description}}\" \/>\r\n\t\t\t<button id=\"{{id}}_stripe_button\" type=\"submit\" class=\"stripe-button-el\" style=\"visibility: visible;\" disabled=\"disabled\">\r\n\t\t\t\t<span style=\"display: block; min-height: 30px;\">{{#content.label}}{{content.label}}{{\/content.label}}{{^content.label}}Pay with Card{{\/content.label}}<\/span>\r\n\t\t\t<\/button>\r\n\t\t<\/form>\r\n\t\t<script type=\"text\/javascript\" src=\"https:\/\/checkout.stripe.com\/checkout.js\"><\/script>\r\n\t\t<script type=\"text\/javascript\">\r\n\t\t\t(function() {\r\n\t\t\t\tvar handler = null;\r\n\t\t\t\t$('#{{id}}_stripe_form').on('beforesend', function() {\r\n\t\t\t\t\thandler.open({\r\n\t\t\t\t\t\tname: '{{content.description}}',\r\n\t\t\t\t\t\tamount: this.elements['amount'].value * 100,\r\n\t\t\t\t\t\tcurrency: '{{content.currency}}'\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t\tvar stripeOnReady = function() {\r\n\t\t\t\t\tif (!window.StripeCheckout) {\r\n\t\t\t\t\t\tsetTimeout(stripeOnReady, 50);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t$('#{{id}}_stripe_button').removeAttr('disabled');\r\n\t\t\t\t\t\thandler = StripeCheckout.configure({\r\n\t\t\t\t\t\t\tkey: '{{content.publishable_key}}',\r\n\t\t\t\t\t\t\tlocale: '{currLang}',\r\n\t\t\t\t\t\t\ttoken: function(token) {\r\n\t\t\t\t\t\t\t\tvar params = {\r\n\t\t\t\t\t\t\t\t\tstripeToken: token.id,\r\n\t\t\t\t\t\t\t\t\tstripeEmail: token.email\r\n\t\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t\t\tvar qs = '';\r\n\t\t\t\t\t\t\t\tfor (var i in params) qs += (i + '=' + encodeURIComponent(params[i]) + '&');\r\n\t\t\t\t\t\t\t\tqs = qs.substring(0, qs.length - 1);\r\n\t\t\t\t\t\t\t\tlocation.href = '{callbackUrl}' + '\/?' + qs;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t\tstripeOnReady();\r\n\t\t\t})();\r\n\t\t<\/script>\r\n\t{{\/content.store}}\r\n\t{{^content.store}}\r\n\t\t{{{requireService}}}\r\n\t{{\/content.store}}\r\n{{\/isPublished}}";
PluginWrapper._config.serviceUrl = 'http://sitepro4.mychrome.pt/plugins/stripe/main.php';
PluginWrapper._config.active = true;
ElementRegister.registerPaymentGateway({
	name: 'Stripe',
	id: 'stripe',
	pageUrl: 'https://stripe.com/',
	keyField: __('Publishable Key'),
	keyFieldId: 'publishable_key',
	keyField2: __('Secret Key'),
	keyField2Id: 'secret_key',
	titleFieldId: 'label',
	nameFieldId: 'description',
	priceFieldId: 'amount',
	currencyFieldId: 'currency',
	globalVars: ['secret_key']
});
PluginWrapper.registerPlugin('stripe', {
	name: 'Stripe',
	element: {
		minSize: {width: 68, height: 34},
		defaultSize: {width: 120, height: 34},
		resizable: true
	},
	propertyDialog: {
		noScroll: true,
		tabs: [
			{children: [
				{type: 'VerticalLayout', spacing: 15, children: [
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Publishable Key'), helpText: __('Your publishable key')},
							{type: 'TextField', id: 'publishable_key'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Secret Key'), helpText: __('Your secret key')},
							{type: 'TextField', id: 'secret_key'}
						]}
					]},
					{type: 'HorizontalLayout', columnWeights: [6, 3, 3], css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Item Name')},
							{type: 'TextField', id: 'description'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Amount')},
							{type: 'TextField', id: 'amount'}
						]},
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Currency')},
							{type: 'DropdownBox', id: 'currency', options: [
								{id: '#USD', name: 'USD', value: 'USD'},
								{id: '#EUR', name: 'EUR', value: 'EUR'},
								{id: '#AED', name: 'AED', value: 'AED'},
								{id: '#AFN', name: 'AFN', value: 'AFN'},
								{id: '#ALL', name: 'ALL', value: 'ALL'},
								{id: '#AMD', name: 'AMD', value: 'AMD'},
								{id: '#ANG', name: 'ANG', value: 'ANG'},
								{id: '#AOA', name: 'AOA', value: 'AOA'},
								{id: '#AUD', name: 'AUD', value: 'AUD'},
								{id: '#AWG', name: 'AWG', value: 'AWG'},
								{id: '#AZN', name: 'AZN', value: 'AZN'},
								{id: '#BAM', name: 'BAM', value: 'BAM'},
								{id: '#BBD', name: 'BBD', value: 'BBD'},
								{id: '#BDT', name: 'BDT', value: 'BDT'},
								{id: '#BGN', name: 'BGN', value: 'BGN'},
								{id: '#BIF', name: 'BIF', value: 'BIF'},
								{id: '#BMD', name: 'BMD', value: 'BMD'},
								{id: '#BND', name: 'BND', value: 'BND'},
								{id: '#BOB', name: 'BOB', value: 'BOB'},
								{id: '#BRL', name: 'BRL', value: 'BRL'},
								{id: '#BSD', name: 'BSD', value: 'BSD'},
								{id: '#BWP', name: 'BWP', value: 'BWP'},
								{id: '#BZD', name: 'BZD', value: 'BZD'},
								{id: '#CAD', name: 'CAD', value: 'CAD'},
								{id: '#CDF', name: 'CDF', value: 'CDF'},
								{id: '#CHF', name: 'CHF', value: 'CHF'},
								{id: '#CLP', name: 'CLP', value: 'CLP'},
								{id: '#CNY', name: 'CNY', value: 'CNY'},
								{id: '#COP', name: 'COP', value: 'COP'},
								{id: '#CRC', name: 'CRC', value: 'CRC'},
								{id: '#CVE', name: 'CVE', value: 'CVE'},
								{id: '#CZK', name: 'CZK', value: 'CZK'},
								{id: '#DJF', name: 'DJF', value: 'DJF'},
								{id: '#DKK', name: 'DKK', value: 'DKK'},
								{id: '#DOP', name: 'DOP', value: 'DOP'},
								{id: '#DZD', name: 'DZD', value: 'DZD'},
								{id: '#EGP', name: 'EGP', value: 'EGP'},
								{id: '#ETB', name: 'ETB', value: 'ETB'},
								{id: '#FJD', name: 'FJD', value: 'FJD'},
								{id: '#FKP', name: 'FKP', value: 'FKP'},
								{id: '#GBP', name: 'GBP', value: 'GBP'},
								{id: '#GEL', name: 'GEL', value: 'GEL'},
								{id: '#GIP', name: 'GIP', value: 'GIP'},
								{id: '#GMD', name: 'GMD', value: 'GMD'},
								{id: '#GNF', name: 'GNF', value: 'GNF'},
								{id: '#GTQ', name: 'GTQ', value: 'GTQ'},
								{id: '#GYD', name: 'GYD', value: 'GYD'},
								{id: '#HKD', name: 'HKD', value: 'HKD'},
								{id: '#HNL', name: 'HNL', value: 'HNL'},
								{id: '#HRK', name: 'HRK', value: 'HRK'},
								{id: '#HTG', name: 'HTG', value: 'HTG'},
								{id: '#HUF', name: 'HUF', value: 'HUF'},
								{id: '#IDR', name: 'IDR', value: 'IDR'},
								{id: '#ILS', name: 'ILS', value: 'ILS'},
								{id: '#INR', name: 'INR', value: 'INR'},
								{id: '#ISK', name: 'ISK', value: 'ISK'},
								{id: '#JMD', name: 'JMD', value: 'JMD'},
								{id: '#JPY', name: 'JPY', value: 'JPY'},
								{id: '#KES', name: 'KES', value: 'KES'},
								{id: '#KGS', name: 'KGS', value: 'KGS'},
								{id: '#KHR', name: 'KHR', value: 'KHR'},
								{id: '#KMF', name: 'KMF', value: 'KMF'},
								{id: '#KRW', name: 'KRW', value: 'KRW'},
								{id: '#KYD', name: 'KYD', value: 'KYD'},
								{id: '#KZT', name: 'KZT', value: 'KZT'},
								{id: '#LAK', name: 'LAK', value: 'LAK'},
								{id: '#LBP', name: 'LBP', value: 'LBP'},
								{id: '#LKR', name: 'LKR', value: 'LKR'},
								{id: '#LRD', name: 'LRD', value: 'LRD'},
								{id: '#LSL', name: 'LSL', value: 'LSL'},
								{id: '#MAD', name: 'MAD', value: 'MAD'},
								{id: '#MDL', name: 'MDL', value: 'MDL'},
								{id: '#MGA', name: 'MGA', value: 'MGA'},
								{id: '#MKD', name: 'MKD', value: 'MKD'},
								{id: '#MMK', name: 'MMK', value: 'MMK'},
								{id: '#MNT', name: 'MNT', value: 'MNT'},
								{id: '#MOP', name: 'MOP', value: 'MOP'},
								{id: '#MRO', name: 'MRO', value: 'MRO'},
								{id: '#MUR', name: 'MUR', value: 'MUR'},
								{id: '#MVR', name: 'MVR', value: 'MVR'},
								{id: '#MWK', name: 'MWK', value: 'MWK'},
								{id: '#MXN', name: 'MXN', value: 'MXN'},
								{id: '#MYR', name: 'MYR', value: 'MYR'},
								{id: '#MZN', name: 'MZN', value: 'MZN'},
								{id: '#NAD', name: 'NAD', value: 'NAD'},
								{id: '#NGN', name: 'NGN', value: 'NGN'},
								{id: '#NIO', name: 'NIO', value: 'NIO'},
								{id: '#NOK', name: 'NOK', value: 'NOK'},
								{id: '#NPR', name: 'NPR', value: 'NPR'},
								{id: '#NZD', name: 'NZD', value: 'NZD'},
								{id: '#PAB', name: 'PAB', value: 'PAB'},
								{id: '#PEN', name: 'PEN', value: 'PEN'},
								{id: '#PGK', name: 'PGK', value: 'PGK'},
								{id: '#PHP', name: 'PHP', value: 'PHP'},
								{id: '#PKR', name: 'PKR', value: 'PKR'},
								{id: '#PLN', name: 'PLN', value: 'PLN'},
								{id: '#PYG', name: 'PYG', value: 'PYG'},
								{id: '#QAR', name: 'QAR', value: 'QAR'},
								{id: '#RON', name: 'RON', value: 'RON'},
								{id: '#RSD', name: 'RSD', value: 'RSD'},
								{id: '#RUB', name: 'RUB', value: 'RUB'},
								{id: '#RWF', name: 'RWF', value: 'RWF'},
								{id: '#SAR', name: 'SAR', value: 'SAR'},
								{id: '#SBD', name: 'SBD', value: 'SBD'},
								{id: '#SCR', name: 'SCR', value: 'SCR'},
								{id: '#SEK', name: 'SEK', value: 'SEK'},
								{id: '#SGD', name: 'SGD', value: 'SGD'},
								{id: '#SHP', name: 'SHP', value: 'SHP'},
								{id: '#SLL', name: 'SLL', value: 'SLL'},
								{id: '#SOS', name: 'SOS', value: 'SOS'},
								{id: '#SRD', name: 'SRD', value: 'SRD'},
								{id: '#STD', name: 'STD', value: 'STD'},
								{id: '#SVC', name: 'SVC', value: 'SVC'},
								{id: '#SZL', name: 'SZL', value: 'SZL'},
								{id: '#THB', name: 'THB', value: 'THB'},
								{id: '#TJS', name: 'TJS', value: 'TJS'},
								{id: '#TOP', name: 'TOP', value: 'TOP'},
								{id: '#TRY', name: 'TRY', value: 'TRY'},
								{id: '#TTD', name: 'TTD', value: 'TTD'},
								{id: '#TWD', name: 'TWD', value: 'TWD'},
								{id: '#TZS', name: 'TZS', value: 'TZS'},
								{id: '#UAH', name: 'UAH', value: 'UAH'},
								{id: '#UGX', name: 'UGX', value: 'UGX'},
								{id: '#UYU', name: 'UYU', value: 'UYU'},
								{id: '#UZS', name: 'UZS', value: 'UZS'},
								{id: '#VND', name: 'VND', value: 'VND'},
								{id: '#VUV', name: 'VUV', value: 'VUV'},
								{id: '#WST', name: 'WST', value: 'WST'},
								{id: '#XAF', name: 'XAF', value: 'XAF'},
								{id: '#XCD', name: 'XCD', value: 'XCD'},
								{id: '#XOF', name: 'XOF', value: 'XOF'},
								{id: '#XPF', name: 'XPF', value: 'XPF'},
								{id: '#YER', name: 'YER', value: 'YER'},
								{id: '#ZAR', name: 'ZAR', value: 'ZAR'},
								{id: '#ZMW', name: 'ZMW', value: 'ZMW'}
							]}
						]}
					]},
					{type: 'HorizontalLayout', css: {marginTop: 15}, children: [
						{type: 'VerticalLayout', children: [
							{type: 'Label', text: __('Button Label'), helpText: __('The text to be shown on the blue button.')},
							{type: 'TextField', id: 'label'}
						]}
					]}
				]}
			]}
		]
	},
	openAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getItemById('#' + data.content.currency);
		fields.currency.selectItem(itm);
		fields.description.setText(data.content.description);
		fields.amount.setText(data.content.amount);
		fields.publishable_key.setText(data.content.publishable_key);
		fields.secret_key.setText(data.content.secret_key);
		fields.label.setText(data.content.label);
	},
	applyAction: function (fields, data, elem) {
		var itm;
		itm = fields.currency.getSelectedItem();
		data.content.currency = itm.getOriginal().value;
		data.content.description = fields.description.getText();
		data.content.amount = fields.amount.getText();
		data.content.publishable_key = fields.publishable_key.getText();
		data.content.secret_key = fields.secret_key.getText();
		data.content.label = fields.label.getText();
	},
	loadAction: function (data) {
		if (!data.content.description)
			data.content.description = ''; // Items description
		if (!data.content.amount)
			data.content.amount = '1'; // 999
		if (!data.content.currency)
			data.content.currency = 'EUR';
		if (!data.content.publishable_key)
			data.content.publishable_key = '';
		if (!data.content.secret_key)
			data.content.secret_key = ''; // pk_test_6pRNASCoBOKtIshFeQd4XMUh
		if (!data.content.label)
			data.content.label = 'Pay with Card';
	}
});});
};
