wincanton.service-now.com
Open in
urlscan Pro
148.139.16.212
Public Scan
URL:
https://wincanton.service-now.com/scripts/sn/concourse/js_includes_concourse.jsx
Submission: On October 06 via manual from US — Scanned from GB
Submission: On October 06 via manual from US — Scanned from GB
Form analysis
0 forms found in the DOMText Content
/*! RESOURCE: /scripts/sn/concourse/js_includes_concourse.js */ /*! RESOURCE: /scripts/lib/jquery2_includes.js */ /*! RESOURCE: /scripts/lib/jquery/jquery_clean.js */ (function() { if (!window.jQuery) return; if (!window.$j_glide) window.$j = jQuery.noConflict(); if (window.$j_glide && jQuery != window.$j_glide) { if (window.$j_glide) jQuery.noConflict(true); window.$j = window.$j_glide; } })(); ; /*! RESOURCE: /scripts/lib/jquery/jquery-2.2.3-legacy.min.js */ /*! jQuery v2.2.3-snc3-legacy | (c) jQuery Foundation | 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=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.3-snc3-legacy",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?a<0?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c<b?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.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||n.isFunction(g)||(g={}),h===i&&(g=this,h--);h<i;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],"__proto__"!==b&&g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;(a=n.trim(a))&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;d<c;d++)if(!1===b.call(a[d],d,a[d]))break}else for(d in a)if(!1===b.call(a[d],d,a[d]))break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;d<c;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;f<g;f++)(d=!b(a[f],f))!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;g<d;g++)null!=(e=b(a[g],g,c))&&h.push(e);else for(g in a)null!=(e=b(a[g],g,c))&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;if("string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a))return d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"!==c&&!n.isWindow(a)&&("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a)}var t=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=fa(),z=fa(),A=fa(),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;c<d;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="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),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")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(xa){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 ea(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+pa(r[h]);s=r.join(","),w=_.test(a)&&na(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function fa(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ga(a){return a[u]=!0,a}function ha(a){var b=n.createElement("div");try{return!!a(b)}catch(xa){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ia(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ja(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 ka(a){return function(b){return"input"===b.nodeName.toLowerCase()&&b.type===a}}function la(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function ma(a){return ga(function(b){return b=+b,ga(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 na(a){return a&&void 0!==a.getElementsByTagName&&a}c=ea.support={},f=ea.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ea.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ha(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ha(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ha(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(void 0!==b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c=void 0!==a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return void 0!==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){if(void 0!==b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ha(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' 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(".#.+[+~]")}),ha(function(a){var b=n.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=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ha(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.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=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||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,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ja(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ja(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ea.matches=function(a,b){return ea(a,null,null,b)},ea.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!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(xa){}return ea(b,n,null,[a]).length>0},ea.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ea.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},ea.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ea.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=ea.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=ea.selectors={cacheLength:50,createPseudo:ga,match:W,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(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===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]||ea.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]&&ea.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.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(ba,ca).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||void 0!==a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ea.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(P," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},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,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),!1===t)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return(t-=e)===d||t%d==0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ea.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ga(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:ga(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ga(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:ga(function(a){return function(b){return ea(a,b).length>0}}),contains:ga(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ga(function(a){return V.test(a||"")||ea.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do{if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return(c=c.toLowerCase())===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!1===a.disabled},disabled:function(a){return!0===a.disabled},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,!0===a.selected},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 Y.test(a.nodeName)},input:function(a){return X.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:ma(function(){return[0]}),last:ma(function(a,b){return[b-1]}),eq:ma(function(a,b,c){return[c<0?c+b:c]}),even:ma(function(a,b){for(var c=0;c<b;c+=2)a.push(c);return a}),odd:ma(function(a,b){for(var c=1;c<b;c+=2)a.push(c);return a}),lt:ma(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:ma(function(a,b,c){for(var d=c<0?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]=ka(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=la(b);function oa(){}oa.prototype=d.filters=d.pseudos,d.setFilters=new oa,g=ea.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=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[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?ea.error(a):z(a,i).slice(0)};function pa(a){for(var b=0,c=a.length,d="";b<c;b++)d+=a[b].value;return d}function qa(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,k=[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(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function ra(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 sa(a,b,c){for(var d=0,e=b.length;d<e;d++)ea(a,b[d],c);return c}function ta(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;h<i;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function ua(a,b,c,d,e,f){return d&&!d[u]&&(d=ua(d)),e&&!e[u]&&(e=ua(e,f)),ga(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||sa(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ta(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ta(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=ta(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function va(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=qa(function(a){return a===b},h,!0),l=qa(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}];i<f;i++)if(c=d.relative[a[i].type])m=[qa(ra(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;e<f;e++)if(d.relative[a[e].type])break;return ua(i>1&&ra(m),i>1&&pa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,i<e&&va(a.slice(i,e)),e<f&&va(a=a.slice(e)),e<f&&pa(a))}m.push(c)}return ra(m)}function wa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ta(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ea.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ga(f):f}return h=ea.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=va(b[c]),f[u]?d.push(f):e.push(f);f=A(a,wa(e,d)),f.selector=a}return f},i=ea.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(ba,ca),b)||[])[0]))return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.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(ba,ca),_.test(j[0].type)&&na(b.parentNode)||b))){if(j.splice(i,1),!(a=f.length&&pa(j)))return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&na(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ha(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ha(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ia("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ha(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ia("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ha(function(a){return null==a.getAttribute("disabled")})||ia(K,function(a,b,c){var d;if(!c)return!0===a[b]?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ea}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;b<c;b++)if(n.contains(e[b],this))return!0}));for(b=0;b<c;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/;(n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(!(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a))||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))}).prototype=n.fn,A=n(d);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;a<c;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;d<e;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||n.uniqueSort(e),C.test(a)&&e.reverse()),this.pushStack(e)}});var F=/\S+/g;function G(a){var b={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)!1===f[h].apply(c[0],c[1])&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function b(c){n.each(c,function(c,d){n.isFunction(d)?a.unique&&j.has(d)||f.push(d):d&&d.length&&"string"!==n.type(d)&&b(d)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.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=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);b<d;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(!0===a?--n.readyWait:n.isReady)||(n.isReady=!0,!0!==a&&--n.readyWait>0||(H.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function I(){d.removeEventListener("DOMContentLoaded",I),a.removeEventListener("load",I),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",I),a.addEventListener("load",I))),H.promise(b)},n.ready.promise();var J=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)J(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;h<i;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},K=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function L(){this.expando=n.expando+L.uid++}L.uid=1,L.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!K(a))return{};var b=a[this.expando];return b||(b={},K(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(F)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var M=new L,N=new L,O=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,P=/[A-Z]/g;function Q(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(P,"-$&").toLowerCase(),"string"==typeof(c=a.getAttribute(d))){try{c="true"===c||"false"!==c&&("null"===c?null:+c+""===c?+c:O.test(c)?n.parseJSON(c):c) }catch(e){}N.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return N.hasData(a)||M.hasData(a)},data:function(a,b,c){return N.access(a,b,c)},removeData:function(a,b){N.remove(a,b)},_data:function(a,b,c){return M.access(a,b,c)},_removeData:function(a,b){M.remove(a,b)}}),n.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=N.get(f),1===f.nodeType&&!M.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),Q(f,d,e[d])));M.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){N.set(this,a)}):J(this,function(b){var c,d;if(f&&void 0===b){if(void 0!==(c=N.get(f,a)||N.get(f,a.replace(P,"-$&").toLowerCase())))return c;if(d=n.camelCase(a),void 0!==(c=N.get(f,d)))return c;if(void 0!==(c=Q(f,d,void 0)))return c}else d=n.camelCase(a),this.each(function(){var c=N.get(this,d);N.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&N.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){N.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=M.get(a,b),c&&(!d||n.isArray(c)?d=M.access(a,b,n.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.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.get(a,c)||M.access(a,c,{empty:n.Callbacks("once memory").add(function(){M.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.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.get(f[g],a+"queueHooks"))&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var R=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,S=new RegExp("^(?:([+-])=|)("+R+")([a-z%]*)$","i"),T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function V(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&S.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do{f=f||".5",k/=f,n.style(a,b,k+j)}while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var W=/^(?:checkbox|radio)$/i,X=/<([\w:-]+)/,Y=/^$|\/(?:java|ecma)script/i;!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,b.innerHTML="<option></option>",l.option=!!b.lastChild}();var Z={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};Z.tbody=Z.tfoot=Z.colgroup=Z.caption=Z.thead,Z.th=Z.td,l.option||(Z.optgroup=Z.option=[1,"<select multiple='multiple'>","</select>"]);function $(a,b){var c=void 0!==a.getElementsByTagName?a.getElementsByTagName(b||"*"):void 0!==a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function _(a,b){for(var c=0,d=a.length;c<d;c++)M.set(a[c],"globalEval",!b||M.get(b[c],"globalEval"))}var aa=/<|&#?\w+;/;function ba(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;o<p;o++)if((f=a[o])||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(aa.test(f)){g=g||l.appendChild(b.createElement("div")),h=(X.exec(f)||["",""])[1].toLowerCase(),i=Z[h]||Z._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=$(l.appendChild(f),"script"),j&&_(g),c){k=0;while(f=g[k++])Y.test(f.type||"")&&c.push(f)}return l}var ca=/^key/,da=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ea=/^([^.]*)(?:\.(.+)|)/;function fa(){return!0}function ga(){return!1}function ha(){try{return d.activeElement}catch(a){}}function ia(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ia(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),!1===e)e=ga;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=M.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return void 0!==n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(F)||[""],j=b.length;while(j--)h=ea.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&!1!==l.setup.call(a,d,p,g)||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=M.hasData(a)&&M.get(a);if(r&&(i=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ea.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&!1!==l.teardown.call(a,p,r.handle)||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&M.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(M.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||!1!==k.preDispatch.call(this,a)){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,void 0!==(d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i))&&!1===(a.result=d)&&(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&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(!0!==i.disabled||"click"!==a.type)){for(d=[],c=0;c<h;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget detail 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||d,e=c.documentElement,f=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=da.test(f)?this.mouseHooks:ca.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=d),3===a.target.nodeType&&(a.target=a.target.parentNode),h.filter?h.filter(a,g):a},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ha()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===ha()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&n.nodeName(this,"input"))return this.click(),!1},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},n.Event=function(a,b){if(!(this instanceof n.Event))return new n.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&!1===a.returnValue?fa:ga):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),this[n.expando]=!0},n.Event.prototype={constructor:n.Event,isDefaultPrevented:ga,isPropagationStopped:ga,isImmediatePropagationStopped:ga,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=fa,a&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=fa,a&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=fa,a&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),n.fn.extend({on:function(a,b,c,d){return ia(this,a,b,c,d)},one:function(a,b,c,d){return ia(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(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!1!==b&&"function"!=typeof b||(c=b,b=void 0),!1===c&&(c=ga),this.each(function(){n.event.remove(this,a,c,b)})}});var ja=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,ka=/<script|<style|<link/i,la=/checked\s*(?:[^=]|=\s*.checked.)/i,ma=/^true\/(.*)/,na=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function oa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function pa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function qa(a){var b=ma.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ra(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(M.hasData(a)&&(f=M.access(a),g=M.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c<d;c++)n.event.add(b,e,j[e][c])}N.hasData(a)&&(h=N.access(a),i=n.extend({},h),N.set(b,i))}}function sa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&W.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ta(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&la.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ta(f,b,c,d)});if(o&&(e=ba(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map($(e,"script"),pa),i=h.length;m<o;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,$(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,qa),m=0;m<i;m++)j=h[m],Y.test(j.type||"")&&!M.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(na,"")))}return a}function ua(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData($(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&_($(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ja,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=$(h),f=$(a),d=0,e=f.length;d<e;d++)sa(f[d],g[d]);if(b)if(c)for(f=f||$(a),g=g||$(h),d=0,e=f.length;d<e;d++)ra(f[d],g[d]);else ra(a,h);return g=$(h,"script"),g.length>0&&_(g,!i&&$(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(K(c)){if(b=c[M.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[M.expando]=void 0}c[N.expando]&&(c[N.expando]=void 0)}}}),n.fn.extend({domManip:ta,detach:function(a){return ua(this,a,!0)},remove:function(a){return ua(this,a)},text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ta(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){oa(this,a).appendChild(a)}})},prepend:function(){return ta(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=oa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ta(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ta(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData($(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!ka.test(a)&&!Z[(X.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;c<d;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData($(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ta(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData($(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;h<=f;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var va,wa={HTML:"block",BODY:"block"};function xa(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function ya(a){var b=d,c=wa[a];return c||(c=xa(a,b),"none"!==c&&c||(va=(va||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=va[0].contentDocument,b.write(),b.close(),c=xa(a,b),va.detach()),wa[a]=c),c}var za=/^margin/,Aa=new RegExp("^("+R+")(?!px)[a-z%]+$","i"),Ba=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Ca=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},Da=d.documentElement;!function(){var b,c,e,f,g=d.createElement("div"),h=d.createElement("div");function i(){h.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",h.innerHTML="",Da.appendChild(g);var d=a.getComputedStyle(h);b="1%"!==d.top,f="2px"===d.marginLeft,c="4px"===d.width,h.style.marginRight="50%",e="4px"===d.marginRight,Da.removeChild(g)}h.style&&(h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,g.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",g.appendChild(h),n.extend(l,{pixelPosition:function(){return i(),b},boxSizingReliable:function(){return null==c&&i(),c},pixelMarginRight:function(){return null==c&&i(),e},reliableMarginLeft:function(){return null==c&&i(),f},reliableMarginRight:function(){var b,c=h.appendChild(d.createElement("div"));return c.style.cssText=h.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",h.style.width="1px",Da.appendChild(g),b=!parseFloat(a.getComputedStyle(c).marginRight),Da.removeChild(g),h.removeChild(c),b}}))}();function Ea(a,b,c){var d,e,f,g,h=a.style;return c=c||Ba(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Aa.test(g)&&za.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}function Fa(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Ga=/^(none|table(?!-c[ea]).+)/,Ha={position:"absolute",visibility:"hidden",display:"block"},Ia={letterSpacing:"0",fontWeight:"400"},Ja=["Webkit","O","Moz","ms"],Ka=d.createElement("div").style;function La(a){if(a in Ka)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ja.length;while(c--)if((a=Ja[c]+b)in Ka)return a}function Ma(a,b,c){var d=S.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Na(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;f<4;f+=2)"margin"===c&&(g+=n.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+T[f]+"Width",!0,e))):(g+=n.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+T[f]+"Width",!0,e)));return g}function Oa(b,c,e){var f=!0,g="width"===c?b.offsetWidth:b.offsetHeight,h=Ba(b),i="border-box"===n.css(b,"boxSizing",!1,h);if(d.msFullscreenElement&&a.top!==a&&b.getClientRects().length&&(g=Math.round(100*b.getBoundingClientRect()[c])),g<=0||null==g){if(g=Ea(b,c,h),(g<0||null==g)&&(g=b.style[c]),Aa.test(g))return g;f=i&&(l.boxSizingReliable()||g===b.style[c]),g=parseFloat(g)||0}return g+Na(b,c,e||(i?"border":"content"),f,h)+"px"}function Pa(a,b){for(var c,d,e,f=[],g=0,h=a.length;g<h;g++)d=a[g],d.style&&(f[g]=M.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=M.access(d,"olddisplay",ya(d.nodeName)))):(e=U(d),"none"===c&&e||M.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;g<h;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ea(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,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:"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=La(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];f=typeof c,"string"===f&&(e=S.exec(c))&&e[1]&&(c=V(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c))}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=La(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Ea(a,b,d)),"normal"===e&&b in Ia&&(e=Ia[b]),""===c||c?(f=parseFloat(e),!0===c||isFinite(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){if(c)return Ga.test(n.css(a,"display"))&&0===a.offsetWidth?Ca(a,Ha,function(){return Oa(a,b,d)}):Oa(a,b,d)},set:function(a,c,d){var e,f=d&&Ba(a),g=d&&Na(a,b,d,"border-box"===n.css(a,"boxSizing",!1,f),f);return g&&(e=S.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=n.css(a,b)),Ma(a,c,g)}}}),n.cssHooks.marginLeft=Fa(l.reliableMarginLeft,function(a,b){if(b)return(parseFloat(Ea(a,"marginLeft"))||a.getBoundingClientRect().left-Ca(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px"}),n.cssHooks.marginRight=Fa(l.reliableMarginRight,function(a,b){if(b)return Ca(a,{display:"inline-block"},Ea,[a,"marginRight"])}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];d<4;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},za.test(a)||(n.cssHooks[a+b].set=Ma)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ba(a),e=b.length;g<e;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Pa(this,!0)},hide:function(){return Pa(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?n(this).show():n(this).hide()})}});function Qa(a,b,c,d,e){return new Qa.prototype.init(a,b,c,d,e)}n.Tween=Qa,Qa.prototype={constructor:Qa,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Qa.propHooks[this.prop];return a&&a.get?a.get(this):Qa.propHooks._default.get(this)},run:function(a){var b,c=Qa.propHooks[this.prop];return this.options.duration?this.pos=b=n.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):Qa.propHooks._default.set(this),this}},Qa.prototype.init.prototype=Qa.prototype,Qa.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},Qa.propHooks.scrollTop=Qa.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=Qa.prototype.init,n.fx.step={};var Ra,Sa,Ta=/^(?:toggle|show|hide)$/,Ua=/queueHooks$/;function Va(){return a.setTimeout(function(){Ra=void 0}),Ra=n.now()}function Wa(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=T[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Xa(a,b,c){for(var d,e=($a.tweeners[b]||[]).concat($a.tweeners["*"]),f=0,g=e.length;f<g;f++)if(d=e[f].call(c,b,a))return d}function Ya(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&U(a),q=M.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),"inline"===(k="none"===j?M.get(a,"olddisplay")||ya(a.nodeName):j)&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Ta.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?ya(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=M.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;M.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Xa(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Za(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),(g=n.cssHooks[d])&&"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 $a(a,b,c){var d,e,f=0,g=$a.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Ra||Va(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;g<i;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),f<1&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:Ra||Va(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.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;c<d;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Za(k,j.opts.specialEasing);f<g;f++)if(d=$a.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,Xa,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.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)}n.Animation=n.extend($a,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return V(c.elem,a,S.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(F);for(var c,d=0,e=a.length;d<e;d++)c=a[d],$a.tweeners[c]=$a.tweeners[c]||[],$a.tweeners[c].unshift(b)},prefilters:[Ya],prefilter:function(a,b){b?$a.prefilters.unshift(a):$a.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&!0!==d.queue||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.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=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=$a(this,n.extend({},a),f);(e||M.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||!1===f.queue?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&&!1!==a&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=M.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Ua.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||n.dequeue(this,a)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var b,c=M.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.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;b<g;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Wa(b,!0),a,d,e)}}),n.each({slideDown:Wa("show"),slideUp:Wa("hide"),slideToggle:Wa("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Ra=n.now();b<c.length;b++)(a=c[b])()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Ra=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Sa||(Sa=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(Sa),Sa=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=d.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var _a,ab=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return void 0===a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?_a:void 0)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)}}),_a={set:function(a,b,c){return!1===b?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ab[b]||n.find.attr;ab[b]=function(a,b,d){var e,f;return d||(f=ab[b],ab[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ab[b]=f),e}});var bb=/^(?:input|select|textarea|button)$/i,cb=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b, e=n.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=n.find.attr(a,"tabindex");return b?parseInt(b,10):bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var db=/[\t\r\n\f]/g;function eb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,eb(this)))});if("string"==typeof a&&a){b=a.match(F)||[];while(c=this[i++])if(e=eb(c),d=1===c.nodeType&&(" "+e+" ").replace(db," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,eb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(F)||[];while(c=this[i++])if(e=eb(c),d=1===c.nodeType&&(" "+e+" ").replace(db," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,eb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=eb(this),b&&M.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||!1===a?"":M.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+eb(c)+" ").replace(db," ").indexOf(b)>-1)return!0;return!1}});var fb=/\r/g,gb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),(b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()])&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return(b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()])&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(fb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(gb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||e<0,g=f?null:[],h=f?e+1:d.length,i=e<0?h:f?e:0;i<h;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){if(n.isArray(b))return a.checked=n.inArray(n(a).val(),b)>-1}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var hb=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!hb.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||!1!==o.trigger.apply(e,c))){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,hb.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(M.get(h,"events")||{})[b.type]&&M.get(h,"handle"),m&&m.apply(h,c),(m=l&&h[l])&&m.apply&&K(h)&&(b.result=m.apply(h,c),!1===b.result&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&!1!==o._default.apply(p.pop(),c)||!K(e)||l&&n.isFunction(e[q])&&!n.isWindow(e)&&(i=e[l],i&&(e[l]=null),n.event.triggered=q,e[q](),n.event.triggered=void 0,i&&(e[l]=i)),b.result}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}}),n.fn.extend({trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return n.event.trigger(a,b,c,!0)}}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),l.focusin="onfocusin"in a,l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=M.access(d,b);e||d.addEventListener(a,c,!0),M.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=M.access(d,b)-1;e?M.access(d,b,e):(d.removeEventListener(a,c,!0),M.remove(d,b))}}});var ib=a.location,jb=n.now(),kb=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var lb=/#.*$/,mb=/([?&])_=[^&]*/,nb=/^(.*?):[ \t]*([^\r\n]*)$/gm,ob=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,pb=/^(?:GET|HEAD)$/,qb=/^\/\//,rb={},sb={},tb="*/".concat("*"),ub=d.createElement("a");ub.href=ib.href;function vb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function wb(a,b,c,d){var e={},f=a===sb;function g(h){var i;return e[h]=!0,n.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 xb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function yb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function zb(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(a.crossDomain&&"script"===f)continue;if(!(g=j[i+" "+f]||j["* "+f]))for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){!0===g?g=j[e]:!0!==j[e]&&(f=h[0],k.unshift(h[1]));break}if(!0!==g)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}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ib.href,type:"GET",isLocal:ob.test(ib.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":tb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?xb(xb(a,n.ajaxSettings),b):xb(n.ajaxSettings,a)},ajaxPrefilter:vb(rb),ajaxTransport:vb(sb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m=n.ajaxSetup({},c),o=m.context||m,p=m.context&&(o.nodeType||o.jquery)?n(o):n.event,q=n.Deferred(),r=n.Callbacks("once memory"),s=m.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===v){if(!h){h={};while(b=nb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===v?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return v||(a=u[c]=u[c]||a,t[a]=b),this},overrideMimeType:function(a){return v||(m.mimeType=a),this},statusCode:function(a){var b;if(a)if(v<2)for(b in a)s[b]=[s[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||w;return e&&e.abort(b),y(0,b),this}};if(q.promise(x).complete=r.add,x.success=x.done,x.error=x.fail,m.url=((b||m.url||ib.href)+"").replace(lb,"").replace(qb,ib.protocol+"//"),m.type=c.method||c.type||m.method||m.type,m.dataTypes=n.trim(m.dataType||"*").toLowerCase().match(F)||[""],null==m.crossDomain){j=d.createElement("a");try{j.href=m.url,j.href=j.href,m.crossDomain=ub.protocol+"//"+ub.host!=j.protocol+"//"+j.host}catch(z){m.crossDomain=!0}}if(m.data&&m.processData&&"string"!=typeof m.data&&(m.data=n.param(m.data,m.traditional)),wb(rb,m,c,x),2===v)return x;k=n.event&&m.global,k&&0==n.active++&&n.event.trigger("ajaxStart"),m.type=m.type.toUpperCase(),m.hasContent=!pb.test(m.type),f=m.url,m.hasContent||(m.data&&(f=m.url+=(kb.test(f)?"&":"?")+m.data,delete m.data),!1===m.cache&&(m.url=mb.test(f)?f.replace(mb,"$1_="+jb++):f+(kb.test(f)?"&":"?")+"_="+jb++)),m.ifModified&&(n.lastModified[f]&&x.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&x.setRequestHeader("If-None-Match",n.etag[f])),(m.data&&m.hasContent&&!1!==m.contentType||c.contentType)&&x.setRequestHeader("Content-Type",m.contentType),x.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+tb+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)x.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(!1===m.beforeSend.call(o,x,m)||2===v))return x.abort();w="abort";for(l in{success:1,error:1,complete:1})x[l](m[l]);if(e=wb(sb,m,c,x)){if(x.readyState=1,k&&p.trigger("ajaxSend",[x,m]),2===v)return x;m.async&&m.timeout>0&&(i=a.setTimeout(function(){x.abort("timeout")},m.timeout));try{v=1,e.send(t,y)}catch(z){if(!(v<2))throw z;y(-1,z)}}else y(-1,"No Transport");function y(b,c,d,h){var j,l,t,u,w,y=c;2!==v&&(v=2,i&&a.clearTimeout(i),e=void 0,g=h||"",x.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(u=yb(m,x,d)),u=zb(m,u,x,j),j?(m.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(n.lastModified[f]=w),(w=x.getResponseHeader("etag"))&&(n.etag[f]=w)),204===b||"HEAD"===m.type?y="nocontent":304===b?y="notmodified":(y=u.state,l=u.data,t=u.error,j=!t)):(t=y,!b&&y||(y="error",b<0&&(b=0))),x.status=b,x.statusText=(c||y)+"",j?q.resolveWith(o,[l,y,x]):q.rejectWith(o,[x,y,t]),x.statusCode(s),s=void 0,k&&p.trigger(j?"ajaxSuccess":"ajaxError",[x,m,j?l:t]),r.fireWith(o,[x,y]),k&&(p.trigger("ajaxComplete",[x,m]),--n.active||n.event.trigger("ajaxStop")))}return x},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,throws:!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return!n.expr.filters.visible(a)},n.expr.filters.visible=function(a){return a.offsetWidth>0||a.offsetHeight>0||a.getClientRects().length>0};var Ab=/%20/g,Bb=/\[\]$/,Cb=/\r?\n/g,Db=/^(?:submit|button|image|reset|file)$/i,Eb=/^(?:input|select|textarea|keygen)/i;function Fb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Bb.test(a)?d(a,e):Fb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Fb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Fb(c,a[c],b,e);return d.join("&").replace(Ab,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Eb.test(this.nodeName)&&!Db.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Cb,"\r\n")}}):{name:b.name,value:c.replace(Cb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Gb={0:200,1223:204},Hb=n.ajaxSettings.xhr();l.cors=!!Hb&&"withCredentials"in Hb,l.ajax=Hb=!!Hb,n.ajaxTransport(function(b){var c,d;if(l.cors||Hb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Gb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),n.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=n("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Ib=[],Jb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Ib.pop()||n.expando+"_"+jb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=!1!==b.jsonp&&(Jb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Jb.test(b.data)&&"data");if(h||"jsonp"===b.dataTypes[0])return e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Jb,"$1"+e):!1!==b.jsonp&&(b.url+=(kb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Ib.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1);var e=x.exec(a),f=!c&&[],g=n.isFunction(d.implementation.createHTMLDocument)?d.implementation.createHTMLDocument(""):d;return b=b||g,e?[b.createElement(e[1])]:(e=ba([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var Kb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Kb)return Kb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function Lb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(e=d.getBoundingClientRect(),c=Lb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Da})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;n.fn[a]=function(d){return J(this,function(a,d,e){var f=Lb(a);if(void 0===e)return f?f[b]:a[d];f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e},a,d,arguments.length)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Fa(l.pixelPosition,function(a,c){if(c)return c=Ea(a,b),Aa.test(c)?n(a).position()[b]+"px":c})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(!0===d||!0===e?"margin":"border");return J(this,function(b,c,d){var e;return n.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?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({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)},size:function(){return this.length}}),n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Mb=a.jQuery,Nb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Nb),b&&a.jQuery===n&&(a.jQuery=Mb),n},b||(a.jQuery=a.$=n),n}); /*! RESOURCE: /scripts/lib/jquery/jquery_no_conflict.js */ (function() { if (window.$j_glide) { jQuery.noConflict(true); window.jQuery = $j_glide; } window.$j = window.$j_glide = jQuery.noConflict(); })(); ; ; /*! RESOURCE: /scripts/doctype/CustomEventManager.js */ var NOW = NOW || {}; var CustomEventManager = (function (existingCustomEvent) { "use strict"; var events = (existingCustomEvent && existingCustomEvent.events) || {}; var isFiringFlag = false; var trace = false; var suppressEvents = false; var NOW_MSG = 'NOW.PostMessage'; function observe(eventName, fn){ if (trace) jslog("$CustomEventManager observing: " + eventName); on(eventName, fn); } function on(name, func) { if (!func || typeof func !== 'function') return; if (typeof name === 'undefined') return; if (!events[name]) events[name] = []; events[name].push(func); } function un(name, func) { if (!events[name]) return; var idx = -1; for (var i = 0; i < events[name].length; i++) { if (events[name][i] === func) { idx = i; break; } } if (idx >= 0) events[name].splice(idx, 1) } function unAll(name) { if (events[name]) delete events[name]; } function fire(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); return fireEvent.apply(null, arguments); } function fireUp(eventName, args){ var win = window; while (win){ try { if (win.CustomEvent.fireEvent.apply(null, arguments) === false) return; win = win.parent === win ? null : win.parent; }catch(e){ return; } } } function fireEvent() { if (suppressEvents) return true; var args = Array.prototype.slice.apply(arguments); var name = args.shift(); var eventList = events[name]; if (!eventList) return true; var event = eventList.slice(); isFiringFlag = true; for (var i = 0, l = event.length; i < l; i++) { var ev = event[i]; if (!ev) continue; if (ev.apply(null, args) === false) { isFiringFlag = false; return false; } } isFiringFlag = false; return true; } function isFiring() { return isFiringFlag; } function forward(name, element, func) { on(name, func); element.addEventListener(name, function(e) { fireEvent(e.type, this, e); }.bind(api)); } function isOriginInWhiteList(origin, whitelistStr) { if (!whitelistStr) { return false; } var delimiterRegex = /[\n, ]/; var whitelist = whitelistStr.split(delimiterRegex) .filter(function(whiteListedOrigin) { return whiteListedOrigin; }) .map(function(whiteListedOrigin) { return whiteListedOrigin.toLowerCase(); }); if (~whitelist.indexOf(origin.toLowerCase())) { return true; } return false; } function shouldProcessMessage(sourceOrigin) { if (!window.g_concourse_onmessage_enforce_same_origin || sourceOrigin === window.location.origin) { return true; } return isOriginInWhiteList(sourceOrigin, window.g_concourse_onmessage_enforce_same_origin_whitelist); } function registerPostMessageEvent() { if (NOW.registeredPostMessageEvent) { return; } if (!window.postMessage) { return; } window.addEventListener('message', function (event) { if (!shouldProcessMessage(event.origin)) { console.warn('Incoming message ignored due to origin mismatch.'); return; } var nowMessageJSON = event.data; var nowMessage; try { nowMessage = JSON.parse(nowMessageJSON.toString()); } catch (e) { return; } if (!nowMessage.type == NOW_MSG) { return; } fire(nowMessage.eventName, nowMessage.args); }, false); NOW.registeredPostMessageEvent = true; } function doPostMessage(win, event, msg, targetOrigin) { var nowMessage = {type: NOW_MSG, eventName: event, args: msg}; var nowMessageJSON; if (!win || !win.postMessage) { return } nowMessageJSON = JSON.stringify(nowMessage); win.postMessage(nowMessageJSON, targetOrigin); } function fireTop(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); fireEvent.apply(null, arguments); var t = getTopWindow(); if (t !== null && window !== t) t.CustomEvent.fire(eventName, args); } function fireAll(eventName, args) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); var topWindow = getTopWindow(); if (topWindow !== window.self) CustomEvent.fireEvent(eventName, args); notifyAllFrom(topWindow); function notifyAllFrom(rootFrame) { var childFrame; rootFrame.CustomEvent.fireEvent(eventName, args); for (var i = 0; i < rootFrame.frames.length; i++) { try { childFrame = rootFrame.frames[i]; if (!childFrame) continue; if (childFrame.CustomEvent && typeof childFrame.CustomEvent.fireEvent === "function") { notifyAllFrom(childFrame); } } catch(e) { } } } } function fireToWindow(targetWindow, eventName, args, usePostMessage, targetOrigin) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + args.length); if (usePostMessage) { doPostMessage(targetWindow, eventName, args, targetOrigin); } else { targetWindow.CustomEvent.fireEvent(eventName, args); } } function getTopWindow() { var topWindow = window.self; try { while (topWindow.CustomEvent.fireEvent && topWindow !== topWindow.parent && topWindow.parent.CustomEvent.fireEvent) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } function isTopWindow() { return getTopWindow() == window.self; } function jslog(msg, src, dateTime) { try { if (!src) { var path = window.self.location.pathname; src = path.substring(path.lastIndexOf('/') + 1); } if (window.self.opener && window != window.self.opener) { if (window.self.opener.jslog) { window.self.opener.jslog(msg, src, dateTime); } } else if (parent && parent.jslog && jslog != parent.jslog) { parent.jslog(msg, src, dateTime); } else { if (window.console && window.console.log) console.log(msg); } } catch (e) { } } var api = { set trace(value) { trace = !!value; }, get trace() { return trace; }, set suppressEvents(value) { suppressEvents = !!value; }, get suppressEvents() { return suppressEvents; }, get events() { return events; }, set events(value) { events = value; }, on: on, un: un, unAll: unAll, forward: forward, isFiring: isFiring, fireEvent: fireEvent, observe: observe, fire: fire, fireTop: fireTop, fireAll: fireAll, fireToWindow: fireToWindow, isTopWindow: isTopWindow, fireUp: fireUp, toString: function() { return 'CustomEventManager'; } }; registerPostMessageEvent(); return api; })(NOW.CustomEvent); NOW.CustomEvent = CustomEventManager; if (typeof CustomEvent !== "undefined") { CustomEvent.observe = NOW.CustomEvent.observe.bind(NOW.CustomEvent); CustomEvent.fire = NOW.CustomEvent.fire.bind(NOW.CustomEvent); CustomEvent.fireUp = NOW.CustomEvent.fireUp.bind(NOW.CustomEvent); CustomEvent.fireTop = NOW.CustomEvent.fireTop.bind(NOW.CustomEvent); CustomEvent.fireAll = NOW.CustomEvent.fireAll.bind(NOW.CustomEvent); CustomEvent.fireToWindow = NOW.CustomEvent.fireToWindow.bind(NOW.CustomEvent); CustomEvent.on = NOW.CustomEvent.on.bind(NOW.CustomEvent); CustomEvent.un = NOW.CustomEvent.un.bind(NOW.CustomEvent); CustomEvent.unAll = NOW.CustomEvent.unAll.bind(NOW.CustomEvent); CustomEvent.forward = NOW.CustomEvent.forward.bind(NOW.CustomEvent); CustomEvent.isFiring = NOW.CustomEvent.isFiring.bind(NOW.CustomEvent); CustomEvent.fireEvent = NOW.CustomEvent.fireEvent.bind(NOW.CustomEvent); CustomEvent.events = NOW.CustomEvent.events; CustomEvent.isTopWindow = NOW.CustomEvent.isTopWindow.bind(NOW.CustomEvent); } else { window.CustomEvent = NOW.CustomEvent; } ; /*! RESOURCE: /scripts/heisenberg/heisenberg_all.js */ /*! RESOURCE: /scripts/heisenberg/bootstrap/affix.js */ +function ($) { 'use strict'; var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) var target = this.options.target === Affix.DEFAULTS.target ? $(this.options.target) : $(document).find(this.options.target === '#' ? [] : this.options.target) this.$target = target .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.2.0' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger($.Event(affixType.replace('affix', 'affixed'))) if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - this.$element.height() - offsetBottom }) } } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix $.fn.affix.noConflict = function () { $.fn.affix = old return this } $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/alert.js */ +function ($) { 'use strict'; var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.2.0' Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') } selector = selector === '#' ? [] : selector var $parent = $(document).find(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(150) : removeElement() } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert $.fn.alert.noConflict = function () { $.fn.alert = old return this } $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/button.js */ +function ($) { 'use strict'; var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.2.0' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) $el[val](data[state] == null ? this.options[state] : data[state]) setTimeout($.proxy(function () { if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button $.fn.button.noConflict = function () { $.fn.button = old return this } $(document).on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') e.preventDefault() }) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/carousel.js */ +function ($) { 'use strict'; var Carousel = function (element, options) { this.$element = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.2.0' Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true } Carousel.prototype.keydown = function (e) { switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this) var href = $this.attr('href') if (href) { href = href.replace(/.*(?=#[^\s]+$)/, '') } var target = $this.attr('data-target') || href target = target === '#' ? [] : target var $target = $(document).find(target) if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/collapse.js */ +function ($) { 'use strict'; var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(document).find(this.options.parent === '#' ? [] : this.options.parent) if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.2.0' Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return Plugin.call(actives, 'hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(350)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') option = !option if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var href var $this = $(this) var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') target = target === '#' ? [] : target var $target = $(document).find(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } Plugin.call($target, option) }) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/dropdown.js */ +function ($) { 'use strict'; var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.2.0' Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32|9)/.test(e.keyCode) || /input|textarea/i.test(e.target.tagName)) return if (e.keyCode == 9) { clearMenus() return } var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if ((!isActive && e.keyCode != 27) || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click'); } var desc = ' li:not(.divider):visible a' var $items = $parent.find('.dropdown-menu' + desc) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38) { if(index > 0) index-- else if(index == 0) index = $items.length - 1 } if (e.keyCode == 40) { if(index < $items.length - 1) index++ else if(index == $items.length - 1) index = 0 } if (!~index) index = 0 $items.eq(index).trigger('focus') } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') } selector = selector === '#' ? [] : selector var $parent = selector && $(document).find(selector) return $parent && $parent.length ? $parent : $this.parent() } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/tooltip.js */ +function ($) { 'use strict'; var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'] var uriAttrs = [ 'background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href' ] var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i var DefaultWhitelist = { '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN], a: ['target', 'href', 'title', 'rel'], area: [], b: [], br: [], col: [], code: [], div: [], em: [], hr: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [], i: [], img: ['src', 'alt', 'title', 'width', 'height'], li: [], ol: [], p: [], pre: [], s: [], small: [], span: [], sub: [], sup: [], strong: [], u: [], ul: [] } var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i function allowedAttribute(attr, allowedAttributeList) { var attrName = attr.nodeName.toLowerCase() if ($.inArray(attrName, allowedAttributeList) !== -1) { if ($.inArray(attrName, uriAttrs) !== -1) { return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN)) } return true } var regExp = $(allowedAttributeList).filter(function (index, value) { return value instanceof RegExp }) for (var i = 0, l = regExp.length; i < l; i++) { if (attrName.match(regExp[i])) { return true } } return false } function sanitizeHtml(unsafeHtml, whiteList, sanitizeFn) { if (unsafeHtml.length === 0) { return unsafeHtml } if (sanitizeFn && typeof sanitizeFn === 'function') { return sanitizeFn(unsafeHtml) } if (!document.implementation || !document.implementation.createHTMLDocument) { return unsafeHtml } var createdDocument = document.implementation.createHTMLDocument('sanitization') createdDocument.body.innerHTML = unsafeHtml var whitelistKeys = $.map(whiteList, function (el, i) { return i }) var elements = $(createdDocument.body).find('*') for (var i = 0, len = elements.length; i < len; i++) { var el = elements[i] var elName = el.nodeName.toLowerCase() if ($.inArray(elName, whitelistKeys) === -1) { el.parentNode.removeChild(el) continue } var attributeList = $.map(el.attributes, function (el) { return el }) var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []) for (var j = 0, len2 = attributeList.length; j < len2; j++) { if (!allowedAttribute(attributeList[j], whitelistedAttributes)) { el.removeAttribute(attributeList[j].nodeName) } } } return createdDocument.body.innerHTML } var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.orphanCheck= this.$element = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.2.0' Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner" style="overflow-wrap: break-word;"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 }, sanitize : false, sanitizeFn : null, whiteList : DefaultWhitelist } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var viewport = this.options.viewport && (this.options.viewport.selector || this.options.viewport) viewport = viewport === '#' ? [] : viewport; this.$viewport = this.options.viewport && $(document).find(viewport) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) var dataAttributes = this.$element.data() for (var dataAttr in dataAttributes) { if (dataAttributes.hasOwnProperty(dataAttr) && $.inArray(dataAttr, DISALLOWED_ATTRIBUTES) !== -1) { delete dataAttributes[dataAttr] } } options = $.extend({}, this.getDefaults(), dataAttributes, options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } if (options.sanitize) { options.template = sanitizeHtml(options.template, options.whiteList, options.sanitizeFn) } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) clearInterval(self.orphanCheck); self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) self.orphanCheck = setInterval(function() { if (self.$element && !self.$element.is(':visible')) { self.hide() clearInterval(self.orphanCheck) } }, 1000) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) clearInterval(self.orphanCheck); self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(document.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) if (this.options.omitAriaDescribedby !== true) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo($(document).find(this.options.container === '#' ? [] : this.options.container)) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var $container = this.options.container ? $($(document).find(this.options.container === '#' ? [] : this.options.container)) : this.$element.parent() var containerDim = this.getPosition($container) placement = placement == 'bottom' && pos.top + pos.height + actualHeight - containerDim.scroll > containerDim.height ? 'top' : placement == 'top' && pos.top - containerDim.scroll - actualHeight < containerDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(150) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft var viewportDimensions = this.getPosition(this.$viewport); $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left), width: width+1 }) } }, offset), 0) $tip.addClass('in') var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight, viewportDimensions) var isVertical = /top|bottom/.test(placement) if(isVertical && this.options && this.options.container) { var $container = this.$element.closest(this.options.container) const isContainerSameAsViewport = this.$viewport && this.$viewport[0] === $container[0] if($container.length && !isContainerSameAsViewport) { var containerDim = this.getPosition($container) var tooltipExtraLengthAfterThisEle = (actualWidth - this.getPosition().width)/2 var deltaRWithRespectToContainer = (this.getPosition().right + tooltipExtraLengthAfterThisEle) - (containerDim.left + containerDim.width) var deltaLWithRespectToContainer = (containerDim.left) - (this.getPosition().left - tooltipExtraLengthAfterThisEle) if(deltaRWithRespectToContainer > 0) { if(delta.left <= 0) { if(Math.abs(delta.left) < deltaRWithRespectToContainer) { delta.left = -deltaRWithRespectToContainer } } } if(deltaLWithRespectToContainer > 0) { if(delta.left >= 0) { if(Math.abs(delta.left) < deltaLWithRespectToContainer) { delta.left = deltaLWithRespectToContainer } } } } } if (delta.left) offset.left += delta.left else offset.top += delta.top var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical, viewportDimensions) } Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal, viewportDimensions) { var $arrow = this.arrow(); if ($arrow.length === 0) return; $arrow .css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isHorizontal ? 'right' : 'bottom', 'auto') .css(isHorizontal ? 'top' : 'left', ''); if (!viewportDimensions) return ; var arrPostion = $arrow.position(); var arrowLeft = arrPostion.left; var arrowTop = arrPostion.right; var tipWidth = this.$tip[0].offsetWidth; var arrowWidth = $arrow[0].offsetWidth;; var arrowMarginLeft = parseInt($arrow.css("margin-left"), 10); var tipBorderRadius = parseInt(this.$tip.css("border-radius"), 10); var arrowRight = arrowLeft + arrowWidth + arrowMarginLeft; var scrollBarWidth = viewportDimensions.scrollbarWidth; if (isHorizontal && tipWidth > arrowWidth) { if (arrowLeft < arrowWidth/2 + tipBorderRadius) arrowLeft = arrowWidth/2 + tipBorderRadius; else if (arrowRight > tipWidth) arrowLeft = tipWidth - arrowWidth/2 - tipBorderRadius; arrowLeft = arrowLeft - (arrowMarginLeft + arrowWidth / 2); $arrow .css('right', 'auto') .css('left', arrowLeft) .css('top', arrowTop); } else if(isHorizontal && tipWidth < arrowWidth) { $arrow .css('margin-bottom', tipBorderRadius); } } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() if (this.options.html) { if (this.options.sanitize) { title = sanitizeHtml(title, this.options.whiteList, this.options.sanitizeFn) } $tip.find('.tooltip-inner').html(title) } else { $tip.find('.tooltip-inner').text(title) } $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(150) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var viewPortScrollOffset = document.viewport ? document.viewport.getScrollOffsets() : {left:0, right: 0}; return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : null, { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop(), width: isBody ? document.documentElement.scrollWidth : $element.outerWidth(), height: isBody ? $(window).height() : $element.outerHeight() }, isBody ? { top: 0, left: 0 } : $element.offset(), {viewPortScrollOffset:viewPortScrollOffset}, { scrollbarWidth: window.innerWidth - document.documentElement.clientWidth}) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight, viewportDimensions) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var scrollBarWidth = viewportDimensions.scrollbarWidth; if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left; var rightEdgeOffset = pos.left + actualWidth; var scrollLeft = viewportDimensions.x !== undefined && viewportDimensions.viewPortScrollOffset.left === 0 ? viewportDimensions.x : viewportDimensions.viewPortScrollOffset.left; var docWidth = document.documentElement.offsetWidth; var scrollbarWidthForRTL = document.dir === 'rtl' ? scrollBarWidth : 0; var viewportScrollWidth = 0; if(this.$viewport && this.$viewport[0]) { viewportScrollWidth = this.$viewport[0].offsetWidth - this.$viewport[0].clientWidth; } if (leftEdgeOffset < scrollLeft) { delta.left = scrollbarWidthForRTL + scrollLeft - leftEdgeOffset; if(document.dir === 'rtl') { delta.left += viewportScrollWidth; } } else if (rightEdgeOffset > docWidth + scrollLeft) { delta.left = docWidth + scrollLeft - rightEdgeOffset + scrollbarWidthForRTL if(document.dir === 'ltr') { delta.left -= viewportScrollWidth; } } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { return (this.$tip = this.$tip || $(this.options.template)) } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) }) } Tooltip.prototype.sanitizeHtml = function (unsafeHtml) { return sanitizeHtml(unsafeHtml, this.options.whiteList, this.options.sanitizeFn) } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/modal.js */ +function ($) { 'use strict'; var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$backdrop = this.isShown = null this.scrollbarWidth = 0 if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.2.0' Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.$body.addClass('modal-open') this.setScrollbar() this.escape() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) } that.$element .show() .scrollTop(0) if (transition) { that.$element[0].offsetWidth } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(300) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.$body.removeClass('modal-open') this.resetScrollbar() this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(150) : callbackRemove() } else if (callback) { callback() } } Modal.prototype.checkScrollbar = function () { if (document.body.clientWidth >= window.innerWidth) return this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', '') } Modal.prototype.measureScrollbar = function () { var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal $.fn.modal.noConflict = function () { $.fn.modal = old return this } $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var target = $this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, '')) target = target === '#' ? [] : target var $target = $(document).find(target) var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/popover.js */ +function ($) { 'use strict'; var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.2.0' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="dialog"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = ((this.options.title) ? this.options.title : this.getTitle()); var content = this.getContent() if (this.options.html) { var typeContent = typeof content if (this.options.sanitize) { title = this.sanitizeHtml(title) if (typeContent === 'string') { content = this.sanitizeHtml(content) } } $tip.find('.popover-title').html(title) $tip.find('.popover-content').children().detach().end()[ typeContent === 'string' ? 'html' : 'append' ](content) } else { $tip.find('.popover-title').text(title) $tip.find('.popover-content').children().detach().end().text(content) } $tip.removeClass('fade top bottom left right in') if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/scrollspy.js */ +function ($) { 'use strict'; function ScrollSpy(element, options) { var process = $.proxy(this.process, this) this.$body = $('body') this.$scrollElement = $(element).is('body') ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', process) this.refresh() this.process() } ScrollSpy.VERSION = '3.2.0' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var offsetMethod = 'offset' var offsetBase = 0 if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() var self = this this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop <= offsets[0]) { return activeTarget != (i = targets[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/bootstrap/transition.js */ +function ($) { 'use strict'; function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false } $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/prototype.hidefix.js */ (function($) { "use strict"; $.fn.hideFix = function() { return this.each(function() { if (!window.Prototype) return this; this.hide = function() { if (!jQuery.event.triggered) Element.hide(this); } this.show = function() { if (!jQuery.event.triggered) Element.show(this); } return this; }) } })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/collapse.js */ (function($) { "use strict"; var bsCollapse = $.fn.collapse; $.fn.collapse = function(options) { var $this = this; $this.hideFix(); return bsCollapse.call($this, options); }; $(document).on('click.bs.collapse.data-api', '[data-sn-toggle="collapse"]', function(e) { var href var $this = $(this) var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $.fn.collapse.call($target, option) }); })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/dropdowns.js */ (function($) { "use strict"; $(document).on('show.bs.dropdown', function(evt) { $(evt.relatedTarget).hideFix() .parent().hideFix() .closest('.dropup, .dropdown').hideFix(); $('.dropdown-menu', evt.target).data('menu-trigger', evt.relatedTarget); }); })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/modals.js */ (function($) { "use strict"; var bsModal = $.fn.modal.Constructor; var bsModalShow = bsModal.prototype.show; var bsModalHide = bsModal.prototype.hide; var visibleModalStack = []; var $document = $(document); function isMobileSafari() { return navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i); } function forceRedraw(element) { return element.offsetLeft; } function getFirstTabbableElement(container, depth) { if (typeof depth === 'undefined') depth = 1; if (depth === 3) return null; var elements = window.tabbable(container, 'input, select, a[href], textarea, button, [tabindex]:not(.focus-trap-boundary-south), iframe'); if (elements.length === 0) return null; var result = null; if (elements[0].tagName !== 'IFRAME') return elements[0]; for (var i = 0; i <= elements.length - 1 && result === null; i++) { result = elements[i]; if (result.tagName === 'IFRAME') result = getFirstTabbableElement(result.contentDocument, depth + 1); } return result; } function getLastTabbableElement(container, depth) { if (typeof depth === 'undefined') depth = 1; if (depth === 3) return null; var elements = window.tabbable(container, 'input, select, a[href], textarea, button, [tabindex]:not(.focus-trap-boundary-south), iframe'); if (elements.length === 0) return null; if (elements[elements.length - 1].tagName !== 'IFRAME') return elements[elements.length - 1]; var result = null; for (var i = elements.length - 1; i >= 0 && result === null; i--) { result = elements[i]; if (result.tagName === 'IFRAME') result = getLastTabbableElement(result.contentDocument, depth + 1); } return result; } function visibleModalFocusInHandler(event) { var $modal = visibleModalStack[visibleModalStack.length - 1]; if (!$modal || !$modal.$element) return; $modal = $modal.$element; if ($modal.attr('focus-escape') === 'true') return; var modal = $modal[0]; var targetIsModal = modal === event.target; var modalContainsTarget = $modal.has(event.target).length > 0; var targetIsSouthernBoundary = event.target.classList.contains('focus-trap-boundary-south'); var targetIsIframe = event.target.tagName === "IFRAME"; if (!targetIsModal) { if (!modalContainsTarget) { var lastTabbableElement = getLastTabbableElement(modal); if (lastTabbableElement && typeof lastTabbableElement.focus === 'function') lastTabbableElement.focus(); else $modal.trigger('focus'); } else if (targetIsSouthernBoundary){ var firstTabbableElement = getFirstTabbableElement(modal); if (firstTabbableElement && typeof firstTabbableElement.focus === 'function') firstTabbableElement.focus(); else $modal.trigger('focus'); } else if (targetIsIframe) { var firstTabbableElement = getFirstTabbableElement(event.target.contentDocument); if (firstTabbableElement && typeof firstTabbableElement.focus === 'function') firstTabbableElement.focus(); } } } bsModal.prototype.show = function() { bsModalShow.apply(this, arguments); visibleModalStack.push(this); var $backdrop = $('body').find('.modal-backdrop').not('.stacked'); var zmodal = this.$element.css('z-index'); var zbackdrop = $backdrop.css('z-index'); this.$element.css('z-index', (~~zmodal) + (10 * visibleModalStack.length)); $backdrop.css('z-index', (~~zbackdrop) + (10 * visibleModalStack.length)); $backdrop.addClass('stacked'); forceRedraw(this.$element[0]); }; bsModal.prototype.hide = function(e) { bsModalHide.apply(this, arguments); var modalPosition = visibleModalStack.indexOf(this); if (modalPosition !== -1) visibleModalStack.splice(modalPosition, 1); if (this.isShown) return; if (visibleModalStack.length > 0) $document.on('focusin.bs.modal', visibleModalFocusInHandler) this.$element.css('z-index', ''); forceRedraw(this.$element[0]); }; $document.on('shown.bs.modal hidden.bs.modal', function() { if (window._frameChanged) _frameChanged(); }) $document.on('shown.bs.modal', function(event) { $document.off('focusin.bs.modal'); $document.on('focusin.bs.modal', visibleModalFocusInHandler); var modal = event.target; var autoFocus = true; if (modal.getAttribute('data-auto-focus') === 'false') { autoFocus = false; } if (autoFocus && window.tabbable) { var tabbableElements = window.tabbable(modal); if ( tabbableElements && tabbableElements.length && tabbableElements[0] ) { tabbableElements[0].focus(); } } }); })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/tooltips.js */ (function($) { "use strict"; var bsTooltip = $.fn.tooltip.Constructor; bsTooltip.DEFAULTS.placement = 'auto'; bsTooltip.DEFAULTS.delay = { 'show': 500, 'hide': 100 }; var SN_TOOLTIP_SELECTOR = '.sn-tooltip-basic, *[title]:not(.accessibility_no_tooltip), *[data-dynamic-title]:not(.accessibility_no_tooltip), [data-tooltip-overflow-only="true"]'; $(function() { if ('ontouchstart' in document.documentElement) return; var $tooltips = $(SN_TOOLTIP_SELECTOR); (function setupTooltips() { $tooltips.each(function() { var $this = $(this); $this.hideFix(); if (this.hasAttribute('title') && !this.hasAttribute('data-original-title')) this.setAttribute('data-original-title', this.getAttribute('title')); }) })(); $(document.body).on('mouseenter focus', SN_TOOLTIP_SELECTOR, function(evt) { if (this.tagName == 'IFRAME' || this.tagName == 'OPTION') return; var $this = $(this); $this.hideFix(); var $target = $(evt.target); if ($this.data('bs.tooltip')) return; if (this.getAttribute('data-tooltip-overflow-only') === 'true' && !this.hasAttribute('title')) { var text = $this.find('[data-tooltip-overflow-only-text="true"]')[0]; if (text && text.offsetWidth < text.scrollWidth) { this.setAttribute('title', text.textContent); } } if (this.hasAttribute('title') && !this.hasAttribute('data-original-title')) this.setAttribute('data-original-title', this.getAttribute('title')); $this.tooltip({ container: $this.attr('data-container') || 'body', title: function() { return $(this).attr('data-dynamic-title'); }, omitAriaDescribedby: $target.data('omit-aria-describedby') }); $this.on('click', function() { $this.tooltip('hide'); }); var tooltipDuration = 10; if (window.g_accessibility && typeof g_accessibility_tooltip_duration !== 'undefined') tooltipDuration = g_accessibility_tooltip_duration; if (tooltipDuration !== 0) { $this.on('shown.bs.tooltip', function() { setTimeout(function() { $this.tooltip('hide'); }, tooltipDuration * 1000); }); } $this.data('hover', setTimeout(function() { $this.tooltip('show'); }, bsTooltip.DEFAULTS.delay.show)); }); $(document.body).on('mouseleave blur', SN_TOOLTIP_SELECTOR, function() { var $this = $(this); var hover = $this.data('hover'); if (hover) { clearTimeout($this.data('hover')); $this.removeData('hover') } }); $(document).bind('mouseleave', function(evt) { if ($('.tooltip').length === 0) return; $('.sn-tooltip-basic, *[title]').each(function() { if (this.tagName == 'IFRAME') return; var $this = $(this); if ($this.data('bs.tooltip')) $this.tooltip('hide'); }) }) }); })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/snPopover.js */ (function($) { "use strict"; var Popover = $.fn.popover.Constructor; var popoverCount = 0; var bsPopoverInit = Popover.prototype.init; var bsPopoverShow = Popover.prototype.show; var bsPopoverHide = Popover.prototype.hide; var bsPopoverFixTitle = Popover.prototype.fixTitle; Popover.prototype.init = function (type, element, options) { var $e = $(element); var $target = $($e.data('target')); var popoverId = popoverCount++; var wide = !!$e.data('wide'); $e.hideFix(); this.$target = $target; this.$target.hide(); this.popoverId = popoverId; options = $.extend({}, { html: true, content: function () { if (wide) this.tip().addClass('wide'); var placeholderId = 'popover-placeholder-' + popoverId; if (!document.getElementById(placeholderId)) $target.before('<div id="' + placeholderId + '" class="popover-placeholder" />'); $target.show(); return $target; }.bind(this) }, options); bsPopoverInit.call(this, type, element, options); }; Popover.prototype.fixTitle = function() { var trigger = this.options.trigger; if (typeof trigger === "undefined" || trigger === "" || /hover/.test(trigger)) bsPopoverFixTitle.apply(this, arguments); }; Popover.prototype.show = function () { var $e = this.$element; bsPopoverShow.apply(this, arguments); $e.addClass('active'); this.tip().one('click', '[data-dismiss=popover]', function () { $e.popover('hide'); $e[0].focus(); }); }; Popover.prototype.hide = function () { var $e = this.$element; var $target = this.$target; var $popover = $target.closest('.popover'); var popoverId = this.popoverId; function saveOffContent() { $e.removeClass('active'); var $placeholder = $('#popover-placeholder-' + popoverId); if (!$placeholder.length || !$target.length) return; var $innerContent = $target.detach(); if ($innerContent.length === 0) return; $innerContent.hide(); $placeholder.replaceWith($innerContent); } if ($.support.transition && $popover.hasClass('fade')) $popover.one('bsTransitionEnd', saveOffContent); else saveOffContent(); bsPopoverHide.apply(this, arguments); }; Popover.prototype.getTitle = function() { var $e = this.$element; var title = $e.data('popover-title'); var expectingHtml = this.options && this.options.html; var isHtml = typeof $e.data('popover-title-is-html') !== 'undefined' ? $e.data('popover-title-is-html') : expectingHtml; if (expectingHtml && !isHtml) { title = $('<div />').text(title).html(); } return title || $.fn.tooltip.Constructor.prototype.getTitle.call(this); } })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/popovers.js */ (function($) { "use strict"; $(function() { $('.sn-popover-basic').each(function() { var $this = $(this); if (!$this.data('bs.popover')) $(this).popover(); }); function hideOpenPopovers() { $('.sn-popover-basic').each(function() { var $this = $(this); if ($this.attr('aria-describedby') !== undefined) $this.popover('hide'); }); } function resetContainer() { $('.sn-popover-basic').each(function() { var $this = $(this); $this.popover({container: $this.data('container')}); }); } function debounce(fn, threshold, fireOnStart) { var timeout; return function() { var obj = this, args = arguments; threshold = (threshold !== undefined) ? threshold : 500; function delayed() { if (!fireOnStart) fn.apply(obj, args); timeout = null; } if (timeout) clearTimeout(timeout); else if (fireOnStart) fn.apply(obj, args); timeout = setTimeout(delayed, threshold); }; } function closeOnBlur(e) { function eventTargetInElement(elem) { return elem.is(e.target) || elem.has(e.target).length !== 0 } $('.sn-popover-basic').each(function() { var $popoverButton = $(this); var $popoverContent = $($popoverButton.data('target')); if (!$popoverButton.hasClass('active')) return; if (e.target.closest("#tag_form")) return; if (eventTargetInElement($popoverButton) || eventTargetInElement($popoverContent)) return; if ($popoverButton.data('auto-close') === false && !$(e.target).is('.sn-popover-basic')) return; $popoverButton.popover('hide'); }); } var debouncedResetContainer = debounce(resetContainer); var debouncedHideOpenPopovers = debounce(hideOpenPopovers, 0, true); var debouncedCloseOnBlur = debounce(closeOnBlur, 10); $(window).on('resize', function() { if ('ontouchstart' in document.documentElement && document.activeElement.type === 'text') return; debouncedHideOpenPopovers(); debouncedResetContainer(); }); $('html').on('click', function(e) { debouncedCloseOnBlur(e); }); if (CustomEvent && CustomEvent.observe) { CustomEvent.observe('body_clicked', function(e) { debouncedCloseOnBlur(e); }); } }); $(document).on('show.bs.popover hide.bs.popover', function() { if (window._frameChanged) _frameChanged(); }) })(jQuery); ; /*! RESOURCE: /scripts/select2_doctype/select2.min.js */ (function($){if(typeof $.fn.each2=="undefined"){$.extend($.fn,{each2:function(c){var j=$([0]),i=-1,l=this.length;while(++i<l&&(j.context=j[0]=this[i])&&c.call(j[0],i,j)!==false);return this}})}})(jQuery);(function($,undefined){"use strict";if(window.Select2!==undefined){return}var KEY,AbstractSelect2,SingleSelect2,MultiSelect2,nextUid,sizer,lastMousePosition={x:0,y:0},$document,scrollBarDimensions,KEY={TAB:9,ENTER:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,SHIFT:16,CTRL:17,ALT:18,PAGE_UP:33,PAGE_DOWN:34,HOME:36,END:35,BACKSPACE:8,DELETE:46,isArrow:function(k){k=k.which?k.which:k;switch(k){case KEY.LEFT:case KEY.RIGHT:case KEY.UP:case KEY.DOWN:return true}return false},isControl:function(e){var k=e.which;switch(k){case KEY.SHIFT:case KEY.CTRL:case KEY.ALT:return true}if(e.metaKey)return true;return false},isFunctionKey:function(k){k=k.which?k.which:k;return k>=112&&k<=123}},MEASURE_SCROLLBAR_TEMPLATE="<div class='select2-measure-scrollbar'></div>",DIACRITICS={"Ⓐ":"A","A":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A","Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","B":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","C":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","D":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","DZ":"DZ","DŽ":"DZ","Dz":"Dz","Dž":"Dz","Ⓔ":"E","E":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","F":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","G":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","H":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","I":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","J":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","K":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","L":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","LJ":"LJ","Lj":"Lj","Ⓜ":"M","M":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","N":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","NJ":"NJ","Nj":"Nj","Ⓞ":"O","O":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","P":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Q":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","R":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","S":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","T":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","U":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","V":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","W":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","X":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Y":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Z":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","a":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","b":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","c":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","d":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","dz":"dz","dž":"dz","ⓔ":"e","e":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","f":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","g":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","h":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","i":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","j":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","k":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","l":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","lj":"lj","ⓜ":"m","m":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","n":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ʼn":"n","ꞑ":"n","ꞥ":"n","nj":"nj","ⓞ":"o","o":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","p":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","q":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","r":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","s":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","t":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","u":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","v":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","w":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","x":"x","ẋ":"x","ẍ":"x","ⓨ":"y","y":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","z":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z","Ά":"Α","Έ":"Ε","Ή":"Η","Ί":"Ι","Ϊ":"Ι","Ό":"Ο","Ύ":"Υ","Ϋ":"Υ","Ώ":"Ω","ά":"α","έ":"ε","ή":"η","ί":"ι","ϊ":"ι","ΐ":"ι","ό":"ο","ύ":"υ","ϋ":"υ","ΰ":"υ","ω":"ω","ς":"σ"};$document=$(document);nextUid=function(){var counter=1;return function(){return counter++}}();function reinsertElement(element){var placeholder=$(document.createTextNode(""));element.before(placeholder);placeholder.before(element);placeholder.remove()}function stripDiacritics(str){function match(a){return DIACRITICS[a]||a}return str.replace(/[^\u0000-\u007E]/g,match)}function indexOf(value,array){var i=0,l=array.length;for(;i<l;i=i+1){if(equal(value,array[i]))return i}return-1}function measureScrollbar(){var $template=$(MEASURE_SCROLLBAR_TEMPLATE);$template.appendTo("body");var dim={width:$template.width()-$template[0].clientWidth,height:$template.height()-$template[0].clientHeight};$template.remove();return dim}function equal(a,b){if(a===b)return true;if(a===undefined||b===undefined)return false;if(a===null||b===null)return false;if(a.constructor===String)return a+""===b+"";if(b.constructor===String)return b+""===a+"";return false}function splitVal(string,separator){var val,i,l;if(string===null||string.length<1)return[];val=string.split(separator);for(i=0,l=val.length;i<l;i=i+1)val[i]=$.trim(val[i]);return val}function getSideBorderPadding(element){return element.outerWidth(false)-element.width()}function installKeyUpChangeEvent(element){var key="keyup-change-value";element.on("keydown",function(){if($.data(element,key)===undefined){$.data(element,key,element.val())}});element.on("keyup",function(){var val=$.data(element,key);if(val!==undefined&&element.val()!==val){$.removeData(element,key);element.trigger("keyup-change")}})}function installFilteredMouseMove(element){element.on("mousemove",function(e){var lastpos=lastMousePosition;if(lastpos===undefined||lastpos.x!==e.pageX||lastpos.y!==e.pageY){$(e.target).trigger("mousemove-filtered",e)}})}function debounce(quietMillis,fn,ctx){ctx=ctx||undefined;var timeout;return function(){var args=arguments;window.clearTimeout(timeout);timeout=window.setTimeout(function(){fn.apply(ctx,args)},quietMillis)}}function installDebouncedScroll(threshold,element){var notify=debounce(threshold,function(e){element.trigger("scroll-debounced",e)});element.on("scroll",function(e){if(indexOf(e.target,element.get())>=0)notify(e)})}function focus($el){if($el[0]===document.activeElement)return;window.setTimeout(function(){var el=$el[0],pos=$el.val().length,range;$el.focus();var isVisible=el.offsetWidth>0||el.offsetHeight>0;if(isVisible&&el===document.activeElement){if(el.setSelectionRange){el.setSelectionRange(pos,pos)}else if(el.createTextRange){range=el.createTextRange();range.collapse(false);range.select()}}},0)}function getCursorInfo(el){el=$(el)[0];var offset=0;var length=0;if("selectionStart"in el){offset=el.selectionStart;length=el.selectionEnd-offset}else if("selection"in document){el.focus();var sel=document.selection.createRange();length=document.selection.createRange().text.length;sel.moveStart("character",-el.value.length);offset=sel.text.length-length}return{offset:offset,length:length}}function killEvent(event){event.preventDefault();event.stopPropagation()}function killEventImmediately(event){event.preventDefault();event.stopImmediatePropagation()}function measureTextWidth(e){if(!sizer){var style=e[0].currentStyle||window.getComputedStyle(e[0],null);sizer=$(document.createElement("div")).css({position:"absolute",left:"-10000px",top:"-10000px",display:"none",fontSize:style.fontSize,fontFamily:style.fontFamily,fontStyle:style.fontStyle,fontWeight:style.fontWeight,letterSpacing:style.letterSpacing,textTransform:style.textTransform,whiteSpace:"nowrap"});sizer.attr("class","select2-sizer");$("body").append(sizer)}sizer.text(e.val());return sizer.width()}function syncCssClasses(dest,src,adapter){var classes,replacements=[],adapted;classes=$.trim(dest.attr("class"));if(classes){classes=""+classes;$(classes.split(/\s+/)).each2(function(){if(this.indexOf("select2-")===0){replacements.push(this)}})}classes=$.trim(src.attr("class"));if(classes){classes=""+classes;$(classes.split(/\s+/)).each2(function(){if(this.indexOf("select2-")!==0){adapted=adapter(this);if(adapted){replacements.push(adapted)}}})}dest.attr("class",replacements.join(" "));if(replacements.indexOf("hidden-select2")>-1)dest.attr("aria-hidden","true")}function markMatch(text,term,markup,escapeMarkup){var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),tl=term.length;if(match<0){markup.push(escapeMarkup(text));return}markup.push(escapeMarkup(text.substring(0,match)));markup.push("<span class='select2-match'>");markup.push(escapeMarkup(text.substring(match,match+tl)));markup.push("</span>");markup.push(escapeMarkup(text.substring(match+tl,text.length)))}function defaultEscapeMarkup(markup){var replace_map={"\\":"\","&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return String(markup).replace(/[&<>"'\/\\]/g,function(match){return replace_map[match]})}function ajax(options){var timeout,handler=null,quietMillis=options.quietMillis||100,ajaxUrl=options.url,self=this;return function(query){window.clearTimeout(timeout);timeout=window.setTimeout(function(){var data=options.data,url=ajaxUrl,transport=options.transport||$.fn.select2.ajaxDefaults.transport,deprecated={type:options.type||"GET",cache:options.cache||false,jsonpCallback:options.jsonpCallback||undefined,dataType:options.dataType||"json"},params=$.extend({},$.fn.select2.ajaxDefaults.params,deprecated);data=data?data.call(self,query.term,query.page,query.context):null;url=typeof url==="function"?url.call(self,query.term,query.page,query.context):url;if(handler&&typeof handler.abort==="function"){handler.abort()}if(options.params){if($.isFunction(options.params)){$.extend(params,options.params.call(self))}else{$.extend(params,options.params)}}$.extend(params,{url:url,dataType:options.dataType,data:data,success:function(data){var results=options.results(data,query.page,query);query.callback(results)},error:function(jqXHR,textStatus,errorThrown){var results={hasError:true,jqXHR:jqXHR,textStatus:textStatus,errorThrown:errorThrown};query.callback(results)}});handler=transport.call(self,params)},quietMillis)}}function local(options){var data=options,dataText,tmp,text=function(item){return""+item.text};if($.isArray(data)){tmp=data;data={results:tmp}}if($.isFunction(data)===false){tmp=data;data=function(){return tmp}}var dataItem=data();if(dataItem.text){text=dataItem.text;if(!$.isFunction(text)){dataText=dataItem.text;text=function(item){return item[dataText]}}}return function(query){var t=query.term,filtered={results:[]},process;if(t===""){query.callback(data());return}process=function(datum,collection){var group,attr;datum=datum[0];if(datum.children){group={};for(attr in datum){if(datum.hasOwnProperty(attr))group[attr]=datum[attr]}group.children=[];$(datum.children).each2(function(i,childDatum){process(childDatum,group.children)});if(group.children.length||query.matcher(t,text(group),datum)){collection.push(group)}}else{if(query.matcher(t,text(datum),datum)){collection.push(datum)}}};$(data().results).each2(function(i,datum){process(datum,filtered.results)});query.callback(filtered)}}function tags(data){var isFunc=$.isFunction(data);return function(query){var t=query.term,filtered={results:[]};var result=isFunc?data(query):data;if($.isArray(result)){$(result).each(function(){var isObject=this.text!==undefined,text=isObject?this.text:this;if(t===""||query.matcher(t,text)){filtered.results.push(isObject?this:{id:this,text:this})}});query.callback(filtered)}}}function checkFormatter(formatter,formatterName){if($.isFunction(formatter))return true;if(!formatter)return false;if(typeof formatter==="string")return true;throw new Error(formatterName+" must be a string, function, or falsy value")}function evaluate(val,context){if($.isFunction(val)){var args=Array.prototype.slice.call(arguments,2);return val.apply(context,args)}return val}function countResults(results){var count=0;$.each(results,function(i,item){if(item.children){count+=countResults(item.children)}else{count++}});return count}function defaultTokenizer(input,selection,selectCallback,opts){var original=input,dupe=false,token,index,i,l,separator;if(!opts.createSearchChoice||!opts.tokenSeparators||opts.tokenSeparators.length<1)return undefined;while(true){index=-1;for(i=0,l=opts.tokenSeparators.length;i<l;i++){separator=opts.tokenSeparators[i];index=input.indexOf(separator);if(index>=0)break}if(index<0)break;token=input.substring(0,index);input=input.substring(index+separator.length);if(token.length>0){token=opts.createSearchChoice.call(this,token,selection);if(token!==undefined&&token!==null&&opts.id(token)!==undefined&&opts.id(token)!==null){dupe=false;for(i=0,l=selection.length;i<l;i++){if(equal(opts.id(token),opts.id(selection[i]))){dupe=true;break}}if(!dupe)selectCallback(token)}}}if(original!==input)return input}function cleanupJQueryElements(){var self=this;$.each(arguments,function(i,element){self[element].remove();self[element]=null})}function clazz(SuperClass,methods){var constructor=function(){};constructor.prototype=new SuperClass;constructor.prototype.constructor=constructor;constructor.prototype.parent=SuperClass.prototype;constructor.prototype=$.extend(constructor.prototype,methods);return constructor}AbstractSelect2=clazz(Object,{bind:function(func){var self=this;return function(){func.apply(self,arguments)}},init:function(opts){var results,search,resultsSelector=".select2-results";this.opts=opts=this.prepareOpts(opts);this.id=opts.id;if(opts.element.data("select2")!==undefined&&opts.element.data("select2")!==null){opts.element.data("select2").destroy()}this.container=this.createContainer();this.liveRegion=$("<span>",{role:"status","aria-live":"polite"}).addClass("select2-hidden-accessible").appendTo(document.body);this.containerId="s2id_"+(opts.element.attr("id")||"autogen"+nextUid());this.containerEventName=this.containerId.replace(/([.])/g,"_").replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g,"\\$1");this.container.attr("id",this.containerId);this.container.attr("title",opts.element.attr("title"));this.body=$("body");syncCssClasses(this.container,this.opts.element,this.opts.adaptContainerCssClass);this.container.attr("style",opts.element.attr("style"));this.container.css(evaluate(opts.containerCss,this.opts.element));this.container.addClass(evaluate(opts.containerCssClass,this.opts.element));this.container.attr("role","none");this.elementTabIndex=this.opts.element.attr("tabindex");this.opts.element.data("select2",this).attr("tabindex","-1").before(this.container).on("click.select2",killEvent);this.container.data("select2",this);this.dropdown=this.container.find(".select2-drop");syncCssClasses(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass);this.dropdown.addClass(evaluate(opts.dropdownCssClass,this.opts.element));this.dropdown.data("select2",this);this.dropdown.on("click",killEvent);this.results=results=this.container.find(resultsSelector);this.search=search=this.container.find("input.select2-input");this.queryCount=0;this.resultsPage=0;this.context=null;this.initContainer();this.container.on("click",killEvent);installFilteredMouseMove(this.results);this.dropdown.on("mousemove-filtered",resultsSelector,this.bind(this.highlightUnderEvent));this.dropdown.on("touchstart touchmove touchend",resultsSelector,this.bind(function(event){this._touchEvent=true;this.highlightUnderEvent(event)}));this.dropdown.on("touchmove",resultsSelector,this.bind(this.touchMoved));this.dropdown.on("touchstart touchend",resultsSelector,this.bind(this.clearTouchMoved));this.dropdown.on("click",this.bind(function(event){if(this._touchEvent){this._touchEvent=false;this.selectHighlighted()}}));installDebouncedScroll(80,this.results);this.dropdown.on("scroll-debounced",resultsSelector,this.bind(this.loadMoreIfNeeded));$(this.container).on("change",".select2-input",function(e){e.stopPropagation()});$(this.dropdown).on("change",".select2-input",function(e){e.stopPropagation()});if($.fn.mousewheel){results.mousewheel(function(e,delta,deltaX,deltaY){var top=results.scrollTop();if(deltaY>0&&top-deltaY<=0){results.scrollTop(0);killEvent(e)}else if(deltaY<0&&results.get(0).scrollHeight-results.scrollTop()+deltaY<=results.height()){results.scrollTop(results.get(0).scrollHeight-results.height());killEvent(e)}})}installKeyUpChangeEvent(search);search.on("keyup-change input paste",this.bind(this.updateResults));search.on("focus",function(){search.addClass("select2-focused")});search.on("blur",function(){search.removeClass("select2-focused")});this.dropdown.on("mouseup",resultsSelector,this.bind(function(e){if($(e.target).closest(".select2-result-selectable").length>0){this.highlightUnderEvent(e);this.selectHighlighted(e)}}));this.dropdown.on("click mouseup mousedown touchstart touchend focusin",function(e){e.stopPropagation()});this.nextSearchTerm=undefined;if($.isFunction(this.opts.initSelection)){this.initSelection();this.monitorSource()}if(opts.maximumInputLength!==null){this.search.attr("maxlength",opts.maximumInputLength)}var disabled=opts.element.prop("disabled");if(disabled===undefined)disabled=false;this.enable(!disabled);var readonly=opts.element.prop("readonly");if(readonly===undefined)readonly=false;this.readonly(readonly);scrollBarDimensions=scrollBarDimensions||measureScrollbar();this.autofocus=opts.element.prop("autofocus");opts.element.prop("autofocus",false);if(this.autofocus)this.focus();this.search.attr("placeholder",opts.searchInputPlaceholder)},destroy:function(){var element=this.opts.element,select2=element.data("select2"),self=this;this.close();if(element.length&&element[0].detachEvent){element.each(function(){this.detachEvent("onpropertychange",self._sync)})}if(this.propertyObserver){this.propertyObserver.disconnect();this.propertyObserver=null}this._sync=null;if(select2!==undefined){select2.container.remove();select2.liveRegion.remove();select2.dropdown.remove();element.removeClass("select2-offscreen").removeData("select2").off(".select2").prop("autofocus",this.autofocus||false);if(this.elementTabIndex){element.attr({tabindex:this.elementTabIndex})}else{element.removeAttr("tabindex")}element.show()}cleanupJQueryElements.call(this,"container","liveRegion","dropdown","results","search")},optionToData:function(element){if(element.is("option")){return{id:element.prop("value"),text:element.text(),element:element.get(),css:element.attr("class"),disabled:element.prop("disabled"),locked:equal(element.attr("locked"),"locked")||equal(element.data("locked"),true)}}else if(element.is("optgroup")){return{text:element.attr("label"),children:[],element:element.get(),css:element.attr("class")}}},prepareOpts:function(opts){var element,select,idKey,ajaxUrl,self=this;element=opts.element;if(element.get(0).tagName.toLowerCase()==="select"){this.select=select=opts.element}if(select){$.each(["id","multiple","ajax","query","createSearchChoice","initSelection","data","tags"],function(){if(this in opts){throw new Error("Option '"+this+"' is not allowed for Select2 when attached to a <select> element.")}})}opts=$.extend({},{populateResults:function(container,results,query){var populate,id=this.opts.id,liveRegion=this.liveRegion;populate=function(results,container,depth){var i,l,result,selectable,disabled,compound,node,label,innerContainer,formatted;results=opts.sortResults(results,container,query);var nodes=[];for(i=0,l=results.length;i<l;i=i+1){result=results[i];disabled=result.disabled===true;selectable=!disabled&&id(result)!==undefined;compound=result.children&&result.children.length>0;node=$("<li></li>");node.addClass("select2-results-dept-"+depth);node.addClass("select2-result");node.addClass(selectable?"select2-result-selectable":"select2-result-unselectable");if(disabled){node.addClass("select2-disabled")}if(compound){node.addClass("select2-result-with-children")}node.addClass(self.opts.formatResultCssClass(result));node.attr("role","presentation");label=$(document.createElement("div"));label.addClass("select2-result-label");label.attr("id","select2-result-label-"+nextUid());label.attr("role","option");formatted=opts.formatResult(result,label,query,self.opts.escapeMarkup);if(formatted!==undefined){label.html(formatted);node.append(label)}if(compound){innerContainer=$("<ul></ul>");innerContainer.addClass("select2-result-sub");populate(result.children,innerContainer,depth+1);node.append(innerContainer)}node.data("select2-data",result);nodes.push(node[0])}container.append(nodes);liveRegion.text(opts.formatMatches(results.length))};populate(results,container,0)}},$.fn.select2.defaults,opts);if(typeof opts.id!=="function"){idKey=opts.id;opts.id=function(e){return e[idKey]}}if($.isArray(opts.element.data("select2Tags"))){if("tags"in opts){throw"tags specified as both an attribute 'data-select2-tags' and in options of Select2 "+opts.element.attr("id")}opts.tags=opts.element.data("select2Tags")}if(select){opts.query=this.bind(function(query){var data={results:[],more:false},term=query.term,children,placeholderOption,process;process=function(element,collection){var group;if(element.is("option")){if(query.matcher(term,element.text(),element)){collection.push(self.optionToData(element))}}else if(element.is("optgroup")){group=self.optionToData(element);element.children().each2(function(i,elm){process(elm,group.children)});if(group.children.length>0){collection.push(group)}}};children=element.children();if(this.getPlaceholder()!==undefined&&children.length>0){placeholderOption=this.getPlaceholderOption();if(placeholderOption){children=children.not(placeholderOption)}}children.each2(function(i,elm){process(elm,data.results)});query.callback(data)});opts.id=function(e){return e.id}}else{if(!("query"in opts)){if("ajax"in opts){ajaxUrl=opts.element.data("ajax-url");if(ajaxUrl&&ajaxUrl.length>0){opts.ajax.url=ajaxUrl}opts.query=ajax.call(opts.element,opts.ajax)}else if("data"in opts){opts.query=local(opts.data)}else if("tags"in opts){opts.query=tags(opts.tags);if(opts.createSearchChoice===undefined){opts.createSearchChoice=function(term){return{id:$.trim(term),text:$.trim(term)}}}if(opts.initSelection===undefined){opts.initSelection=function(element,callback){var data=[];$(splitVal(element.val(),opts.separator)).each(function(){var obj={id:this,text:this},tags=opts.tags;if($.isFunction(tags))tags=tags();$(tags).each(function(){if(equal(this.id,obj.id)){obj=this;return false}});data.push(obj)});callback(data)}}}}}if(typeof opts.query!=="function"){throw"query function not defined for Select2 "+opts.element.attr("id")}if(opts.createSearchChoicePosition==="top"){opts.createSearchChoicePosition=function(list,item){list.unshift(item)}}else if(opts.createSearchChoicePosition==="bottom"){opts.createSearchChoicePosition=function(list,item){list.push(item)}}else if(typeof opts.createSearchChoicePosition!=="function"){throw"invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function"}return opts},monitorSource:function(){var el=this.opts.element,observer,self=this;el.on("change.select2",this.bind(function(e){if(this.opts.element.data("select2-change-triggered")!==true){this.initSelection()}}));this._sync=this.bind(function(){var disabled=el.prop("disabled");if(disabled===undefined)disabled=false;this.enable(!disabled);var readonly=el.prop("readonly");if(readonly===undefined)readonly=false;this.readonly(readonly);syncCssClasses(this.container,this.opts.element,this.opts.adaptContainerCssClass);this.container.addClass(evaluate(this.opts.containerCssClass,this.opts.element));syncCssClasses(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass);this.dropdown.addClass(evaluate(this.opts.dropdownCssClass,this.opts.element))});if(el.length&&el[0].attachEvent){el.each(function(){this.attachEvent("onpropertychange",self._sync)})}observer=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver;if(observer!==undefined){if(this.propertyObserver){delete this.propertyObserver;this.propertyObserver=null}this.propertyObserver=new observer(function(mutations){$.each(mutations,self._sync)});this.propertyObserver.observe(el.get(0),{attributes:true,subtree:false})}},triggerSelect:function(data){var evt=$.Event("select2-selecting",{val:this.id(data),object:data,choice:data});this.opts.element.trigger(evt);return!evt.isDefaultPrevented()},triggerChange:function(details){details=details||{};details=$.extend({},details,{type:"change",val:this.val()});this.opts.element.data("select2-change-triggered",true);this.opts.element.trigger(details);this.opts.element.data("select2-change-triggered",false);this.opts.element.click();if(this.opts.blurOnChange)this.opts.element.blur()},isInterfaceEnabled:function(){return this.enabledInterface===true},enableInterface:function(){var enabled=this._enabled&&!this._readonly,disabled=!enabled;if(enabled===this.enabledInterface)return false;this.container.toggleClass("select2-container-disabled",disabled);this.close();this.enabledInterface=enabled;return true},enable:function(enabled){if(enabled===undefined)enabled=true;if(this._enabled===enabled)return;this._enabled=enabled;this.opts.element.prop("disabled",!enabled);this.enableInterface()},disable:function(){this.enable(false)},readonly:function(enabled){if(enabled===undefined)enabled=false;if(this._readonly===enabled)return;this._readonly=enabled;this.opts.element.prop("readonly",enabled);this.enableInterface()},opened:function(){return this.container?this.container.hasClass("select2-dropdown-open"):false},positionDropdown:function(){var $dropdown=this.dropdown,offset=this.container.offset(),height=this.container.outerHeight(false),width=this.container.outerWidth(false),dropHeight=$dropdown.outerHeight(false),$window=$(window),windowWidth=$window.width(),windowHeight=$window.height(),viewPortRight=$window.scrollLeft()+windowWidth,viewportBottom=$window.scrollTop()+windowHeight,dropTop=offset.top+height,dropLeft=offset.left,enoughRoomBelow=dropTop+dropHeight<=viewportBottom,enoughRoomAbove=offset.top-dropHeight>=$window.scrollTop(),dropWidth=$dropdown.outerWidth(false),enoughRoomOnRight=dropLeft+dropWidth<=viewPortRight,aboveNow=$dropdown.hasClass("select2-drop-above"),bodyOffset,above,changeDirection,css,resultsListNode;if(aboveNow){above=true;if(!enoughRoomAbove&&enoughRoomBelow){changeDirection=true;above=false}}else{above=false;if(!enoughRoomBelow&&enoughRoomAbove){changeDirection=true;above=true}}if(changeDirection){$dropdown.hide();offset=this.container.offset();height=this.container.outerHeight(false);width=this.container.outerWidth(false);dropHeight=$dropdown.outerHeight(false);viewPortRight=$window.scrollLeft()+windowWidth;viewportBottom=$window.scrollTop()+windowHeight;dropTop=offset.top+height;dropLeft=offset.left;dropWidth=$dropdown.outerWidth(false);enoughRoomOnRight=dropLeft+dropWidth<=viewPortRight;$dropdown.show();this.focusSearch()}if(this.opts.dropdownAutoWidth){resultsListNode=$(".select2-results",$dropdown)[0];$dropdown.addClass("select2-drop-auto-width");$dropdown.css("width","");dropWidth=$dropdown.outerWidth(false)+(resultsListNode.scrollHeight===resultsListNode.clientHeight?0:scrollBarDimensions.width);dropWidth>width?width=dropWidth:dropWidth=width;dropHeight=$dropdown.outerHeight(false);enoughRoomOnRight=dropLeft+dropWidth<=viewPortRight}else{this.container.removeClass("select2-drop-auto-width")}if(this.body.css("position")!=="static"){bodyOffset=this.body.offset();dropTop-=bodyOffset.top;dropLeft-=bodyOffset.left}if(!enoughRoomOnRight){dropLeft=offset.left+this.container.outerWidth(false)-dropWidth}css={left:dropLeft,width:width};if(above){css.top=offset.top-dropHeight;var searchBarTopOffset=5;if(css.top<searchBarTopOffset){var $dropdownList=$dropdown.find(".select2-results");var newDropdownListHeight=$dropdownList.height()+css.top-searchBarTopOffset;$dropdownList.css("max-height",newDropdownListHeight+"px");css.top=searchBarTopOffset}css.bottom="auto";this.container.addClass("select2-drop-above");$dropdown.addClass("select2-drop-above")}else{css.top=dropTop;css.bottom="auto";this.container.removeClass("select2-drop-above");$dropdown.removeClass("select2-drop-above")}css=$.extend(css,evaluate(this.opts.dropdownCss,this.opts.element));$dropdown.css(css)},shouldOpen:function(){var event;if(this.opened())return false;if(this._enabled===false||this._readonly===true)return false;event=$.Event("select2-opening");this.opts.element.trigger(event);return!event.isDefaultPrevented()},clearDropdownAlignmentPreference:function(){this.container.removeClass("select2-drop-above");this.dropdown.removeClass("select2-drop-above")},open:function(){if(!this.shouldOpen())return false;this.opening();$document.on("mousemove.select2Event",function(e){lastMousePosition.x=e.pageX;lastMousePosition.y=e.pageY});return true},opening:function(){var cid=this.containerEventName,scroll="scroll."+cid,resize="resize."+cid,orient="orientationchange."+cid,mask;this.container.addClass("select2-dropdown-open").addClass("select2-container-active");this.clearDropdownAlignmentPreference();if(this.dropdown[0]!==this.body.children().last()[0]){this.dropdown.detach().appendTo(this.body)}mask=$("#select2-drop-mask");if(mask.length==0){mask=$(document.createElement("div"));mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");mask.hide();mask.appendTo(this.body);mask.on("mousedown touchstart click",function(e){reinsertElement(mask);var dropdown=$("#select2-drop"),self;if(dropdown.length>0){self=dropdown.data("select2");if(self.opts.selectOnBlur){self.selectHighlighted({noFocus:true})}self.close();e.preventDefault();e.stopPropagation()}})}if(this.dropdown.prev()[0]!==mask[0]){this.dropdown.before(mask)}$("#select2-drop").removeAttr("id");this.dropdown.attr("id","select2-drop");mask.show();this.positionDropdown();this.dropdown.show();this.positionDropdown();this.dropdown.addClass("select2-drop-active");var that=this;this.container.parents().add(window).each(function(){$(this).on(resize+" "+scroll+" "+orient,function(e){if(that.opened())that.positionDropdown()})})},close:function(){if(!this.opened())return;var cid=this.containerEventName,scroll="scroll."+cid,resize="resize."+cid,orient="orientationchange."+cid;this.container.parents().add(window).each(function(){$(this).off(scroll).off(resize).off(orient)});this.clearDropdownAlignmentPreference();$("#select2-drop-mask").hide();this.dropdown.removeAttr("id");this.dropdown.hide();this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");this.results.empty();$document.off("mousemove.select2Event");this.clearSearch();this.search.removeClass("select2-active");this.opts.element.trigger($.Event("select2-close"))},externalSearch:function(term){this.open();this.search.val(term);this.updateResults(false)},clearSearch:function(){},getMaximumSelectionSize:function(){return evaluate(this.opts.maximumSelectionSize,this.opts.element)},ensureHighlightVisible:function(){var results=this.results,children,index,child,hb,rb,y,more,topOffset;index=this.highlight();if(index<0)return;if(index==0){results.scrollTop(0);return}children=this.findHighlightableChoices().find(".select2-result-label");child=$(children[index]);topOffset=(child.offset()||{}).top||0;hb=topOffset+child.outerHeight(true);if(index===children.length-1){more=results.find("li.select2-more-results");if(more.length>0){hb=more.offset().top+more.outerHeight(true)}}rb=results.offset().top+results.outerHeight(true);if(hb>rb){results.scrollTop(results.scrollTop()+(hb-rb))}y=topOffset-results.offset().top;if(y<0&&child.css("display")!="none"){results.scrollTop(results.scrollTop()+y)}},findHighlightableChoices:function(){return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)")},moveHighlight:function(delta){var choices=this.findHighlightableChoices(),index=this.highlight();while(index>-1&&index<choices.length){index+=delta;var choice=$(choices[index]);if(choice.hasClass("select2-result-selectable")&&!choice.hasClass("select2-disabled")&&!choice.hasClass("select2-selected")){this.highlight(index);break}}},highlight:function(index){var isIE11=!!navigator.userAgent.match(/Trident.*rv\:11\./),choices=this.findHighlightableChoices(),choice,data;if(arguments.length===0){return indexOf(choices.filter(".select2-highlighted")[0],choices.get())}if(index>=choices.length)index=choices.length-1;if(index<0)index=0;this.removeHighlight();choice=$(choices[index]);choice.addClass("select2-highlighted");this.search.attr("aria-activedescendant",choice.find(".select2-result-label").attr("id"));this.ensureHighlightVisible();if(!isIE11)this.liveRegion.text(choice.text());data=choice.data("select2-data");if(data){this.opts.element.trigger({type:"select2-highlight",val:this.id(data),choice:data})}},removeHighlight:function(){this.results.find(".select2-highlighted").removeClass("select2-highlighted")},touchMoved:function(){this._touchMoved=true},clearTouchMoved:function(){this._touchMoved=false},countSelectableResults:function(){return this.findHighlightableChoices().length},highlightUnderEvent:function(event){var el=$(event.target).closest(".select2-result-selectable");if(el.length>0&&!el.is(".select2-highlighted")){var choices=this.findHighlightableChoices();this.highlight(choices.index(el))}else if(el.length==0){this.removeHighlight()}},loadMoreIfNeeded:function(){var results=this.results,more=results.find("li.select2-more-results"),below,page=this.resultsPage+1,self=this,term=this.search.val(),context=this.context;if(more.length===0)return;below=more.offset().top-results.offset().top-results.height();if(below<=this.opts.loadMorePadding){more.addClass("select2-active");this.opts.query({element:this.opts.element,term:term,page:page,context:context,matcher:this.opts.matcher,callback:this.bind(function(data){if(!self.opened())return;self.opts.populateResults.call(this,results,data.results,{term:term,page:page,context:context});self.postprocessResults(data,false,false);if(data.more===true){more.detach().appendTo(results).text(evaluate(self.opts.formatLoadMore,self.opts.element,page+1));window.setTimeout(function(){self.loadMoreIfNeeded()},10)}else{more.remove()}self.positionDropdown();self.resultsPage=page;self.context=data.context;this.opts.element.trigger({type:"select2-loaded",items:data})})})}},tokenize:function(){},updateResults:function(initial){var search=this.search,results=this.results,opts=this.opts,data,self=this,input,term=search.val(),lastTerm=$.data(this.container,"select2-last-term"),queryNumber;if(initial!==true&&lastTerm&&equal(term,lastTerm))return;$.data(this.container,"select2-last-term",term);if(initial!==true&&(this.showSearchInput===false||!this.opened())){return}function postRender(){search.removeClass("select2-active");self.positionDropdown();if(results.find(".select2-no-results,.select2-selection-limit,.select2-searching").length){self.liveRegion.text(results.text())}else{self.liveRegion.text(self.opts.formatMatches(results.find(".select2-result-selectable").length))}}function render(html){results.html(html);postRender()}queryNumber=++this.queryCount;var maxSelSize=this.getMaximumSelectionSize();if(maxSelSize>=1){data=this.data();if($.isArray(data)&&data.length>=maxSelSize&&checkFormatter(opts.formatSelectionTooBig,"formatSelectionTooBig")){render("<li class='select2-selection-limit'>"+evaluate(opts.formatSelectionTooBig,opts.element,maxSelSize)+"</li>");return}}if(search.val().length<opts.minimumInputLength){if(checkFormatter(opts.formatInputTooShort,"formatInputTooShort")){render("<li class='select2-no-results'>"+evaluate(opts.formatInputTooShort,opts.element,search.val(),opts.minimumInputLength)+"</li>")}else{render("")}if(initial&&this.showSearch)this.showSearch(true);return}if(opts.maximumInputLength&&search.val().length>opts.maximumInputLength){if(checkFormatter(opts.formatInputTooLong,"formatInputTooLong")){render("<li class='select2-no-results'>"+evaluate(opts.formatInputTooLong,opts.element,search.val(),opts.maximumInputLength)+"</li>")}else{render("")}return}if(opts.formatSearching&&this.findHighlightableChoices().length===0){render("<li class='select2-searching'>"+evaluate(opts.formatSearching,opts.element)+"</li>")}search.addClass("select2-active");this.removeHighlight();input=this.tokenize();if(input!=undefined&&input!=null){search.val(input)}this.resultsPage=1;opts.query({element:opts.element,term:search.val(),page:this.resultsPage,context:null,matcher:opts.matcher,callback:this.bind(function(data){var def;if(queryNumber!=this.queryCount){return}if(!this.opened()){this.search.removeClass("select2-active");return}if(data.hasError!==undefined&&checkFormatter(opts.formatAjaxError,"formatAjaxError")){render("<li class='select2-ajax-error'>"+evaluate(opts.formatAjaxError,opts.element,data.jqXHR,data.textStatus,data.errorThrown)+"</li>");return}this.context=data.context===undefined?null:data.context;if(this.opts.createSearchChoice&&search.val()!==""){def=this.opts.createSearchChoice.call(self,search.val(),data.results);if(def!==undefined&&def!==null&&self.id(def)!==undefined&&self.id(def)!==null){if($(data.results).filter(function(){return equal(self.id(this),self.id(def))}).length===0){this.opts.createSearchChoicePosition(data.results,def)}}}if(data.results.length===0&&checkFormatter(opts.formatNoMatches,"formatNoMatches")){render("<li class='select2-no-results'>"+evaluate(opts.formatNoMatches,opts.element,search.val())+"</li>");return}results.empty();self.opts.populateResults.call(this,results,data.results,{term:search.val(),page:this.resultsPage,context:null});if(data.more===true&&checkFormatter(opts.formatLoadMore,"formatLoadMore")){results.append("<li class='select2-more-results'>"+opts.escapeMarkup(evaluate(opts.formatLoadMore,opts.element,this.resultsPage))+"</li>");window.setTimeout(function(){self.loadMoreIfNeeded()},10)}this.postprocessResults(data,initial);postRender();this.opts.element.trigger({type:"select2-loaded",items:data})})})},cancel:function(){this.close()},blur:function(){if(this.opts.selectOnBlur)this.selectHighlighted({noFocus:true});this.close();this.container.removeClass("select2-container-active");if(this.search[0]===document.activeElement){this.search.blur()}this.clearSearch();this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus")},focusSearch:function(){focus(this.search)},selectHighlighted:function(options){if(this._touchMoved){this.clearTouchMoved();return}var index=this.highlight(),highlighted=this.results.find(".select2-highlighted"),data=highlighted.closest(".select2-result").data("select2-data");if(data){this.highlight(index);this.onSelect(data,options)}else if(options&&options.noFocus){this.close()}},getPlaceholder:function(){var placeholderOption;return this.opts.element.attr("placeholder")||this.opts.element.attr("data-placeholder")||this.opts.element.data("placeholder")||this.opts.placeholder||((placeholderOption=this.getPlaceholderOption())!==undefined?placeholderOption.text():undefined)},getPlaceholderOption:function(){if(this.select){var firstOption=this.select.children("option").first();if(this.opts.placeholderOption!==undefined){return this.opts.placeholderOption==="first"&&firstOption||typeof this.opts.placeholderOption==="function"&&this.opts.placeholderOption(this.select)}else if($.trim(firstOption.text())===""&&firstOption.val()===""){return firstOption}}},initContainerWidth:function(){function resolveContainerWidth(){var style,attrs,matches,i,l,attr;if(this.opts.width==="off"){return null}else if(this.opts.width==="element"){return this.opts.element.outerWidth(false)===0?"auto":this.opts.element.outerWidth(false)+"px"}else if(this.opts.width==="copy"||this.opts.width==="resolve"){style=this.opts.element.attr("style");if(style!==undefined){attrs=style.split(";");for(i=0,l=attrs.length;i<l;i=i+1){attr=attrs[i].replace(/\s/g,"");matches=attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);if(matches!==null&&matches.length>=1)return matches[1]}}if(this.opts.width==="resolve"){style=this.opts.element.css("width");if(style.indexOf("%")>0)return style;return this.opts.element.outerWidth(false)===0?"auto":this.opts.element.outerWidth(false)+"px"}return null}else if($.isFunction(this.opts.width)){return this.opts.width()}else{return this.opts.width}}var width=resolveContainerWidth.call(this);if(width!==null){this.container.css("width",width)}}});SingleSelect2=clazz(AbstractSelect2,{createContainer:function(){var labelAriaLabel=this.opts.element.attr("aria-label");var container=$(document.createElement("div")).attr({class:"select2-container"}).html(["<input class='select2-focusser select2-offscreen' type='text' role='combobox' aria-expanded='false' />","<a href='javascript:void(0)' class='select2-choice' tabindex='-1' aria-hidden='true' role='button'>"," <span class='select2-chosen'> </span>"," <span class='select2-arrow' aria-hidden='true'><b></b></span>","</a>","<abbr role='button' class='select2-search-choice-close' tabindex='0' "+(this.opts.clearAriaLabel?"aria-label='"+this.opts.clearAriaLabel+"'":"")+"></abbr>","<div class='select2-drop select2-display-none'>"," <div class='select2-search'>"," <label for='' class='select2-offscreen'",labelAriaLabel?"aria-label='"+labelAriaLabel+"'":"","></label>"," <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'"," aria-autocomplete='list' />"," </div>"," <ul class='select2-results' role='listbox'>"," </ul>","</div>"].join(""));return container},enableInterface:function(){if(this.parent.enableInterface.apply(this,arguments)){this.focusser.prop("disabled",!this.isInterfaceEnabled())}},opening:function(){var el,range,len;if(this.opts.minimumResultsForSearch>=0){this.showSearch(true)}this.parent.opening.apply(this,arguments);if(this.showSearchInput!==false){this.search.val(this.focusser.val())}if(this.opts.shouldFocusInput(this)){this.search.focus();el=this.search.get(0);if(el.createTextRange){range=el.createTextRange();range.collapse(false);range.select()}else if(el.setSelectionRange){len=this.search.val().length;el.setSelectionRange(len,len)}}if(this.search.val()===""){if(this.nextSearchTerm!=undefined){this.search.val(this.nextSearchTerm);this.search.select()}}this.focusser.prop("disabled",true).val("");this.updateResults(true);this.opts.element.trigger($.Event("select2-open"));this.container.find("input")[0].ariaExpanded=true},close:function(){if(!this.opened())return;this.parent.close.apply(this,arguments);this.focusser.prop("disabled",false);if(this.opts.shouldFocusInput(this)){this.focusser.focus()}this.container.find("input")[0].ariaExpanded=false},focus:function(){if(this.opened()){this.close()}else{this.focusser.prop("disabled",false);if(this.opts.shouldFocusInput(this)){this.focusser.focus()}}},isFocused:function(){return this.container.hasClass("select2-container-active")},cancel:function(){this.parent.cancel.apply(this,arguments);this.focusser.prop("disabled",false);if(this.opts.shouldFocusInput(this)){this.focusser.focus()}},destroy:function(){$("label[for='"+this.focusser.attr("id")+"']").attr("for",this.opts.element.attr("id"));this.parent.destroy.apply(this,arguments);cleanupJQueryElements.call(this,"selection","focusser")},initContainer:function(){var selection,container=this.container,dropdown=this.dropdown,idSuffix=nextUid(),elementLabel;if(this.opts.minimumResultsForSearch<0){this.showSearch(false)}else{this.showSearch(true)}this.selection=selection=container.find(".select2-choice");this.focusser=container.find(".select2-focusser");selection.find(".select2-chosen").attr("id","select2-chosen-"+idSuffix);this.focusser.attr("aria-labelledby","select2-chosen-"+idSuffix);this.results.attr("id","select2-results-"+idSuffix);this.search.attr("aria-owns","select2-results-"+idSuffix);if(this.opts.element.attr("aria-required")){this.focusser.attr("aria-required",this.opts.element.attr("aria-required"))}this.focusser.attr("id","s2id_autogen"+idSuffix);this.originalLabel=$("label[for='"+this.opts.element.attr("id")+"']");if(this.originalLabel.length){this.originalLabel.attr("for",this.focusser.attr("id"));var id=this.originalLabel.attr("id")||this.focusser.attr("id")+"-label";this.originalLabel.attr("id",id);this.focusser.attr("aria-labelledby",this.focusser.attr("aria-labelledby")+" "+this.originalLabel.attr("id"))}var originalTitle=this.opts.element.attr("title");this.opts.element.attr("title",originalTitle||this.originalLabel.text());this.focusser.attr("tabindex",this.elementTabIndex);this.search.attr("id",this.focusser.attr("id")+"_search");this.search.prev().text($("label[for='"+this.focusser.attr("id")+"']").text()).attr("for",this.search.attr("id"));this.search.on("keydown",this.bind(function(e){if(!this.isInterfaceEnabled())return;if(229==e.keyCode)return;if(e.which===KEY.PAGE_UP||e.which===KEY.PAGE_DOWN){killEvent(e);return}switch(e.which){case KEY.UP:case KEY.DOWN:this.moveHighlight(e.which===KEY.UP?-1:1);killEvent(e);return;case KEY.ENTER:this.selectHighlighted();killEvent(e);return;case KEY.TAB:this.selectHighlighted({noFocus:true});return;case KEY.ESC:this.cancel(e);killEvent(e);return}}));this.search.on("blur",this.bind(function(e){if(document.activeElement===this.body.get(0)&&e.relatedTarget){window.setTimeout(this.bind(function(){if(this.opened()){this.search.focus()}}),0)}}));this.focusser.on("keydown",this.bind(function(e){if(!this.isInterfaceEnabled())return;if(e.which===KEY.TAB||KEY.isControl(e)||KEY.isFunctionKey(e)||e.which===KEY.ESC){return}if(this.opts.openOnEnter===false&&e.which===KEY.ENTER){killEvent(e);return}if(e.which==KEY.DOWN||e.which==KEY.ENTER&&this.opts.openOnEnter){if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey)return;this.open();killEvent(e);return}if(e.which==KEY.DELETE||e.which==KEY.BACKSPACE){if(this.opts.allowClear){this.clear()}killEvent(e);return}}));installKeyUpChangeEvent(this.focusser);this.focusser.on("keyup-change input",this.bind(function(e){if(this.opts.minimumResultsForSearch>=0){e.stopPropagation();if(this.opened())return;this.open()}}));var clearValue=this.bind(function(e){if(!this.isInterfaceEnabled())return;this.clear();killEventImmediately(e);this.close();this.selection.focus()});container.on("mousedown touchstart","abbr",clearValue).on("keydown","abbr",function(e){switch(e.which){case KEY.ENTER:case KEY.SPACE:clearValue(e)}});selection.on("mousedown touchstart",this.bind(function(e){reinsertElement(selection);if(!this.container.hasClass("select2-container-active")){this.opts.element.trigger($.Event("select2-focus"))}if(this.opened()){this.close()}else if(this.isInterfaceEnabled()){this.open()}killEvent(e)}));dropdown.on("mousedown touchstart",this.bind(function(){if(this.opts.shouldFocusInput(this)){this.search.focus()}}));selection.on("focus",this.bind(function(e){killEvent(e)}));this.focusser.on("focus",this.bind(function(){if(!this.container.hasClass("select2-container-active")){this.opts.element.trigger($.Event("select2-focus"))}this.container.addClass("select2-container-active")})).on("blur",this.bind(function(){if(!this.opened()){this.container.removeClass("select2-container-active");this.opts.element.trigger($.Event("select2-blur"))}}));this.search.on("focus",this.bind(function(){if(!this.container.hasClass("select2-container-active")){this.opts.element.trigger($.Event("select2-focus"))}this.container.addClass("select2-container-active")}));this.initContainerWidth();this.opts.element.addClass("select2-offscreen");this.opts.element.attr("aria-hidden","true");this.setPlaceholder()},clear:function(triggerChange){var data=this.selection.data("select2-data");if(data){var evt=$.Event("select2-clearing");this.opts.element.trigger(evt);if(evt.isDefaultPrevented()){return}var placeholderOption=this.getPlaceholderOption();this.opts.element.val(placeholderOption?placeholderOption.val():"");this.selection.find(".select2-chosen").empty();this.selection.removeData("select2-data");this.setPlaceholder();if(triggerChange!==false){this.opts.element.trigger({type:"select2-removed",val:this.id(data),choice:data});this.triggerChange({removed:data})}}},initSelection:function(){var selected;if(this.isPlaceholderOptionSelected()){this.updateSelection(null);this.close();this.setPlaceholder()}else{var self=this;this.opts.initSelection.call(null,this.opts.element,function(selected){if(selected!==undefined&&selected!==null){self.updateSelection(selected);self.close();self.setPlaceholder();self.nextSearchTerm=self.opts.nextSearchTerm(selected,self.search.val())}})}},isPlaceholderOptionSelected:function(){var placeholderOption;if(this.getPlaceholder()===undefined)return false;return(placeholderOption=this.getPlaceholderOption())!==undefined&&placeholderOption.prop("selected")||this.opts.element.val()===""||this.opts.element.val()===undefined||this.opts.element.val()===null},prepareOpts:function(){var opts=this.parent.prepareOpts.apply(this,arguments),self=this;if(opts.element.get(0).tagName.toLowerCase()==="select"){opts.initSelection=function(element,callback){var selected=element.find("option").filter(function(){return this.selected&&!this.disabled});callback(self.optionToData(selected))}}else if("data"in opts){opts.initSelection=opts.initSelection||function(element,callback){var id=element.val();var match=null;opts.query({matcher:function(term,text,el){var is_match=equal(id,opts.id(el));if(is_match){match=el}return is_match},callback:!$.isFunction(callback)?$.noop:function(){callback(match)}})}}return opts},getPlaceholder:function(){if(this.select){if(this.getPlaceholderOption()===undefined){return undefined}}return this.parent.getPlaceholder.apply(this,arguments)},setPlaceholder:function(){var placeholder=this.getPlaceholder();if(this.isPlaceholderOptionSelected()&&placeholder!==undefined){if(this.select&&this.getPlaceholderOption()===undefined)return;this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));this.selection.addClass("select2-default");this.container.removeClass("select2-allowclear")}},postprocessResults:function(data,initial,noHighlightUpdate){var selected=0,self=this,showSearchInput=true;this.findHighlightableChoices().each2(function(i,elm){if(equal(self.id(elm.data("select2-data")),self.opts.element.val())){selected=i;return false}});if(noHighlightUpdate!==false){if(initial===true&&selected>=0){this.highlight(selected)}else{this.highlight(0)}}if(initial===true){var min=this.opts.minimumResultsForSearch;if(min>=0){this.showSearch(countResults(data.results)>=min)}}},showSearch:function(showSearchInput){if(this.showSearchInput===showSearchInput)return;this.showSearchInput=showSearchInput;this.dropdown.find(".select2-search").toggleClass("select2-search-hidden",!showSearchInput);this.dropdown.find(".select2-search").toggleClass("select2-offscreen",!showSearchInput);$(this.dropdown,this.container).toggleClass("select2-with-searchbox",showSearchInput)},onSelect:function(data,options){if(!this.triggerSelect(data)){return}var old=this.opts.element.val(),oldData=this.data();this.opts.element.val(this.id(data));this.updateSelection(data);this.opts.element.trigger({type:"select2-selected",val:this.id(data),choice:data});this.nextSearchTerm=this.opts.nextSearchTerm(data,this.search.val());this.close();if((!options||!options.noFocus)&&this.opts.shouldFocusInput(this)){this.focusser.focus()}if(!equal(old,this.id(data))){this.triggerChange({added:data,removed:oldData})}},updateSelection:function(data){var container=this.selection.find(".select2-chosen"),formatted,cssClass;this.selection.data("select2-data",data);container.empty();if(data!==null){formatted=this.opts.formatSelection(data,container,this.opts.escapeMarkup)}if(formatted!==undefined){container.append(formatted)}cssClass=this.opts.formatSelectionCssClass(data,container);if(cssClass!==undefined){container.addClass(cssClass)}this.selection.removeClass("select2-default");if(this.opts.allowClear&&this.getPlaceholder()!==undefined){this.container.addClass("select2-allowclear")}},val:function(){var val,triggerChange=false,data=null,self=this,oldData=this.data();if(arguments.length===0){return this.opts.element.val()}val=arguments[0];if(arguments.length>1){triggerChange=arguments[1]}if(this.select){this.select.val(val).find("option").filter(function(){return this.selected}).each2(function(i,elm){data=self.optionToData(elm);return false});this.updateSelection(data);this.setPlaceholder();if(triggerChange){this.triggerChange({added:data,removed:oldData})}}else{if(!val&&val!==0){this.clear(triggerChange);return}if(this.opts.initSelection===undefined){throw new Error("cannot call val() if initSelection() is not defined")}this.opts.element.val(val);this.opts.initSelection(this.opts.element,function(data){self.opts.element.val(!data?"":self.id(data));self.updateSelection(data);self.setPlaceholder();if(triggerChange){self.triggerChange({added:data,removed:oldData})}})}},clearSearch:function(){this.search.val("");this.focusser.val("")},data:function(value){var data,triggerChange=false;if(arguments.length===0){data=this.selection.data("select2-data");if(data==undefined)data=null;return data}else{if(arguments.length>1){triggerChange=arguments[1]}if(!value){this.clear(triggerChange)}else{data=this.data();this.opts.element.val(!value?"":this.id(value));this.updateSelection(value);if(triggerChange){this.triggerChange({added:value,removed:data})}}}}});MultiSelect2=clazz(AbstractSelect2,{createContainer:function(){var labelAriaLabel=this.opts.element.attr("aria-label");var container=$(document.createElement("div")).attr({class:"select2-container select2-container-multi"}).html(["<ul class='select2-choices' role='presentation'>"," <li class='select2-search-field'>"," <label for='' class='select2-offscreen' ",labelAriaLabel?"aria-label='"+labelAriaLabel+"'":"","></label>"," <input type='text' role='combobox' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' aria-autocomplete='list' />"," </li>","</ul>","<div class='select2-drop select2-drop-multi select2-display-none'>"," <ul class='select2-results' role='listbox'>"," </ul>","</div>"].join(""));return container},prepareOpts:function(){var opts=this.parent.prepareOpts.apply(this,arguments),self=this;if(opts.element.get(0).tagName.toLowerCase()==="select"){opts.initSelection=function(element,callback){var data=[];element.find("option").filter(function(){return this.selected&&!this.disabled}).each2(function(i,elm){data.push(self.optionToData(elm))});callback(data)}}else if("data"in opts){opts.initSelection=opts.initSelection||function(element,callback){var ids=splitVal(element.val(),opts.separator);var matches=[];opts.query({matcher:function(term,text,el){var is_match=$.grep(ids,function(id){return equal(id,opts.id(el))}).length;if(is_match){matches.push(el)}return is_match},callback:!$.isFunction(callback)?$.noop:function(){var ordered=[];for(var i=0;i<ids.length;i++){var id=ids[i];for(var j=0;j<matches.length;j++){var match=matches[j];if(equal(id,opts.id(match))){ordered.push(match);matches.splice(j,1);break}}}callback(ordered)}})}}return opts},selectChoice:function(choice){var selected=this.container.find(".select2-search-choice-focus");if(selected.length&&choice&&choice[0]==selected[0]){}else{if(selected.length){this.opts.element.trigger("choice-deselected",selected)}selected.removeClass("select2-search-choice-focus");if(choice&&choice.length){this.close();choice.addClass("select2-search-choice-focus");this.opts.element.trigger("choice-selected",choice);this.liveRegion.text(choice.text())}}},destroy:function(){$("label[for='"+this.search.attr("id")+"']").attr("for",this.opts.element.attr("id"));this.parent.destroy.apply(this,arguments);cleanupJQueryElements.call(this,"searchContainer","selection")},initContainer:function(){var selector=".select2-choices",selection;this.searchContainer=this.container.find(".select2-search-field");this.selection=selection=this.container.find(selector);var _this=this;this.selection.on("click",".select2-search-choice:not(.select2-locked)",function(e){_this.search[0].focus();_this.selectChoice($(this))});this.search.attr("id","s2id_autogen"+nextUid());this.results.attr("id",this.search.attr("id")+"_results");this.search.attr("aria-owns",this.results.attr("id"));this.originalLabel=$("label[for='"+this.opts.element.attr("id")+"']");if(this.originalLabel.length){this.originalLabel.attr("for",this.search.attr("id"))}if(this.opts.element.attr("aria-required")){this.search.attr("aria-required",this.opts.element.attr("aria-required"))}this.search.on("input paste",this.bind(function(){if(this.search.attr("placeholder")&&this.search.val().length==0)return;if(!this.isInterfaceEnabled())return;if(!this.opened()){this.open()}}));this.search.attr("tabindex",this.elementTabIndex);this.keydowns=0;this.search.on("keydown",this.bind(function(e){if(!this.isInterfaceEnabled())return;++this.keydowns;var selected=selection.find(".select2-search-choice-focus");var prev=selected.prev(".select2-search-choice:not(.select2-locked)");var next=selected.next(".select2-search-choice:not(.select2-locked)");var pos=getCursorInfo(this.search);if(selected.length&&(e.which==KEY.LEFT||e.which==KEY.RIGHT||e.which==KEY.BACKSPACE||e.which==KEY.DELETE||e.which==KEY.ENTER)){var selectedChoice=selected;if(e.which==KEY.LEFT&&prev.length){selectedChoice=prev}else if(e.which==KEY.RIGHT){selectedChoice=next.length?next:null}else if(e.which===KEY.BACKSPACE){if(this.unselect(selected.first())){this.search.width(10);selectedChoice=prev.length?prev:next}}else if(e.which==KEY.DELETE){if(this.unselect(selected.first())){this.search.width(10);selectedChoice=next.length?next:null}}else if(e.which==KEY.ENTER){selectedChoice=null}this.selectChoice(selectedChoice);killEvent(e);if(!selectedChoice||!selectedChoice.length){this.open()}return}else if((e.which===KEY.BACKSPACE&&this.keydowns==1||e.which==KEY.LEFT)&&(pos.offset==0&&!pos.length)){this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());killEvent(e);return}else{this.selectChoice(null)}if(this.opened()){switch(e.which){case KEY.UP:case KEY.DOWN:this.moveHighlight(e.which===KEY.UP?-1:1);killEvent(e);return;case KEY.ENTER:this.selectHighlighted();killEvent(e);return;case KEY.TAB:this.selectHighlighted({noFocus:true});this.close();return;case KEY.ESC:this.cancel(e);killEvent(e);return}}if(e.which===KEY.TAB||KEY.isControl(e)||KEY.isFunctionKey(e)||e.which===KEY.BACKSPACE||e.which===KEY.ESC){return}if(e.which===KEY.ENTER){if(this.opts.openOnEnter===false){return}else if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey){return}}this.open();if(e.which===KEY.PAGE_UP||e.which===KEY.PAGE_DOWN){killEvent(e)}if(e.which===KEY.ENTER){killEvent(e)}}));this.search.on("keyup",this.bind(function(e){this.keydowns=0;this.resizeSearch()}));this.search.on("blur",this.bind(function(e){this.container.removeClass("select2-container-active");this.search.removeClass("select2-focused");this.selectChoice(null);if(!this.opened())this.clearSearch();e.stopImmediatePropagation();this.opts.element.trigger($.Event("select2-blur"))}));this.container.on("click",selector,this.bind(function(e){if(!this.isInterfaceEnabled())return;if($(e.target).closest(".select2-search-choice").length>0){return}this.selectChoice(null);this.clearPlaceholder();if(!this.container.hasClass("select2-container-active")){this.opts.element.trigger($.Event("select2-focus"))}this.open();this.focusSearch();e.preventDefault()}));this.container.on("focus",selector,this.bind(function(){if(!this.isInterfaceEnabled())return;if(!this.container.hasClass("select2-container-active")){this.opts.element.trigger($.Event("select2-focus"))}this.container.addClass("select2-container-active");this.dropdown.addClass("select2-drop-active");this.clearPlaceholder()}));this.initContainerWidth();this.opts.element.addClass("select2-offscreen");this.clearSearch()},enableInterface:function(){if(this.parent.enableInterface.apply(this,arguments)){this.search.prop("disabled",!this.isInterfaceEnabled())}},initSelection:function(){var data;if(this.opts.element.val()===""&&this.opts.element.text()===""){this.updateSelection([]);this.close();this.clearSearch()}if(this.select||this.opts.element.val()!==""){var self=this;this.opts.initSelection.call(null,this.opts.element,function(data){if(data!==undefined&&data!==null){self.updateSelection(data);self.close();self.clearSearch()}})}},clearSearch:function(){var placeholder=this.getPlaceholder(),maxWidth=this.getMaxSearchWidth();if(placeholder!==undefined&&this.getVal().length===0&&this.search.hasClass("select2-focused")===false){this.search.val(placeholder).addClass("select2-default");this.search.width(maxWidth>0?maxWidth:this.container.css("width"))}else{this.search.val("").width(10)}},clearPlaceholder:function(){if(this.search.hasClass("select2-default")){this.search.val("").removeClass("select2-default")}},opening:function(){this.clearPlaceholder();this.resizeSearch();this.parent.opening.apply(this,arguments);this.focusSearch();if(this.search.val()===""){if(this.nextSearchTerm!=undefined){this.search.val(this.nextSearchTerm);this.search.select()}}this.updateResults(true);if(this.opts.shouldFocusInput(this)){this.search.focus()}this.opts.element.trigger($.Event("select2-open"))},close:function(){if(!this.opened())return;this.parent.close.apply(this,arguments)},focus:function(){this.close();this.search.focus()},isFocused:function(){return this.search.hasClass("select2-focused")},updateSelection:function(data){var ids=[],filtered=[],self=this;$(data).each(function(){if(indexOf(self.id(this),ids)<0){ids.push(self.id(this));filtered.push(this)}});data=filtered;this.selection.find(".select2-search-choice").remove();$(data).each(function(){self.addSelectedChoice(this)});self.postprocessResults()},tokenize:function(){var input=this.search.val();input=this.opts.tokenizer.call(this,input,this.data(),this.bind(this.onSelect),this.opts);if(input!=null&&input!=undefined){this.search.val(input);if(input.length>0){this.open()}}},onSelect:function(data,options){if(!this.triggerSelect(data)||data.text===""){return}this.addSelectedChoice(data);this.opts.element.trigger({type:"selected",val:this.id(data),choice:data});this.nextSearchTerm=this.opts.nextSearchTerm(data,this.search.val());this.clearSearch();this.updateResults();var describedString=this.getVal().map(function(val){return this.search.attr("id")+"_choice_"+val},this).join(" ");this.search.attr("aria-describedby",describedString);if(this.select||!this.opts.closeOnSelect)this.postprocessResults(data,false,this.opts.closeOnSelect===true);if(this.opts.closeOnSelect){this.close();this.search.width(10)}else{if(this.countSelectableResults()>0){this.search.width(10);this.resizeSearch();if(this.getMaximumSelectionSize()>0&&this.val().length>=this.getMaximumSelectionSize()){this.updateResults(true)}else{if(this.nextSearchTerm!=undefined){this.search.val(this.nextSearchTerm);this.updateResults();this.search.select()}}this.positionDropdown()}else{this.close();this.search.width(10)}}this.triggerChange({added:data});if(!options||!options.noFocus)this.focusSearch()},cancel:function(){this.close();this.focusSearch()},addSelectedChoice:function(data){var enableChoice=!data.locked,enabledItem=$("<li class='select2-search-choice'>"+" <div></div>"+" <a href='#' role='button' class='select2-search-choice-close' tabindex='-1'></a>"+"</li>"),disabledItem=$("<li class='select2-search-choice select2-locked'>"+"<div></div>"+"</li>");var choice=enableChoice?enabledItem:disabledItem,id=this.id(data),val=this.getVal(),formatted,cssClass;choice.attr("id",this.search.attr("id")+"_choice_"+id);formatted=this.opts.formatSelection(data,choice.find("div"),this.opts.escapeMarkup);if(formatted!=undefined){choice.find("div").replaceWith("<div>"+formatted+"</div>")}cssClass=this.opts.formatSelectionCssClass(data,choice.find("div"));if(cssClass!=undefined){choice.addClass(cssClass)}if(enableChoice){choice.find(".select2-search-choice-close").on("mousedown",killEvent).on("click dblclick",this.bind(function(e){if(!this.isInterfaceEnabled())return;this.unselect($(e.target));this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");killEvent(e);this.close();this.focusSearch()})).on("focus",this.bind(function(){if(!this.isInterfaceEnabled())return;this.container.addClass("select2-container-active");this.dropdown.addClass("select2-drop-active")}))}choice.data("select2-data",data);choice.insertBefore(this.searchContainer);val.push(id);this.setVal(val)},unselect:function(selected){var val=this.getVal(),data,index;selected=selected.closest(".select2-search-choice");if(selected.length===0){throw"Invalid argument: "+selected+". Must be .select2-search-choice"}data=selected.data("select2-data");if(!data){return}var evt=$.Event("select2-removing");evt.val=this.id(data);evt.choice=data;this.opts.element.trigger(evt);if(evt.isDefaultPrevented()){return false}while((index=indexOf(this.id(data),val))>=0){val.splice(index,1);this.setVal(val);if(this.select)this.postprocessResults()}selected.remove();this.opts.element.trigger({type:"select2-removed",val:this.id(data),choice:data});this.triggerChange({removed:data});return true},postprocessResults:function(data,initial,noHighlightUpdate){var val=this.getVal(),choices=this.results.find(".select2-result"),compound=this.results.find(".select2-result-with-children"),self=this;choices.each2(function(i,choice){var id=self.id(choice.data("select2-data"));if(indexOf(id,val)>=0){choice.addClass("select2-selected");choice.find(".select2-result-selectable").addClass("select2-selected")}});compound.each2(function(i,choice){if(!choice.is(".select2-result-selectable")&&choice.find(".select2-result-selectable:not(.select2-selected)").length===0){choice.addClass("select2-selected")}});if(this.highlight()==-1&&noHighlightUpdate!==false){self.highlight(0)}if(!this.opts.createSearchChoice&&!choices.filter(".select2-result:not(.select2-selected)").length>0){if(!data||data&&!data.more&&this.results.find(".select2-no-results").length===0){if(checkFormatter(self.opts.formatNoMatches,"formatNoMatches")){this.results.append("<li class='select2-no-results'>"+evaluate(self.opts.formatNoMatches,self.opts.element,self.search.val())+"</li>")}}}},getMaxSearchWidth:function(){return this.selection.width()-getSideBorderPadding(this.search)},resizeSearch:function(){var minimumWidth,left,maxWidth,containerLeft,searchWidth,sideBorderPadding=getSideBorderPadding(this.search);minimumWidth=measureTextWidth(this.search)+10;left=this.search.offset().left;maxWidth=this.selection.width();containerLeft=this.selection.offset().left;searchWidth=maxWidth-(left-containerLeft)-sideBorderPadding;if(searchWidth<minimumWidth){searchWidth=maxWidth-sideBorderPadding}if(searchWidth<40){searchWidth=maxWidth-sideBorderPadding}if(searchWidth<=0){searchWidth=minimumWidth}this.search.width(Math.floor(searchWidth))},getVal:function(){var val;if(this.select){val=this.select.val();return val===null?[]:val}else{val=this.opts.element.val();return splitVal(val,this.opts.separator)}},setVal:function(val){var unique;if(this.select){this.select.val(val)}else{unique=[];$(val).each(function(){if(indexOf(this,unique)<0)unique.push(this)});this.opts.element.val(unique.length===0?"":unique.join(this.opts.separator))}},buildChangeDetails:function(old,current){var current=current.slice(0),old=old.slice(0);for(var i=0;i<current.length;i++){for(var j=0;j<old.length;j++){if(equal(this.opts.id(current[i]),this.opts.id(old[j]))){current.splice(i,1);if(i>0){i--}old.splice(j,1);j--}}}return{added:current,removed:old}},val:function(val,triggerChange){var oldData,self=this;if(arguments.length===0){return this.getVal()}oldData=this.data();if(!oldData.length)oldData=[];if(!val&&val!==0){this.opts.element.val("");this.updateSelection([]);this.clearSearch();if(triggerChange){this.triggerChange({added:this.data(),removed:oldData})}return}this.setVal(val);if(this.select){this.opts.initSelection(this.select,this.bind(this.updateSelection));if(triggerChange){this.triggerChange(this.buildChangeDetails(oldData,this.data()))}}else{if(this.opts.initSelection===undefined){throw new Error("val() cannot be called if initSelection() is not defined")}this.opts.initSelection(this.opts.element,function(data){var ids=$.map(data,self.id);self.setVal(ids);self.updateSelection(data);self.clearSearch();if(triggerChange){self.triggerChange(self.buildChangeDetails(oldData,self.data()))}})}this.clearSearch()},onSortStart:function(){if(this.select){throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.")}this.search.width(0);this.searchContainer.hide()},onSortEnd:function(){var val=[],self=this;this.searchContainer.show();this.searchContainer.appendTo(this.searchContainer.parent());this.resizeSearch();this.selection.find(".select2-search-choice").each(function(){val.push(self.opts.id($(this).data("select2-data")))});this.setVal(val);this.triggerChange()},data:function(values,triggerChange){var self=this,ids,old;if(arguments.length===0){return this.selection.children(".select2-search-choice").map(function(){return $(this).data("select2-data")}).get()}else{old=this.data();if(!values){values=[]}ids=$.map(values,function(e){return self.opts.id(e)});this.setVal(ids);this.updateSelection(values);this.clearSearch();if(triggerChange){this.triggerChange(this.buildChangeDetails(old,this.data()))}}}});$.fn.select2=function(){var args=Array.prototype.slice.call(arguments,0),opts,select2,method,value,multiple,allowedMethods=["val","destroy","opened","open","close","focus","isFocused","container","dropdown","onSortStart","onSortEnd","enable","disable","readonly","positionDropdown","data","search"],valueMethods=["opened","isFocused","container","dropdown"],propertyMethods=["val","data"],methodsMap={search:"externalSearch"};this.each(function(){if(args.length===0||typeof args[0]==="object"){opts=args.length===0?{}:$.extend({},args[0]);opts.element=$(this);if(opts.element.get(0).tagName.toLowerCase()==="select"){multiple=opts.element.prop("multiple")}else{multiple=opts.multiple||false;if("tags"in opts){opts.multiple=multiple=true}}select2=multiple?new window.Select2["class"].multi:new window.Select2["class"].single;select2.init(opts)}else if(typeof args[0]==="string"){if(indexOf(args[0],allowedMethods)<0){throw"Unknown method: "+args[0]}value=undefined;select2=$(this).data("select2");if(select2===undefined)return;method=args[0];if(method==="container"){value=select2.container}else if(method==="dropdown"){value=select2.dropdown}else{if(methodsMap[method])method=methodsMap[method];value=select2[method].apply(select2,args.slice(1))}if(indexOf(args[0],valueMethods)>=0||indexOf(args[0],propertyMethods)>=0&&args.length==1){return false}}else{throw"Invalid arguments to select2 plugin: "+args}});return value===undefined?this:value};$.fn.select2.defaults={width:"copy",loadMorePadding:0,closeOnSelect:true,openOnEnter:true,containerCss:{},dropdownCss:{},containerCssClass:"",dropdownCssClass:"",formatResult:function(result,container,query,escapeMarkup){var markup=[];markMatch(result.text,query.term,markup,escapeMarkup);return markup.join("")},formatSelection:function(data,container,escapeMarkup){return data?escapeMarkup(data.text):undefined},sortResults:function(results,container,query){return results},formatResultCssClass:function(data){return data.css},formatSelectionCssClass:function(data,container){return undefined},minimumResultsForSearch:0,minimumInputLength:0,maximumInputLength:null,maximumSelectionSize:0,id:function(e){return e==undefined?null:e.id},matcher:function(term,text){return stripDiacritics(""+text).toUpperCase().indexOf(stripDiacritics(""+term).toUpperCase())>=0},separator:",",tokenSeparators:[],tokenizer:defaultTokenizer,escapeMarkup:defaultEscapeMarkup,blurOnChange:false,selectOnBlur:false,adaptContainerCssClass:function(c){return c},adaptDropdownCssClass:function(c){return null},nextSearchTerm:function(selectedObject,currentSearchTerm){return undefined},searchInputPlaceholder:"",createSearchChoicePosition:"top",shouldFocusInput:function(instance){var supportsTouchEvents="ontouchstart"in window||navigator.msMaxTouchPoints>0;if(!supportsTouchEvents){return true}if(instance.opts.minimumResultsForSearch<0){return false}return true}};$.fn.select2.locales=[];$.fn.select2.locales["en"]={formatMatches:function(matches){if(matches===1){return"One result is available, press enter to select it."}return matches+" results are available, use up and down arrow keys to navigate."},formatNoMatches:function(){return"No matches found"},formatAjaxError:function(jqXHR,textStatus,errorThrown){return"Loading failed"},formatInputTooShort:function(input,min){var n=min-input.length;return"Please enter "+n+" or more character"+(n==1?"":"s")},formatInputTooLong:function(input,max){var n=input.length-max;return"Please delete "+n+" character"+(n==1?"":"s")},formatSelectionTooBig:function(limit){return"You can only select "+limit+" item"+(limit==1?"":"s")},formatLoadMore:function(pageNumber){return"Loading more results…"},formatSearching:function(){return"Searching…"}};$.extend($.fn.select2.defaults,$.fn.select2.locales["en"]);$.fn.select2.ajaxDefaults={transport:$.ajax,params:{type:"GET",cache:false,dataType:"json"}};window.Select2={query:{ajax:ajax,local:local,tags:tags},util:{debounce:debounce,markMatch:markMatch,escapeMarkup:defaultEscapeMarkup,stripDiacritics:stripDiacritics},class:{abstract:AbstractSelect2,single:SingleSelect2,multi:MultiSelect2}}})(jQuery); /*! RESOURCE: /scripts/select2_translations.js */ (function($) { if (!$ || !window.GwtMessage) { return; } function getMessage() { var gwt = new GwtMessage(); return gwt.getMessage.apply(gwt, arguments); } $.extend($.fn.select2.defaults, { formatMatches: function(matches) { return getMessage("{0} result(s) available, use up and down arrow keys to navigate and enter to select", matches); }, formatNoMatches: function() { return getMessage("No matches found"); }, formatAjaxError: function(jqXHR, textStatus, errorThrown) { return getMessage("Loading failed"); }, formatInputTooShort: function(input, min) { var n = min - input.length; return getMessage("Please enter {0} or more character(s)", n); }, formatInputTooLong: function(input, max) { var n = input.length - max; return getMessage("Please delete {0} character(s)", n); }, formatSelectionTooBig: function(limit) { return getMessage("You can only select {0} item(s)", limit); }, formatLoadMore: function(pageNumber) { return getMessage("Loading more results…"); }, formatSearching: function() { return getMessage("Searching…"); } }); })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/selects.js */ jQuery(function($) { "use strict"; window.NOW = window.NOW || {}; var $select2 = $('select.select2, select.sn-select-basic').not('select[readonly]'); $select2 .each(function() { var required = $(this).prop('required'); if (required) $(this).addClass('required'); }) .select2(); $(window).bind('blur', function() { $select2.select2('close'); }); }); ; /*! RESOURCE: /scripts/heisenberg/custom/tabs.js */ (function($) { "use strict"; $.fn.tabs = (function() { return function() { var $elem = this; var api = {}; $elem.data('sn.tabs', api); attachTabClickHandler($elem); attachFocusHandler($elem); }; function attachTabClickHandler($elem) { $elem.on('click', 'li, [data-toggle=tab], [data-toggle=segmented]', function (e) { var $el = $(this); var $tabLi, $tabTrigger; if ($el.is('li')) { $tabLi = $el; $tabTrigger = $el.find('[data-toggle]').first(); } else { $tabTrigger = $el; $tabLi = $el.closest('li'); } if ($tabLi.hasClass('disabled')) return; var $selectedTab = $tabLi.siblings('.active'); var $selectedTabTrigger = $selectedTab.find('[data-toggle]').first(); setTabDisplay($selectedTab, $selectedTabTrigger, false); setTabDisplay($tabLi, $tabTrigger, true); e.preventDefault(); }) } function attachFocusHandler($elem) { $elem.on('focusin focusout', '[data-toggle=tab], [data-toggle=segmented]', function(e) { var $el = $(this).closest('li'); switch (e.type) { case 'focusin': $el.addClass('focus'); break; case 'focusout': $el.removeClass('focus'); break; } }) } function setTabDisplay($tabLi, $tabTrigger, display) { $tabTrigger.attr('aria-selected', display ? 'true' : 'false'); var selector = $tabTrigger.data('tab-target') || $tabTrigger.attr('href'); selector = selector && selector.replace(/.*(?=#[^\s]*$)/, ''); var $tabpanel = $(selector); $tabpanel.attr('aria-hidden', display ? 'false' : 'true'); if (display) { $tabLi.addClass('active justselected'); $tabpanel.addClass('active'); $tabLi.one('focusout', function () { $tabLi.removeClass('justselected'); }) } else { $tabLi.removeClass('active'); $tabpanel.removeClass('active'); } } })(); $(function() { $('.sn-tabs-basic').each(function() { var $this = $(this); if (!$this.data('sn.tabs')) $this.tabs(); }); }); })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/custom/tables.js */ (function($) { "use strict"; $.fn.tableDetailRowHover = function() { this.each(function() { $(this) .on('mouseenter mouseleave', 'tr', function(evt) { var row = getTargetAdjRow($(this)); evt.type == 'mouseenter' ? row.addClass('hover') : row.removeClass('hover'); }); }) } function getTargetAdjRow(row) { return row.hasClass('detail-row') ? row.prev() : row.next(); } })(jQuery); jQuery(function($) { "use strict"; $('.detail-row:nth-child(2)').closest('table.table').addClass('table-detail-row'); $('.table-hover.table-detail-row').tableDetailRowHover(); }); ; /*! RESOURCE: /scripts/lib/tabbable/tabbable.js */ (function() { window.tabbable = function(el, selectorList) { var basicTabbables = []; var orderedTabbables = []; var isHidden = createIsHidden(); var candidates = el.querySelectorAll(selectorList || 'input, select, a[href], textarea, button, [tabindex], [contenteditable]:not([contenteditable="false"])'); var candidate, candidateIndex; for (var i = 0, l = candidates.length; i < l; i++) { candidate = candidates[i]; candidateIndex = getTabindex(candidate); if ( candidateIndex < 0 || (candidate.tagName === 'INPUT' && candidate.type === 'hidden') || candidate.disabled || isHidden(candidate) ) { continue; } if (candidateIndex === 0) { basicTabbables.push(candidate); } else { orderedTabbables.push({ tabIndex: candidateIndex, node: candidate, }); } } var tabbableNodes = orderedTabbables .sort(function(a, b) { return a.tabIndex - b.tabIndex; }) .map(function(a) { return a.node }); Array.prototype.push.apply(tabbableNodes, basicTabbables); return tabbableNodes; } function isContentEditable(node) { return node.contentEditable === "true"; } function getTabindex(node) { var tabindexAttr = parseInt(node.getAttribute('tabindex'), 10); if (!isNaN(tabindexAttr)) return tabindexAttr; if (isContentEditable(node)) return 0; return node.tabIndex; } function createIsHidden() { var nodeCache = []; return function isHidden(node) { if (node === document.documentElement || !node.tagName) return false; for (var i = 0, length = nodeCache.length; i < length; i++) { if (nodeCache[i][0] === node) return nodeCache[i][1]; } var result = false; var style = window.getComputedStyle(node); if (style.visibility === 'hidden' || style.display === 'none') { result = true; } else if (node.parentNode) { result = isHidden(node.parentNode); } nodeCache.push([node, result]); return result; } } })(); ; /*! RESOURCE: /scripts/lib/focus-trap/focus-trap.js */ (function() { var listeningFocusTrap = null; function focusTrap(element, userOptions) { var tabbableNodes = []; var nodeFocusedBeforeActivation = null; var active = false; var container = (typeof element === 'string') ? document.querySelector(element) : element; var config = userOptions || {}; config.returnFocusOnDeactivate = (userOptions && userOptions.returnFocusOnDeactivate != undefined) ? userOptions.returnFocusOnDeactivate : true; config.escapeDeactivates = (userOptions && userOptions.escapeDeactivates != undefined) ? userOptions.escapeDeactivates : true; var trap = { activate: activate, deactivate: deactivate, pause: removeListeners, unpause: addListeners }; return trap; function activate(activateOptions) { var defaultedActivateOptions = { onActivate: (activateOptions && activateOptions.onActivate !== undefined) ? activateOptions.onActivate : config.onActivate, }; active = true; nodeFocusedBeforeActivation = getFocusedElement(); if (defaultedActivateOptions.onActivate) { defaultedActivateOptions.onActivate(); } addListeners(); return trap; } function deactivate(deactivateOptions) { var defaultedDeactivateOptions = { returnFocus: (deactivateOptions && deactivateOptions.returnFocus != undefined) ? deactivateOptions.returnFocus : config.returnFocusOnDeactivate, returnFocusTo: deactivateOptions && deactivateOptions.returnFocusTo, onDeactivate: (deactivateOptions && deactivateOptions.onDeactivate !== undefined) ? deactivateOptions.onDeactivate : config.onDeactivate, }; removeListeners(); if (defaultedDeactivateOptions.onDeactivate) { defaultedDeactivateOptions.onDeactivate(); } if (defaultedDeactivateOptions.returnFocus) { setTimeout(function() { tryFocus(defaultedDeactivateOptions.returnFocusTo || nodeFocusedBeforeActivation); }, 0); } active = false; return this; } function addListeners() { if (!active) return; if (listeningFocusTrap) { listeningFocusTrap.pause(); } listeningFocusTrap = trap; updateTabbableNodes(); tryFocus(firstFocusNode()); document.addEventListener('focus', checkFocus, true); document.addEventListener('click', checkClick, true); document.addEventListener('mousedown', checkPointerDown, true); document.addEventListener('touchstart', checkPointerDown, true); document.addEventListener('keydown', checkKey, true); return trap; } function removeListeners() { if (!active || !listeningFocusTrap) return; document.removeEventListener('focus', checkFocus, true); document.removeEventListener('click', checkClick, true); document.removeEventListener('mousedown', checkPointerDown, true); document.removeEventListener('touchstart', checkPointerDown, true); document.removeEventListener('keydown', checkKey, true); listeningFocusTrap = null; return trap; } function firstFocusNode() { var node; if (!config.initialFocus) { node = tabbableNodes[0]; if (!node) { throw new Error('You can\'t have a focus-trap without at least one focusable element'); } return node; } node = (typeof config.initialFocus === 'string') ? document.querySelector(config.initialFocus) : config.initialFocus; if (!node) { throw new Error('`initialFocus` refers to no known node'); } return node; } function checkPointerDown(e) { if (config.clickOutsideDeactivates) { deactivate({ returnFocus: false }); } } function checkClick(e) { if (config.clickOutsideDeactivates) return; var composedPath = getEventPath(e); if (composedPath.indexOf(container) >= 0) return; e.preventDefault(); e.stopImmediatePropagation(); } function checkFocus(e) { if (config.focusOutsideDeactivates === false) return; var composedPath = getEventPath(e); var target = composedPath[0]; if (composedPath.indexOf(container) >= 0) return; e.preventDefault(); e.stopImmediatePropagation(); target.blur(); } function checkKey(e) { if (e.key === 'Tab' || e.keyCode === 9) { handleTab(e); } if (config.escapeDeactivates !== false && isEscapeEvent(e)) { deactivate(); } } function handleTab(e) { e.preventDefault(); updateTabbableNodes(); var target = getEventPath(e)[0]; var currentFocusIndex = tabbableNodes.indexOf(target); var lastTabbableNode = tabbableNodes[tabbableNodes.length - 1]; var firstTabbableNode = tabbableNodes[0]; if (e.shiftKey) { if (target === firstTabbableNode || tabbableNodes.indexOf(target) === -1) { return tryFocus(lastTabbableNode); } return tryFocus(tabbableNodes[currentFocusIndex - 1]); } if (target === lastTabbableNode) return tryFocus(firstTabbableNode); tryFocus(tabbableNodes[currentFocusIndex + 1]); } function updateTabbableNodes() { tabbableNodes = tabbable(container); } } function isEscapeEvent(e) { return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27; } function tryFocus(node) { if (!node || !node.focus) return; node.focus(); if (node.tagName.toLowerCase() === 'input') { node.select(); } } function getFocusedElement() { var activeElement = document.activeElement; if (!activeElement || activeElement === document.body) { return; } var getShadowActiveElement = function(element) { if (element.shadowRoot && element.shadowRoot.activeElement) { element = getShadowActiveElement(element.shadowRoot.activeElement); } return element; }; return getShadowActiveElement(activeElement); } function getEventPath(evt) { return evt.path || (evt.composedPath && evt.composedPath()) || composedPath(evt.target); } function composedPath(el) { var path = []; while (el) { if (el.shadowRoot) { if (el.shadowRoot.activeElement) { path.push(el.shadowRoot.activeElement); } path.push(el.shadowRoot); } path.push(el); if (el.tagName === 'HTML') { path.push(document); path.push(window); break; } el = el.parentElement; } return path; } window.focusTrap = focusTrap; })(); ; /*! RESOURCE: /scripts/heisenberg/custom/accessibility.js */ jQuery(function($) { if (!window.WeakMap) return; window.NOW = window.NOW || {}; if (window.NOW.accessibilityJSLoaded) { return; } window.NOW.accessibilityJSLoaded = true; var $document = $(document), store = new WeakMap(); $document.on('show.bs.modal', function(evt) { var modal = evt.target, previouslyFocusedElement = document.activeElement; if (hasOptions(modal)) return; createOptions(modal); rememberTrigger(modal, previouslyFocusedElement); }); $document.on('hidden.bs.modal', function(evt) { var modal = evt.target; restoreTriggerFocus(modal); destroyOptions(modal); }); function createOptions(modal) { store.set(modal, {}); } function hasOptions(modal) { return !!store.get(modal); } function destroyOptions(modal) { store.delete(modal); } function getOption(modal, key) { var options = store.get(modal); return options && options[key]; } function setOption(modal, key, value) { var options = store.get(modal); if (options) { options[key] = value; } } function rememberTrigger(modal, triggerElement) { setOption(modal, 'trigger-element', triggerElement); } function restoreTriggerFocus(modal) { var $target = $(getOption(modal, 'trigger-element')); var isFocusable = function($el) { if ($el.filter(':visible').length > 0) { return $el[0].tabIndex > -1; } return false; } var tryFocus = function(el) { var $el = $(el); if (isFocusable($el)) { $el.focus(); return true; } return false; } do { if (tryFocus($target) || tryFocus($target.data('menu-trigger'))) { return; } $target = $target.parent(); } while ($target.length > 0); } }); ; ; /*! RESOURCE: /scripts/angular_includes_1.5.11.js */ /*! RESOURCE: /scripts/angular_1.5.11/angular.min.js */ /* AngularJS v1.5.11 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(y){'use strict';function G(a,b){b=b||Error;return function(){var d=arguments[0],c;c="["+(a?a+":":"")+d+"] http://errors.angularjs.org/1.5.11/"+(a?a+"/":"")+d;for(d=1;d<arguments.length;d++){c=c+(1==d?"?":"&")+"p"+(d-1)+"=";var f=encodeURIComponent,e;e=arguments[d];e="function"==typeof e?e.toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof e?"undefined":"string"!=typeof e?JSON.stringify(e):e;c+=f(e)}return new b(c)}}function la(a){if(null==a||Ya(a))return!1;if(I(a)||D(a)||F&&a instanceof F)return!0;var b="length"in Object(a)&&a.length;return ba(b)&&(0<=b&&(b-1 in a||a instanceof Array)||"function"===typeof a.item)}function q(a,b,d){var c,f;if(a)if(C(a))for(c in a)"prototype"===c||"length"===c||"name"===c||a.hasOwnProperty&&!a.hasOwnProperty(c)||b.call(d,a[c],c,a);else if(I(a)||la(a)){var e="object"!==typeof a;c=0;for(f=a.length;c<f;c++)(e||c in a)&&b.call(d,a[c],c,a)}else if(a.forEach&&a.forEach!==q)a.forEach(b,d,a);else if(xc(a))for(c in a)b.call(d,a[c],c,a);else if("function"=== typeof a.hasOwnProperty)for(c in a)a.hasOwnProperty(c)&&b.call(d,a[c],c,a);else for(c in a)ua.call(a,c)&&b.call(d,a[c],c,a);return a}function yc(a,b,d){for(var c=Object.keys(a).sort(),f=0;f<c.length;f++)b.call(d,a[c[f]],c[f]);return c}function zc(a){return function(b,d){a(d,b)}}function ke(){return++sb}function Rb(a,b,d){for(var c=a.$$hashKey,f=0,e=b.length;f<e;++f){var g=b[f];if(E(g)||C(g))for(var h=Object.keys(g),k=0,l=h.length;k<l;k++){var m=h[k],n=g[m];d&&E(n)?ja(n)?a[m]=new Date(n.valueOf()): Za(n)?a[m]=new RegExp(n):n.nodeName?a[m]=n.cloneNode(!0):Sb(n)?a[m]=n.clone():"__proto__"!==m&&(E(a[m])||(a[m]=I(n)?[]:{}),Rb(a[m],[n],!0)):a[m]=n}}c?a.$$hashKey=c:delete a.$$hashKey;return a}function R(a){return Rb(a,va.call(arguments,1),!1)}function le(a){return Rb(a,va.call(arguments,1),!0)}function Z(a){return parseInt(a,10)}function Tb(a,b){return R(Object.create(a),b)}function w(){}function $a(a){return a}function ha(a){return function(){return a}}function Ac(a){return C(a.toString)&&a.toString!== ma}function z(a){return"undefined"===typeof a}function x(a){return"undefined"!==typeof a}function E(a){return null!==a&&"object"===typeof a}function xc(a){return null!==a&&"object"===typeof a&&!Bc(a)}function D(a){return"string"===typeof a}function ba(a){return"number"===typeof a}function ja(a){return"[object Date]"===ma.call(a)}function C(a){return"function"===typeof a}function Za(a){return"[object RegExp]"===ma.call(a)}function Ya(a){return a&&a.window===a}function ab(a){return a&&a.$evalAsync&& a.$watch}function Ka(a){return"boolean"===typeof a}function me(a){return a&&ba(a.length)&&ne.test(ma.call(a))}function Sb(a){return!(!a||!(a.nodeName||a.prop&&a.attr&&a.find))}function oe(a){var b={};a=a.split(",");var d;for(d=0;d<a.length;d++)b[a[d]]=!0;return b}function wa(a){return Q(a.nodeName||a[0]&&a[0].nodeName)}function bb(a,b){var d=a.indexOf(b);0<=d&&a.splice(d,1);return d}function sa(a,b){function d(a,b){var d=b.$$hashKey,e;if(I(a)){e=0;for(var f=a.length;e<f;e++)b.push(c(a[e]))}else if(xc(a))for(e in a)b[e]= c(a[e]);else if(a&&"function"===typeof a.hasOwnProperty)for(e in a)a.hasOwnProperty(e)&&(b[e]=c(a[e]));else for(e in a)ua.call(a,e)&&(b[e]=c(a[e]));d?b.$$hashKey=d:delete b.$$hashKey;return b}function c(a){if(!E(a))return a;var b=e.indexOf(a);if(-1!==b)return g[b];if(Ya(a)||ab(a))throw xa("cpws");var b=!1,c=f(a);void 0===c&&(c=I(a)?[]:Object.create(Bc(a)),b=!0);e.push(a);g.push(c);return b?d(a,c):c}function f(a){switch(ma.call(a)){case "[object Int8Array]":case "[object Int16Array]":case "[object Int32Array]":case "[object Float32Array]":case "[object Float64Array]":case "[object Uint8Array]":case "[object Uint8ClampedArray]":case "[object Uint16Array]":case "[object Uint32Array]":return new a.constructor(c(a.buffer), a.byteOffset,a.length);case "[object ArrayBuffer]":if(!a.slice){var b=new ArrayBuffer(a.byteLength);(new Uint8Array(b)).set(new Uint8Array(a));return b}return a.slice(0);case "[object Boolean]":case "[object Number]":case "[object String]":case "[object Date]":return new a.constructor(a.valueOf());case "[object RegExp]":return b=new RegExp(a.source,a.toString().match(/[^/]*$/)[0]),b.lastIndex=a.lastIndex,b;case "[object Blob]":return new a.constructor([a],{type:a.type})}if(C(a.cloneNode))return a.cloneNode(!0)} var e=[],g=[];if(b){if(me(b)||"[object ArrayBuffer]"===ma.call(b))throw xa("cpta");if(a===b)throw xa("cpi");I(b)?b.length=0:q(b,function(a,d){"$$hashKey"!==d&&delete b[d]});e.push(a);g.push(b);return d(a,b)}return c(a)}function na(a,b){if(a===b)return!0;if(null===a||null===b)return!1;if(a!==a&&b!==b)return!0;var d=typeof a,c;if(d===typeof b&&"object"===d)if(I(a)){if(!I(b))return!1;if((d=a.length)===b.length){for(c=0;c<d;c++)if(!na(a[c],b[c]))return!1;return!0}}else{if(ja(a))return ja(b)?na(a.getTime(), b.getTime()):!1;if(Za(a))return Za(b)?a.toString()===b.toString():!1;if(ab(a)||ab(b)||Ya(a)||Ya(b)||I(b)||ja(b)||Za(b))return!1;d=V();for(c in a)if("$"!==c.charAt(0)&&!C(a[c])){if(!na(a[c],b[c]))return!1;d[c]=!0}for(c in b)if(!(c in d)&&"$"!==c.charAt(0)&&x(b[c])&&!C(b[c]))return!1;return!0}return!1}function cb(a,b,d){return a.concat(va.call(b,d))}function db(a,b){var d=2<arguments.length?va.call(arguments,2):[];return!C(b)||b instanceof RegExp?b:d.length?function(){return arguments.length?b.apply(a, cb(d,arguments,0)):b.apply(a,d)}:function(){return arguments.length?b.apply(a,arguments):b.call(a)}}function pe(a,b){var d=b;"string"===typeof a&&"$"===a.charAt(0)&&"$"===a.charAt(1)?d=void 0:Ya(b)?d="$WINDOW":b&&y.document===b?d="$DOCUMENT":ab(b)&&(d="$SCOPE");return d}function eb(a,b){if(!z(a))return ba(b)||(b=b?2:null),JSON.stringify(a,pe,b)}function Cc(a){return D(a)?JSON.parse(a):a}function Dc(a,b){a=a.replace(qe,"");var d=Date.parse("Jan 01, 1970 00:00:00 "+a)/6E4;return ia(d)?b:d}function Ub(a, b,d){d=d?-1:1;var c=a.getTimezoneOffset();b=Dc(b,c);d*=b-c;a=new Date(a.getTime());a.setMinutes(a.getMinutes()+d);return a}function ya(a){a=F(a).clone();try{a.empty()}catch(b){}var d=F("<div>").append(a).html();try{return a[0].nodeType===La?Q(d):d.match(/^(<[^>]+>)/)[1].replace(/^<([\w-]+)/,function(a,b){return"<"+Q(b)})}catch(c){return Q(d)}}function Ec(a){try{return decodeURIComponent(a)}catch(b){}}function Fc(a){var b={};q((a||"").split("&"),function(a){var c,f,e;a&&(f=a=a.replace(/\+/g,"%20"), c=a.indexOf("="),-1!==c&&(f=a.substring(0,c),e=a.substring(c+1)),f=Ec(f),x(f)&&(e=x(e)?Ec(e):!0,ua.call(b,f)?I(b[f])?b[f].push(e):b[f]=[b[f],e]:b[f]=e))});return b}function Vb(a){var b=[];q(a,function(a,c){I(a)?q(a,function(a){b.push(oa(c,!0)+(!0===a?"":"="+oa(a,!0)))}):b.push(oa(c,!0)+(!0===a?"":"="+oa(a,!0)))});return b.length?b.join("&"):""}function tb(a){return oa(a,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function oa(a,b){return encodeURIComponent(a).replace(/%40/gi, "@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%20/g,b?"%20":"+")}function re(a,b){var d,c,f=Oa.length;for(c=0;c<f;++c)if(d=Oa[c]+b,D(d=a.getAttribute(d)))return d;return null}function se(a,b){var d,c,f={};q(Oa,function(b){b+="app";!d&&a.hasAttribute&&a.hasAttribute(b)&&(d=a,c=a.getAttribute(b))});q(Oa,function(b){b+="app";var f;!d&&(f=a.querySelector("["+b.replace(":","\\:")+"]"))&&(d=f,c=f.getAttribute(b))});d&&(te?(f.strictDi=null!==re(d,"strict-di"), b(d,c?[c]:[],f)):y.console.error("Angular: disabling automatic bootstrap. <script> protocol indicates an extension, document.location.href does not match."))}function Gc(a,b,d){E(d)||(d={});d=R({strictDi:!1},d);var c=function(){a=F(a);if(a.injector()){var c=a[0]===y.document?"document":ya(a);throw xa("btstrpd",c.replace(/</,"<").replace(/>/,">"));}b=b||[];b.unshift(["$provide",function(b){b.value("$rootElement",a)}]);d.debugInfoEnabled&&b.push(["$compileProvider",function(a){a.debugInfoEnabled(!0)}]); b.unshift("ng");c=fb(b,d.strictDi);c.invoke(["$rootScope","$rootElement","$compile","$injector",function(a,b,c,d){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return c},f=/^NG_ENABLE_DEBUG_INFO!/,e=/^NG_DEFER_BOOTSTRAP!/;y&&f.test(y.name)&&(d.debugInfoEnabled=!0,y.name=y.name.replace(f,""));if(y&&!e.test(y.name))return c();y.name=y.name.replace(e,"");$.resumeBootstrap=function(a){q(a,function(a){b.push(a)});return c()};C($.resumeDeferredBootstrap)&&$.resumeDeferredBootstrap()}function ue(){y.name= "NG_ENABLE_DEBUG_INFO!"+y.name;y.location.reload()}function ve(a){a=$.element(a).injector();if(!a)throw xa("test");return a.get("$$testability")}function Hc(a,b){b=b||"_";return a.replace(we,function(a,c){return(c?b:"")+a.toLowerCase()})}function xe(){var a;if(!Ic){var b=ub();(za=z(b)?y.jQuery:b?y[b]:void 0)&&za.fn.on?(F=za,R(za.fn,{scope:Pa.scope,isolateScope:Pa.isolateScope,controller:Pa.controller,injector:Pa.injector,inheritedData:Pa.inheritedData}),a=za.cleanData,za.cleanData=function(b){for(var c, f=0,e;null!=(e=b[f]);f++)(c=za._data(e,"events"))&&c.$destroy&&za(e).triggerHandler("$destroy");a(b)}):F=W;$.element=F;Ic=!0}}function gb(a,b,d){if(!a)throw xa("areq",b||"?",d||"required");return a}function Qa(a,b,d){d&&I(a)&&(a=a[a.length-1]);gb(C(a),b,"not a function, got "+(a&&"object"===typeof a?a.constructor.name||"Object":typeof a));return a}function Ra(a,b){if("hasOwnProperty"===a)throw xa("badname",b);}function Jc(a,b,d){if(!b)return a;b=b.split(".");for(var c,f=a,e=b.length,g=0;g<e;g++)c= b[g],a&&(a=(f=a)[c]);return!d&&C(a)?db(f,a):a}function vb(a){for(var b=a[0],d=a[a.length-1],c,f=1;b!==d&&(b=b.nextSibling);f++)if(c||a[f]!==b)c||(c=F(va.call(a,0,f))),c.push(b);return c||a}function V(){return Object.create(null)}function ye(a){function b(a,b,c){return a[b]||(a[b]=c())}var d=G("$injector"),c=G("ng");a=b(a,"angular",Object);a.$$minErr=a.$$minErr||G;return b(a,"module",function(){var a={};return function(e,g,h){if("hasOwnProperty"===e)throw c("badname","module");g&&a.hasOwnProperty(e)&& (a[e]=null);return b(a,e,function(){function a(b,d,e,f){f||(f=c);return function(){f[e||"push"]([b,d,arguments]);return H}}function b(a,d){return function(b,f){f&&C(f)&&(f.$$moduleName=e);c.push([a,d,arguments]);return H}}if(!g)throw d("nomod",e);var c=[],f=[],r=[],s=a("$injector","invoke","push",f),H={_invokeQueue:c,_configBlocks:f,_runBlocks:r,requires:g,name:e,provider:b("$provide","provider"),factory:b("$provide","factory"),service:b("$provide","service"),value:a("$provide","value"),constant:a("$provide", "constant","unshift"),decorator:b("$provide","decorator"),animation:b("$animateProvider","register"),filter:b("$filterProvider","register"),controller:b("$controllerProvider","register"),directive:b("$compileProvider","directive"),component:b("$compileProvider","component"),config:s,run:function(a){r.push(a);return this}};h&&s(h);return H})}})}function ka(a,b){if(I(a)){b=b||[];for(var d=0,c=a.length;d<c;d++)b[d]=a[d]}else if(E(a))for(d in b=b||{},a)if("$"!==d.charAt(0)||"$"!==d.charAt(1))b[d]=a[d]; return b||a}function ze(a){R(a,{bootstrap:Gc,copy:sa,extend:R,merge:le,equals:na,element:F,forEach:q,injector:fb,noop:w,bind:db,toJson:eb,fromJson:Cc,identity:$a,isUndefined:z,isDefined:x,isString:D,isFunction:C,isObject:E,isNumber:ba,isElement:Sb,isArray:I,version:Ae,isDate:ja,lowercase:Q,uppercase:wb,callbacks:{$$counter:0},getTestability:ve,$$minErr:G,$$csp:da,reloadWithDebugInfo:ue});Wb=ye(y);Wb("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:Be});a.provider("$compile",Kc).directive({a:Ce, input:Lc,textarea:Lc,form:De,script:Ee,select:Fe,option:Ge,ngBind:He,ngBindHtml:Ie,ngBindTemplate:Je,ngClass:Ke,ngClassEven:Le,ngClassOdd:Me,ngCloak:Ne,ngController:Oe,ngForm:Pe,ngHide:Qe,ngIf:Re,ngInclude:Se,ngInit:Te,ngNonBindable:Ue,ngPluralize:Ve,ngRepeat:We,ngShow:Xe,ngStyle:Ye,ngSwitch:Ze,ngSwitchWhen:$e,ngSwitchDefault:af,ngOptions:bf,ngTransclude:cf,ngModel:df,ngList:ef,ngChange:ff,pattern:Mc,ngPattern:Mc,required:Nc,ngRequired:Nc,minlength:Oc,ngMinlength:Oc,maxlength:Pc,ngMaxlength:Pc,ngValue:gf, ngModelOptions:hf}).directive({ngInclude:jf}).directive(xb).directive(Qc);a.provider({$anchorScroll:kf,$animate:lf,$animateCss:mf,$$animateJs:nf,$$animateQueue:of,$$AnimateRunner:pf,$$animateAsyncRun:qf,$browser:rf,$cacheFactory:sf,$controller:tf,$document:uf,$exceptionHandler:vf,$filter:Rc,$$forceReflow:wf,$interpolate:xf,$interval:yf,$http:zf,$httpParamSerializer:Af,$httpParamSerializerJQLike:Bf,$httpBackend:Cf,$xhrFactory:Df,$jsonpCallbacks:Ef,$location:Ff,$log:Gf,$parse:Hf,$rootScope:If,$q:Jf, $$q:Kf,$sce:Lf,$sceDelegate:Mf,$sniffer:Nf,$templateCache:Of,$templateRequest:Pf,$$testability:Qf,$timeout:Rf,$window:Sf,$$rAF:Tf,$$jqLite:Uf,$$HashMap:Vf,$$cookieReader:Wf})}])}function hb(a){return a.replace(Xf,function(a,d,c,f){return f?c.toUpperCase():c}).replace(Yf,"Moz$1")}function Sc(a){a=a.nodeType;return 1===a||!a||9===a}function Tc(a,b){var d,c,f=b.createDocumentFragment(),e=[];if(Xb.test(a)){d=f.appendChild(b.createElement("div"));c=(Zf.exec(a)||["",""])[1].toLowerCase();c=pa[c]||pa._default; d.innerHTML=c[1]+a.replace($f,"<$1></$2>")+c[2];for(c=c[0];c--;)d=d.lastChild;e=cb(e,d.childNodes);d=f.firstChild;d.textContent=""}else e.push(b.createTextNode(a));f.textContent="";f.innerHTML="";q(e,function(a){f.appendChild(a)});return f}function Uc(a,b){var d=a.parentNode;d&&d.replaceChild(b,a);b.appendChild(a)}function W(a){if(a instanceof W)return a;var b;D(a)&&(a=Y(a),b=!0);if(!(this instanceof W)){if(b&&"<"!==a.charAt(0))throw Yb("nosel");return new W(a)}if(b){b=y.document;var d;a=(d=ag.exec(a))? [b.createElement(d[1])]:(d=Tc(a,b))?d.childNodes:[]}Vc(this,a)}function Zb(a){return a.cloneNode(!0)}function yb(a,b){b||ib(a);if(a.querySelectorAll)for(var d=a.querySelectorAll("*"),c=0,f=d.length;c<f;c++)ib(d[c])}function Wc(a,b,d,c){if(x(c))throw Yb("offargs");var f=(c=zb(a))&&c.events,e=c&&c.handle;if(e)if(b){var g=function(b){var c=f[b];x(d)&&bb(c||[],d);x(d)&&c&&0<c.length||(a.removeEventListener(b,e,!1),delete f[b])};q(b.split(" "),function(a){g(a);Ab[a]&&g(Ab[a])})}else for(b in f)"$destroy"!== b&&a.removeEventListener(b,e,!1),delete f[b]}function ib(a,b){var d=a.ng339,c=d&&jb[d];c&&(b?delete c.data[b]:(c.handle&&(c.events.$destroy&&c.handle({},"$destroy"),Wc(a)),delete jb[d],a.ng339=void 0))}function zb(a,b){var d=a.ng339,d=d&&jb[d];b&&!d&&(a.ng339=d=++bg,d=jb[d]={events:{},data:{},handle:void 0});return d}function $b(a,b,d){if(Sc(a)){var c=x(d),f=!c&&b&&!E(b),e=!b;a=(a=zb(a,!f))&&a.data;if(c)a[b]=d;else{if(e)return a;if(f)return a&&a[b];R(a,b)}}}function Bb(a,b){return a.getAttribute? -1<(" "+(a.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+b+" "):!1}function Cb(a,b){b&&a.setAttribute&&q(b.split(" "),function(b){a.setAttribute("class",Y((" "+(a.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+Y(b)+" "," ")))})}function Db(a,b){if(b&&a.setAttribute){var d=(" "+(a.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");q(b.split(" "),function(a){a=Y(a);-1===d.indexOf(" "+a+" ")&&(d+=a+" ")});a.setAttribute("class",Y(d))}}function Vc(a,b){if(b)if(b.nodeType)a[a.length++]= b;else{var d=b.length;if("number"===typeof d&&b.window!==b){if(d)for(var c=0;c<d;c++)a[a.length++]=b[c]}else a[a.length++]=b}}function Xc(a,b){return Eb(a,"$"+(b||"ngController")+"Controller")}function Eb(a,b,d){9===a.nodeType&&(a=a.documentElement);for(b=I(b)?b:[b];a;){for(var c=0,f=b.length;c<f;c++)if(x(d=F.data(a,b[c])))return d;a=a.parentNode||11===a.nodeType&&a.host}}function Yc(a){for(yb(a,!0);a.firstChild;)a.removeChild(a.firstChild)}function Fb(a,b){b||yb(a);var d=a.parentNode;d&&d.removeChild(a)} function cg(a,b){b=b||y;if("complete"===b.document.readyState)b.setTimeout(a);else F(b).on("load",a)}function Zc(a,b){var d=Gb[b.toLowerCase()];return d&&$c[wa(a)]&&d}function dg(a,b){var d=function(c,d){c.isDefaultPrevented=function(){return c.defaultPrevented};var e=b[d||c.type],g=e?e.length:0;if(g){if(z(c.immediatePropagationStopped)){var h=c.stopImmediatePropagation;c.stopImmediatePropagation=function(){c.immediatePropagationStopped=!0;c.stopPropagation&&c.stopPropagation();h&&h.call(c)}}c.isImmediatePropagationStopped= function(){return!0===c.immediatePropagationStopped};var k=e.specialHandlerWrapper||eg;1<g&&(e=ka(e));for(var l=0;l<g;l++)c.isImmediatePropagationStopped()||k(a,c,e[l])}};d.elem=a;return d}function eg(a,b,d){d.call(a,b)}function fg(a,b,d){var c=b.relatedTarget;c&&(c===a||gg.call(a,c))||d.call(a,b)}function Uf(){this.$get=function(){return R(W,{hasClass:function(a,b){a.attr&&(a=a[0]);return Bb(a,b)},addClass:function(a,b){a.attr&&(a=a[0]);return Db(a,b)},removeClass:function(a,b){a.attr&&(a=a[0]); return Cb(a,b)}})}}function Aa(a,b){var d=a&&a.$$hashKey;if(d)return"function"===typeof d&&(d=a.$$hashKey()),d;d=typeof a;return d="function"===d||"object"===d&&null!==a?a.$$hashKey=d+":"+(b||ke)():d+":"+a}function Sa(a,b){if(b){var d=0;this.nextUid=function(){return++d}}q(a,this.put,this)}function ad(a){a=(Function.prototype.toString.call(a)+" ").replace(hg,"");return a.match(ig)||a.match(jg)}function kg(a){return(a=ad(a))?"function("+(a[1]||"").replace(/[\s\r\n]+/," ")+")":"fn"}function fb(a,b){function d(a){return function(b, c){if(E(b))q(b,zc(a));else return a(b,c)}}function c(a,b){Ra(a,"service");if(C(b)||I(b))b=r.instantiate(b);if(!b.$get)throw Ba("pget",a);return n[a+"Provider"]=b}function f(a,b){return function(){var c=u.invoke(b,this);if(z(c))throw Ba("undef",a);return c}}function e(a,b,d){return c(a,{$get:!1!==d?f(a,b):b})}function g(a){gb(z(a)||I(a),"modulesToLoad","not an array");var b=[],c;q(a,function(a){function d(a){var b,c;b=0;for(c=a.length;b<c;b++){var e=a[b],f=r.get(e[0]);f[e[1]].apply(f,e[2])}}if(!m.get(a)){m.put(a, !0);try{D(a)?(c=Wb(a),b=b.concat(g(c.requires)).concat(c._runBlocks),d(c._invokeQueue),d(c._configBlocks)):C(a)?b.push(r.invoke(a)):I(a)?b.push(r.invoke(a)):Qa(a,"module")}catch(e){throw I(a)&&(a=a[a.length-1]),e.message&&e.stack&&-1===e.stack.indexOf(e.message)&&(e=e.message+"\n"+e.stack),Ba("modulerr",a,e.stack||e.message||e);}}});return b}function h(a,c){function d(b,e){if(a.hasOwnProperty(b)){if(a[b]===k)throw Ba("cdep",b+" <- "+l.join(" <- "));return a[b]}try{return l.unshift(b),a[b]=k,a[b]= c(b,e),a[b]}catch(f){throw a[b]===k&&delete a[b],f;}finally{l.shift()}}function e(a,c,f){var g=[];a=fb.$$annotate(a,b,f);for(var h=0,k=a.length;h<k;h++){var l=a[h];if("string"!==typeof l)throw Ba("itkn",l);g.push(c&&c.hasOwnProperty(l)?c[l]:d(l,f))}return g}return{invoke:function(a,b,c,d){"string"===typeof c&&(d=c,c=null);c=e(a,c,d);I(a)&&(a=a[a.length-1]);d=11>=Ia?!1:"function"===typeof a&&/^(?:class\b|constructor\()/.test(Function.prototype.toString.call(a)+" ");return d?(c.unshift(null),new (Function.prototype.bind.apply(a, c))):a.apply(b,c)},instantiate:function(a,b,c){var d=I(a)?a[a.length-1]:a;a=e(a,b,c);a.unshift(null);return new (Function.prototype.bind.apply(d,a))},get:d,annotate:fb.$$annotate,has:function(b){return n.hasOwnProperty(b+"Provider")||a.hasOwnProperty(b)}}}b=!0===b;var k={},l=[],m=new Sa([],!0),n={$provide:{provider:d(c),factory:d(e),service:d(function(a,b){return e(a,["$injector",function(a){return a.instantiate(b)}])}),value:d(function(a,b){return e(a,ha(b),!1)}),constant:d(function(a,b){Ra(a,"constant"); n[a]=b;s[a]=b}),decorator:function(a,b){var c=r.get(a+"Provider"),d=c.$get;c.$get=function(){var a=u.invoke(d,c);return u.invoke(b,null,{$delegate:a})}}}},r=n.$injector=h(n,function(a,b){$.isString(b)&&l.push(b);throw Ba("unpr",l.join(" <- "));}),s={},H=h(s,function(a,b){var c=r.get(a+"Provider",b);return u.invoke(c.$get,c,void 0,a)}),u=H;n.$injectorProvider={$get:ha(H)};var p=g(a),u=H.get("$injector");u.strictDi=b;q(p,function(a){a&&u.invoke(a)});return u}function kf(){var a=!0;this.disableAutoScrolling= function(){a=!1};this.$get=["$window","$location","$rootScope",function(b,d,c){function f(a){var b=null;Array.prototype.some.call(a,function(a){if("a"===wa(a))return b=a,!0});return b}function e(a){if(a){a.scrollIntoView();var c;c=g.yOffset;C(c)?c=c():Sb(c)?(c=c[0],c="fixed"!==b.getComputedStyle(c).position?0:c.getBoundingClientRect().bottom):ba(c)||(c=0);c&&(a=a.getBoundingClientRect().top,b.scrollBy(0,a-c))}else b.scrollTo(0,0)}function g(a){a=D(a)?a:ba(a)?a.toString():d.hash();var b;a?(b=h.getElementById(a))? e(b):(b=f(h.getElementsByName(a)))?e(b):"top"===a&&e(null):e(null)}var h=b.document;a&&c.$watch(function(){return d.hash()},function(a,b){a===b&&""===a||cg(function(){c.$evalAsync(g)})});return g}]}function kb(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;I(a)&&(a=a.join(" "));I(b)&&(b=b.join(" "));return a+" "+b}function lg(a){D(a)&&(a=a.split(" "));var b=V();q(a,function(a){a.length&&(b[a]=!0)});return b}function Ca(a){return E(a)?a:{}}function mg(a,b,d,c){function f(a){try{a.apply(null, va.call(arguments,1))}finally{if(H--,0===H)for(;u.length;)try{u.pop()()}catch(b){d.error(b)}}}function e(){N=null;g();h()}function g(){p=L();p=z(p)?null:p;na(p,J)&&(p=J);J=p}function h(){if(A!==k.url()||K!==p)A=k.url(),K=p,q(O,function(a){a(k.url(),p)})}var k=this,l=a.location,m=a.history,n=a.setTimeout,r=a.clearTimeout,s={};k.isMock=!1;var H=0,u=[];k.$$completeOutstandingRequest=f;k.$$incOutstandingRequestCount=function(){H++};k.notifyWhenNoOutstandingRequests=function(a){0===H?a():u.push(a)};var p, K,A=l.href,v=b.find("base"),N=null,L=c.history?function(){try{return m.state}catch(a){}}:w;g();K=p;k.url=function(b,d,e){z(e)&&(e=null);l!==a.location&&(l=a.location);m!==a.history&&(m=a.history);if(b){var f=K===e;if(A===b&&(!c.history||f))return k;var h=A&&Ga(A)===Ga(b);A=b;K=e;!c.history||h&&f?(h||(N=b),d?l.replace(b):h?(d=l,e=b.indexOf("#"),e=-1===e?"":b.substr(e),d.hash=e):l.href=b,l.href!==b&&(N=b)):(m[d?"replaceState":"pushState"](e,"",b),g(),K=p);N&&(N=b);return k}return N||l.href.replace(/%27/g, "'")};k.state=function(){return p};var O=[],M=!1,J=null;k.onUrlChange=function(b){if(!M){if(c.history)F(a).on("popstate",e);F(a).on("hashchange",e);M=!0}O.push(b);return b};k.$$applicationDestroyed=function(){F(a).off("hashchange popstate",e)};k.$$checkUrlChange=h;k.baseHref=function(){var a=v.attr("href");return a?a.replace(/^(https?:)?\/\/[^/]*/,""):""};k.defer=function(a,b){var c;H++;c=n(function(){delete s[c];f(a)},b||0);s[c]=!0;return c};k.defer.cancel=function(a){return s[a]?(delete s[a],r(a), f(w),!0):!1}}function rf(){this.$get=["$window","$log","$sniffer","$document",function(a,b,d,c){return new mg(a,c,b,d)}]}function sf(){this.$get=function(){function a(a,c){function f(a){a!==n&&(r?r===a&&(r=a.n):r=a,e(a.n,a.p),e(a,n),n=a,n.n=null)}function e(a,b){a!==b&&(a&&(a.p=b),b&&(b.n=a))}if(a in b)throw G("$cacheFactory")("iid",a);var g=0,h=R({},c,{id:a}),k=V(),l=c&&c.capacity||Number.MAX_VALUE,m=V(),n=null,r=null;return b[a]={put:function(a,b){if(!z(b)){if(l<Number.MAX_VALUE){var c=m[a]||(m[a]= {key:a});f(c)}a in k||g++;k[a]=b;g>l&&this.remove(r.key);return b}},get:function(a){if(l<Number.MAX_VALUE){var b=m[a];if(!b)return;f(b)}return k[a]},remove:function(a){if(l<Number.MAX_VALUE){var b=m[a];if(!b)return;b===n&&(n=b.p);b===r&&(r=b.n);e(b.n,b.p);delete m[a]}a in k&&(delete k[a],g--)},removeAll:function(){k=V();g=0;m=V();n=r=null},destroy:function(){m=h=k=null;delete b[a]},info:function(){return R({},h,{size:g})}}}var b={};a.info=function(){var a={};q(b,function(b,f){a[f]=b.info()});return a}; a.get=function(a){return b[a]};return a}}function Of(){this.$get=["$cacheFactory",function(a){return a("templates")}]}function Kc(a,b){function d(a,b,c){var d=/^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/,e=V();q(a,function(a,f){if(a in n)e[f]=n[a];else{var g=a.match(d);if(!g)throw fa("iscp",b,f,a,c?"controller bindings definition":"isolate scope definition");e[f]={mode:g[1][0],collection:"*"===g[2],optional:"?"===g[3],attrName:g[4]||f};g[4]&&(n[a]=e[f])}});return e}function c(a){var b=a.charAt(0);if(!b|| b!==Q(b))throw fa("baddir",a);if(a!==a.trim())throw fa("baddir",a);}function f(a){var b=a.require||a.controller&&a.name;!I(b)&&E(b)&&q(b,function(a,c){var d=a.match(l);a.substring(d[0].length)||(b[c]=d[0]+c)});return b}var e={},g=/^\s*directive:\s*([\w-]+)\s+(.*)$/,h=/(([\w-]+)(?::([^;]+))?;?)/,k=oe("ngSrc,ngSrcset,src,srcset"),l=/^(?:(\^\^?)?(\?)?(\^\^?)?)?/,m=/^(on[a-z]+|formaction)$/,n=V();this.directive=function A(b,d){gb(b,"name");Ra(b,"directive");D(b)?(c(b),gb(d,"directiveFactory"),e.hasOwnProperty(b)|| (e[b]=[],a.factory(b+"Directive",["$injector","$exceptionHandler",function(a,c){var d=[];q(e[b],function(e,g){try{var h=a.invoke(e);C(h)?h={compile:ha(h)}:!h.compile&&h.link&&(h.compile=ha(h.link));h.priority=h.priority||0;h.index=g;h.name=h.name||b;h.require=f(h);var k=h,l=h.restrict;if(l&&(!D(l)||!/[EACM]/.test(l)))throw fa("badrestrict",l,b);k.restrict=l||"EA";h.$$moduleName=e.$$moduleName;d.push(h)}catch(m){c(m)}});return d}])),e[b].push(d)):q(b,zc(A));return this};this.component=function(a,b){function c(a){function e(b){return C(b)|| I(b)?function(c,d){return a.invoke(b,this,{$element:c,$attrs:d})}:b}var f=b.template||b.templateUrl?b.template:"",g={controller:d,controllerAs:ng(b.controller)||b.controllerAs||"$ctrl",template:e(f),templateUrl:e(b.templateUrl),transclude:b.transclude,scope:{},bindToController:b.bindings||{},restrict:"E",require:b.require};q(b,function(a,b){"$"===b.charAt(0)&&(g[b]=a)});return g}var d=b.controller||function(){};q(b,function(a,b){"$"===b.charAt(0)&&(c[b]=a,C(d)&&(d[b]=a))});c.$inject=["$injector"]; return this.directive(a,c)};this.aHrefSanitizationWhitelist=function(a){return x(a)?(b.aHrefSanitizationWhitelist(a),this):b.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=function(a){return x(a)?(b.imgSrcSanitizationWhitelist(a),this):b.imgSrcSanitizationWhitelist()};var r=!0;this.debugInfoEnabled=function(a){return x(a)?(r=a,this):r};var s=!0;this.preAssignBindingsEnabled=function(a){return x(a)?(s=a,this):s};var H=10;this.onChangesTtl=function(a){return arguments.length?(H=a,this): H};var u=!0;this.commentDirectivesEnabled=function(a){return arguments.length?(u=a,this):u};var p=!0;this.cssClassDirectivesEnabled=function(a){return arguments.length?(p=a,this):p};this.$get=["$injector","$interpolate","$exceptionHandler","$templateRequest","$parse","$controller","$rootScope","$sce","$animate","$$sanitizeUri",function(a,b,c,f,n,M,J,B,T,S){function P(){try{if(!--xa)throw da=void 0,fa("infchng",H);J.$apply(function(){for(var a=[],b=0,c=da.length;b<c;++b)try{da[b]()}catch(d){a.push(d)}da= void 0;if(a.length)throw a;})}finally{xa++}}function t(a,b){if(b){var c=Object.keys(b),d,e,f;d=0;for(e=c.length;d<e;d++)f=c[d],this[f]=b[f]}else this.$attr={};this.$$element=a}function qa(a,b,c){ta.innerHTML="<span "+b+">";b=ta.firstChild.attributes;var d=b[0];b.removeNamedItem(d.name);d.value=c;a.attributes.setNamedItem(d)}function Ja(a,b){try{a.addClass(b)}catch(c){}}function ca(a,b,c,d,e){a instanceof F||(a=F(a));for(var f=/\S+/,g=0,h=a.length;g<h;g++){var k=a[g];k.nodeType===La&&k.nodeValue.match(f)&& Uc(k,a[g]=y.document.createElement("span"))}var l=Ma(a,b,a,c,d,e);ca.$$addScopeClass(a);var m=null;return function(b,c,d){gb(b,"scope");e&&e.needsNewScope&&(b=b.$parent.$new());d=d||{};var f=d.parentBoundTranscludeFn,g=d.transcludeControllers;d=d.futureParentElement;f&&f.$$boundTransclude&&(f=f.$$boundTransclude);m||(m=(d=d&&d[0])?"foreignobject"!==wa(d)&&ma.call(d).match(/SVG/)?"svg":"html":"html");d="html"!==m?F(ha(m,F("<div>").append(a).html())):c?Pa.clone.call(a):a;if(g)for(var h in g)d.data("$"+ h+"Controller",g[h].instance);ca.$$addScopeInfo(d,b);c&&c(d,b);l&&l(b,d,d,f);return d}}function Ma(a,b,c,d,e,f){function g(a,c,d,e){var f,k,l,m,n,s,A;if(p)for(A=Array(c.length),m=0;m<h.length;m+=3)f=h[m],A[f]=c[f];else A=c;m=0;for(n=h.length;m<n;)k=A[h[m++]],c=h[m++],f=h[m++],c?(c.scope?(l=a.$new(),ca.$$addScopeInfo(F(k),l)):l=a,s=c.transcludeOnThisElement?G(a,c.transclude,e):!c.templateOnThisElement&&e?e:!e&&b?G(a,b):null,c(f,l,k,d,s)):f&&f(a,k.childNodes,void 0,e)}for(var h=[],k,l,m,n,p,s=0;s<a.length;s++){k= new t;l=cc(a[s],[],k,0===s?d:void 0,e);(f=l.length?W(l,a[s],k,b,c,null,[],[],f):null)&&f.scope&&ca.$$addScopeClass(k.$$element);k=f&&f.terminal||!(m=a[s].childNodes)||!m.length?null:Ma(m,f?(f.transcludeOnThisElement||!f.templateOnThisElement)&&f.transclude:b);if(f||k)h.push(s,f,k),n=!0,p=p||f;f=null}return n?g:null}function G(a,b,c){function d(e,f,g,h,k){e||(e=a.$new(!1,k),e.$$transcluded=!0);return b(e,f,{parentBoundTranscludeFn:c,transcludeControllers:g,futureParentElement:h})}var e=d.$$slots=V(), f;for(f in b.$$slots)e[f]=b.$$slots[f]?G(a,b.$$slots[f],c):null;return d}function cc(a,b,c,d,e){var f=c.$attr,g;switch(a.nodeType){case 1:g=wa(a);U(b,Da(g),"E",d,e);for(var k,l,m,n,p=a.attributes,s=0,A=p&&p.length;s<A;s++){var r=!1,u=!1;k=p[s];l=k.name;m=Y(k.value);k=Da(l);(n=Ga.test(k))&&(l=l.replace(bd,"").substr(8).replace(/_(.)/g,function(a,b){return b.toUpperCase()}));(k=k.match(Ha))&&Z(k[1])&&(r=l,u=l.substr(0,l.length-5)+"end",l=l.substr(0,l.length-6));k=Da(l.toLowerCase());f[k]=l;if(n||!c.hasOwnProperty(k))c[k]= m,Zc(a,k)&&(c[k]=!0);pa(a,b,m,k,n);U(b,k,"A",d,e,r,u)}"input"===g&&"hidden"===a.getAttribute("type")&&a.setAttribute("autocomplete","off");if(!Fa)break;f=a.className;E(f)&&(f=f.animVal);if(D(f)&&""!==f)for(;a=h.exec(f);)k=Da(a[2]),U(b,k,"C",d,e)&&(c[k]=Y(a[3])),f=f.substr(a.index+a[0].length);break;case La:if(11===Ia)for(;a.parentNode&&a.nextSibling&&a.nextSibling.nodeType===La;)a.nodeValue+=a.nextSibling.nodeValue,a.parentNode.removeChild(a.nextSibling);ka(b,a.nodeValue);break;case 8:if(!Ea)break; Ta(a,b,c,d,e)}b.sort(ja);return b}function Ta(a,b,c,d,e){try{var f=g.exec(a.nodeValue);if(f){var h=Da(f[1]);U(b,h,"M",d,e)&&(c[h]=Y(f[2]))}}catch(k){}}function cd(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw fa("uterdir",b,c);1===a.nodeType&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return F(d)}function dd(a,b,c){return function(d,e,f,g,h){e=cd(e[0],b,c);return a(d,e,f,g,h)}}function dc(a,b,c,d,e,f){var g;return a? ca(b,c,d,e,f):function(){g||(g=ca(b,c,d,e,f),b=c=f=null);return g.apply(this,arguments)}}function W(a,b,d,e,f,g,h,k,l){function m(a,b,c,d){if(a){c&&(a=dd(a,c,d));a.require=v.require;a.directiveName=S;if(u===v||v.$$isolateScope)a=ra(a,{isolateScope:!0});h.push(a)}if(b){c&&(b=dd(b,c,d));b.require=v.require;b.directiveName=S;if(u===v||v.$$isolateScope)b=ra(b,{isolateScope:!0});k.push(b)}}function n(a,e,f,g,l){function m(a,b,c,d){var e;ab(a)||(d=c,c=b,b=a,a=void 0);H&&(e=J);c||(c=H?P.parent():P);if(d){var f= l.$$slots[d];if(f)return f(a,b,e,c,qa);if(z(f))throw fa("noslot",d,ya(P));}else return l(a,b,e,c,qa)}var p,v,B,M,T,J,S,P;b===f?(g=d,P=d.$$element):(P=F(f),g=new t(P,d));T=e;u?M=e.$new(!0):A&&(T=e.$parent);l&&(S=m,S.$$boundTransclude=l,S.isSlotFilled=function(a){return!!l.$$slots[a]});r&&(J=ba(P,g,S,r,M,e,u));u&&(ca.$$addScopeInfo(P,M,!0,!(O&&(O===u||O===u.$$originalDirective))),ca.$$addScopeClass(P,!0),M.$$isolateBindings=u.$$isolateBindings,v=la(e,g,M,M.$$isolateBindings,u),v.removeWatches&&M.$on("$destroy", v.removeWatches));for(p in J){v=r[p];B=J[p];var L=v.$$bindings.bindToController;if(s){B.bindingInfo=L?la(T,g,B.instance,L,v):{};var ac=B();ac!==B.instance&&(B.instance=ac,P.data("$"+v.name+"Controller",ac),B.bindingInfo.removeWatches&&B.bindingInfo.removeWatches(),B.bindingInfo=la(T,g,B.instance,L,v))}else B.instance=B(),P.data("$"+v.name+"Controller",B.instance),B.bindingInfo=la(T,g,B.instance,L,v)}q(r,function(a,b){var c=a.require;a.bindToController&&!I(c)&&E(c)&&R(J[b].instance,X(b,c,P,J))});q(J, function(a){var b=a.instance;if(C(b.$onChanges))try{b.$onChanges(a.bindingInfo.initialChanges)}catch(d){c(d)}if(C(b.$onInit))try{b.$onInit()}catch(e){c(e)}C(b.$doCheck)&&(T.$watch(function(){b.$doCheck()}),b.$doCheck());C(b.$onDestroy)&&T.$on("$destroy",function(){b.$onDestroy()})});p=0;for(v=h.length;p<v;p++)B=h[p],sa(B,B.isolateScope?M:e,P,g,B.require&&X(B.directiveName,B.require,P,J),S);var qa=e;u&&(u.template||null===u.templateUrl)&&(qa=M);a&&a(qa,f.childNodes,void 0,l);for(p=k.length-1;0<=p;p--)B= k[p],sa(B,B.isolateScope?M:e,P,g,B.require&&X(B.directiveName,B.require,P,J),S);q(J,function(a){a=a.instance;C(a.$postLink)&&a.$postLink()})}l=l||{};for(var p=-Number.MAX_VALUE,A=l.newScopeDirective,r=l.controllerDirectives,u=l.newIsolateScopeDirective,O=l.templateDirective,M=l.nonTlbTranscludeDirective,T=!1,J=!1,H=l.hasElementTranscludeDirective,B=d.$$element=F(b),v,S,P,L=e,qa,x=!1,Ja=!1,w,y=0,D=a.length;y<D;y++){v=a[y];var Ta=v.$$start,Ma=v.$$end;Ta&&(B=cd(b,Ta,Ma));P=void 0;if(p>v.priority)break; if(w=v.scope)v.templateUrl||(E(w)?($("new/isolated scope",u||A,v,B),u=v):$("new/isolated scope",u,v,B)),A=A||v;S=v.name;if(!x&&(v.replace&&(v.templateUrl||v.template)||v.transclude&&!v.$$tlb)){for(w=y+1;x=a[w++];)if(x.transclude&&!x.$$tlb||x.replace&&(x.templateUrl||x.template)){Ja=!0;break}x=!0}!v.templateUrl&&v.controller&&(r=r||V(),$("'"+S+"' controller",r[S],v,B),r[S]=v);if(w=v.transclude)if(T=!0,v.$$tlb||($("transclusion",M,v,B),M=v),"element"===w)H=!0,p=v.priority,P=B,B=d.$$element=F(ca.$$createComment(S, d[S])),b=B[0],ga(f,va.call(P,0),b),P[0].$$parentNode=P[0].parentNode,L=dc(Ja,P,e,p,g&&g.name,{nonTlbTranscludeDirective:M});else{var G=V();P=F(Zb(b)).contents();if(E(w)){P=[];var Q=V(),bc=V();q(w,function(a,b){var c="?"===a.charAt(0);a=c?a.substring(1):a;Q[a]=b;G[b]=null;bc[b]=c});q(B.contents(),function(a){var b=Q[Da(wa(a))];b?(bc[b]=!0,G[b]=G[b]||[],G[b].push(a)):P.push(a)});q(bc,function(a,b){if(!a)throw fa("reqslot",b);});for(var U in G)G[U]&&(G[U]=dc(Ja,G[U],e))}B.empty();L=dc(Ja,P,e,void 0, void 0,{needsNewScope:v.$$isolateScope||v.$$newScope});L.$$slots=G}if(v.template)if(J=!0,$("template",O,v,B),O=v,w=C(v.template)?v.template(B,d):v.template,w=Ca(w),v.replace){g=v;P=Xb.test(w)?ed(ha(v.templateNamespace,Y(w))):[];b=P[0];if(1!==P.length||1!==b.nodeType)throw fa("tplrt",S,"");ga(f,B,b);D={$attr:{}};w=cc(b,[],D);var og=a.splice(y+1,a.length-(y+1));(u||A)&&aa(w,u,A);a=a.concat(w).concat(og);ea(d,D);D=a.length}else B.html(w);if(v.templateUrl)J=!0,$("template",O,v,B),O=v,v.replace&&(g=v), n=ia(a.splice(y,a.length-y),B,d,f,T&&L,h,k,{controllerDirectives:r,newScopeDirective:A!==v&&A,newIsolateScopeDirective:u,templateDirective:O,nonTlbTranscludeDirective:M}),D=a.length;else if(v.compile)try{qa=v.compile(B,d,L);var Z=v.$$originalDirective||v;C(qa)?m(null,db(Z,qa),Ta,Ma):qa&&m(db(Z,qa.pre),db(Z,qa.post),Ta,Ma)}catch(da){c(da,ya(B))}v.terminal&&(n.terminal=!0,p=Math.max(p,v.priority))}n.scope=A&&!0===A.scope;n.transcludeOnThisElement=T;n.templateOnThisElement=J;n.transclude=L;l.hasElementTranscludeDirective= H;return n}function X(a,b,c,d){var e;if(D(b)){var f=b.match(l);b=b.substring(f[0].length);var g=f[1]||f[3],f="?"===f[2];"^^"===g?c=c.parent():e=(e=d&&d[b])&&e.instance;if(!e){var h="$"+b+"Controller";e=g?c.inheritedData(h):c.data(h)}if(!e&&!f)throw fa("ctreq",b,a);}else if(I(b))for(e=[],g=0,f=b.length;g<f;g++)e[g]=X(a,b[g],c,d);else E(b)&&(e={},q(b,function(b,f){e[f]=X(a,b,c,d)}));return e||null}function ba(a,b,c,d,e,f,g){var h=V(),k;for(k in d){var l=d[k],m={$scope:l===g||l.$$isolateScope?e:f,$element:a, $attrs:b,$transclude:c},n=l.controller;"@"===n&&(n=b[l.name]);m=M(n,m,!0,l.controllerAs);h[l.name]=m;a.data("$"+l.name+"Controller",m.instance)}return h}function aa(a,b,c){for(var d=0,e=a.length;d<e;d++)a[d]=Tb(a[d],{$$isolateScope:b,$$newScope:c})}function U(b,c,f,g,h,k,l){if(c===h)return null;var m=null;if(e.hasOwnProperty(c)){h=a.get(c+"Directive");for(var n=0,p=h.length;n<p;n++)if(c=h[n],(z(g)||g>c.priority)&&-1!==c.restrict.indexOf(f)){k&&(c=Tb(c,{$$start:k,$$end:l}));if(!c.$$bindings){var s= m=c,r=c.name,v={isolateScope:null,bindToController:null};E(s.scope)&&(!0===s.bindToController?(v.bindToController=d(s.scope,r,!0),v.isolateScope={}):v.isolateScope=d(s.scope,r,!1));E(s.bindToController)&&(v.bindToController=d(s.bindToController,r,!0));if(v.bindToController&&!s.controller)throw fa("noctrl",r);m=m.$$bindings=v;E(m.isolateScope)&&(c.$$isolateBindings=m.isolateScope)}b.push(c);m=c}}return m}function Z(b){if(e.hasOwnProperty(b))for(var c=a.get(b+"Directive"),d=0,f=c.length;d<f;d++)if(b= c[d],b.multiElement)return!0;return!1}function ea(a,b){var c=b.$attr,d=a.$attr;q(a,function(d,e){"$"!==e.charAt(0)&&(b[e]&&b[e]!==d&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});q(b,function(b,e){a.hasOwnProperty(e)||"$"===e.charAt(0)||(a[e]=b,"class"!==e&&"style"!==e&&(d[e]=c[e]))})}function ia(a,b,c,d,e,g,h,k){var l=[],m,n,p=b[0],s=a.shift(),A=Tb(s,{templateUrl:null,transclude:null,replace:null,$$originalDirective:s}),r=C(s.templateUrl)?s.templateUrl(b,c):s.templateUrl,v=s.templateNamespace; b.empty();f(r).then(function(f){var u,B;f=Ca(f);if(s.replace){f=Xb.test(f)?ed(ha(v,Y(f))):[];u=f[0];if(1!==f.length||1!==u.nodeType)throw fa("tplrt",s.name,r);f={$attr:{}};ga(d,b,u);var O=cc(u,[],f);E(s.scope)&&aa(O,!0);a=O.concat(a);ea(c,f)}else u=p,b.html(f);a.unshift(A);m=W(a,u,c,e,b,s,g,h,k);q(d,function(a,c){a===u&&(d[c]=b[0])});for(n=Ma(b[0].childNodes,e);l.length;){f=l.shift();B=l.shift();var M=l.shift(),T=l.shift(),O=b[0];if(!f.$$destroyed){if(B!==p){var J=B.className;k.hasElementTranscludeDirective&& s.replace||(O=Zb(u));ga(M,F(B),O);Ja(F(O),J)}B=m.transcludeOnThisElement?G(f,m.transclude,T):T;m(n,f,O,d,B)}}l=null});return function(a,b,c,d,e){a=e;b.$$destroyed||(l?l.push(b,c,d,a):(m.transcludeOnThisElement&&(a=G(b,m.transclude,e)),m(n,b,c,d,a)))}}function ja(a,b){var c=b.priority-a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function $(a,b,c,d){function e(a){return a?" (module: "+a+")":""}if(b)throw fa("multidir",b.name,e(b.$$moduleName),c.name,e(c.$$moduleName), a,ya(d));}function ka(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:function(a){a=a.parent();var b=!!a.length;b&&ca.$$addBindingClass(a);return function(a,c){var e=c.parent();b||ca.$$addBindingClass(e);ca.$$addBindingInfo(e,d.expressions);a.$watch(d,function(a){c[0].nodeValue=a})}}})}function ha(a,b){a=Q(a||"html");switch(a){case "svg":case "math":var c=y.document.createElement("div");c.innerHTML="<"+a+">"+b+"</"+a+">";return c.childNodes[0].childNodes;default:return b}}function oa(a,b){if("srcdoc"=== b)return B.HTML;var c=wa(a);if("src"===b||"ngSrc"===b){if(-1===["img","video","audio","source","track"].indexOf(c))return B.RESOURCE_URL}else if("xlinkHref"===b||"form"===c&&"action"===b)return B.RESOURCE_URL}function pa(a,c,d,e,f){var g=oa(a,e),h=k[e]||f,l=b(d,!f,g,h);if(l){if("multiple"===e&&"select"===wa(a))throw fa("selmulti",ya(a));c.push({priority:100,compile:function(){return{pre:function(a,c,f){c=f.$$observers||(f.$$observers=V());if(m.test(e))throw fa("nodomevents");var k=f[e];k!==d&&(l= k&&b(k,!0,g,h),d=k);l&&(f[e]=l(a),(c[e]||(c[e]=[])).$$inter=!0,(f.$$observers&&f.$$observers[e].$$scope||a).$watch(l,function(a,b){"class"===e&&a!==b?f.$updateClass(a,b):f.$set(e,a)}))}}}})}}function ga(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=0,h=a.length;g<h;g++)if(a[g]===d){a[g++]=c;h=g+e-1;for(var k=a.length;g<k;g++,h++)h<k?a[g]=a[h]:delete a[g];a.length-=e-1;a.context===d&&(a.context=c);break}f&&f.replaceChild(c,d);a=y.document.createDocumentFragment();for(g=0;g<e;g++)a.appendChild(b[g]); F.hasData(d)&&(F.data(c,F.data(d)),F(d).off("$destroy"));F.cleanData(a.querySelectorAll("*"));for(g=1;g<e;g++)delete b[g];b[0]=c;b.length=1}function ra(a,b){return R(function(){return a.apply(null,arguments)},a,b)}function sa(a,b,d,e,f,g){try{a(b,d,e,f,g)}catch(h){c(h,ya(d))}}function la(a,c,d,e,f){function g(b,c,e){!C(d.$onChanges)||c===e||c!==c&&e!==e||(da||(a.$$postDigest(P),da=[]),m||(m={},da.push(h)),m[b]&&(e=m[b].previousValue),m[b]=new Hb(e,c))}function h(){d.$onChanges(m);m=void 0}var k=[], l={},m;q(e,function(e,h){var m=e.attrName,p=e.optional,s,A,r,u;switch(e.mode){case "@":p||ua.call(c,m)||(d[h]=c[m]=void 0);p=c.$observe(m,function(a){if(D(a)||Ka(a))g(h,a,d[h]),d[h]=a});c.$$observers[m].$$scope=a;s=c[m];D(s)?d[h]=b(s)(a):Ka(s)&&(d[h]=s);l[h]=new Hb(ec,d[h]);k.push(p);break;case "=":if(!ua.call(c,m)){if(p)break;c[m]=void 0}if(p&&!c[m])break;A=n(c[m]);u=A.literal?na:function(a,b){return a===b||a!==a&&b!==b};r=A.assign||function(){s=d[h]=A(a);throw fa("nonassign",c[m],m,f.name);};s= d[h]=A(a);p=function(b){u(b,d[h])||(u(b,s)?r(a,b=d[h]):d[h]=b);return s=b};p.$stateful=!0;p=e.collection?a.$watchCollection(c[m],p):a.$watch(n(c[m],p),null,A.literal);k.push(p);break;case "<":if(!ua.call(c,m)){if(p)break;c[m]=void 0}if(p&&!c[m])break;A=n(c[m]);var B=A.literal,M=d[h]=A(a);l[h]=new Hb(ec,d[h]);p=a.$watch(A,function(a,b){if(b===a){if(b===M||B&&na(b,M))return;b=M}g(h,a,b);d[h]=a},B);k.push(p);break;case "&":A=c.hasOwnProperty(m)?n(c[m]):w;if(A===w&&p)break;d[h]=function(b){return A(a, b)}}});return{initialChanges:l,removeWatches:k.length&&function(){for(var a=0,b=k.length;a<b;++a)k[a]()}}}var za=/^\w/,ta=y.document.createElement("div"),Ea=u,Fa=p,xa=H,da;t.prototype={$normalize:Da,$addClass:function(a){a&&0<a.length&&T.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&T.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=fd(a,b);c&&c.length&&T.addClass(this.$$element,c);(c=fd(b,a))&&c.length&&T.removeClass(this.$$element,c)},$set:function(a,b,d,e){var f= Zc(this.$$element[0],a),g=gd[a],h=a;f?(this.$$element.prop(a,b),e=f):g&&(this[g]=b,h=g);this[a]=b;e?this.$attr[a]=e:(e=this.$attr[a])||(this.$attr[a]=e=Hc(a,"-"));f=wa(this.$$element);if("a"===f&&("href"===a||"xlinkHref"===a)||"img"===f&&"src"===a)this[a]=b=S(b,"src"===a);else if("img"===f&&"srcset"===a&&x(b)){for(var f="",g=Y(b),k=/(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/,k=/\s/.test(g)?k:/(,)/,g=g.split(k),k=Math.floor(g.length/2),l=0;l<k;l++)var m=2*l,f=f+S(Y(g[m]),!0),f=f+(" "+Y(g[m+1]));g=Y(g[2* l]).split(/\s/);f+=S(Y(g[0]),!0);2===g.length&&(f+=" "+Y(g[1]));this[a]=b=f}!1!==d&&(null===b||z(b)?this.$$element.removeAttr(e):za.test(e)?this.$$element.attr(e,b):qa(this.$$element[0],e,b));(a=this.$$observers)&&q(a[h],function(a){try{a(b)}catch(d){c(d)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers=V()),e=d[a]||(d[a]=[]);e.push(b);J.$evalAsync(function(){e.$$inter||!c.hasOwnProperty(a)||z(c[a])||b(c[a])});return function(){bb(e,b)}}};var Aa=b.startSymbol(),Ba=b.endSymbol(), Ca="{{"===Aa&&"}}"===Ba?$a:function(a){return a.replace(/\{\{/g,Aa).replace(/}}/g,Ba)},Ga=/^ngAttr[A-Z]/,Ha=/^(.+)Start$/;ca.$$addBindingInfo=r?function(a,b){var c=a.data("$binding")||[];I(b)?c=c.concat(b):c.push(b);a.data("$binding",c)}:w;ca.$$addBindingClass=r?function(a){Ja(a,"ng-binding")}:w;ca.$$addScopeInfo=r?function(a,b,c,d){a.data(c?d?"$isolateScopeNoTemplate":"$isolateScope":"$scope",b)}:w;ca.$$addScopeClass=r?function(a,b){Ja(a,b?"ng-isolate-scope":"ng-scope")}:w;ca.$$createComment=function(a, b){var c="";r&&(c=" "+(a||"")+": ",b&&(c+=b+" "));return y.document.createComment(c)};return ca}]}function Hb(a,b){this.previousValue=a;this.currentValue=b}function Da(a){return hb(a.replace(bd,""))}function fd(a,b){var d="",c=a.split(/\s+/),f=b.split(/\s+/),e=0;a:for(;e<c.length;e++){for(var g=c[e],h=0;h<f.length;h++)if(g===f[h])continue a;d+=(0<d.length?" ":"")+g}return d}function ed(a){a=F(a);var b=a.length;if(1>=b)return a;for(;b--;){var d=a[b];(8===d.nodeType||d.nodeType===La&&""===d.nodeValue.trim())&& pg.call(a,b,1)}return a}function ng(a,b){if(b&&D(b))return b;if(D(a)){var d=hd.exec(a);if(d)return d[3]}}function tf(){var a={},b=!1;this.has=function(b){return a.hasOwnProperty(b)};this.register=function(b,c){Ra(b,"controller");E(b)?R(a,b):a[b]=c};this.allowGlobals=function(){b=!0};this.$get=["$injector","$window",function(d,c){function f(a,b,c,d){if(!a||!E(a.$scope))throw G("$controller")("noscp",d,b);a.$scope[b]=c}return function(e,g,h,k){var l,m,n;h=!0===h;k&&D(k)&&(n=k);if(D(e)){k=e.match(hd); if(!k)throw id("ctrlfmt",e);m=k[1];n=n||k[3];e=a.hasOwnProperty(m)?a[m]:Jc(g.$scope,m,!0)||(b?Jc(c,m,!0):void 0);if(!e)throw id("ctrlreg",m);Qa(e,m,!0)}if(h)return h=(I(e)?e[e.length-1]:e).prototype,l=Object.create(h||null),n&&f(g,n,l,m||e.name),R(function(){var a=d.invoke(e,l,g,m);a!==l&&(E(a)||C(a))&&(l=a,n&&f(g,n,l,m||e.name));return l},{instance:l,identifier:n});l=d.instantiate(e,g,m);n&&f(g,n,l,m||e.name);return l}}]}function uf(){this.$get=["$window",function(a){return F(a.document)}]}function vf(){this.$get= ["$log",function(a){return function(b,d){a.error.apply(a,arguments)}}]}function fc(a){return E(a)?ja(a)?a.toISOString():eb(a):a}function Af(){this.$get=function(){return function(a){if(!a)return"";var b=[];yc(a,function(a,c){null===a||z(a)||(I(a)?q(a,function(a){b.push(oa(c)+"="+oa(fc(a)))}):b.push(oa(c)+"="+oa(fc(a))))});return b.join("&")}}}function Bf(){this.$get=function(){return function(a){function b(a,f,e){null===a||z(a)||(I(a)?q(a,function(a,c){b(a,f+"["+(E(a)?c:"")+"]")}):E(a)&&!ja(a)?yc(a, function(a,c){b(a,f+(e?"":"[")+c+(e?"":"]"))}):d.push(oa(f)+"="+oa(fc(a))))}if(!a)return"";var d=[];b(a,"",!0);return d.join("&")}}}function gc(a,b){if(D(a)){var d=a.replace(qg,"").trim();if(d){var c=b("Content-Type");(c=c&&0===c.indexOf(jd))||(c=(c=d.match(rg))&&sg[c[0]].test(d));c&&(a=Cc(d))}}return a}function kd(a){var b=V(),d;D(a)?q(a.split("\n"),function(a){d=a.indexOf(":");var f=Q(Y(a.substr(0,d)));a=Y(a.substr(d+1));f&&(b[f]=b[f]?b[f]+", "+a:a)}):E(a)&&q(a,function(a,d){var e=Q(d),g=Y(a);e&& (b[e]=b[e]?b[e]+", "+g:g)});return b}function ld(a){var b;return function(d){b||(b=kd(a));return d?(d=b[Q(d)],void 0===d&&(d=null),d):b}}function md(a,b,d,c){if(C(c))return c(a,b,d);q(c,function(c){a=c(a,b,d)});return a}function zf(){var a=this.defaults={transformResponse:[gc],transformRequest:[function(a){return E(a)&&"[object File]"!==ma.call(a)&&"[object Blob]"!==ma.call(a)&&"[object FormData]"!==ma.call(a)?eb(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:ka(hc),put:ka(hc), patch:ka(hc)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",paramSerializer:"$httpParamSerializer"},b=!1;this.useApplyAsync=function(a){return x(a)?(b=!!a,this):b};var d=!0;this.useLegacyPromiseExtensions=function(a){return x(a)?(d=!!a,this):d};var c=this.interceptors=[];this.$get=["$httpBackend","$$cookieReader","$cacheFactory","$rootScope","$q","$injector",function(f,e,g,h,k,l){function m(b){function c(a,b){for(var d=0,e=b.length;d<e;){var f=b[d++],g=b[d++];a=a.then(f,g)}b.length=0; return a}function e(a,b){var c,d={};q(a,function(a,e){C(a)?(c=a(b),null!=c&&(d[e]=c)):d[e]=a});return d}function f(a){var b=R({},a);b.data=md(a.data,a.headers,a.status,g.transformResponse);a=a.status;return 200<=a&&300>a?b:k.reject(b)}if(!E(b))throw G("$http")("badreq",b);if(!D(b.url))throw G("$http")("badreq",b.url);var g=R({method:"get",transformRequest:a.transformRequest,transformResponse:a.transformResponse,paramSerializer:a.paramSerializer},b);g.headers=function(b){var c=a.headers,d=R({},b.headers), f,g,h,c=R({},c.common,c[Q(b.method)]);a:for(f in c){g=Q(f);for(h in d)if(Q(h)===g)continue a;d[f]=c[f]}return e(d,ka(b))}(b);g.method=wb(g.method);g.paramSerializer=D(g.paramSerializer)?l.get(g.paramSerializer):g.paramSerializer;var h=[],m=[],s=k.when(g);q(H,function(a){(a.request||a.requestError)&&h.unshift(a.request,a.requestError);(a.response||a.responseError)&&m.push(a.response,a.responseError)});s=c(s,h);s=s.then(function(b){var c=b.headers,d=md(b.data,ld(c),void 0,b.transformRequest);z(d)&& q(c,function(a,b){"content-type"===Q(b)&&delete c[b]});z(b.withCredentials)&&!z(a.withCredentials)&&(b.withCredentials=a.withCredentials);return n(b,d).then(f,f)});s=c(s,m);d?(s.success=function(a){Qa(a,"fn");s.then(function(b){a(b.data,b.status,b.headers,g)});return s},s.error=function(a){Qa(a,"fn");s.then(null,function(b){a(b.data,b.status,b.headers,g)});return s}):(s.success=nd("success"),s.error=nd("error"));return s}function n(c,d){function g(a){if(a){var c={};q(a,function(a,d){c[d]=function(c){function d(){a(c)} b?h.$applyAsync(d):h.$$phase?d():h.$apply(d)}});return c}}function l(a,c,d,e){function f(){n(c,a,d,e)}J&&(200<=a&&300>a?J.put(S,[a,c,kd(d),e]):J.remove(S));b?h.$applyAsync(f):(f(),h.$$phase||h.$apply())}function n(a,b,d,e){b=-1<=b?b:0;(200<=b&&300>b?O.resolve:O.reject)({data:a,status:b,headers:ld(d),config:c,statusText:e})}function H(a){n(a.data,a.status,ka(a.headers()),a.statusText)}function L(){var a=m.pendingRequests.indexOf(c);-1!==a&&m.pendingRequests.splice(a,1)}var O=k.defer(),M=O.promise, J,B,T=c.headers,S=r(c.url,c.paramSerializer(c.params));m.pendingRequests.push(c);M.then(L,L);!c.cache&&!a.cache||!1===c.cache||"GET"!==c.method&&"JSONP"!==c.method||(J=E(c.cache)?c.cache:E(a.cache)?a.cache:s);J&&(B=J.get(S),x(B)?B&&C(B.then)?B.then(H,H):I(B)?n(B[1],B[0],ka(B[2]),B[3]):n(B,200,{},"OK"):J.put(S,M));z(B)&&((B=od(c.url)?e()[c.xsrfCookieName||a.xsrfCookieName]:void 0)&&(T[c.xsrfHeaderName||a.xsrfHeaderName]=B),f(c.method,S,d,l,T,c.timeout,c.withCredentials,c.responseType,g(c.eventHandlers), g(c.uploadEventHandlers)));return M}function r(a,b){0<b.length&&(a+=(-1===a.indexOf("?")?"?":"&")+b);return a}var s=g("$http");a.paramSerializer=D(a.paramSerializer)?l.get(a.paramSerializer):a.paramSerializer;var H=[];q(c,function(a){H.unshift(D(a)?l.get(a):l.invoke(a))});m.pendingRequests=[];(function(a){q(arguments,function(a){m[a]=function(b,c){return m(R({},c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){q(arguments,function(a){m[a]=function(b,c,d){return m(R({},d||{}, {method:a,url:b,data:c}))}})})("post","put","patch");m.defaults=a;return m}]}function Df(){this.$get=function(){return function(){return new y.XMLHttpRequest}}}function Cf(){this.$get=["$browser","$jsonpCallbacks","$document","$xhrFactory",function(a,b,d,c){return tg(a,c,a.defer,b,d[0])}]}function tg(a,b,d,c,f){function e(a,b,d){a=a.replace("JSON_CALLBACK",b);var e=f.createElement("script"),m=null;e.type="text/javascript";e.src=a;e.async=!0;m=function(a){e.removeEventListener("load",m,!1);e.removeEventListener("error", m,!1);f.body.removeChild(e);e=null;var g=-1,s="unknown";a&&("load"!==a.type||c.wasCalled(b)||(a={type:"error"}),s=a.type,g="error"===a.type?404:200);d&&d(g,s)};e.addEventListener("load",m,!1);e.addEventListener("error",m,!1);f.body.appendChild(e);return m}return function(f,h,k,l,m,n,r,s,H,u){function p(){v&&v();N&&N.abort()}function K(b,c,e,f,g){x(O)&&d.cancel(O);v=N=null;b(c,e,f,g);a.$$completeOutstandingRequest(w)}a.$$incOutstandingRequestCount();h=h||a.url();if("jsonp"===Q(f))var A=c.createCallback(h), v=e(h,A,function(a,b){var d=200===a&&c.getResponse(A);K(l,a,d,"",b);c.removeCallback(A)});else{var N=b(f,h);N.open(f,h,!0);q(m,function(a,b){x(a)&&N.setRequestHeader(b,a)});N.onload=function(){var a=N.statusText||"",b="response"in N?N.response:N.responseText,c=1223===N.status?204:N.status;0===c&&(c=b?200:"file"===ta(h).protocol?404:0);K(l,c,b,N.getAllResponseHeaders(),a)};f=function(){K(l,-1,null,null,"")};N.onerror=f;N.onabort=f;N.ontimeout=f;q(H,function(a,b){N.addEventListener(b,a)});q(u,function(a, b){N.upload.addEventListener(b,a)});r&&(N.withCredentials=!0);if(s)try{N.responseType=s}catch(L){if("json"!==s)throw L;}N.send(z(k)?null:k)}if(0<n)var O=d(p,n);else n&&C(n.then)&&n.then(p)}}function xf(){var a="{{",b="}}";this.startSymbol=function(b){return b?(a=b,this):a};this.endSymbol=function(a){return a?(b=a,this):b};this.$get=["$parse","$exceptionHandler","$sce",function(d,c,f){function e(a){return"\\\\\\"+a}function g(c){return c.replace(n,a).replace(r,b)}function h(a,b,c,d){var e=a.$watch(function(a){e(); return d(a)},b,c);return e}function k(e,k,n,p){function r(a){try{var b=a;a=n?f.getTrusted(n,b):f.valueOf(b);var d;if(p&&!x(a))d=a;else if(null==a)d="";else{switch(typeof a){case "string":break;case "number":a=""+a;break;default:a=eb(a)}d=a}return d}catch(g){c(Ha.interr(e,g))}}if(!e.length||-1===e.indexOf(a)){var A;k||(k=g(e),A=ha(k),A.exp=e,A.expressions=[],A.$$watchDelegate=h);return A}p=!!p;var v,q,L=0,O=[],M=[];A=e.length;for(var J=[],B=[];L<A;)if(-1!==(v=e.indexOf(a,L))&&-1!==(q=e.indexOf(b,v+ l)))L!==v&&J.push(g(e.substring(L,v))),L=e.substring(v+l,q),O.push(L),M.push(d(L,r)),L=q+m,B.push(J.length),J.push("");else{L!==A&&J.push(g(e.substring(L)));break}n&&1<J.length&&Ha.throwNoconcat(e);if(!k||O.length){var T=function(a){for(var b=0,c=O.length;b<c;b++){if(p&&z(a[b]))return;J[B[b]]=a[b]}return J.join("")};return R(function(a){var b=0,d=O.length,f=Array(d);try{for(;b<d;b++)f[b]=M[b](a);return T(f)}catch(g){c(Ha.interr(e,g))}},{exp:e,expressions:O,$$watchDelegate:function(a,b){var c;return a.$watchGroup(M, function(d,e){var f=T(d);C(b)&&b.call(this,f,d!==e?c:f,a);c=f})}})}}var l=a.length,m=b.length,n=new RegExp(a.replace(/./g,e),"g"),r=new RegExp(b.replace(/./g,e),"g");k.startSymbol=function(){return a};k.endSymbol=function(){return b};return k}]}function yf(){this.$get=["$rootScope","$window","$q","$$q","$browser",function(a,b,d,c,f){function e(e,k,l,m){function n(){r?e.apply(null,s):e(p)}var r=4<arguments.length,s=r?va.call(arguments,4):[],H=b.setInterval,u=b.clearInterval,p=0,K=x(m)&&!m,A=(K?c:d).defer(), v=A.promise;l=x(l)?l:0;v.$$intervalId=H(function(){K?f.defer(n):a.$evalAsync(n);A.notify(p++);0<l&&p>=l&&(A.resolve(p),u(v.$$intervalId),delete g[v.$$intervalId]);K||a.$apply()},k);g[v.$$intervalId]=A;return v}var g={};e.cancel=function(a){return a&&a.$$intervalId in g?(g[a.$$intervalId].reject("canceled"),b.clearInterval(a.$$intervalId),delete g[a.$$intervalId],!0):!1};return e}]}function ic(a){a=a.split("/");for(var b=a.length;b--;)a[b]=tb(a[b]);return a.join("/")}function pd(a,b){var d=ta(a);b.$$protocol= d.protocol;b.$$host=d.hostname;b.$$port=Z(d.port)||ug[d.protocol]||null}function qd(a,b){if(vg.test(a))throw lb("badpath",a);var d="/"!==a.charAt(0);d&&(a="/"+a);var c=ta(a);b.$$path=decodeURIComponent(d&&"/"===c.pathname.charAt(0)?c.pathname.substring(1):c.pathname);b.$$search=Fc(c.search);b.$$hash=decodeURIComponent(c.hash);b.$$path&&"/"!==b.$$path.charAt(0)&&(b.$$path="/"+b.$$path)}function ra(a,b){if(b.slice(0,a.length)===a)return b.substr(a.length)}function Ga(a){var b=a.indexOf("#");return-1=== b?a:a.substr(0,b)}function mb(a){return a.replace(/(#.+)|#$/,"$1")}function jc(a,b,d){this.$$html5=!0;d=d||"";pd(a,this);this.$$parse=function(a){var d=ra(b,a);if(!D(d))throw lb("ipthprfx",a,b);qd(d,this);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Vb(this.$$search),d=this.$$hash?"#"+tb(this.$$hash):"";this.$$url=ic(this.$$path)+(a?"?"+a:"")+d;this.$$absUrl=b+this.$$url.substr(1)};this.$$parseLinkUrl=function(c,f){if(f&&"#"===f[0])return this.hash(f.slice(1)), !0;var e,g;x(e=ra(a,c))?(g=e,g=d&&x(e=ra(d,e))?b+(ra("/",e)||e):a+g):x(e=ra(b,c))?g=b+e:b===c+"/"&&(g=b);g&&this.$$parse(g);return!!g}}function kc(a,b,d){pd(a,this);this.$$parse=function(c){var f=ra(a,c)||ra(b,c),e;z(f)||"#"!==f.charAt(0)?this.$$html5?e=f:(e="",z(f)&&(a=c,this.replace())):(e=ra(d,f),z(e)&&(e=f));qd(e,this);c=this.$$path;var f=a,g=/^\/[A-Z]:(\/.*)/;e.slice(0,f.length)===f&&(e=e.replace(f,""));g.exec(e)||(c=(e=g.exec(c))?e[1]:c);this.$$path=c;this.$$compose()};this.$$compose=function(){var b= Vb(this.$$search),f=this.$$hash?"#"+tb(this.$$hash):"";this.$$url=ic(this.$$path)+(b?"?"+b:"")+f;this.$$absUrl=a+(this.$$url?d+this.$$url:"")};this.$$parseLinkUrl=function(b,d){return Ga(a)===Ga(b)?(this.$$parse(b),!0):!1}}function rd(a,b,d){this.$$html5=!0;kc.apply(this,arguments);this.$$parseLinkUrl=function(c,f){if(f&&"#"===f[0])return this.hash(f.slice(1)),!0;var e,g;a===Ga(c)?e=c:(g=ra(b,c))?e=a+d+g:b===c+"/"&&(e=b);e&&this.$$parse(e);return!!e};this.$$compose=function(){var b=Vb(this.$$search), f=this.$$hash?"#"+tb(this.$$hash):"";this.$$url=ic(this.$$path)+(b?"?"+b:"")+f;this.$$absUrl=a+d+this.$$url}}function Ib(a){return function(){return this[a]}}function sd(a,b){return function(d){if(z(d))return this[a];this[a]=b(d);this.$$compose();return this}}function Ff(){var a="",b={enabled:!1,requireBase:!0,rewriteLinks:!0};this.hashPrefix=function(b){return x(b)?(a=b,this):a};this.html5Mode=function(a){if(Ka(a))return b.enabled=a,this;if(E(a)){Ka(a.enabled)&&(b.enabled=a.enabled);Ka(a.requireBase)&& (b.requireBase=a.requireBase);if(Ka(a.rewriteLinks)||D(a.rewriteLinks))b.rewriteLinks=a.rewriteLinks;return this}return b};this.$get=["$rootScope","$browser","$sniffer","$rootElement","$window",function(d,c,f,e,g){function h(a,b,d){var e=l.url(),f=l.$$state;try{c.url(a,b,d),l.$$state=c.state()}catch(g){throw l.url(e),l.$$state=f,g;}}function k(a,b){d.$broadcast("$locationChangeSuccess",l.absUrl(),a,l.$$state,b)}var l,m;m=c.baseHref();var n=c.url(),r;if(b.enabled){if(!m&&b.requireBase)throw lb("nobase"); r=n.substring(0,n.indexOf("/",n.indexOf("//")+2))+(m||"/");m=f.history?jc:rd}else r=Ga(n),m=kc;var s=r.substr(0,Ga(r).lastIndexOf("/")+1);l=new m(r,s,"#"+a);l.$$parseLinkUrl(n,n);l.$$state=c.state();var H=/^\s*(javascript|mailto):/i;e.on("click",function(a){var f=b.rewriteLinks;if(f&&!a.ctrlKey&&!a.metaKey&&!a.shiftKey&&2!==a.which&&2!==a.button){for(var h=F(a.target);"a"!==wa(h[0]);)if(h[0]===e[0]||!(h=h.parent())[0])return;if(!D(f)||!z(h.attr(f))){var f=h.prop("href"),k=h.attr("href")||h.attr("xlink:href"); E(f)&&"[object SVGAnimatedString]"===f.toString()&&(f=ta(f.animVal).href);H.test(f)||!f||h.attr("target")||a.isDefaultPrevented()||!l.$$parseLinkUrl(f,k)||(a.preventDefault(),l.absUrl()!==c.url()&&(d.$apply(),g.angular["ff-684208-preventDefault"]=!0))}}});mb(l.absUrl())!==mb(n)&&c.url(l.absUrl(),!0);var u=!0;c.onUrlChange(function(a,b){z(ra(s,a))?g.location.href=a:(d.$evalAsync(function(){var c=l.absUrl(),e=l.$$state,f;a=mb(a);l.$$parse(a);l.$$state=b;f=d.$broadcast("$locationChangeStart",a,c,b,e).defaultPrevented; l.absUrl()===a&&(f?(l.$$parse(c),l.$$state=e,h(c,!1,e)):(u=!1,k(c,e)))}),d.$$phase||d.$digest())});d.$watch(function(){var a=mb(c.url()),b=mb(l.absUrl()),e=c.state(),g=l.$$replace,m=a!==b||l.$$html5&&f.history&&e!==l.$$state;if(u||m)u=!1,d.$evalAsync(function(){var b=l.absUrl(),c=d.$broadcast("$locationChangeStart",b,a,l.$$state,e).defaultPrevented;l.absUrl()===b&&(c?(l.$$parse(a),l.$$state=e):(m&&h(b,g,e===l.$$state?null:l.$$state),k(a,e)))});l.$$replace=!1});return l}]}function Gf(){var a=!0,b= this;this.debugEnabled=function(b){return x(b)?(a=b,this):a};this.$get=["$window",function(d){function c(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function f(a){var b=d.console||{},f=b[a]||b.log||w;a=!1;try{a=!!f.apply}catch(k){}return a?function(){var a=[];q(arguments,function(b){a.push(c(b))});return f.apply(b,a)}:function(a,b){f(a,null==b?"":b)}}return{log:f("log"), info:f("info"),warn:f("warn"),error:f("error"),debug:function(){var c=f("debug");return function(){a&&c.apply(b,arguments)}}()}}]}function Ua(a,b){if("__defineGetter__"===a||"__defineSetter__"===a||"__lookupGetter__"===a||"__lookupSetter__"===a||"__proto__"===a)throw ea("isecfld",b);return a}function wg(a){return a+""}function Ea(a,b){if(a){if(a.constructor===a)throw ea("isecfn",b);if(a.window===a)throw ea("isecwindow",b);if(a.children&&(a.nodeName||a.prop&&a.attr&&a.find))throw ea("isecdom",b);if(a=== Object)throw ea("isecobj",b);}return a}function td(a,b){if(a){if(a.constructor===a)throw ea("isecfn",b);if(a===xg||a===yg||a===zg)throw ea("isecff",b);}}function Jb(a,b){if(a&&(a===ud||a===vd||a===wd||a===xd||a===yd||a===zd||a===Ag||a===Bg||a===Kb||a===Cg||a===Ad||a===Dg))throw ea("isecaf",b);}function Eg(a,b){return"undefined"!==typeof a?a:b}function Bd(a,b){return"undefined"===typeof a?b:"undefined"===typeof b?a:a+b}function X(a,b){var d,c,f;switch(a.type){case t.Program:d=!0;q(a.body,function(a){X(a.expression, b);d=d&&a.expression.constant});a.constant=d;break;case t.Literal:a.constant=!0;a.toWatch=[];break;case t.UnaryExpression:X(a.argument,b);a.constant=a.argument.constant;a.toWatch=a.argument.toWatch;break;case t.BinaryExpression:X(a.left,b);X(a.right,b);a.constant=a.left.constant&&a.right.constant;a.toWatch=a.left.toWatch.concat(a.right.toWatch);break;case t.LogicalExpression:X(a.left,b);X(a.right,b);a.constant=a.left.constant&&a.right.constant;a.toWatch=a.constant?[]:[a];break;case t.ConditionalExpression:X(a.test, b);X(a.alternate,b);X(a.consequent,b);a.constant=a.test.constant&&a.alternate.constant&&a.consequent.constant;a.toWatch=a.constant?[]:[a];break;case t.Identifier:a.constant=!1;a.toWatch=[a];break;case t.MemberExpression:X(a.object,b);a.computed&&X(a.property,b);a.constant=a.object.constant&&(!a.computed||a.property.constant);a.toWatch=[a];break;case t.CallExpression:d=f=a.filter?!b(a.callee.name).$stateful:!1;c=[];q(a.arguments,function(a){X(a,b);d=d&&a.constant;a.constant||c.push.apply(c,a.toWatch)}); a.constant=d;a.toWatch=f?c:[a];break;case t.AssignmentExpression:X(a.left,b);X(a.right,b);a.constant=a.left.constant&&a.right.constant;a.toWatch=[a];break;case t.ArrayExpression:d=!0;c=[];q(a.elements,function(a){X(a,b);d=d&&a.constant;a.constant||c.push.apply(c,a.toWatch)});a.constant=d;a.toWatch=c;break;case t.ObjectExpression:d=!0;c=[];q(a.properties,function(a){X(a.value,b);d=d&&a.value.constant&&!a.computed;a.value.constant||c.push.apply(c,a.value.toWatch)});a.constant=d;a.toWatch=c;break;case t.ThisExpression:a.constant= !1;a.toWatch=[];break;case t.LocalsExpression:a.constant=!1,a.toWatch=[]}}function Cd(a){if(1===a.length){a=a[0].expression;var b=a.toWatch;return 1!==b.length?b:b[0]!==a?b:void 0}}function Dd(a){return a.type===t.Identifier||a.type===t.MemberExpression}function Ed(a){if(1===a.body.length&&Dd(a.body[0].expression))return{type:t.AssignmentExpression,left:a.body[0].expression,right:{type:t.NGValueParameter},operator:"="}}function Fd(a){return 0===a.body.length||1===a.body.length&&(a.body[0].expression.type=== t.Literal||a.body[0].expression.type===t.ArrayExpression||a.body[0].expression.type===t.ObjectExpression)}function Gd(a,b){this.astBuilder=a;this.$filter=b}function Hd(a,b){this.astBuilder=a;this.$filter=b}function Lb(a){return"constructor"===a}function lc(a){return C(a.valueOf)?a.valueOf():Fg.call(a)}function Hf(){var a=V(),b=V(),d={"true":!0,"false":!1,"null":null,undefined:void 0},c,f;this.addLiteral=function(a,b){d[a]=b};this.setIdentifierFns=function(a,b){c=a;f=b;return this};this.$get=["$filter", function(e){function g(c,d,f){var g,k,H;f=f||K;switch(typeof c){case "string":H=c=c.trim();var q=f?b:a;g=q[H];if(!g){":"===c.charAt(0)&&":"===c.charAt(1)&&(k=!0,c=c.substring(2));g=f?p:u;var B=new mc(g);g=(new nc(B,e,g)).parse(c);g.constant?g.$$watchDelegate=r:k?g.$$watchDelegate=g.literal?n:m:g.inputs&&(g.$$watchDelegate=l);f&&(g=h(g));q[H]=g}return s(g,d);case "function":return s(c,d);default:return s(w,d)}}function h(a){function b(c,d,e,f){var g=K;K=!0;try{return a(c,d,e,f)}finally{K=g}}if(!a)return a; b.$$watchDelegate=a.$$watchDelegate;b.assign=h(a.assign);b.constant=a.constant;b.literal=a.literal;for(var c=0;a.inputs&&c<a.inputs.length;++c)a.inputs[c]=h(a.inputs[c]);b.inputs=a.inputs;return b}function k(a,b){return null==a||null==b?a===b:"object"===typeof a&&(a=lc(a),"object"===typeof a)?!1:a===b||a!==a&&b!==b}function l(a,b,c,d,e){var f=d.inputs,g;if(1===f.length){var h=k,f=f[0];return a.$watch(function(a){var b=f(a);k(b,h)||(g=d(a,void 0,void 0,[b]),h=b&&lc(b));return g},b,c,e)}for(var l=[], m=[],n=0,s=f.length;n<s;n++)l[n]=k,m[n]=null;return a.$watch(function(a){for(var b=!1,c=0,e=f.length;c<e;c++){var h=f[c](a);if(b||(b=!k(h,l[c])))m[c]=h,l[c]=h&&lc(h)}b&&(g=d(a,void 0,void 0,m));return g},b,c,e)}function m(a,b,c,d){var e,f;return e=a.$watch(function(a){return d(a)},function(a,c,d){f=a;C(b)&&b.apply(this,arguments);x(a)&&d.$$postDigest(function(){x(f)&&e()})},c)}function n(a,b,c,d){function e(a){var b=!0;q(a,function(a){x(a)||(b=!1)});return b}var f,g;return f=a.$watch(function(a){return d(a)}, function(a,c,d){g=a;C(b)&&b.call(this,a,c,d);e(a)&&d.$$postDigest(function(){e(g)&&f()})},c)}function r(a,b,c,d){var e=a.$watch(function(a){e();return d(a)},b,c);return e}function s(a,b){if(!b)return a;var c=a.$$watchDelegate,d=!1,c=c!==n&&c!==m?function(c,e,f,g){f=d&&g?g[0]:a(c,e,f,g);return b(f,c,e)}:function(c,d,e,f){e=a(c,d,e,f);c=b(e,c,d);return x(e)?c:e};a.$$watchDelegate&&a.$$watchDelegate!==l?c.$$watchDelegate=a.$$watchDelegate:b.$stateful||(c.$$watchDelegate=l,d=!a.inputs,c.inputs=a.inputs? a.inputs:[a]);return c}var H=da().noUnsafeEval,u={csp:H,expensiveChecks:!1,literals:sa(d),isIdentifierStart:C(c)&&c,isIdentifierContinue:C(f)&&f},p={csp:H,expensiveChecks:!0,literals:sa(d),isIdentifierStart:C(c)&&c,isIdentifierContinue:C(f)&&f},K=!1;g.$$runningExpensiveChecks=function(){return K};return g}]}function Jf(){this.$get=["$rootScope","$exceptionHandler",function(a,b){return Id(function(b){a.$evalAsync(b)},b)}]}function Kf(){this.$get=["$browser","$exceptionHandler",function(a,b){return Id(function(b){a.defer(b)}, b)}]}function Id(a,b){function d(){var a=new g;a.resolve=f(a,a.resolve);a.reject=f(a,a.reject);a.notify=f(a,a.notify);return a}function c(){this.$$state={status:0}}function f(a,b){return function(c){b.call(a,c)}}function e(c){!c.processScheduled&&c.pending&&(c.processScheduled=!0,a(function(){var a,d,e;e=c.pending;c.processScheduled=!1;c.pending=void 0;for(var f=0,g=e.length;f<g;++f){d=e[f][0];a=e[f][c.status];try{C(a)?d.resolve(a(c.value)):1===c.status?d.resolve(c.value):d.reject(c.value)}catch(h){d.reject(h), b(h)}}}))}function g(){this.promise=new c}function h(a){var b=new g;b.reject(a);return b.promise}function k(a,b,c){var d=null;try{C(c)&&(d=c())}catch(e){return h(e)}return d&&C(d.then)?d.then(function(){return b(a)},h):b(a)}function l(a,b,c,d){var e=new g;e.resolve(a);return e.promise.then(b,c,d)}function m(a){if(!C(a))throw n("norslvr",a);var b=new g;a(function(a){b.resolve(a)},function(a){b.reject(a)});return b.promise}var n=G("$q",TypeError);R(c.prototype,{then:function(a,b,c){if(z(a)&&z(b)&&z(c))return this; var d=new g;this.$$state.pending=this.$$state.pending||[];this.$$state.pending.push([d,a,b,c]);0<this.$$state.status&&e(this.$$state);return d.promise},"catch":function(a){return this.then(null,a)},"finally":function(a,b){return this.then(function(b){return k(b,r,a)},function(b){return k(b,h,a)},b)}});R(g.prototype,{resolve:function(a){this.promise.$$state.status||(a===this.promise?this.$$reject(n("qcycle",a)):this.$$resolve(a))},$$resolve:function(a){function c(a){k||(k=!0,h.$$resolve(a))}function d(a){k|| (k=!0,h.$$reject(a))}var g,h=this,k=!1;try{if(E(a)||C(a))g=a&&a.then;C(g)?(this.promise.$$state.status=-1,g.call(a,c,d,f(this,this.notify))):(this.promise.$$state.value=a,this.promise.$$state.status=1,e(this.promise.$$state))}catch(l){d(l),b(l)}},reject:function(a){this.promise.$$state.status||this.$$reject(a)},$$reject:function(a){this.promise.$$state.value=a;this.promise.$$state.status=2;e(this.promise.$$state)},notify:function(c){var d=this.promise.$$state.pending;0>=this.promise.$$state.status&& d&&d.length&&a(function(){for(var a,e,f=0,g=d.length;f<g;f++){e=d[f][0];a=d[f][3];try{e.notify(C(a)?a(c):c)}catch(h){b(h)}}})}});var r=l;m.prototype=c.prototype;m.defer=d;m.reject=h;m.when=l;m.resolve=r;m.all=function(a){var b=new g,c=0,d=I(a)?[]:{};q(a,function(a,e){c++;l(a).then(function(a){d[e]=a;--c||b.resolve(d)},function(a){b.reject(a)})});0===c&&b.resolve(d);return b.promise};m.race=function(a){var b=d();q(a,function(a){l(a).then(b.resolve,b.reject)});return b.promise};return m}function Tf(){this.$get= ["$window","$timeout",function(a,b){var d=a.requestAnimationFrame||a.webkitRequestAnimationFrame,c=a.cancelAnimationFrame||a.webkitCancelAnimationFrame||a.webkitCancelRequestAnimationFrame,f=!!d,e=f?function(a){var b=d(a);return function(){c(b)}}:function(a){var c=b(a,16.66,!1);return function(){b.cancel(c)}};e.supported=f;return e}]}function If(){function a(a){function b(){this.$$watchers=this.$$nextSibling=this.$$childHead=this.$$childTail=null;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount= 0;this.$id=++sb;this.$$ChildScope=null}b.prototype=a;return b}var b=10,d=G("$rootScope"),c=null,f=null;this.digestTtl=function(a){arguments.length&&(b=a);return b};this.$get=["$exceptionHandler","$parse","$browser",function(e,g,h){function k(a){a.currentScope.$$destroyed=!0}function l(a){9===Ia&&(a.$$childHead&&l(a.$$childHead),a.$$nextSibling&&l(a.$$nextSibling));a.$parent=a.$$nextSibling=a.$$prevSibling=a.$$childHead=a.$$childTail=a.$root=a.$$watchers=null}function m(){this.$id=++sb;this.$$phase= this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;this.$root=this;this.$$destroyed=!1;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$$isolateBindings=null}function n(a){if(K.$$phase)throw d("inprog",K.$$phase);K.$$phase=a}function r(a,b){do a.$$watchersCount+=b;while(a=a.$parent)}function s(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&delete a.$$listenerCount[c];while(a=a.$parent)}function H(){}function u(){for(;t.length;)try{t.shift()()}catch(a){e(a)}f= null}function p(){null===f&&(f=h.defer(function(){K.$apply(u)}))}m.prototype={constructor:m,$new:function(b,c){var d;c=c||this;b?(d=new m,d.$root=this.$root):(this.$$ChildScope||(this.$$ChildScope=a(this)),d=new this.$$ChildScope);d.$parent=c;d.$$prevSibling=c.$$childTail;c.$$childHead?(c.$$childTail.$$nextSibling=d,c.$$childTail=d):c.$$childHead=c.$$childTail=d;(b||c!==this)&&d.$on("$destroy",k);return d},$watch:function(a,b,d,e){var f=g(a);if(f.$$watchDelegate)return f.$$watchDelegate(this,b,d, f,a);var h=this,k=h.$$watchers,l={fn:b,last:H,get:f,exp:e||a,eq:!!d};c=null;C(b)||(l.fn=w);k||(k=h.$$watchers=[],k.$$digestWatchIndex=-1);k.unshift(l);k.$$digestWatchIndex++;r(this,1);return function(){var a=bb(k,l);0<=a&&(r(h,-1),a<k.$$digestWatchIndex&&k.$$digestWatchIndex--);c=null}},$watchGroup:function(a,b){function c(){h=!1;k?(k=!1,b(e,e,g)):b(e,d,g)}var d=Array(a.length),e=Array(a.length),f=[],g=this,h=!1,k=!0;if(!a.length){var l=!0;g.$evalAsync(function(){l&&b(e,e,g)});return function(){l= !1}}if(1===a.length)return this.$watch(a[0],function(a,c,f){e[0]=a;d[0]=c;b(e,a===c?e:d,f)});q(a,function(a,b){var k=g.$watch(a,function(a,f){e[b]=a;d[b]=f;h||(h=!0,g.$evalAsync(c))});f.push(k)});return function(){for(;f.length;)f.shift()()}},$watchCollection:function(a,b){function c(a){e=a;var b,d,g,h;if(!z(e)){if(E(e))if(la(e))for(f!==n&&(f=n,s=f.length=0,l++),a=e.length,s!==a&&(l++,f.length=s=a),b=0;b<a;b++)h=f[b],g=e[b],d=h!==h&&g!==g,d||h===g||(l++,f[b]=g);else{f!==r&&(f=r={},s=0,l++);a=0;for(b in e)ua.call(e, b)&&(a++,g=e[b],h=f[b],b in f?(d=h!==h&&g!==g,d||h===g||(l++,f[b]=g)):(s++,f[b]=g,l++));if(s>a)for(b in l++,f)ua.call(e,b)||(s--,delete f[b])}else f!==e&&(f=e,l++);return l}}c.$stateful=!0;var d=this,e,f,h,k=1<b.length,l=0,m=g(a,c),n=[],r={},p=!0,s=0;return this.$watch(m,function(){p?(p=!1,b(e,e,d)):b(e,h,d);if(k)if(E(e))if(la(e)){h=Array(e.length);for(var a=0;a<e.length;a++)h[a]=e[a]}else for(a in h={},e)ua.call(e,a)&&(h[a]=e[a]);else h=e})},$digest:function(){var a,g,k,l,m,r,p,s=b,q,t=[],N,x;n("$digest"); h.$$checkUrlChange();this===K&&null!==f&&(h.defer.cancel(f),u());c=null;do{p=!1;q=this;for(r=0;r<A.length;r++){try{x=A[r],x.scope.$eval(x.expression,x.locals)}catch(z){e(z)}c=null}A.length=0;a:do{if(r=q.$$watchers)for(r.$$digestWatchIndex=r.length;r.$$digestWatchIndex--;)try{if(a=r[r.$$digestWatchIndex])if(m=a.get,(g=m(q))!==(k=a.last)&&!(a.eq?na(g,k):ia(g)&&ia(k)))p=!0,c=a,a.last=a.eq?sa(g,null):g,l=a.fn,l(g,k===H?g:k,q),5>s&&(N=4-s,t[N]||(t[N]=[]),t[N].push({msg:C(a.exp)?"fn: "+(a.exp.name||a.exp.toString()): a.exp,newVal:g,oldVal:k}));else if(a===c){p=!1;break a}}catch(w){e(w)}if(!(r=q.$$watchersCount&&q.$$childHead||q!==this&&q.$$nextSibling))for(;q!==this&&!(r=q.$$nextSibling);)q=q.$parent}while(q=r);if((p||A.length)&&!s--)throw K.$$phase=null,d("infdig",b,t);}while(p||A.length);for(K.$$phase=null;L<v.length;)try{v[L++]()}catch(y){e(y)}v.length=L=0},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this===K&&h.$$applicationDestroyed();r(this, -this.$$watchersCount);for(var b in this.$$listenerCount)s(this,this.$$listenerCount[b],b);a&&a.$$childHead===this&&(a.$$childHead=this.$$nextSibling);a&&a.$$childTail===this&&(a.$$childTail=this.$$prevSibling);this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling);this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling);this.$destroy=this.$digest=this.$apply=this.$evalAsync=this.$applyAsync=w;this.$on=this.$watch=this.$watchGroup=function(){return w};this.$$listeners= {};this.$$nextSibling=null;l(this)}},$eval:function(a,b){return g(a)(this,b)},$evalAsync:function(a,b){K.$$phase||A.length||h.defer(function(){A.length&&K.$digest()});A.push({scope:this,expression:g(a),locals:b})},$$postDigest:function(a){v.push(a)},$apply:function(a){try{n("$apply");try{return this.$eval(a)}finally{K.$$phase=null}}catch(b){e(b)}finally{try{K.$digest()}catch(c){throw e(c),c;}}},$applyAsync:function(a){function b(){c.$eval(a)}var c=this;a&&t.push(b);a=g(a);p()},$on:function(a,b){var c= this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);var d=this;do d.$$listenerCount[a]||(d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){var d=c.indexOf(b);-1!==d&&(c[d]=null,s(e,1,a))}},$emit:function(a,b){var c=[],d,f=this,g=!1,h={name:a,targetScope:f,stopPropagation:function(){g=!0},preventDefault:function(){h.defaultPrevented=!0},defaultPrevented:!1},k=cb([h],arguments,1),l,m;do{d=f.$$listeners[a]||c;h.currentScope=f;l=0;for(m=d.length;l< m;l++)if(d[l])try{d[l].apply(null,k)}catch(n){e(n)}else d.splice(l,1),l--,m--;if(g)return h.currentScope=null,h;f=f.$parent}while(f);h.currentScope=null;return h},$broadcast:function(a,b){var c=this,d=this,f={name:a,targetScope:this,preventDefault:function(){f.defaultPrevented=!0},defaultPrevented:!1};if(!this.$$listenerCount[a])return f;for(var g=cb([f],arguments,1),h,k;c=d;){f.currentScope=c;d=c.$$listeners[a]||[];h=0;for(k=d.length;h<k;h++)if(d[h])try{d[h].apply(null,g)}catch(l){e(l)}else d.splice(h, 1),h--,k--;if(!(d=c.$$listenerCount[a]&&c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(d=c.$$nextSibling);)c=c.$parent}f.currentScope=null;return f}};var K=new m,A=K.$$asyncQueue=[],v=K.$$postDigestQueue=[],t=K.$$applyAsyncQueue=[],L=0;return K}]}function Be(){var a=/^\s*(https?|ftp|mailto|tel|file):/,b=/^\s*((https?|ftp|file|blob):|data:image\/)/;this.aHrefSanitizationWhitelist=function(b){return x(b)?(a=b,this):a};this.imgSrcSanitizationWhitelist=function(a){return x(a)?(b=a,this):b}; this.$get=function(){return function(d,c){var f=c?b:a,e;e=ta(d).href;return""===e||e.match(f)?d:"unsafe:"+e}}}function Gg(a){if("self"===a)return a;if(D(a)){if(-1<a.indexOf("***"))throw Fa("iwcard",a);a=Jd(a).replace(/\\\*\\\*/g,".*").replace(/\\\*/g,"[^:/.?&;]*");return new RegExp("^"+a+"$")}if(Za(a))return new RegExp("^"+a.source+"$");throw Fa("imatcher");}function Kd(a){var b=[];x(a)&&q(a,function(a){b.push(Gg(a))});return b}function Mf(){this.SCE_CONTEXTS=ga;var a=["self"],b=[];this.resourceUrlWhitelist= function(b){arguments.length&&(a=Kd(b));return a};this.resourceUrlBlacklist=function(a){arguments.length&&(b=Kd(a));return b};this.$get=["$injector",function(d){function c(a,b){return"self"===a?od(b):!!a.exec(b.href)}function f(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var e=function(a){throw Fa("unsafe"); };d.has("$sanitize")&&(e=d.get("$sanitize"));var g=f(),h={};h[ga.HTML]=f(g);h[ga.CSS]=f(g);h[ga.URL]=f(g);h[ga.JS]=f(g);h[ga.RESOURCE_URL]=f(h[ga.URL]);return{trustAs:function(a,b){var c=h.hasOwnProperty(a)?h[a]:null;if(!c)throw Fa("icontext",a,b);if(null===b||z(b)||""===b)return b;if("string"!==typeof b)throw Fa("itype",a);return new c(b)},getTrusted:function(d,f){if(null===f||z(f)||""===f)return f;var g=h.hasOwnProperty(d)?h[d]:null;if(g&&f instanceof g)return f.$$unwrapTrustedValue();if(d===ga.RESOURCE_URL){var g= ta(f.toString()),n,r,s=!1;n=0;for(r=a.length;n<r;n++)if(c(a[n],g)){s=!0;break}if(s)for(n=0,r=b.length;n<r;n++)if(c(b[n],g)){s=!1;break}if(s)return f;throw Fa("insecurl",f.toString());}if(d===ga.HTML)return e(f);throw Fa("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}function Lf(){var a=!0;this.enabled=function(b){arguments.length&&(a=!!b);return a};this.$get=["$parse","$sceDelegate",function(b,d){if(a&&8>Ia)throw Fa("iequirks");var c=ka(ga);c.isEnabled=function(){return a}; c.trustAs=d.trustAs;c.getTrusted=d.getTrusted;c.valueOf=d.valueOf;a||(c.trustAs=c.getTrusted=function(a,b){return b},c.valueOf=$a);c.parseAs=function(a,d){var e=b(d);return e.literal&&e.constant?e:b(d,function(b){return c.getTrusted(a,b)})};var f=c.parseAs,e=c.getTrusted,g=c.trustAs;q(ga,function(a,b){var d=Q(b);c[hb("parse_as_"+d)]=function(b){return f(a,b)};c[hb("get_trusted_"+d)]=function(b){return e(a,b)};c[hb("trust_as_"+d)]=function(b){return g(a,b)}});return c}]}function Nf(){this.$get=["$window", "$document",function(a,b){var d={},c=!(a.chrome&&(a.chrome.app&&a.chrome.app.runtime||!a.chrome.app&&a.chrome.runtime&&a.chrome.runtime.id))&&a.history&&a.history.pushState,f=Z((/android (\d+)/.exec(Q((a.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((a.navigator||{}).userAgent),g=b[0]||{},h,k=/^(Moz|webkit|ms)(?=[A-Z])/,l=g.body&&g.body.style,m=!1,n=!1;if(l){for(var r in l)if(m=k.exec(r)){h=m[0];h=h[0].toUpperCase()+h.substr(1);break}h||(h="WebkitOpacity"in l&&"webkit");m=!!("transition"in l|| h+"Transition"in l);n=!!("animation"in l||h+"Animation"in l);!f||m&&n||(m=D(l.webkitTransition),n=D(l.webkitAnimation))}return{history:!(!c||4>f||e),hasEvent:function(a){if("input"===a&&11>=Ia)return!1;if(z(d[a])){var b=g.createElement("div");d[a]="on"+a in b}return d[a]},csp:da(),vendorPrefix:h,transitions:m,animations:n,android:f}}]}function Pf(){var a;this.httpOptions=function(b){return b?(a=b,this):a};this.$get=["$templateCache","$http","$q","$sce",function(b,d,c,f){function e(g,h){e.totalPendingRequests++; if(!D(g)||z(b.get(g)))g=f.getTrustedResourceUrl(g);var k=d.defaults&&d.defaults.transformResponse;I(k)?k=k.filter(function(a){return a!==gc}):k===gc&&(k=null);return d.get(g,R({cache:b,transformResponse:k},a))["finally"](function(){e.totalPendingRequests--}).then(function(a){b.put(g,a.data);return a.data},function(a){if(!h)throw Hg("tpload",g,a.status,a.statusText);return c.reject(a)})}e.totalPendingRequests=0;return e}]}function Qf(){this.$get=["$rootScope","$browser","$location",function(a,b,d){return{findBindings:function(a, b,d){a=a.getElementsByClassName("ng-binding");var g=[];q(a,function(a){var c=$.element(a).data("$binding");c&&q(c,function(c){d?(new RegExp("(^|\\s)"+Jd(b)+"(\\s|\\||$)")).test(c)&&g.push(a):-1!==c.indexOf(b)&&g.push(a)})});return g},findModels:function(a,b,d){for(var g=["ng-","data-ng-","ng\\:"],h=0;h<g.length;++h){var k=a.querySelectorAll("["+g[h]+"model"+(d?"=":"*=")+'"'+b+'"]');if(k.length)return k}},getLocation:function(){return d.url()},setLocation:function(b){b!==d.url()&&(d.url(b),a.$digest())}, whenStable:function(a){b.notifyWhenNoOutstandingRequests(a)}}}]}function Rf(){this.$get=["$rootScope","$browser","$q","$$q","$exceptionHandler",function(a,b,d,c,f){function e(e,k,l){C(e)||(l=k,k=e,e=w);var m=va.call(arguments,3),n=x(l)&&!l,r=(n?c:d).defer(),s=r.promise,q;q=b.defer(function(){try{r.resolve(e.apply(null,m))}catch(b){r.reject(b),f(b)}finally{delete g[s.$$timeoutId]}n||a.$apply()},k);s.$$timeoutId=q;g[q]=r;return s}var g={};e.cancel=function(a){return a&&a.$$timeoutId in g?(g[a.$$timeoutId].reject("canceled"), delete g[a.$$timeoutId],b.defer.cancel(a.$$timeoutId)):!1};return e}]}function ta(a){Ia&&(aa.setAttribute("href",a),a=aa.href);aa.setAttribute("href",a);return{href:aa.href,protocol:aa.protocol?aa.protocol.replace(/:$/,""):"",host:aa.host,search:aa.search?aa.search.replace(/^\?/,""):"",hash:aa.hash?aa.hash.replace(/^#/,""):"",hostname:aa.hostname,port:aa.port,pathname:"/"===aa.pathname.charAt(0)?aa.pathname:"/"+aa.pathname}}function od(a){a=D(a)?ta(a):a;return a.protocol===Ld.protocol&&a.host===Ld.host} function Sf(){this.$get=ha(y)}function Md(a){function b(a){try{return decodeURIComponent(a)}catch(b){return a}}var d=a[0]||{},c={},f="";return function(){var a,g,h,k,l;try{a=d.cookie||""}catch(m){a=""}if(a!==f)for(f=a,a=f.split("; "),c={},h=0;h<a.length;h++)g=a[h],k=g.indexOf("="),0<k&&(l=b(g.substring(0,k)),z(c[l])&&(c[l]=b(g.substring(k+1))));return c}}function Wf(){this.$get=Md}function Rc(a){function b(d,c){if(E(d)){var f={};q(d,function(a,c){f[c]=b(c,a)});return f}return a.factory(d+"Filter", c)}this.register=b;this.$get=["$injector",function(a){return function(b){return a.get(b+"Filter")}}];b("currency",Nd);b("date",Od);b("filter",Ig);b("json",Jg);b("limitTo",Kg);b("lowercase",Lg);b("number",Pd);b("orderBy",Qd);b("uppercase",Mg)}function Ig(){return function(a,b,d,c){if(!la(a)){if(null==a)return a;throw G("filter")("notarray",a);}c=c||"$";var f;switch(oc(b)){case "function":break;case "boolean":case "null":case "number":case "string":f=!0;case "object":b=Ng(b,d,c,f);break;default:return a}return Array.prototype.filter.call(a, b)}}function Ng(a,b,d,c){var f=E(a)&&d in a;!0===b?b=na:C(b)||(b=function(a,b){if(z(a))return!1;if(null===a||null===b)return a===b;if(E(b)||E(a)&&!Ac(a))return!1;a=Q(""+a);b=Q(""+b);return-1!==a.indexOf(b)});return function(e){return f&&!E(e)?Na(e,a[d],b,d,!1):Na(e,a,b,d,c)}}function Na(a,b,d,c,f,e){var g=oc(a),h=oc(b);if("string"===h&&"!"===b.charAt(0))return!Na(a,b.substring(1),d,c,f);if(I(a))return a.some(function(a){return Na(a,b,d,c,f)});switch(g){case "object":var k;if(f){for(k in a)if("$"!== k.charAt(0)&&Na(a[k],b,d,c,!0))return!0;return e?!1:Na(a,b,d,c,!1)}if("object"===h){for(k in b)if(e=b[k],!C(e)&&!z(e)&&(g=k===c,!Na(g?a:a[k],e,d,c,g,g)))return!1;return!0}return d(a,b);case "function":return!1;default:return d(a,b)}}function oc(a){return null===a?"null":typeof a}function Nd(a){var b=a.NUMBER_FORMATS;return function(a,c,f){z(c)&&(c=b.CURRENCY_SYM);z(f)&&(f=b.PATTERNS[1].maxFrac);return null==a?a:Rd(a,b.PATTERNS[1],b.GROUP_SEP,b.DECIMAL_SEP,f).replace(/\u00A4/g,c)}}function Pd(a){var b= a.NUMBER_FORMATS;return function(a,c){return null==a?a:Rd(a,b.PATTERNS[0],b.GROUP_SEP,b.DECIMAL_SEP,c)}}function Og(a){var b=0,d,c,f,e,g;-1<(c=a.indexOf(Sd))&&(a=a.replace(Sd,""));0<(f=a.search(/e/i))?(0>c&&(c=f),c+=+a.slice(f+1),a=a.substring(0,f)):0>c&&(c=a.length);for(f=0;a.charAt(f)===pc;f++);if(f===(g=a.length))d=[0],c=1;else{for(g--;a.charAt(g)===pc;)g--;c-=f;d=[];for(e=0;f<=g;f++,e++)d[e]=+a.charAt(f)}c>Td&&(d=d.splice(0,Td-1),b=c-1,c=1);return{d:d,e:b,i:c}}function Pg(a,b,d,c){var f=a.d,e= f.length-a.i;b=z(b)?Math.min(Math.max(d,e),c):+b;d=b+a.i;c=f[d];if(0<d){f.splice(Math.max(a.i,d));for(var g=d;g<f.length;g++)f[g]=0}else for(e=Math.max(0,e),a.i=1,f.length=Math.max(1,d=b+1),f[0]=0,g=1;g<d;g++)f[g]=0;if(5<=c)if(0>d-1){for(c=0;c>d;c--)f.unshift(0),a.i++;f.unshift(1);a.i++}else f[d-1]++;for(;e<Math.max(0,b);e++)f.push(0);if(b=f.reduceRight(function(a,b,c,d){b+=a;d[c]=b%10;return Math.floor(b/10)},0))f.unshift(b),a.i++}function Rd(a,b,d,c,f){if(!D(a)&&!ba(a)||isNaN(a))return"";var e= !isFinite(a),g=!1,h=Math.abs(a)+"",k="";if(e)k="\u221e";else{g=Og(h);Pg(g,f,b.minFrac,b.maxFrac);k=g.d;h=g.i;f=g.e;e=[];for(g=k.reduce(function(a,b){return a&&!b},!0);0>h;)k.unshift(0),h++;0<h?e=k.splice(h,k.length):(e=k,k=[0]);h=[];for(k.length>=b.lgSize&&h.unshift(k.splice(-b.lgSize,k.length).join(""));k.length>b.gSize;)h.unshift(k.splice(-b.gSize,k.length).join(""));k.length&&h.unshift(k.join(""));k=h.join(d);e.length&&(k+=c+e.join(""));f&&(k+="e+"+f)}return 0>a&&!g?b.negPre+k+b.negSuf:b.posPre+ k+b.posSuf}function Mb(a,b,d,c){var f="";if(0>a||c&&0>=a)c?a=-a+1:(a=-a,f="-");for(a=""+a;a.length<b;)a=pc+a;d&&(a=a.substr(a.length-b));return f+a}function U(a,b,d,c,f){d=d||0;return function(e){e=e["get"+a]();if(0<d||e>-d)e+=d;0===e&&-12===d&&(e=12);return Mb(e,b,c,f)}}function nb(a,b,d){return function(c,f){var e=c["get"+a](),g=wb((d?"STANDALONE":"")+(b?"SHORT":"")+a);return f[g][e]}}function Ud(a){var b=(new Date(a,0,1)).getDay();return new Date(a,0,(4>=b?5:12)-b)}function Vd(a){return function(b){var d= Ud(b.getFullYear());b=+new Date(b.getFullYear(),b.getMonth(),b.getDate()+(4-b.getDay()))-+d;b=1+Math.round(b/6048E5);return Mb(b,a)}}function qc(a,b){return 0>=a.getFullYear()?b.ERAS[0]:b.ERAS[1]}function Od(a){function b(a){var b;if(b=a.match(d)){a=new Date(0);var e=0,g=0,h=b[8]?a.setUTCFullYear:a.setFullYear,k=b[8]?a.setUTCHours:a.setHours;b[9]&&(e=Z(b[9]+b[10]),g=Z(b[9]+b[11]));h.call(a,Z(b[1]),Z(b[2])-1,Z(b[3]));e=Z(b[4]||0)-e;g=Z(b[5]||0)-g;h=Z(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]|| 0)));k.call(a,e,g,h,b)}return a}var d=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,d,e){var g="",h=[],k,l;d=d||"mediumDate";d=a.DATETIME_FORMATS[d]||d;D(c)&&(c=Qg.test(c)?Z(c):b(c));ba(c)&&(c=new Date(c));if(!ja(c)||!isFinite(c.getTime()))return c;for(;d;)(l=Rg.exec(d))?(h=cb(h,l,1),d=h.pop()):(h.push(d),d=null);var m=c.getTimezoneOffset();e&&(m=Dc(e,m),c=Ub(c,e,!0));q(h,function(b){k=Sg[b];g+=k?k(c,a.DATETIME_FORMATS,m): "''"===b?"'":b.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function Jg(){return function(a,b){z(b)&&(b=2);return eb(a,b)}}function Kg(){return function(a,b,d){b=Infinity===Math.abs(Number(b))?Number(b):Z(b);if(ia(b))return a;ba(a)&&(a=a.toString());if(!la(a))return a;d=!d||isNaN(d)?0:Z(d);d=0>d?Math.max(0,a.length+d):d;return 0<=b?rc(a,d,d+b):0===d?rc(a,b,a.length):rc(a,Math.max(0,d+b),d)}}function rc(a,b,d){return D(a)?a.slice(b,d):va.call(a,b,d)}function Qd(a){function b(b){return b.map(function(b){var c= 1,d=$a;if(C(b))d=b;else if(D(b)){if("+"===b.charAt(0)||"-"===b.charAt(0))c="-"===b.charAt(0)?-1:1,b=b.substring(1);if(""!==b&&(d=a(b),d.constant))var f=d(),d=function(a){return a[f]}}return{get:d,descending:c}})}function d(a){switch(typeof a){case "number":case "boolean":case "string":return!0;default:return!1}}function c(a,b){var c=0,d=a.type,k=b.type;if(d===k){var k=a.value,l=b.value;"string"===d?(k=k.toLowerCase(),l=l.toLowerCase()):"object"===d&&(E(k)&&(k=a.index),E(l)&&(l=b.index));k!==l&&(c= k<l?-1:1)}else c=d<k?-1:1;return c}return function(a,e,g,h){if(null==a)return a;if(!la(a))throw G("orderBy")("notarray",a);I(e)||(e=[e]);0===e.length&&(e=["+"]);var k=b(e),l=g?-1:1,m=C(h)?h:c;a=Array.prototype.map.call(a,function(a,b){return{value:a,tieBreaker:{value:b,type:"number",index:b},predicateValues:k.map(function(c){var e=c.get(a);c=typeof e;if(null===e)c="string",e="null";else if("object"===c)a:{if(C(e.valueOf)&&(e=e.valueOf(),d(e)))break a;Ac(e)&&(e=e.toString(),d(e))}return{value:e,type:c, index:b}})}});a.sort(function(a,b){for(var c=0,d=k.length;c<d;c++){var e=m(a.predicateValues[c],b.predicateValues[c]);if(e)return e*k[c].descending*l}return m(a.tieBreaker,b.tieBreaker)*l});return a=a.map(function(a){return a.value})}}function Va(a){C(a)&&(a={link:a});a.restrict=a.restrict||"AC";return ha(a)}function Wd(a,b,d,c,f){var e=this,g=[];e.$error={};e.$$success={};e.$pending=void 0;e.$name=f(b.name||b.ngForm||"")(d);e.$dirty=!1;e.$pristine=!0;e.$valid=!0;e.$invalid=!1;e.$submitted=!1;e.$$parentForm= Nb;e.$rollbackViewValue=function(){q(g,function(a){a.$rollbackViewValue()})};e.$commitViewValue=function(){q(g,function(a){a.$commitViewValue()})};e.$addControl=function(a){Ra(a.$name,"input");g.push(a);a.$name&&(e[a.$name]=a);a.$$parentForm=e};e.$$renameControl=function(a,b){var c=a.$name;e[c]===a&&delete e[c];e[b]=a;a.$name=b};e.$removeControl=function(a){a.$name&&e[a.$name]===a&&delete e[a.$name];q(e.$pending,function(b,c){e.$setValidity(c,null,a)});q(e.$error,function(b,c){e.$setValidity(c,null, a)});q(e.$$success,function(b,c){e.$setValidity(c,null,a)});bb(g,a);a.$$parentForm=Nb};Xd({ctrl:this,$element:a,set:function(a,b,c){var d=a[b];d?-1===d.indexOf(c)&&d.push(c):a[b]=[c]},unset:function(a,b,c){var d=a[b];d&&(bb(d,c),0===d.length&&delete a[b])},$animate:c});e.$setDirty=function(){c.removeClass(a,Wa);c.addClass(a,Ob);e.$dirty=!0;e.$pristine=!1;e.$$parentForm.$setDirty()};e.$setPristine=function(){c.setClass(a,Wa,Ob+" ng-submitted");e.$dirty=!1;e.$pristine=!0;e.$submitted=!1;q(g,function(a){a.$setPristine()})}; e.$setUntouched=function(){q(g,function(a){a.$setUntouched()})};e.$setSubmitted=function(){c.addClass(a,"ng-submitted");e.$submitted=!0;e.$$parentForm.$setSubmitted()}}function sc(a){a.$formatters.push(function(b){return a.$isEmpty(b)?b:b.toString()})}function Xa(a,b,d,c,f,e){var g=Q(b[0].type);if(!f.android){var h=!1;b.on("compositionstart",function(){h=!0});b.on("compositionend",function(){h=!1;l()})}var k,l=function(a){k&&(e.defer.cancel(k),k=null);if(!h){var f=b.val();a=a&&a.type;"password"=== g||d.ngTrim&&"false"===d.ngTrim||(f=Y(f));(c.$viewValue!==f||""===f&&c.$$hasNativeValidators)&&c.$setViewValue(f,a)}};if(f.hasEvent("input"))b.on("input",l);else{var m=function(a,b,c){k||(k=e.defer(function(){k=null;b&&b.value===c||l(a)}))};b.on("keydown",function(a){var b=a.keyCode;91===b||15<b&&19>b||37<=b&&40>=b||m(a,this,this.value)});if(f.hasEvent("paste"))b.on("paste cut",m)}b.on("change",l);if(Yd[g]&&c.$$hasNativeValidators&&g===d.type)b.on("keydown wheel mousedown",function(a){if(!k){var b= this.validity,c=b.badInput,d=b.typeMismatch;k=e.defer(function(){k=null;b.badInput===c&&b.typeMismatch===d||l(a)})}});c.$render=function(){var a=c.$isEmpty(c.$viewValue)?"":c.$viewValue;b.val()!==a&&b.val(a)}}function Pb(a,b){return function(d,c){var f,e;if(ja(d))return d;if(D(d)){'"'===d.charAt(0)&&'"'===d.charAt(d.length-1)&&(d=d.substring(1,d.length-1));if(Tg.test(d))return new Date(d);a.lastIndex=0;if(f=a.exec(d))return f.shift(),e=c?{yyyy:c.getFullYear(),MM:c.getMonth()+1,dd:c.getDate(),HH:c.getHours(), mm:c.getMinutes(),ss:c.getSeconds(),sss:c.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,mm:0,ss:0,sss:0},q(f,function(a,c){c<b.length&&(e[b[c]]=+a)}),new Date(e.yyyy,e.MM-1,e.dd,e.HH,e.mm,e.ss||0,1E3*e.sss||0)}return NaN}}function ob(a,b,d,c){return function(f,e,g,h,k,l,m){function n(a){return a&&!(a.getTime&&a.getTime()!==a.getTime())}function r(a){return x(a)&&!ja(a)?d(a)||void 0:a}tc(f,e,g,h);Xa(f,e,g,h,k,l);var s=h&&h.$options&&h.$options.timezone,q;h.$$parserName=a;h.$parsers.push(function(a){if(h.$isEmpty(a))return null; if(b.test(a))return a=d(a,q),s&&(a=Ub(a,s)),a});h.$formatters.push(function(a){if(a&&!ja(a))throw pb("datefmt",a);if(n(a))return(q=a)&&s&&(q=Ub(q,s,!0)),m("date")(a,c,s);q=null;return""});if(x(g.min)||g.ngMin){var u;h.$validators.min=function(a){return!n(a)||z(u)||d(a)>=u};g.$observe("min",function(a){u=r(a);h.$validate()})}if(x(g.max)||g.ngMax){var p;h.$validators.max=function(a){return!n(a)||z(p)||d(a)<=p};g.$observe("max",function(a){p=r(a);h.$validate()})}}}function tc(a,b,d,c){(c.$$hasNativeValidators= E(b[0].validity))&&c.$parsers.push(function(a){var c=b.prop("validity")||{};return c.badInput||c.typeMismatch?void 0:a})}function Zd(a){a.$$parserName="number";a.$parsers.push(function(b){if(a.$isEmpty(b))return null;if(Ug.test(b))return parseFloat(b)});a.$formatters.push(function(b){if(!a.$isEmpty(b)){if(!ba(b))throw pb("numfmt",b);b=b.toString()}return b})}function qb(a){x(a)&&!ba(a)&&(a=parseFloat(a));return ia(a)?void 0:a}function uc(a){var b=a.toString(),d=b.indexOf(".");return-1===d?-1<a&&1> a&&(a=/e-(\d+)$/.exec(b))?Number(a[1]):0:b.length-d-1}function $d(a,b,d,c,f){if(x(c)){a=a(c);if(!a.constant)throw pb("constexpr",d,c);return a(b)}return f}function vc(a,b){a="ngClass"+a;return["$animate",function(d){function c(a,b){var c=[],d=0;a:for(;d<a.length;d++){for(var f=a[d],m=0;m<b.length;m++)if(f===b[m])continue a;c.push(f)}return c}function f(a){var b=[];return I(a)?(q(a,function(a){b=b.concat(f(a))}),b):D(a)?a.split(" "):E(a)?(q(a,function(a,c){a&&(b=b.concat(c.split(" ")))}),b):a}return{restrict:"AC", link:function(e,g,h){function k(a){a=l(a,1);h.$addClass(a)}function l(a,b){var c=g.data("$classCounts")||V(),d=[];q(a,function(a){if(0<b||c[a])c[a]=(c[a]||0)+b,c[a]===+(0<b)&&d.push(a)});g.data("$classCounts",c);return d.join(" ")}function m(a,b){var e=c(b,a),f=c(a,b),e=l(e,1),f=l(f,-1);e&&e.length&&d.addClass(g,e);f&&f.length&&d.removeClass(g,f)}function n(a){if(!0===b||(e.$index&1)===b){var c=f(a||[]);if(!r)k(c);else if(!na(a,r)){var d=f(r);m(d,c)}}r=I(a)?a.map(function(a){return ka(a)}):ka(a)} var r;h.$observe("class",function(b){n(e.$eval(h[a]))});"ngClass"!==a&&e.$watch("$index",function(a,c){var d=a&1;if(d!==(c&1)){var e=f(r);d===b?k(e):(d=l(e,-1),h.$removeClass(d))}});e.$watch(h[a],n,!0)}}}]}function Xd(a){function b(a,b){b&&!e[a]?(k.addClass(f,a),e[a]=!0):!b&&e[a]&&(k.removeClass(f,a),e[a]=!1)}function d(a,c){a=a?"-"+Hc(a,"-"):"";b(rb+a,!0===c);b(ae+a,!1===c)}var c=a.ctrl,f=a.$element,e={},g=a.set,h=a.unset,k=a.$animate;e[ae]=!(e[rb]=f.hasClass(rb));c.$setValidity=function(a,e,f){z(e)? (c.$pending||(c.$pending={}),g(c.$pending,a,f)):(c.$pending&&h(c.$pending,a,f),be(c.$pending)&&(c.$pending=void 0));Ka(e)?e?(h(c.$error,a,f),g(c.$$success,a,f)):(g(c.$error,a,f),h(c.$$success,a,f)):(h(c.$error,a,f),h(c.$$success,a,f));c.$pending?(b(ce,!0),c.$valid=c.$invalid=void 0,d("",null)):(b(ce,!1),c.$valid=be(c.$error),c.$invalid=!c.$valid,d("",c.$valid));e=c.$pending&&c.$pending[a]?void 0:c.$error[a]?!1:c.$$success[a]?!0:null;d(a,e);c.$$parentForm.$setValidity(a,e,c)}}function be(a){if(a)for(var b in a)if(a.hasOwnProperty(b))return!1; return!0}var Vg=/^\/(.+)\/([a-z]*)$/,ua=Object.prototype.hasOwnProperty,Q=function(a){return D(a)?a.toLowerCase():a},wb=function(a){return D(a)?a.toUpperCase():a},Ia,F,za,va=[].slice,pg=[].splice,Wg=[].push,ma=Object.prototype.toString,Bc=Object.getPrototypeOf,xa=G("ng"),$=y.angular||(y.angular={}),Wb,sb=0;Ia=y.document.documentMode;var ia=Number.isNaN||function(a){return a!==a};w.$inject=[];$a.$inject=[];var I=Array.isArray,ne=/^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/, Y=function(a){return D(a)?a.trim():a},Jd=function(a){return a.replace(/([-()[\]{}+?*.$^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08")},da=function(){if(!x(da.rules)){var a=y.document.querySelector("[ng-csp]")||y.document.querySelector("[data-ng-csp]");if(a){var b=a.getAttribute("ng-csp")||a.getAttribute("data-ng-csp");da.rules={noUnsafeEval:!b||-1!==b.indexOf("no-unsafe-eval"),noInlineStyle:!b||-1!==b.indexOf("no-inline-style")}}else{a=da;try{new Function(""),b=!1}catch(d){b=!0}a.rules={noUnsafeEval:b, noInlineStyle:!1}}}return da.rules},ub=function(){if(x(ub.name_))return ub.name_;var a,b,d=Oa.length,c,f;for(b=0;b<d;++b)if(c=Oa[b],a=y.document.querySelector("["+c.replace(":","\\:")+"jq]")){f=a.getAttribute(c+"jq");break}return ub.name_=f},qe=/:/g,Oa=["ng-","data-ng-","ng:","x-ng-"],te=function(a){var b=a.currentScript,b=b&&b.getAttribute("src");if(!b)return!0;var d=a.createElement("a");d.href=b;if(a.location.origin===d.origin)return!0;switch(d.protocol){case "http:":case "https:":case "ftp:":case "blob:":case "file:":case "data:":return!0; default:return!1}}(y.document),we=/[A-Z]/g,Ic=!1,La=3,Ae={full:"1.5.11",major:1,minor:5,dot:11,codeName:"princely-quest"};W.expando="ng339";var jb=W.cache={},bg=1;W._data=function(a){return this.cache[a[this.expando]]||{}};var Xf=/([:\-_]+(.))/g,Yf=/^moz([A-Z])/,Ab={mouseleave:"mouseout",mouseenter:"mouseover"},Yb=G("jqLite"),ag=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,Xb=/<|&#?\w+;/,Zf=/<([\w:-]+)/,$f=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,pa={option:[1,'<select multiple="multiple">', "</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};pa.optgroup=pa.option;pa.tbody=pa.tfoot=pa.colgroup=pa.caption=pa.thead;pa.th=pa.td;var gg=y.Node.prototype.contains||function(a){return!!(this.compareDocumentPosition(a)&16)},Pa=W.prototype={ready:function(a){function b(){d||(d=!0,a())}var d=!1;"complete"===y.document.readyState?y.setTimeout(b): (this.on("DOMContentLoaded",b),W(y).on("load",b))},toString:function(){var a=[];q(this,function(b){a.push(""+b)});return"["+a.join(", ")+"]"},eq:function(a){return 0<=a?F(this[a]):F(this[this.length+a])},length:0,push:Wg,sort:[].sort,splice:[].splice},Gb={};q("multiple selected checked disabled readOnly required open".split(" "),function(a){Gb[Q(a)]=a});var $c={};q("input select option textarea button form details".split(" "),function(a){$c[a]=!0});var gd={ngMinlength:"minlength",ngMaxlength:"maxlength", ngMin:"min",ngMax:"max",ngPattern:"pattern"};q({data:$b,removeData:ib,hasData:function(a){for(var b in jb[a.ng339])return!0;return!1},cleanData:function(a){for(var b=0,d=a.length;b<d;b++)ib(a[b])}},function(a,b){W[b]=a});q({data:$b,inheritedData:Eb,scope:function(a){return F.data(a,"$scope")||Eb(a.parentNode||a,["$isolateScope","$scope"])},isolateScope:function(a){return F.data(a,"$isolateScope")||F.data(a,"$isolateScopeNoTemplate")},controller:Xc,injector:function(a){return Eb(a,"$injector")},removeAttr:function(a, b){a.removeAttribute(b)},hasClass:Bb,css:function(a,b,d){b=hb(b);if(x(d))a.style[b]=d;else return a.style[b]},attr:function(a,b,d){var c=a.nodeType;if(c!==La&&2!==c&&8!==c)if(c=Q(b),Gb[c])if(x(d))d?(a[b]=!0,a.setAttribute(b,c)):(a[b]=!1,a.removeAttribute(c));else return a[b]||(a.attributes.getNamedItem(b)||w).specified?c:void 0;else if(x(d))a.setAttribute(b,d);else if(a.getAttribute)return a=a.getAttribute(b,2),null===a?void 0:a},prop:function(a,b,d){if(x(d))a[b]=d;else return a[b]},text:function(){function a(a, d){if(z(d)){var c=a.nodeType;return 1===c||c===La?a.textContent:""}a.textContent=d}a.$dv="";return a}(),val:function(a,b){if(z(b)){if(a.multiple&&"select"===wa(a)){var d=[];q(a.options,function(a){a.selected&&d.push(a.value||a.text)});return 0===d.length?null:d}return a.value}a.value=b},html:function(a,b){if(z(b))return a.innerHTML;yb(a,!0);a.innerHTML=b},empty:Yc},function(a,b){W.prototype[b]=function(b,c){var f,e,g=this.length;if(a!==Yc&&z(2===a.length&&a!==Bb&&a!==Xc?b:c)){if(E(b)){for(f=0;f<g;f++)if(a=== $b)a(this[f],b);else for(e in b)a(this[f],e,b[e]);return this}f=a.$dv;g=z(f)?Math.min(g,1):g;for(e=0;e<g;e++){var h=a(this[e],b,c);f=f?f+h:h}return f}for(f=0;f<g;f++)a(this[f],b,c);return this}});q({removeData:ib,on:function(a,b,d,c){if(x(c))throw Yb("onargs");if(Sc(a)){c=zb(a,!0);var f=c.events,e=c.handle;e||(e=c.handle=dg(a,f));c=0<=b.indexOf(" ")?b.split(" "):[b];for(var g=c.length,h=function(b,c,g){var h=f[b];h||(h=f[b]=[],h.specialHandlerWrapper=c,"$destroy"===b||g||a.addEventListener(b,e,!1)); h.push(d)};g--;)b=c[g],Ab[b]?(h(Ab[b],fg),h(b,void 0,!0)):h(b)}},off:Wc,one:function(a,b,d){a=F(a);a.on(b,function f(){a.off(b,d);a.off(b,f)});a.on(b,d)},replaceWith:function(a,b){var d,c=a.parentNode;yb(a);q(new W(b),function(b){d?c.insertBefore(b,d.nextSibling):c.replaceChild(b,a);d=b})},children:function(a){var b=[];q(a.childNodes,function(a){1===a.nodeType&&b.push(a)});return b},contents:function(a){return a.contentDocument||a.childNodes||[]},append:function(a,b){var d=a.nodeType;if(1===d||11=== d){b=new W(b);for(var d=0,c=b.length;d<c;d++)a.appendChild(b[d])}},prepend:function(a,b){if(1===a.nodeType){var d=a.firstChild;q(new W(b),function(b){a.insertBefore(b,d)})}},wrap:function(a,b){Uc(a,F(b).eq(0).clone()[0])},remove:Fb,detach:function(a){Fb(a,!0)},after:function(a,b){var d=a,c=a.parentNode;if(c){b=new W(b);for(var f=0,e=b.length;f<e;f++){var g=b[f];c.insertBefore(g,d.nextSibling);d=g}}},addClass:Db,removeClass:Cb,toggleClass:function(a,b,d){b&&q(b.split(" "),function(b){var f=d;z(f)&& (f=!Bb(a,b));(f?Db:Cb)(a,b)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){return a.nextElementSibling},find:function(a,b){return a.getElementsByTagName?a.getElementsByTagName(b):[]},clone:Zb,triggerHandler:function(a,b,d){var c,f,e=b.type||b,g=zb(a);if(g=(g=g&&g.events)&&g[e])c={preventDefault:function(){this.defaultPrevented=!0},isDefaultPrevented:function(){return!0===this.defaultPrevented},stopImmediatePropagation:function(){this.immediatePropagationStopped= !0},isImmediatePropagationStopped:function(){return!0===this.immediatePropagationStopped},stopPropagation:w,type:e,target:a},b.type&&(c=R(c,b)),b=ka(g),f=d?[c].concat(d):[c],q(b,function(b){c.isImmediatePropagationStopped()||b.apply(a,f)})}},function(a,b){W.prototype[b]=function(b,c,f){for(var e,g=0,h=this.length;g<h;g++)z(e)?(e=a(this[g],b,c,f),x(e)&&(e=F(e))):Vc(e,a(this[g],b,c,f));return x(e)?e:this}});W.prototype.bind=W.prototype.on;W.prototype.unbind=W.prototype.off;Sa.prototype={put:function(a, b){this[Aa(a,this.nextUid)]=b},get:function(a){return this[Aa(a,this.nextUid)]},remove:function(a){var b=this[a=Aa(a,this.nextUid)];delete this[a];return b}};var Vf=[function(){this.$get=[function(){return Sa}]}],ig=/^([^(]+?)=>/,jg=/^[^(]*\(\s*([^)]*)\)/m,Xg=/,/,Yg=/^\s*(_?)(\S+?)\1\s*$/,hg=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ba=G("$injector");fb.$$annotate=function(a,b,d){var c;if("function"===typeof a){if(!(c=a.$inject)){c=[];if(a.length){if(b)throw D(d)&&d||(d=a.name||kg(a)),Ba("strictdi",d);b= ad(a);q(b[1].split(Xg),function(a){a.replace(Yg,function(a,b,d){c.push(d)})})}a.$inject=c}}else I(a)?(b=a.length-1,Qa(a[b],"fn"),c=a.slice(0,b)):Qa(a,"fn",!0);return c};var de=G("$animate"),nf=function(){this.$get=w},of=function(){var a=new Sa,b=[];this.$get=["$$AnimateRunner","$rootScope",function(d,c){function f(a,b,c){var d=!1;b&&(b=D(b)?b.split(" "):I(b)?b:[],q(b,function(b){b&&(d=!0,a[b]=c)}));return d}function e(){q(b,function(b){var c=a.get(b);if(c){var d=lg(b.attr("class")),e="",f="";q(c, function(a,b){a!==!!d[b]&&(a?e+=(e.length?" ":"")+b:f+=(f.length?" ":"")+b)});q(b,function(a){e&&Db(a,e);f&&Cb(a,f)});a.remove(b)}});b.length=0}return{enabled:w,on:w,off:w,pin:w,push:function(g,h,k,l){l&&l();k=k||{};k.from&&g.css(k.from);k.to&&g.css(k.to);if(k.addClass||k.removeClass)if(h=k.addClass,l=k.removeClass,k=a.get(g)||{},h=f(k,h,!0),l=f(k,l,!1),h||l)a.put(g,k),b.push(g),1===b.length&&c.$$postDigest(e);g=new d;g.complete();return g}}}]},lf=["$provide",function(a){var b=this;this.$$registeredAnimations= Object.create(null);this.register=function(d,c){if(d&&"."!==d.charAt(0))throw de("notcsel",d);var f=d+"-animation";b.$$registeredAnimations[d.substr(1)]=f;a.factory(f,c)};this.classNameFilter=function(a){if(1===arguments.length&&(this.$$classNameFilter=a instanceof RegExp?a:null)&&/(\s+|\/)ng-animate(\s+|\/)/.test(this.$$classNameFilter.toString()))throw de("nongcls","ng-animate");return this.$$classNameFilter};this.$get=["$$animateQueue",function(a){function b(a,c,d){if(d){var h;a:{for(h=0;h<d.length;h++){var k= d[h];if(1===k.nodeType){h=k;break a}}h=void 0}!h||h.parentNode||h.previousElementSibling||(d=null)}d?d.after(a):c.prepend(a)}return{on:a.on,off:a.off,pin:a.pin,enabled:a.enabled,cancel:function(a){a.end&&a.end()},enter:function(f,e,g,h){e=e&&F(e);g=g&&F(g);e=e||g.parent();b(f,e,g);return a.push(f,"enter",Ca(h))},move:function(f,e,g,h){e=e&&F(e);g=g&&F(g);e=e||g.parent();b(f,e,g);return a.push(f,"move",Ca(h))},leave:function(b,c){return a.push(b,"leave",Ca(c),function(){b.remove()})},addClass:function(b, c,g){g=Ca(g);g.addClass=kb(g.addclass,c);return a.push(b,"addClass",g)},removeClass:function(b,c,g){g=Ca(g);g.removeClass=kb(g.removeClass,c);return a.push(b,"removeClass",g)},setClass:function(b,c,g,h){h=Ca(h);h.addClass=kb(h.addClass,c);h.removeClass=kb(h.removeClass,g);return a.push(b,"setClass",h)},animate:function(b,c,g,h,k){k=Ca(k);k.from=k.from?R(k.from,c):c;k.to=k.to?R(k.to,g):g;k.tempClasses=kb(k.tempClasses,h||"ng-inline-animate");return a.push(b,"animate",k)}}}]}],qf=function(){this.$get= ["$$rAF",function(a){function b(b){d.push(b);1<d.length||a(function(){for(var a=0;a<d.length;a++)d[a]();d=[]})}var d=[];return function(){var a=!1;b(function(){a=!0});return function(d){a?d():b(d)}}}]},pf=function(){this.$get=["$q","$sniffer","$$animateAsyncRun","$document","$timeout",function(a,b,d,c,f){function e(a){this.setHost(a);var b=d();this._doneCallbacks=[];this._tick=function(a){var d=c[0];d&&d.hidden?f(a,0,!1):b(a)};this._state=0}e.chain=function(a,b){function c(){if(d===a.length)b(!0); else a[d](function(a){!1===a?b(!1):(d++,c())})}var d=0;c()};e.all=function(a,b){function c(f){e=e&&f;++d===a.length&&b(e)}var d=0,e=!0;q(a,function(a){a.done(c)})};e.prototype={setHost:function(a){this.host=a||{}},done:function(a){2===this._state?a():this._doneCallbacks.push(a)},progress:w,getPromise:function(){if(!this.promise){var b=this;this.promise=a(function(a,c){b.done(function(b){!1===b?c():a()})})}return this.promise},then:function(a,b){return this.getPromise().then(a,b)},"catch":function(a){return this.getPromise()["catch"](a)}, "finally":function(a){return this.getPromise()["finally"](a)},pause:function(){this.host.pause&&this.host.pause()},resume:function(){this.host.resume&&this.host.resume()},end:function(){this.host.end&&this.host.end();this._resolve(!0)},cancel:function(){this.host.cancel&&this.host.cancel();this._resolve(!1)},complete:function(a){var b=this;0===b._state&&(b._state=1,b._tick(function(){b._resolve(a)}))},_resolve:function(a){2!==this._state&&(q(this._doneCallbacks,function(b){b(a)}),this._doneCallbacks.length= 0,this._state=2)}};return e}]},mf=function(){this.$get=["$$rAF","$q","$$AnimateRunner",function(a,b,d){return function(b,f){function e(){a(function(){g.addClass&&(b.addClass(g.addClass),g.addClass=null);g.removeClass&&(b.removeClass(g.removeClass),g.removeClass=null);g.to&&(b.css(g.to),g.to=null);h||k.complete();h=!0});return k}var g=f||{};g.$$prepared||(g=sa(g));g.cleanupStyles&&(g.from=g.to=null);g.from&&(b.css(g.from),g.from=null);var h,k=new d;return{start:e,end:e}}}]},fa=G("$compile"),ec=new function(){}; Kc.$inject=["$provide","$$sanitizeUriProvider"];Hb.prototype.isFirstChange=function(){return this.previousValue===ec};var bd=/^((?:x|data)[:\-_])/i,id=G("$controller"),hd=/^(\S+)(\s+as\s+([\w$]+))?$/,wf=function(){this.$get=["$document",function(a){return function(b){b?!b.nodeType&&b instanceof F&&(b=b[0]):b=a[0].body;return b.offsetWidth+1}}]},jd="application/json",hc={"Content-Type":jd+";charset=utf-8"},rg=/^\[|^\{(?!\{)/,sg={"[":/]$/,"{":/}$/},qg=/^\)]\}',?\n/,Zg=G("$http"),nd=function(a){return function(){throw Zg("legacy", a);}},Ha=$.$interpolateMinErr=G("$interpolate");Ha.throwNoconcat=function(a){throw Ha("noconcat",a);};Ha.interr=function(a,b){return Ha("interr",a,b.toString())};var Ef=function(){this.$get=["$window",function(a){function b(a){var b=function(a){b.data=a;b.called=!0};b.id=a;return b}var d=a.angular.callbacks,c={};return{createCallback:function(a){a="_"+(d.$$counter++).toString(36);var e="angular.callbacks."+a,g=b(a);c[e]=d[a]=g;return e},wasCalled:function(a){return c[a].called},getResponse:function(a){return c[a].data}, removeCallback:function(a){delete d[c[a].id];delete c[a]}}}]},$g=/^([^?#]*)(\?([^#]*))?(#(.*))?$/,ug={http:80,https:443,ftp:21},lb=G("$location"),vg=/^\s*[\\/]{2,}/,ah={$$absUrl:"",$$html5:!1,$$replace:!1,absUrl:Ib("$$absUrl"),url:function(a){if(z(a))return this.$$url;var b=$g.exec(a);(b[1]||""===a)&&this.path(decodeURIComponent(b[1]));(b[2]||b[1]||""===a)&&this.search(b[3]||"");this.hash(b[5]||"");return this},protocol:Ib("$$protocol"),host:Ib("$$host"),port:Ib("$$port"),path:sd("$$path",function(a){a= null!==a?a.toString():"";return"/"===a.charAt(0)?a:"/"+a}),search:function(a,b){switch(arguments.length){case 0:return this.$$search;case 1:if(D(a)||ba(a))a=a.toString(),this.$$search=Fc(a);else if(E(a))a=sa(a,{}),q(a,function(b,c){null==b&&delete a[c]}),this.$$search=a;else throw lb("isrcharg");break;default:z(b)||null===b?delete this.$$search[a]:this.$$search[a]=b}this.$$compose();return this},hash:sd("$$hash",function(a){return null!==a?a.toString():""}),replace:function(){this.$$replace=!0;return this}}; q([rd,kc,jc],function(a){a.prototype=Object.create(ah);a.prototype.state=function(b){if(!arguments.length)return this.$$state;if(a!==jc||!this.$$html5)throw lb("nostate");this.$$state=z(b)?null:b;return this}});var ea=G("$parse"),ud=[].constructor,vd=(!1).constructor,wd=Function.constructor,xd=(0).constructor,yd={}.constructor,zd="".constructor,Ag=ud.prototype,Bg=vd.prototype,Kb=wd.prototype,Cg=xd.prototype,Ad=yd.prototype,Dg=zd.prototype,xg=Kb.call,yg=Kb.apply,zg=Kb.bind,Fg=Ad.valueOf,Qb=V();q("+ - * / % === !== == != < > <= >= && || ! = |".split(" "), function(a){Qb[a]=!0});var bh={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},mc=function(a){this.options=a};mc.prototype={constructor:mc,lex:function(a){this.text=a;this.index=0;for(this.tokens=[];this.index<this.text.length;)if(a=this.text.charAt(this.index),'"'===a||"'"===a)this.readString(a);else if(this.isNumber(a)||"."===a&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdentifierStart(this.peekMultichar()))this.readIdent();else if(this.is(a,"(){}[].,;:?"))this.tokens.push({index:this.index, text:a}),this.index++;else if(this.isWhitespace(a))this.index++;else{var b=a+this.peek(),d=b+this.peek(2),c=Qb[b],f=Qb[d];Qb[a]||c||f?(a=f?d:c?b:a,this.tokens.push({index:this.index,text:a,operator:!0}),this.index+=a.length):this.throwError("Unexpected next character ",this.index,this.index+1)}return this.tokens},is:function(a,b){return-1!==b.indexOf(a)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a&&"string"=== typeof a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdentifierStart:function(a){return this.options.isIdentifierStart?this.options.isIdentifierStart(a,this.codePointAt(a)):this.isValidIdentifierStart(a)},isValidIdentifierStart:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isIdentifierContinue:function(a){return this.options.isIdentifierContinue?this.options.isIdentifierContinue(a,this.codePointAt(a)):this.isValidIdentifierContinue(a)}, isValidIdentifierContinue:function(a,b){return this.isValidIdentifierStart(a,b)||this.isNumber(a)},codePointAt:function(a){return 1===a.length?a.charCodeAt(0):(a.charCodeAt(0)<<10)+a.charCodeAt(1)-56613888},peekMultichar:function(){var a=this.text.charAt(this.index),b=this.peek();if(!b)return a;var d=a.charCodeAt(0),c=b.charCodeAt(0);return 55296<=d&&56319>=d&&56320<=c&&57343>=c?a+b:a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,b,d){d=d||this.index;b= x(b)?"s "+b+"-"+this.index+" ["+this.text.substring(b,d)+"]":" "+d;throw ea("lexerr",a,b,this.text);},readNumber:function(){for(var a="",b=this.index;this.index<this.text.length;){var d=Q(this.text.charAt(this.index));if("."===d||this.isNumber(d))a+=d;else{var c=this.peek();if("e"===d&&this.isExpOperator(c))a+=d;else if(this.isExpOperator(d)&&c&&this.isNumber(c)&&"e"===a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||c&&this.isNumber(c)||"e"!==a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}this.tokens.push({index:b, text:a,constant:!0,value:Number(a)})},readIdent:function(){var a=this.index;for(this.index+=this.peekMultichar().length;this.index<this.text.length;){var b=this.peekMultichar();if(!this.isIdentifierContinue(b))break;this.index+=b.length}this.tokens.push({index:a,text:this.text.slice(a,this.index),identifier:!0})},readString:function(a){var b=this.index;this.index++;for(var d="",c=a,f=!1;this.index<this.text.length;){var e=this.text.charAt(this.index),c=c+e;if(f)"u"===e?(f=this.text.substring(this.index+ 1,this.index+5),f.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+f+"]"),this.index+=4,d+=String.fromCharCode(parseInt(f,16))):d+=bh[e]||e,f=!1;else if("\\"===e)f=!0;else{if(e===a){this.index++;this.tokens.push({index:b,text:c,constant:!0,value:d});return}d+=e}this.index++}this.throwError("Unterminated quote",b)}};var t=function(a,b){this.lexer=a;this.options=b};t.Program="Program";t.ExpressionStatement="ExpressionStatement";t.AssignmentExpression="AssignmentExpression";t.ConditionalExpression= "ConditionalExpression";t.LogicalExpression="LogicalExpression";t.BinaryExpression="BinaryExpression";t.UnaryExpression="UnaryExpression";t.CallExpression="CallExpression";t.MemberExpression="MemberExpression";t.Identifier="Identifier";t.Literal="Literal";t.ArrayExpression="ArrayExpression";t.Property="Property";t.ObjectExpression="ObjectExpression";t.ThisExpression="ThisExpression";t.LocalsExpression="LocalsExpression";t.NGValueParameter="NGValueParameter";t.prototype={ast:function(a){this.text= a;this.tokens=this.lexer.lex(a);a=this.program();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);return a},program:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.expressionStatement()),!this.expect(";"))return{type:t.Program,body:a}},expressionStatement:function(){return{type:t.ExpressionStatement,expression:this.filterChain()}},filterChain:function(){for(var a=this.expression();this.expect("|");)a=this.filter(a);return a}, expression:function(){return this.assignment()},assignment:function(){var a=this.ternary();if(this.expect("=")){if(!Dd(a))throw ea("lval");a={type:t.AssignmentExpression,left:a,right:this.assignment(),operator:"="}}return a},ternary:function(){var a=this.logicalOR(),b,d;return this.expect("?")&&(b=this.expression(),this.consume(":"))?(d=this.expression(),{type:t.ConditionalExpression,test:a,alternate:b,consequent:d}):a},logicalOR:function(){for(var a=this.logicalAND();this.expect("||");)a={type:t.LogicalExpression, operator:"||",left:a,right:this.logicalAND()};return a},logicalAND:function(){for(var a=this.equality();this.expect("&&");)a={type:t.LogicalExpression,operator:"&&",left:a,right:this.equality()};return a},equality:function(){for(var a=this.relational(),b;b=this.expect("==","!=","===","!==");)a={type:t.BinaryExpression,operator:b.text,left:a,right:this.relational()};return a},relational:function(){for(var a=this.additive(),b;b=this.expect("<",">","<=",">=");)a={type:t.BinaryExpression,operator:b.text, left:a,right:this.additive()};return a},additive:function(){for(var a=this.multiplicative(),b;b=this.expect("+","-");)a={type:t.BinaryExpression,operator:b.text,left:a,right:this.multiplicative()};return a},multiplicative:function(){for(var a=this.unary(),b;b=this.expect("*","/","%");)a={type:t.BinaryExpression,operator:b.text,left:a,right:this.unary()};return a},unary:function(){var a;return(a=this.expect("+","-","!"))?{type:t.UnaryExpression,operator:a.text,prefix:!0,argument:this.unary()}:this.primary()}, primary:function(){var a;this.expect("(")?(a=this.filterChain(),this.consume(")")):this.expect("[")?a=this.arrayDeclaration():this.expect("{")?a=this.object():this.selfReferential.hasOwnProperty(this.peek().text)?a=sa(this.selfReferential[this.consume().text]):this.options.literals.hasOwnProperty(this.peek().text)?a={type:t.Literal,value:this.options.literals[this.consume().text]}:this.peek().identifier?a=this.identifier():this.peek().constant?a=this.constant():this.throwError("not a primary expression", this.peek());for(var b;b=this.expect("(","[",".");)"("===b.text?(a={type:t.CallExpression,callee:a,arguments:this.parseArguments()},this.consume(")")):"["===b.text?(a={type:t.MemberExpression,object:a,property:this.expression(),computed:!0},this.consume("]")):"."===b.text?a={type:t.MemberExpression,object:a,property:this.identifier(),computed:!1}:this.throwError("IMPOSSIBLE");return a},filter:function(a){a=[a];for(var b={type:t.CallExpression,callee:this.identifier(),arguments:a,filter:!0};this.expect(":");)a.push(this.expression()); return b},parseArguments:function(){var a=[];if(")"!==this.peekToken().text){do a.push(this.filterChain());while(this.expect(","))}return a},identifier:function(){var a=this.consume();a.identifier||this.throwError("is not a valid identifier",a);return{type:t.Identifier,name:a.text}},constant:function(){return{type:t.Literal,value:this.consume().value}},arrayDeclaration:function(){var a=[];if("]"!==this.peekToken().text){do{if(this.peek("]"))break;a.push(this.expression())}while(this.expect(","))}this.consume("]"); return{type:t.ArrayExpression,elements:a}},object:function(){var a=[],b;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;b={type:t.Property,kind:"init"};this.peek().constant?(b.key=this.constant(),b.computed=!1,this.consume(":"),b.value=this.expression()):this.peek().identifier?(b.key=this.identifier(),b.computed=!1,this.peek(":")?(this.consume(":"),b.value=this.expression()):b.value=b.key):this.peek("[")?(this.consume("["),b.key=this.expression(),this.consume("]"),b.computed=!0,this.consume(":"), b.value=this.expression()):this.throwError("invalid key",this.peek());a.push(b)}while(this.expect(","))}this.consume("}");return{type:t.ObjectExpression,properties:a}},throwError:function(a,b){throw ea("syntax",b.text,a,b.index+1,this.text,this.text.substring(b.index));},consume:function(a){if(0===this.tokens.length)throw ea("ueoe",this.text);var b=this.expect(a);b||this.throwError("is unexpected, expecting ["+a+"]",this.peek());return b},peekToken:function(){if(0===this.tokens.length)throw ea("ueoe", this.text);return this.tokens[0]},peek:function(a,b,d,c){return this.peekAhead(0,a,b,d,c)},peekAhead:function(a,b,d,c,f){if(this.tokens.length>a){a=this.tokens[a];var e=a.text;if(e===b||e===d||e===c||e===f||!(b||d||c||f))return a}return!1},expect:function(a,b,d,c){return(a=this.peek(a,b,d,c))?(this.tokens.shift(),a):!1},selfReferential:{"this":{type:t.ThisExpression},$locals:{type:t.LocalsExpression}}};Gd.prototype={compile:function(a,b){var d=this,c=this.astBuilder.ast(a);this.state={nextId:0,filters:{}, expensiveChecks:b,fn:{vars:[],body:[],own:{}},assign:{vars:[],body:[],own:{}},inputs:[]};X(c,d.$filter);var f="",e;this.stage="assign";if(e=Ed(c))this.state.computing="assign",f=this.nextId(),this.recurse(e,f),this.return_(f),f="fn.assign="+this.generateFunction("assign","s,v,l");e=Cd(c.body);d.stage="inputs";q(e,function(a,b){var c="fn"+b;d.state[c]={vars:[],body:[],own:{}};d.state.computing=c;var e=d.nextId();d.recurse(a,e);d.return_(e);d.state.inputs.push(c);a.watchId=b});this.state.computing= "fn";this.stage="main";this.recurse(c);f='"'+this.USE+" "+this.STRICT+'";\n'+this.filterPrefix()+"var fn="+this.generateFunction("fn","s,l,a,i")+f+this.watchFns()+"return fn;";f=(new Function("$filter","ensureSafeMemberName","ensureSafeObject","ensureSafeFunction","getStringValue","ensureSafeAssignContext","ifDefined","plus","text",f))(this.$filter,Ua,Ea,td,wg,Jb,Eg,Bd,a);this.state=this.stage=void 0;f.literal=Fd(c);f.constant=c.constant;return f},USE:"use",STRICT:"strict",watchFns:function(){var a= [],b=this.state.inputs,d=this;q(b,function(b){a.push("var "+b+"="+d.generateFunction(b,"s"))});b.length&&a.push("fn.inputs=["+b.join(",")+"];");return a.join("")},generateFunction:function(a,b){return"function("+b+"){"+this.varsPrefix(a)+this.body(a)+"};"},filterPrefix:function(){var a=[],b=this;q(this.state.filters,function(d,c){a.push(d+"=$filter("+b.escape(c)+")")});return a.length?"var "+a.join(",")+";":""},varsPrefix:function(a){return this.state[a].vars.length?"var "+this.state[a].vars.join(",")+ ";":""},body:function(a){return this.state[a].body.join("")},recurse:function(a,b,d,c,f,e){var g,h,k=this,l,m,n;c=c||w;if(!e&&x(a.watchId))b=b||this.nextId(),this.if_("i",this.lazyAssign(b,this.computedMember("i",a.watchId)),this.lazyRecurse(a,b,d,c,f,!0));else switch(a.type){case t.Program:q(a.body,function(b,c){k.recurse(b.expression,void 0,void 0,function(a){h=a});c!==a.body.length-1?k.current().body.push(h,";"):k.return_(h)});break;case t.Literal:m=this.escape(a.value);this.assign(b,m);c(m);break; case t.UnaryExpression:this.recurse(a.argument,void 0,void 0,function(a){h=a});m=a.operator+"("+this.ifDefined(h,0)+")";this.assign(b,m);c(m);break;case t.BinaryExpression:this.recurse(a.left,void 0,void 0,function(a){g=a});this.recurse(a.right,void 0,void 0,function(a){h=a});m="+"===a.operator?this.plus(g,h):"-"===a.operator?this.ifDefined(g,0)+a.operator+this.ifDefined(h,0):"("+g+")"+a.operator+"("+h+")";this.assign(b,m);c(m);break;case t.LogicalExpression:b=b||this.nextId();k.recurse(a.left,b); k.if_("&&"===a.operator?b:k.not(b),k.lazyRecurse(a.right,b));c(b);break;case t.ConditionalExpression:b=b||this.nextId();k.recurse(a.test,b);k.if_(b,k.lazyRecurse(a.alternate,b),k.lazyRecurse(a.consequent,b));c(b);break;case t.Identifier:b=b||this.nextId();d&&(d.context="inputs"===k.stage?"s":this.assign(this.nextId(),this.getHasOwnProperty("l",a.name)+"?l:s"),d.computed=!1,d.name=a.name);Ua(a.name);k.if_("inputs"===k.stage||k.not(k.getHasOwnProperty("l",a.name)),function(){k.if_("inputs"===k.stage|| "s",function(){f&&1!==f&&k.if_(k.not(k.nonComputedMember("s",a.name)),k.lazyAssign(k.nonComputedMember("s",a.name),"{}"));k.assign(b,k.nonComputedMember("s",a.name))})},b&&k.lazyAssign(b,k.nonComputedMember("l",a.name)));(k.state.expensiveChecks||Lb(a.name))&&k.addEnsureSafeObject(b);c(b);break;case t.MemberExpression:g=d&&(d.context=this.nextId())||this.nextId();b=b||this.nextId();k.recurse(a.object,g,void 0,function(){k.if_(k.notNull(g),function(){f&&1!==f&&k.addEnsureSafeAssignContext(g);if(a.computed)h= k.nextId(),k.recurse(a.property,h),k.getStringValue(h),k.addEnsureSafeMemberName(h),f&&1!==f&&k.if_(k.not(k.computedMember(g,h)),k.lazyAssign(k.computedMember(g,h),"{}")),m=k.ensureSafeObject(k.computedMember(g,h)),k.assign(b,m),d&&(d.computed=!0,d.name=h);else{Ua(a.property.name);f&&1!==f&&k.if_(k.not(k.nonComputedMember(g,a.property.name)),k.lazyAssign(k.nonComputedMember(g,a.property.name),"{}"));m=k.nonComputedMember(g,a.property.name);if(k.state.expensiveChecks||Lb(a.property.name))m=k.ensureSafeObject(m); k.assign(b,m);d&&(d.computed=!1,d.name=a.property.name)}},function(){k.assign(b,"undefined")});c(b)},!!f);break;case t.CallExpression:b=b||this.nextId();a.filter?(h=k.filter(a.callee.name),l=[],q(a.arguments,function(a){var b=k.nextId();k.recurse(a,b);l.push(b)}),m=h+"("+l.join(",")+")",k.assign(b,m),c(b)):(h=k.nextId(),g={},l=[],k.recurse(a.callee,h,g,function(){k.if_(k.notNull(h),function(){k.addEnsureSafeFunction(h);q(a.arguments,function(a){k.recurse(a,k.nextId(),void 0,function(a){l.push(k.ensureSafeObject(a))})}); g.name?(k.state.expensiveChecks||k.addEnsureSafeObject(g.context),m=k.member(g.context,g.name,g.computed)+"("+l.join(",")+")"):m=h+"("+l.join(",")+")";m=k.ensureSafeObject(m);k.assign(b,m)},function(){k.assign(b,"undefined")});c(b)}));break;case t.AssignmentExpression:h=this.nextId();g={};this.recurse(a.left,void 0,g,function(){k.if_(k.notNull(g.context),function(){k.recurse(a.right,h);k.addEnsureSafeObject(k.member(g.context,g.name,g.computed));k.addEnsureSafeAssignContext(g.context);m=k.member(g.context, g.name,g.computed)+a.operator+h;k.assign(b,m);c(b||m)})},1);break;case t.ArrayExpression:l=[];q(a.elements,function(a){k.recurse(a,k.nextId(),void 0,function(a){l.push(a)})});m="["+l.join(",")+"]";this.assign(b,m);c(m);break;case t.ObjectExpression:l=[];n=!1;q(a.properties,function(a){a.computed&&(n=!0)});n?(b=b||this.nextId(),this.assign(b,"{}"),q(a.properties,function(a){a.computed?(g=k.nextId(),k.recurse(a.key,g)):g=a.key.type===t.Identifier?a.key.name:""+a.key.value;h=k.nextId();k.recurse(a.value, h);k.assign(k.member(b,g,a.computed),h)})):(q(a.properties,function(b){k.recurse(b.value,a.constant?void 0:k.nextId(),void 0,function(a){l.push(k.escape(b.key.type===t.Identifier?b.key.name:""+b.key.value)+":"+a)})}),m="{"+l.join(",")+"}",this.assign(b,m));c(b||m);break;case t.ThisExpression:this.assign(b,"s");c("s");break;case t.LocalsExpression:this.assign(b,"l");c("l");break;case t.NGValueParameter:this.assign(b,"v"),c("v")}},getHasOwnProperty:function(a,b){var d=a+"."+b,c=this.current().own;c.hasOwnProperty(d)|| (c[d]=this.nextId(!1,a+"&&("+this.escape(b)+" in "+a+")"));return c[d]},assign:function(a,b){if(a)return this.current().body.push(a,"=",b,";"),a},filter:function(a){this.state.filters.hasOwnProperty(a)||(this.state.filters[a]=this.nextId(!0));return this.state.filters[a]},ifDefined:function(a,b){return"ifDefined("+a+","+this.escape(b)+")"},plus:function(a,b){return"plus("+a+","+b+")"},return_:function(a){this.current().body.push("return ",a,";")},if_:function(a,b,d){if(!0===a)b();else{var c=this.current().body; c.push("if(",a,"){");b();c.push("}");d&&(c.push("else{"),d(),c.push("}"))}},not:function(a){return"!("+a+")"},notNull:function(a){return a+"!=null"},nonComputedMember:function(a,b){var d=/[^$_a-zA-Z0-9]/g;return/^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(b)?a+"."+b:a+'["'+b.replace(d,this.stringEscapeFn)+'"]'},computedMember:function(a,b){return a+"["+b+"]"},member:function(a,b,d){return d?this.computedMember(a,b):this.nonComputedMember(a,b)},addEnsureSafeObject:function(a){this.current().body.push(this.ensureSafeObject(a), ";")},addEnsureSafeMemberName:function(a){this.current().body.push(this.ensureSafeMemberName(a),";")},addEnsureSafeFunction:function(a){this.current().body.push(this.ensureSafeFunction(a),";")},addEnsureSafeAssignContext:function(a){this.current().body.push(this.ensureSafeAssignContext(a),";")},ensureSafeObject:function(a){return"ensureSafeObject("+a+",text)"},ensureSafeMemberName:function(a){return"ensureSafeMemberName("+a+",text)"},ensureSafeFunction:function(a){return"ensureSafeFunction("+a+",text)"}, getStringValue:function(a){this.assign(a,"getStringValue("+a+")")},ensureSafeAssignContext:function(a){return"ensureSafeAssignContext("+a+",text)"},lazyRecurse:function(a,b,d,c,f,e){var g=this;return function(){g.recurse(a,b,d,c,f,e)}},lazyAssign:function(a,b){var d=this;return function(){d.assign(a,b)}},stringEscapeRegex:/[^ a-zA-Z0-9]/g,stringEscapeFn:function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)},escape:function(a){if(D(a))return"'"+a.replace(this.stringEscapeRegex,this.stringEscapeFn)+ "'";if(ba(a))return a.toString();if(!0===a)return"true";if(!1===a)return"false";if(null===a)return"null";if("undefined"===typeof a)return"undefined";throw ea("esc");},nextId:function(a,b){var d="v"+this.state.nextId++;a||this.current().vars.push(d+(b?"="+b:""));return d},current:function(){return this.state[this.state.computing]}};Hd.prototype={compile:function(a,b){var d=this,c=this.astBuilder.ast(a);this.expression=a;this.expensiveChecks=b;X(c,d.$filter);var f,e;if(f=Ed(c))e=this.recurse(f);f=Cd(c.body); var g;f&&(g=[],q(f,function(a,b){var c=d.recurse(a);a.input=c;g.push(c);a.watchId=b}));var h=[];q(c.body,function(a){h.push(d.recurse(a.expression))});f=0===c.body.length?w:1===c.body.length?h[0]:function(a,b){var c;q(h,function(d){c=d(a,b)});return c};e&&(f.assign=function(a,b,c){return e(a,c,b)});g&&(f.inputs=g);f.literal=Fd(c);f.constant=c.constant;return f},recurse:function(a,b,d){var c,f,e=this,g;if(a.input)return this.inputs(a.input,a.watchId);switch(a.type){case t.Literal:return this.value(a.value, b);case t.UnaryExpression:return f=this.recurse(a.argument),this["unary"+a.operator](f,b);case t.BinaryExpression:return c=this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](c,f,b);case t.LogicalExpression:return c=this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](c,f,b);case t.ConditionalExpression:return this["ternary?:"](this.recurse(a.test),this.recurse(a.alternate),this.recurse(a.consequent),b);case t.Identifier:return Ua(a.name,e.expression),e.identifier(a.name, e.expensiveChecks||Lb(a.name),b,d,e.expression);case t.MemberExpression:return c=this.recurse(a.object,!1,!!d),a.computed||(Ua(a.property.name,e.expression),f=a.property.name),a.computed&&(f=this.recurse(a.property)),a.computed?this.computedMember(c,f,b,d,e.expression):this.nonComputedMember(c,f,e.expensiveChecks,b,d,e.expression);case t.CallExpression:return g=[],q(a.arguments,function(a){g.push(e.recurse(a))}),a.filter&&(f=this.$filter(a.callee.name)),a.filter||(f=this.recurse(a.callee,!0)),a.filter? function(a,c,d,e){for(var n=[],r=0;r<g.length;++r)n.push(g[r](a,c,d,e));a=f.apply(void 0,n,e);return b?{context:void 0,name:void 0,value:a}:a}:function(a,c,d,m){var n=f(a,c,d,m),r;if(null!=n.value){Ea(n.context,e.expression);td(n.value,e.expression);r=[];for(var s=0;s<g.length;++s)r.push(Ea(g[s](a,c,d,m),e.expression));r=Ea(n.value.apply(n.context,r),e.expression)}return b?{value:r}:r};case t.AssignmentExpression:return c=this.recurse(a.left,!0,1),f=this.recurse(a.right),function(a,d,g,m){var n=c(a, d,g,m);a=f(a,d,g,m);Ea(n.value,e.expression);Jb(n.context);n.context[n.name]=a;return b?{value:a}:a};case t.ArrayExpression:return g=[],q(a.elements,function(a){g.push(e.recurse(a))}),function(a,c,d,e){for(var f=[],r=0;r<g.length;++r)f.push(g[r](a,c,d,e));return b?{value:f}:f};case t.ObjectExpression:return g=[],q(a.properties,function(a){a.computed?g.push({key:e.recurse(a.key),computed:!0,value:e.recurse(a.value)}):g.push({key:a.key.type===t.Identifier?a.key.name:""+a.key.value,computed:!1,value:e.recurse(a.value)})}), function(a,c,d,e){for(var f={},r=0;r<g.length;++r)g[r].computed?f[g[r].key(a,c,d,e)]=g[r].value(a,c,d,e):f[g[r].key]=g[r].value(a,c,d,e);return b?{value:f}:f};case t.ThisExpression:return function(a){return b?{value:a}:a};case t.LocalsExpression:return function(a,c){return b?{value:c}:c};case t.NGValueParameter:return function(a,c,d){return b?{value:d}:d}}},"unary+":function(a,b){return function(d,c,f,e){d=a(d,c,f,e);d=x(d)?+d:0;return b?{value:d}:d}},"unary-":function(a,b){return function(d,c,f, e){d=a(d,c,f,e);d=x(d)?-d:0;return b?{value:d}:d}},"unary!":function(a,b){return function(d,c,f,e){d=!a(d,c,f,e);return b?{value:d}:d}},"binary+":function(a,b,d){return function(c,f,e,g){var h=a(c,f,e,g);c=b(c,f,e,g);h=Bd(h,c);return d?{value:h}:h}},"binary-":function(a,b,d){return function(c,f,e,g){var h=a(c,f,e,g);c=b(c,f,e,g);h=(x(h)?h:0)-(x(c)?c:0);return d?{value:h}:h}},"binary*":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)*b(c,f,e,g);return d?{value:c}:c}},"binary/":function(a,b,d){return function(c, f,e,g){c=a(c,f,e,g)/b(c,f,e,g);return d?{value:c}:c}},"binary%":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)%b(c,f,e,g);return d?{value:c}:c}},"binary===":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)===b(c,f,e,g);return d?{value:c}:c}},"binary!==":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)!==b(c,f,e,g);return d?{value:c}:c}},"binary==":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)==b(c,f,e,g);return d?{value:c}:c}},"binary!=":function(a,b,d){return function(c, f,e,g){c=a(c,f,e,g)!=b(c,f,e,g);return d?{value:c}:c}},"binary<":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)<b(c,f,e,g);return d?{value:c}:c}},"binary>":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)>b(c,f,e,g);return d?{value:c}:c}},"binary<=":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)<=b(c,f,e,g);return d?{value:c}:c}},"binary>=":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)>=b(c,f,e,g);return d?{value:c}:c}},"binary&&":function(a,b,d){return function(c,f,e,g){c= a(c,f,e,g)&&b(c,f,e,g);return d?{value:c}:c}},"binary||":function(a,b,d){return function(c,f,e,g){c=a(c,f,e,g)||b(c,f,e,g);return d?{value:c}:c}},"ternary?:":function(a,b,d,c){return function(f,e,g,h){f=a(f,e,g,h)?b(f,e,g,h):d(f,e,g,h);return c?{value:f}:f}},value:function(a,b){return function(){return b?{context:void 0,name:void 0,value:a}:a}},identifier:function(a,b,d,c,f){return function(e,g,h,k){e=g&&a in g?g:e;c&&1!==c&&e&&!e[a]&&(e[a]={});g=e?e[a]:void 0;b&&Ea(g,f);return d?{context:e,name:a, value:g}:g}},computedMember:function(a,b,d,c,f){return function(e,g,h,k){var l=a(e,g,h,k),m,n;null!=l&&(m=b(e,g,h,k),m+="",Ua(m,f),c&&1!==c&&(Jb(l),l&&!l[m]&&(l[m]={})),n=l[m],Ea(n,f));return d?{context:l,name:m,value:n}:n}},nonComputedMember:function(a,b,d,c,f,e){return function(g,h,k,l){g=a(g,h,k,l);f&&1!==f&&(Jb(g),g&&!g[b]&&(g[b]={}));h=null!=g?g[b]:void 0;(d||Lb(b))&&Ea(h,e);return c?{context:g,name:b,value:h}:h}},inputs:function(a,b){return function(d,c,f,e){return e?e[b]:a(d,c,f)}}};var nc= function(a,b,d){this.lexer=a;this.$filter=b;this.options=d;this.ast=new t(a,d);this.astCompiler=d.csp?new Hd(this.ast,b):new Gd(this.ast,b)};nc.prototype={constructor:nc,parse:function(a){return this.astCompiler.compile(a,this.options.expensiveChecks)}};var Fa=G("$sce"),ga={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},Hg=G("$compile"),aa=y.document.createElement("a"),Ld=ta(y.location.href);Md.$inject=["$document"];Rc.$inject=["$provide"];var Td=22,Sd=".",pc="0";Nd.$inject=["$locale"]; Pd.$inject=["$locale"];var Sg={yyyy:U("FullYear",4,0,!1,!0),yy:U("FullYear",2,0,!0,!0),y:U("FullYear",1,0,!1,!0),MMMM:nb("Month"),MMM:nb("Month",!0),MM:U("Month",2,1),M:U("Month",1,1),LLLL:nb("Month",!1,!0),dd:U("Date",2),d:U("Date",1),HH:U("Hours",2),H:U("Hours",1),hh:U("Hours",2,-12),h:U("Hours",1,-12),mm:U("Minutes",2),m:U("Minutes",1),ss:U("Seconds",2),s:U("Seconds",1),sss:U("Milliseconds",3),EEEE:nb("Day"),EEE:nb("Day",!0),a:function(a,b){return 12>a.getHours()?b.AMPMS[0]:b.AMPMS[1]},Z:function(a, b,d){a=-1*d;return a=(0<=a?"+":"")+(Mb(Math[0<a?"floor":"ceil"](a/60),2)+Mb(Math.abs(a%60),2))},ww:Vd(2),w:Vd(1),G:qc,GG:qc,GGG:qc,GGGG:function(a,b){return 0>=a.getFullYear()?b.ERANAMES[0]:b.ERANAMES[1]}},Rg=/((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,Qg=/^-?\d+$/;Od.$inject=["$locale"];var Lg=ha(Q),Mg=ha(wb);Qd.$inject=["$parse"];var Ce=ha({restrict:"E",compile:function(a,b){if(!b.href&&!b.xlinkHref)return function(a,b){if("a"===b[0].nodeName.toLowerCase()){var f= "[object SVGAnimatedString]"===ma.call(b.prop("href"))?"xlink:href":"href";b.on("click",function(a){b.attr(f)||a.preventDefault()})}}}}),xb={};q(Gb,function(a,b){function d(a,d,f){a.$watch(f[c],function(a){f.$set(b,!!a)})}if("multiple"!==a){var c=Da("ng-"+b),f=d;"checked"===a&&(f=function(a,b,f){f.ngModel!==f[c]&&d(a,b,f)});xb[c]=function(){return{restrict:"A",priority:100,link:f}}}});q(gd,function(a,b){xb[b]=function(){return{priority:100,link:function(a,c,f){if("ngPattern"===b&&"/"===f.ngPattern.charAt(0)&& (c=f.ngPattern.match(Vg))){f.$set("ngPattern",new RegExp(c[1],c[2]));return}a.$watch(f[b],function(a){f.$set(b,a)})}}}});q(["src","srcset","href"],function(a){var b=Da("ng-"+a);xb[b]=function(){return{priority:99,link:function(d,c,f){var e=a,g=a;"href"===a&&"[object SVGAnimatedString]"===ma.call(c.prop("href"))&&(g="xlinkHref",f.$attr[g]="xlink:href",e=null);f.$observe(b,function(b){b?(f.$set(g,b),Ia&&e&&c.prop(e,f[g])):"href"===a&&f.$set(g,null)})}}}});var Nb={$addControl:w,$$renameControl:function(a, b){a.$name=b},$removeControl:w,$setValidity:w,$setDirty:w,$setPristine:w,$setSubmitted:w};Wd.$inject=["$element","$attrs","$scope","$animate","$interpolate"];var ee=function(a){return["$timeout","$parse",function(b,d){function c(a){return""===a?d('this[""]').assign:d(a).assign||w}return{name:"form",restrict:a?"EAC":"E",require:["form","^^?form"],controller:Wd,compile:function(d,e){d.addClass(Wa).addClass(rb);var g=e.name?"name":a&&e.ngForm?"ngForm":!1;return{pre:function(a,d,e,f){var n=f[0];if(!("action"in e)){var r=function(b){a.$apply(function(){n.$commitViewValue();n.$setSubmitted()});b.preventDefault()};d[0].addEventListener("submit",r,!1);d.on("$destroy",function(){b(function(){d[0].removeEventListener("submit",r,!1)},0,!1)})}(f[1]||n.$$parentForm).$addControl(n);var s=g?c(n.$name):w;g&&(s(a,n),e.$observe(g,function(b){n.$name!==b&&(s(a,void 0),n.$$parentForm.$$renameControl(n,b),s=c(n.$name),s(a,n))}));d.on("$destroy",function(){n.$$parentForm.$removeControl(n);s(a,void 0);R(n,Nb)})}}}}}]},De= ee(),Pe=ee(!0),Tg=/^\d{4,}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)$/,ch=/^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i,dh=/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/,Ug=/^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/,fe=/^(\d{4,})-(\d{2})-(\d{2})$/,ge=/^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/, wc=/^(\d{4,})-W(\d\d)$/,he=/^(\d{4,})-(\d\d)$/,ie=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Yd=V();q(["date","datetime-local","month","time","week"],function(a){Yd[a]=!0});var je={text:function(a,b,d,c,f,e){Xa(a,b,d,c,f,e);sc(c)},date:ob("date",fe,Pb(fe,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":ob("datetimelocal",ge,Pb(ge,"yyyy MM dd HH mm ss sss".split(" ")),"yyyy-MM-ddTHH:mm:ss.sss"),time:ob("time",ie,Pb(ie,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:ob("week",wc,function(a,b){if(ja(a))return a; if(D(a)){wc.lastIndex=0;var d=wc.exec(a);if(d){var c=+d[1],f=+d[2],e=d=0,g=0,h=0,k=Ud(c),f=7*(f-1);b&&(d=b.getHours(),e=b.getMinutes(),g=b.getSeconds(),h=b.getMilliseconds());return new Date(c,0,k.getDate()+f,d,e,g,h)}}return NaN},"yyyy-Www"),month:ob("month",he,Pb(he,["yyyy","MM"]),"yyyy-MM"),number:function(a,b,d,c,f,e){tc(a,b,d,c);Xa(a,b,d,c,f,e);Zd(c);var g,h;if(x(d.min)||d.ngMin)c.$validators.min=function(a){return c.$isEmpty(a)||z(g)||a>=g},d.$observe("min",function(a){g=qb(a);c.$validate()}); if(x(d.max)||d.ngMax)c.$validators.max=function(a){return c.$isEmpty(a)||z(h)||a<=h},d.$observe("max",function(a){h=qb(a);c.$validate()})},url:function(a,b,d,c,f,e){Xa(a,b,d,c,f,e);sc(c);c.$$parserName="url";c.$validators.url=function(a,b){var d=a||b;return c.$isEmpty(d)||ch.test(d)}},email:function(a,b,d,c,f,e){Xa(a,b,d,c,f,e);sc(c);c.$$parserName="email";c.$validators.email=function(a,b){var d=a||b;return c.$isEmpty(d)||dh.test(d)}},radio:function(a,b,d,c){z(d.name)&&b.attr("name",++sb);b.on("click", function(a){b[0].checked&&c.$setViewValue(d.value,a&&a.type)});c.$render=function(){b[0].checked=d.value==c.$viewValue};d.$observe("value",c.$render)},range:function(a,b,d,c,f,e){function g(a,c){b.attr(a,d[a]);d.$observe(a,c)}function h(a){n=qb(a);ia(c.$modelValue)||(m?(a=b.val(),n>a&&(a=n,b.val(a)),c.$setViewValue(a)):c.$validate())}function k(a){r=qb(a);ia(c.$modelValue)||(m?(a=b.val(),r<a&&(b.val(r),a=r<n?n:r),c.$setViewValue(a)):c.$validate())}function l(a){s=qb(a);ia(c.$modelValue)||(m&&c.$viewValue!== b.val()?c.$setViewValue(b.val()):c.$validate())}tc(a,b,d,c);Zd(c);Xa(a,b,d,c,f,e);var m=c.$$hasNativeValidators&&"range"===b[0].type,n=m?0:void 0,r=m?100:void 0,s=m?1:void 0,q=b[0].validity;a=x(d.min);f=x(d.max);e=x(d.step);var u=c.$render;c.$render=m&&x(q.rangeUnderflow)&&x(q.rangeOverflow)?function(){u();c.$setViewValue(b.val())}:u;a&&(c.$validators.min=m?function(){return!0}:function(a,b){return c.$isEmpty(b)||z(n)||b>=n},g("min",h));f&&(c.$validators.max=m?function(){return!0}:function(a,b){return c.$isEmpty(b)|| z(r)||b<=r},g("max",k));e&&(c.$validators.step=m?function(){return!q.stepMismatch}:function(a,b){var d;if(!(d=c.$isEmpty(b)||z(s))){d=n||0;var e=s,f=Number(b);if((f|0)!==f||(d|0)!==d||(e|0)!==e){var g=Math.max(uc(f),uc(d),uc(e)),g=Math.pow(10,g),f=f*g;d*=g;e*=g}d=0===(f-d)%e}return d},g("step",l))},checkbox:function(a,b,d,c,f,e,g,h){var k=$d(h,a,"ngTrueValue",d.ngTrueValue,!0),l=$d(h,a,"ngFalseValue",d.ngFalseValue,!1);b.on("click",function(a){c.$setViewValue(b[0].checked,a&&a.type)});c.$render=function(){b[0].checked= c.$viewValue};c.$isEmpty=function(a){return!1===a};c.$formatters.push(function(a){return na(a,k)});c.$parsers.push(function(a){return a?k:l})},hidden:w,button:w,submit:w,reset:w,file:w},Lc=["$browser","$sniffer","$filter","$parse",function(a,b,d,c){return{restrict:"E",require:["?ngModel"],link:{pre:function(f,e,g,h){if(h[0]){var k=Q(g.type);"range"!==k||g.hasOwnProperty("ngInputRange")||(k="text");(je[k]||je.text)(f,e,g,h[0],b,a,d,c)}}}}}],eh=/^(true|false|\d+)$/,gf=function(){return{restrict:"A", priority:100,compile:function(a,b){return eh.test(b.ngValue)?function(a,b,f){f.$set("value",a.$eval(f.ngValue))}:function(a,b,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},He=["$compile",function(a){return{restrict:"AC",compile:function(b){a.$$addBindingClass(b);return function(b,c,f){a.$$addBindingInfo(c,f.ngBind);c=c[0];b.$watch(f.ngBind,function(a){c.textContent=z(a)?"":a})}}}}],Je=["$interpolate","$compile",function(a,b){return{compile:function(d){b.$$addBindingClass(d);return function(c, d,e){c=a(d.attr(e.$attr.ngBindTemplate));b.$$addBindingInfo(d,c.expressions);d=d[0];e.$observe("ngBindTemplate",function(a){d.textContent=z(a)?"":a})}}}}],Ie=["$sce","$parse","$compile",function(a,b,d){return{restrict:"A",compile:function(c,f){var e=b(f.ngBindHtml),g=b(f.ngBindHtml,function(b){return a.valueOf(b)});d.$$addBindingClass(c);return function(b,c,f){d.$$addBindingInfo(c,f.ngBindHtml);b.$watch(g,function(){var d=e(b);c.html(a.getTrustedHtml(d)||"")})}}}}],ff=ha({restrict:"A",require:"ngModel", link:function(a,b,d,c){c.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),Ke=vc("",!0),Me=vc("Odd",0),Le=vc("Even",1),Ne=Va({compile:function(a,b){b.$set("ngCloak",void 0);a.removeClass("ng-cloak")}}),Oe=[function(){return{restrict:"A",scope:!0,controller:"@",priority:500}}],Qc={},fh={blur:!0,focus:!0};q("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var b=Da("ng-"+a); Qc[b]=["$parse","$rootScope",function(d,c){return{restrict:"A",compile:function(f,e){var g=d(e[b],null,!0);return function(b,d){d.on(a,function(d){var e=function(){g(b,{$event:d})};fh[a]&&c.$$phase?b.$evalAsync(e):b.$apply(e)})}}}}]});var Re=["$animate","$compile",function(a,b){return{multiElement:!0,transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(d,c,f,e,g){var h,k,l;d.$watch(f.ngIf,function(d){d?k||g(function(d,e){k=e;d[d.length++]=b.$$createComment("end ngIf", f.ngIf);h={clone:d};a.enter(d,c.parent(),c)}):(l&&(l.remove(),l=null),k&&(k.$destroy(),k=null),h&&(l=vb(h.clone),a.leave(l).done(function(a){!1!==a&&(l=null)}),h=null))})}}}],Se=["$templateRequest","$anchorScroll","$animate",function(a,b,d){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:$.noop,compile:function(c,f){var e=f.ngInclude||f.src,g=f.onload||"",h=f.autoscroll;return function(c,f,m,n,r){var q=0,t,u,p,z=function(){u&&(u.remove(),u=null);t&&(t.$destroy(),t=null); p&&(d.leave(p).done(function(a){!1!==a&&(u=null)}),u=p,p=null)};c.$watch(e,function(e){var m=function(a){!1===a||!x(h)||h&&!c.$eval(h)||b()},u=++q;e?(a(e,!0).then(function(a){if(!c.$$destroyed&&u===q){var b=c.$new();n.template=a;a=r(b,function(a){z();d.enter(a,null,f).done(m)});t=b;p=a;t.$emit("$includeContentLoaded",e);c.$eval(g)}},function(){c.$$destroyed||u!==q||(z(),c.$emit("$includeContentError",e))}),c.$emit("$includeContentRequested",e)):(z(),n.template=null)})}}}}],jf=["$compile",function(a){return{restrict:"ECA", priority:-400,require:"ngInclude",link:function(b,d,c,f){ma.call(d[0]).match(/SVG/)?(d.empty(),a(Tc(f.template,y.document).childNodes)(b,function(a){d.append(a)},{futureParentElement:d})):(d.html(f.template),a(d.contents())(b))}}}],Te=Va({priority:450,compile:function(){return{pre:function(a,b,d){a.$eval(d.ngInit)}}}}),ef=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,b,d,c){var f=b.attr(d.$attr.ngList)||", ",e="false"!==d.ngTrim,g=e?Y(f):f;c.$parsers.push(function(a){if(!z(a)){var b= [];a&&q(a.split(g),function(a){a&&b.push(e?Y(a):a)});return b}});c.$formatters.push(function(a){if(I(a))return a.join(f)});c.$isEmpty=function(a){return!a||!a.length}}}},rb="ng-valid",ae="ng-invalid",Wa="ng-pristine",Ob="ng-dirty",ce="ng-pending",pb=G("ngModel"),gh=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate","$timeout","$rootScope","$q","$interpolate",function(a,b,d,c,f,e,g,h,k,l){this.$modelValue=this.$viewValue=Number.NaN;this.$$rawModelValue=void 0;this.$validators={}; this.$asyncValidators={};this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$untouched=!0;this.$touched=!1;this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$error={};this.$$success={};this.$pending=void 0;this.$name=l(d.name||"",!1)(a);this.$$parentForm=Nb;var m=f(d.ngModel),n=m.assign,r=m,s=n,t=null,u,p=this;this.$$setOptions=function(a){if((p.$options=a)&&a.getterSetter){var b=f(d.ngModel+"()"),e=f(d.ngModel+"($$$p)");r=function(a){var c=m(a);C(c)&&(c=b(a)); return c};s=function(a,b){C(m(a))?e(a,{$$$p:b}):n(a,b)}}else if(!m.assign)throw pb("nonassign",d.ngModel,ya(c));};this.$render=w;this.$isEmpty=function(a){return z(a)||""===a||null===a||a!==a};this.$$updateEmptyClasses=function(a){p.$isEmpty(a)?(e.removeClass(c,"ng-not-empty"),e.addClass(c,"ng-empty")):(e.removeClass(c,"ng-empty"),e.addClass(c,"ng-not-empty"))};var y=0;Xd({ctrl:this,$element:c,set:function(a,b){a[b]=!0},unset:function(a,b){delete a[b]},$animate:e});this.$setPristine=function(){p.$dirty= !1;p.$pristine=!0;e.removeClass(c,Ob);e.addClass(c,Wa)};this.$setDirty=function(){p.$dirty=!0;p.$pristine=!1;e.removeClass(c,Wa);e.addClass(c,Ob);p.$$parentForm.$setDirty()};this.$setUntouched=function(){p.$touched=!1;p.$untouched=!0;e.setClass(c,"ng-untouched","ng-touched")};this.$setTouched=function(){p.$touched=!0;p.$untouched=!1;e.setClass(c,"ng-touched","ng-untouched")};this.$rollbackViewValue=function(){g.cancel(t);p.$viewValue=p.$$lastCommittedViewValue;p.$render()};this.$validate=function(){if(!ia(p.$modelValue)){var a= p.$$rawModelValue,b=p.$valid,c=p.$modelValue,d=p.$options&&p.$options.allowInvalid;p.$$runValidators(a,p.$$lastCommittedViewValue,function(e){d||b===e||(p.$modelValue=e?a:void 0,p.$modelValue!==c&&p.$$writeModelToScope())})}};this.$$runValidators=function(a,b,c){function d(){var c=!0;q(p.$validators,function(d,e){var g=d(a,b);c=c&&g;f(e,g)});return c?!0:(q(p.$asyncValidators,function(a,b){f(b,null)}),!1)}function e(){var c=[],d=!0;q(p.$asyncValidators,function(e,g){var h=e(a,b);if(!h||!C(h.then))throw pb("nopromise", h);f(g,void 0);c.push(h.then(function(){f(g,!0)},function(){d=!1;f(g,!1)}))});c.length?k.all(c).then(function(){g(d)},w):g(!0)}function f(a,b){h===y&&p.$setValidity(a,b)}function g(a){h===y&&c(a)}y++;var h=y;(function(){var a=p.$$parserName||"parse";if(z(u))f(a,null);else return u||(q(p.$validators,function(a,b){f(b,null)}),q(p.$asyncValidators,function(a,b){f(b,null)})),f(a,u),u;return!0})()?d()?e():g(!1):g(!1)};this.$commitViewValue=function(){var a=p.$viewValue;g.cancel(t);if(p.$$lastCommittedViewValue!== a||""===a&&p.$$hasNativeValidators)p.$$updateEmptyClasses(a),p.$$lastCommittedViewValue=a,p.$pristine&&this.$setDirty(),this.$$parseAndValidate()};this.$$parseAndValidate=function(){var b=p.$$lastCommittedViewValue;if(u=z(b)?void 0:!0)for(var c=0;c<p.$parsers.length;c++)if(b=p.$parsers[c](b),z(b)){u=!1;break}ia(p.$modelValue)&&(p.$modelValue=r(a));var d=p.$modelValue,e=p.$options&&p.$options.allowInvalid;p.$$rawModelValue=b;e&&(p.$modelValue=b,p.$modelValue!==d&&p.$$writeModelToScope());p.$$runValidators(b, p.$$lastCommittedViewValue,function(a){e||(p.$modelValue=a?b:void 0,p.$modelValue!==d&&p.$$writeModelToScope())})};this.$$writeModelToScope=function(){s(a,p.$modelValue);q(p.$viewChangeListeners,function(a){try{a()}catch(c){b(c)}})};this.$setViewValue=function(a,b){p.$viewValue=a;p.$options&&!p.$options.updateOnDefault||p.$$debounceViewValueCommit(b)};this.$$debounceViewValueCommit=function(b){var c=0,d=p.$options;d&&x(d.debounce)&&(d=d.debounce,ba(d)?c=d:ba(d[b])?c=d[b]:ba(d["default"])&&(c=d["default"])); g.cancel(t);c?t=g(function(){p.$commitViewValue()},c):h.$$phase?p.$commitViewValue():a.$apply(function(){p.$commitViewValue()})};a.$watch(function(){var b=r(a);if(b!==p.$modelValue&&(p.$modelValue===p.$modelValue||b===b)){p.$modelValue=p.$$rawModelValue=b;u=void 0;for(var c=p.$formatters,d=c.length,e=b;d--;)e=c[d](e);p.$viewValue!==e&&(p.$$updateEmptyClasses(e),p.$viewValue=p.$$lastCommittedViewValue=e,p.$render(),p.$$runValidators(p.$modelValue,p.$viewValue,w))}return b})}],df=["$rootScope",function(a){return{restrict:"A", require:["ngModel","^?form","^?ngModelOptions"],controller:gh,priority:1,compile:function(b){b.addClass(Wa).addClass("ng-untouched").addClass(rb);return{pre:function(a,b,f,e){var g=e[0];b=e[1]||g.$$parentForm;g.$$setOptions(e[2]&&e[2].$options);b.$addControl(g);f.$observe("name",function(a){g.$name!==a&&g.$$parentForm.$$renameControl(g,a)});a.$on("$destroy",function(){g.$$parentForm.$removeControl(g)})},post:function(b,c,f,e){var g=e[0];if(g.$options&&g.$options.updateOn)c.on(g.$options.updateOn, function(a){g.$$debounceViewValueCommit(a&&a.type)});c.on("blur",function(){g.$touched||(a.$$phase?b.$evalAsync(g.$setTouched):b.$apply(g.$setTouched))})}}}}}],hh=/(\s+|^)default(\s+|$)/,hf=function(){return{restrict:"A",controller:["$scope","$attrs",function(a,b){var d=this;this.$options=sa(a.$eval(b.ngModelOptions));x(this.$options.updateOn)?(this.$options.updateOnDefault=!1,this.$options.updateOn=Y(this.$options.updateOn.replace(hh,function(){d.$options.updateOnDefault=!0;return" "}))):this.$options.updateOnDefault= !0}]}},Ue=Va({terminal:!0,priority:1E3}),ih=G("ngOptions"),jh=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([$\w][$\w]*)|(?:\(\s*([$\w][$\w]*)\s*,\s*([$\w][$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,bf=["$compile","$document","$parse",function(a,b,d){function c(a,b,c){function e(a,b,c,d,f){this.selectValue=a;this.viewValue=b;this.label=c;this.group=d;this.disabled=f}function f(a){var b;if(!q&&la(a))b=a;else{b= [];for(var c in a)a.hasOwnProperty(c)&&"$"!==c.charAt(0)&&b.push(c)}return b}var n=a.match(jh);if(!n)throw ih("iexp",a,ya(b));var r=n[5]||n[7],q=n[6];a=/ as /.test(n[0])&&n[1];var t=n[9];b=d(n[2]?n[1]:r);var u=a&&d(a)||b,p=t&&d(t),x=t?function(a,b){return p(c,b)}:function(a){return Aa(a)},A=function(a,b){return x(a,C(a,b))},v=d(n[2]||n[1]),z=d(n[3]||""),L=d(n[4]||""),w=d(n[8]),y={},C=q?function(a,b){y[q]=b;y[r]=a;return y}:function(a){y[r]=a;return y};return{trackBy:t,getTrackByValue:A,getWatchables:d(w, function(a){var b=[];a=a||[];for(var d=f(a),e=d.length,g=0;g<e;g++){var h=a===d?g:d[g],l=a[h],h=C(l,h),l=x(l,h);b.push(l);if(n[2]||n[1])l=v(c,h),b.push(l);n[4]&&(h=L(c,h),b.push(h))}return b}),getOptions:function(){for(var a=[],b={},d=w(c)||[],g=f(d),h=g.length,n=0;n<h;n++){var p=d===g?n:g[n],r=C(d[p],p),q=u(c,r),p=x(q,r),s=v(c,r),y=z(c,r),r=L(c,r),q=new e(p,q,s,y,r);a.push(q);b[p]=q}return{items:a,selectValueMap:b,getOptionFromViewValue:function(a){return b[A(a)]},getViewValueFromOption:function(a){return t? sa(a.viewValue):a.viewValue}}}}}var f=y.document.createElement("option"),e=y.document.createElement("optgroup");return{restrict:"A",terminal:!0,require:["select","ngModel"],link:{pre:function(a,b,c,d){d[0].registerOption=w},post:function(d,h,k,l){function m(a,b){a.element=b;b.disabled=a.disabled;a.label!==b.label&&(b.label=a.label,b.textContent=a.label);b.value=a.selectValue}function n(){var a=w&&r.readValue();if(w)for(var b=w.items.length-1;0<=b;b--){var c=w.items[b];x(c.group)?Fb(c.element.parentNode): Fb(c.element)}w=C.getOptions();var d={};A&&h.prepend(u);w.items.forEach(function(a){var b;if(x(a.group)){b=d[a.group];b||(b=e.cloneNode(!1),D.appendChild(b),b.label=null===a.group?"null":a.group,d[a.group]=b);var c=f.cloneNode(!1)}else b=D,c=f.cloneNode(!1);b.appendChild(c);m(a,c)});h[0].appendChild(D);s.$render();s.$isEmpty(a)||(b=r.readValue(),(C.trackBy||t?na(a,b):a===b)||(s.$setViewValue(b),s.$render()))}var r=l[0],s=l[1],t=k.multiple,u;l=0;for(var p=h.children(),z=p.length;l<z;l++)if(""===p[l].value){u= p.eq(l);break}var A=!!u,v=!1,y=F(f.cloneNode(!1));y.val("?");var w,C=c(k.ngOptions,h,d),D=b[0].createDocumentFragment(),E=function(){A?v&&u.removeAttr("selected"):u.remove()};t?(s.$isEmpty=function(a){return!a||0===a.length},r.writeValue=function(a){w.items.forEach(function(a){a.element.selected=!1});a&&a.forEach(function(a){if(a=w.getOptionFromViewValue(a))a.element.selected=!0})},r.readValue=function(){var a=h.val()||[],b=[];q(a,function(a){(a=w.selectValueMap[a])&&!a.disabled&&b.push(w.getViewValueFromOption(a))}); return b},C.trackBy&&d.$watchCollection(function(){if(I(s.$viewValue))return s.$viewValue.map(function(a){return C.getTrackByValue(a)})},function(){s.$render()})):(r.writeValue=function(a){var b=w.selectValueMap[h.val()],c=w.getOptionFromViewValue(a);b&&b.element.removeAttribute("selected");c?(h[0].value!==c.selectValue&&(y.remove(),E(),h[0].value=c.selectValue,c.element.selected=!0),c.element.setAttribute("selected","selected")):null===a||A?(y.remove(),A||h.prepend(u),h.val(""),v&&(u.prop("selected", !0),u.attr("selected",!0))):(E(),h.prepend(y),h.val("?"),y.prop("selected",!0),y.attr("selected",!0))},r.readValue=function(){var a=w.selectValueMap[h.val()];return a&&!a.disabled?(E(),y.remove(),w.getViewValueFromOption(a)):null},C.trackBy&&d.$watch(function(){return C.getTrackByValue(s.$viewValue)},function(){s.$render()}));A?(u.remove(),a(u)(d),8===u[0].nodeType?(v=!1,r.registerOption=function(a,b){""===b.val()&&(v=!0,u=b,u.removeClass("ng-scope"),s.$render(),b.on("$destroy",function(){u=void 0; v=!1}))}):(u.removeClass("ng-scope"),v=!0)):u=F(f.cloneNode(!1));h.empty();n();d.$watchCollection(C.getWatchables,n)}}}}],Ve=["$locale","$interpolate","$log",function(a,b,d){var c=/{}/g,f=/^when(Minus)?(.+)$/;return{link:function(e,g,h){function k(a){g.text(a||"")}var l=h.count,m=h.$attr.when&&g.attr(h.$attr.when),n=h.offset||0,r=e.$eval(m)||{},s={},t=b.startSymbol(),u=b.endSymbol(),p=t+l+"-"+n+u,x=$.noop,A;q(h,function(a,b){var c=f.exec(b);c&&(c=(c[1]?"-":"")+Q(c[2]),r[c]=g.attr(h.$attr[b]))});q(r, function(a,d){s[d]=b(a.replace(c,p))});e.$watch(l,function(b){var c=parseFloat(b),f=ia(c);f||c in r||(c=a.pluralCat(c-n));c===A||f&&ia(A)||(x(),f=s[c],z(f)?(null!=b&&d.debug("ngPluralize: no rule defined for '"+c+"' in "+m),x=w,k()):x=e.$watch(f,k),A=c)})}}}],We=["$parse","$animate","$compile",function(a,b,d){var c=G("ngRepeat"),f=function(a,b,c,d,f,m,n){a[c]=d;f&&(a[f]=m);a.$index=b;a.$first=0===b;a.$last=b===n-1;a.$middle=!(a.$first||a.$last);a.$odd=!(a.$even=0===(b&1))};return{restrict:"A",multiElement:!0, transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,compile:function(e,g){var h=g.ngRepeat,k=d.$$createComment("end ngRepeat",h),l=h.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);if(!l)throw c("iexp",h);var m=l[1],n=l[2],r=l[3],s=l[4],l=m.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);if(!l)throw c("iidexp",m);var t=l[3]||l[1],u=l[2];if(r&&(!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(r)||/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(r)))throw c("badident", r);var p,x,A,v,w={$id:Aa};s?p=a(s):(A=function(a,b){return Aa(b)},v=function(a){return a});return function(a,d,e,g,l){p&&(x=function(b,c,d){u&&(w[u]=b);w[t]=c;w.$index=d;return p(a,w)});var m=V();a.$watchCollection(n,function(e){var g,n,p=d[0],s,w=V(),z,y,C,D,F,E,G;r&&(a[r]=e);if(la(e))F=e,n=x||A;else for(G in n=x||v,F=[],e)ua.call(e,G)&&"$"!==G.charAt(0)&&F.push(G);z=F.length;G=Array(z);for(g=0;g<z;g++)if(y=e===F?g:F[g],C=e[y],D=n(y,C,g),m[D])E=m[D],delete m[D],w[D]=E,G[g]=E;else{if(w[D])throw q(G, function(a){a&&a.scope&&(m[a.id]=a)}),c("dupes",h,D,C);G[g]={id:D,scope:void 0,clone:void 0};w[D]=!0}for(s in m){E=m[s];D=vb(E.clone);b.leave(D);if(D[0].parentNode)for(g=0,n=D.length;g<n;g++)D[g].$$NG_REMOVED=!0;E.scope.$destroy()}for(g=0;g<z;g++)if(y=e===F?g:F[g],C=e[y],E=G[g],E.scope){s=p;do s=s.nextSibling;while(s&&s.$$NG_REMOVED);E.clone[0]!==s&&b.move(vb(E.clone),null,p);p=E.clone[E.clone.length-1];f(E.scope,g,t,C,u,y,z)}else l(function(a,c){E.scope=c;var d=k.cloneNode(!1);a[a.length++]=d;b.enter(a, null,p);p=d;E.clone=a;w[E.id]=E;f(E.scope,g,t,C,u,y,z)});m=w})}}}}],Xe=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(b,d,c){b.$watch(c.ngShow,function(b){a[b?"removeClass":"addClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],Qe=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(b,d,c){b.$watch(c.ngHide,function(b){a[b?"addClass":"removeClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],Ye=Va(function(a,b,d){a.$watch(d.ngStyle,function(a, d){d&&a!==d&&q(d,function(a,c){b.css(c,"")});a&&b.css(a)},!0)}),Ze=["$animate","$compile",function(a,b){return{require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(d,c,f,e){var g=[],h=[],k=[],l=[],m=function(a,b){return function(c){!1!==c&&a.splice(b,1)}};d.$watch(f.ngSwitch||f.on,function(c){for(var d,f;k.length;)a.cancel(k.pop());d=0;for(f=l.length;d<f;++d){var t=vb(h[d].clone);l[d].$destroy();(k[d]=a.leave(t)).done(m(k,d))}h.length=0;l.length=0;(g=e.cases["!"+c]||e.cases["?"])&& q(g,function(c){c.transclude(function(d,e){l.push(e);var f=c.element;d[d.length++]=b.$$createComment("end ngSwitchWhen");h.push({clone:d});a.enter(d,f.parent(),f)})})})}}}],$e=Va({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,b,d,c,f){a=d.ngSwitchWhen.split(d.ngSwitchWhenSeparator).sort().filter(function(a,b,c){return c[b-1]!==a});q(a,function(a){c.cases["!"+a]=c.cases["!"+a]||[];c.cases["!"+a].push({transclude:f,element:b})})}}),af=Va({transclude:"element", priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,b,d,c,f){c.cases["?"]=c.cases["?"]||[];c.cases["?"].push({transclude:f,element:b})}}),kh=G("ngTransclude"),cf=["$compile",function(a){return{restrict:"EAC",terminal:!0,compile:function(b){var d=a(b.contents());b.empty();return function(a,b,e,g,h){function k(){d(a,function(a){b.append(a)})}if(!h)throw kh("orphan",ya(b));e.ngTransclude===e.$attr.ngTransclude&&(e.ngTransclude="");e=e.ngTransclude||e.ngTranscludeSlot;h(function(a,c){a.length? b.append(a):(k(),c.$destroy())},null,e);e&&!h.isSlotFilled(e)&&k()}}}}],Ee=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(b,d){"text/ng-template"===d.type&&a.put(d.id,b[0].text)}}}],lh={$setViewValue:w,$render:w},mh=["$element","$scope",function(a,b){var d=this,c=new Sa;d.ngModelCtrl=lh;d.unknownOption=F(y.document.createElement("option"));d.renderUnknownOption=function(b){b="? "+Aa(b)+" ?";d.unknownOption.val(b);a.prepend(d.unknownOption);a.val(b)};b.$on("$destroy", function(){d.renderUnknownOption=w});d.removeUnknownOption=function(){d.unknownOption.parent()&&d.unknownOption.remove()};d.readValue=function(){d.removeUnknownOption();return a.val()};d.writeValue=function(b){d.hasOption(b)?(d.removeUnknownOption(),a.val(b),""===b&&d.emptyOption.prop("selected",!0)):null==b&&d.emptyOption?(d.removeUnknownOption(),a.val("")):d.renderUnknownOption(b)};d.addOption=function(a,b){if(8!==b[0].nodeType){Ra(a,'"option value"');""===a&&(d.emptyOption=b);var g=c.get(a)||0; c.put(a,g+1);d.ngModelCtrl.$render();b[0].hasAttribute("selected")&&(b[0].selected=!0)}};d.removeOption=function(a){var b=c.get(a);b&&(1===b?(c.remove(a),""===a&&(d.emptyOption=void 0)):c.put(a,b-1))};d.hasOption=function(a){return!!c.get(a)};d.registerOption=function(a,b,c,h,k){if(h){var l;c.$observe("value",function(a){x(l)&&d.removeOption(l);l=a;d.addOption(a,b)})}else k?a.$watch(k,function(a,f){c.$set("value",a);f!==a&&d.removeOption(f);d.addOption(a,b)}):d.addOption(c.value,b);b.on("$destroy", function(){d.removeOption(c.value);d.ngModelCtrl.$render()})}}],Fe=function(){return{restrict:"E",require:["select","?ngModel"],controller:mh,priority:1,link:{pre:function(a,b,d,c){var f=c[1];if(f){var e=c[0];e.ngModelCtrl=f;b.on("change",function(){a.$apply(function(){f.$setViewValue(e.readValue())})});if(d.multiple){e.readValue=function(){var a=[];q(b.find("option"),function(b){b.selected&&a.push(b.value)});return a};e.writeValue=function(a){var c=new Sa(a);q(b.find("option"),function(a){a.selected= x(c.get(a.value))})};var g,h=NaN;a.$watch(function(){h!==f.$viewValue||na(g,f.$viewValue)||(g=ka(f.$viewValue),f.$render());h=f.$viewValue});f.$isEmpty=function(a){return!a||0===a.length}}}},post:function(a,b,d,c){var f=c[1];if(f){var e=c[0];f.$render=function(){e.writeValue(f.$viewValue)}}}}}},Ge=["$interpolate",function(a){return{restrict:"E",priority:100,compile:function(b,d){var c,f;x(d.ngValue)?c=!0:x(d.value)?c=a(d.value,!0):(f=a(b.text(),!0))||d.$set("value",b.text());return function(a,b,d){var k= b.parent();(k=k.data("$selectController")||k.parent().data("$selectController"))&&k.registerOption(a,b,d,c,f)}}}}],Nc=function(){return{restrict:"A",require:"?ngModel",link:function(a,b,d,c){c&&(d.required=!0,c.$validators.required=function(a,b){return!d.required||!c.$isEmpty(b)},d.$observe("required",function(){c.$validate()}))}}},Mc=function(){return{restrict:"A",require:"?ngModel",link:function(a,b,d,c){if(c){var f,e=d.ngPattern||d.pattern;d.$observe("pattern",function(a){D(a)&&0<a.length&&(a= new RegExp("^"+a+"$"));if(a&&!a.test)throw G("ngPattern")("noregexp",e,a,ya(b));f=a||void 0;c.$validate()});c.$validators.pattern=function(a,b){return c.$isEmpty(b)||z(f)||f.test(b)}}}}},Pc=function(){return{restrict:"A",require:"?ngModel",link:function(a,b,d,c){if(c){var f=-1;d.$observe("maxlength",function(a){a=Z(a);f=ia(a)?-1:a;c.$validate()});c.$validators.maxlength=function(a,b){return 0>f||c.$isEmpty(b)||b.length<=f}}}}},Oc=function(){return{restrict:"A",require:"?ngModel",link:function(a,b, d,c){if(c){var f=0;d.$observe("minlength",function(a){f=Z(a)||0;c.$validate()});c.$validators.minlength=function(a,b){return c.$isEmpty(b)||b.length>=f}}}}};y.angular.bootstrap?y.console&&console.log("WARNING: Tried to load angular more than once."):(xe(),ze($),$.module("ngLocale",[],["$provide",function(a){function b(a){a+="";var b=a.indexOf(".");return-1==b?0:a.length-b-1}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["AM","PM"],DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"],FIRSTDAYOFWEEK:6,MONTH:"January February March April May June July August September October November December".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),STANDALONEMONTH:"January February March April May June July August September October November December".split(" "),WEEKENDRANGE:[5,6],fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",medium:"MMM d, y h:mm:ss a", mediumDate:"MMM d, y",mediumTime:"h:mm:ss a","short":"M/d/yy h:mm a",shortDate:"M/d/yy",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"$",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"-\u00a4",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"en-us",localeID:"en_US",pluralCat:function(a,c){var f=a|0,e=c;void 0===e&&(e=Math.min(b(a),3));Math.pow(10,e);return 1==f&&0== e?"one":"other"}})}]),F(y.document).ready(function(){se(y.document,Gc)}))})(window);!window.angular.$$csp().noInlineStyle&&window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>'); /*! RESOURCE: /scripts/angular_1.5.11/angular-sanitize.min.js */ /* AngularJS v1.5.11 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(s,g){'use strict';function H(g){var l=[];t(l,A).chars(g);return l.join("")}var B=g.$$minErr("$sanitize"),C,l,D,E,q,A,F,t;g.module("ngSanitize",[]).provider("$sanitize",function(){function k(a,e){var b={},c=a.split(","),h;for(h=0;h<c.length;h++)b[e?q(c[h]):c[h]]=!0;return b}function I(a){for(var e={},b=0,c=a.length;b<c;b++){var h=a[b];e[h.name]=h.value}return e}function G(a){return a.replace(/&/g,"&").replace(J,function(a){var b=a.charCodeAt(0);a=a.charCodeAt(1);return"&#"+(1024*(b-55296)+ (a-56320)+65536)+";"}).replace(K,function(a){return"&#"+a.charCodeAt(0)+";"}).replace(/</g,"<").replace(/>/g,">")}function x(a){for(;a;){if(a.nodeType===s.Node.ELEMENT_NODE)for(var e=a.attributes,b=0,c=e.length;b<c;b++){var h=e[b],d=h.name.toLowerCase();if("xmlns:ns1"===d||0===d.lastIndexOf("ns1:",0))a.removeAttributeNode(h),b--,c--}(e=a.firstChild)&&x(e);a=a.nextSibling}}var u=!1;this.$get=["$$sanitizeUri",function(a){u&&l(v,w);return function(e){var b=[];F(e,t(b,function(b,h){return!/^unsafe:/.test(a(b, h))}));return b.join("")}}];this.enableSvg=function(a){return E(a)?(u=a,this):u};C=g.bind;l=g.extend;D=g.forEach;E=g.isDefined;q=g.lowercase;A=g.noop;F=function(a,e){null===a||void 0===a?a="":"string"!==typeof a&&(a=""+a);f.innerHTML=a;var b=5;do{if(0===b)throw B("uinput");b--;s.document.documentMode&&x(f);a=f.innerHTML;f.innerHTML=a}while(a!==f.innerHTML);for(b=f.firstChild;b;){switch(b.nodeType){case 1:e.start(b.nodeName.toLowerCase(),I(b.attributes));break;case 3:e.chars(b.textContent)}var c;if(!(c= b.firstChild)&&(1===b.nodeType&&e.end(b.nodeName.toLowerCase()),c=b.nextSibling,!c))for(;null==c;){b=b.parentNode;if(b===f)break;c=b.nextSibling;1===b.nodeType&&e.end(b.nodeName.toLowerCase())}b=c}for(;b=f.firstChild;)f.removeChild(b)};t=function(a,e){var b=!1,c=C(a,a.push);return{start:function(a,d){a=q(a);!b&&z[a]&&(b=a);b||!0!==v[a]||(c("<"),c(a),D(d,function(b,d){var f=q(d),g="img"===a&&"src"===f||"background"===f;!0!==m[f]||!0===n[f]&&!e(b,g)||(c(" "),c(d),c('="'),c(G(b)),c('"'))}),c(">"))}, end:function(a){a=q(a);b||!0!==v[a]||!0===y[a]||(c("</"),c(a),c(">"));a==b&&(b=!1)},chars:function(a){b||c(G(a))}}};var J=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,K=/([^#-~ |!])/g,y=k("area,br,col,hr,img,wbr"),d=k("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),r=k("rp,rt"),p=l({},r,d),d=l({},d,k("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul")),r=l({},r,k("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")), w=k("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,stop,svg,switch,text,title,tspan"),z=k("script,style"),v=l({},y,d,r,p),n=k("background,cite,href,longdesc,src,xlink:href,xml:base"),p=k("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,valign,value,vspace,width"), r=k("accent-height,accumulate,additive,alphabetic,arabic-form,ascent,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan", !0),m=l({},n,r,p),f;(function(a){if(a.document&&a.document.implementation)a=a.document.implementation.createHTMLDocument("inert");else throw B("noinert");var e=(a.documentElement||a.getDocumentElement()).getElementsByTagName("body");1===e.length?f=e[0]:(e=a.createElement("html"),f=a.createElement("body"),e.appendChild(f),a.appendChild(e))})(s)});g.module("ngSanitize").filter("linky",["$sanitize",function(k){var l=/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, q=/^mailto:/i,x=g.$$minErr("linky"),u=g.isDefined,s=g.isFunction,t=g.isObject,y=g.isString;return function(d,g,p){function w(a){a&&m.push(H(a))}function z(a,b){var c,d=v(a);m.push("<a ");for(c in d)m.push(c+'="'+d[c]+'" ');!u(g)||"target"in d||m.push('target="',g,'" ');m.push('href="',a.replace(/"/g,"""),'">');w(b);m.push("</a>")}if(null==d||""===d)return d;if(!y(d))throw x("notstring",d);for(var v=s(p)?p:t(p)?function(){return p}:function(){return{}},n=d,m=[],f,a;d=n.match(l);)f=d[0],d[2]|| d[4]||(f=(d[3]?"http://":"mailto:")+f),a=d.index,w(n.substr(0,a)),z(f,d[0].replace(q,"")),n=n.substring(a+d[0].length);w(n);return k(m.join(""))}}])})(window,window.angular); /*! RESOURCE: /scripts/angular_1.5.11/angular-animate.min.js */ /* AngularJS v1.5.11-461c892 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(R,B){'use strict';function Da(a,b,c){if(!a)throw Ma("areq",b||"?",c||"required");return a}function Ea(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;X(a)&&(a=a.join(" "));X(b)&&(b=b.join(" "));return a+" "+b}function Na(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function Y(a,b,c){var d="";a=X(a)?a:a&&G(a)&&a.length?a.split(/\s+/):[];s(a,function(a,l){a&&0<a.length&&(d+=0<l?" ":"",d+=c?b+a:a+b)});return d}function Oa(a){if(a instanceof F)switch(a.length){case 0:return a; case 1:if(1===a[0].nodeType)return a;break;default:return F(ta(a))}if(1===a.nodeType)return F(a)}function ta(a){if(!a[0])return a;for(var b=0;b<a.length;b++){var c=a[b];if(1===c.nodeType)return c}}function Pa(a,b,c){s(b,function(b){a.addClass(b,c)})}function Qa(a,b,c){s(b,function(b){a.removeClass(b,c)})}function Z(a){return function(b,c){c.addClass&&(Pa(a,b,c.addClass),c.addClass=null);c.removeClass&&(Qa(a,b,c.removeClass),c.removeClass=null)}}function oa(a){a=a||{};if(!a.$$prepared){var b=a.domOperation|| P;a.domOperation=function(){a.$$domOperationFired=!0;b();b=P};a.$$prepared=!0}return a}function ha(a,b){Fa(a,b);Ga(a,b)}function Fa(a,b){b.from&&(a.css(b.from),b.from=null)}function Ga(a,b){b.to&&(a.css(b.to),b.to=null)}function V(a,b,c){var d=b.options||{};c=c.options||{};var e=(d.addClass||"")+" "+(c.addClass||""),l=(d.removeClass||"")+" "+(c.removeClass||"");a=Ra(a.attr("class"),e,l);c.preparationClasses&&(d.preparationClasses=$(c.preparationClasses,d.preparationClasses),delete c.preparationClasses); e=d.domOperation!==P?d.domOperation:null;ua(d,c);e&&(d.domOperation=e);d.addClass=a.addClass?a.addClass:null;d.removeClass=a.removeClass?a.removeClass:null;b.addClass=d.addClass;b.removeClass=d.removeClass;return d}function Ra(a,b,c){function d(a){G(a)&&(a=a.split(" "));var b={};s(a,function(a){a.length&&(b[a]=!0)});return b}var e={};a=d(a);b=d(b);s(b,function(a,b){e[b]=1});c=d(c);s(c,function(a,b){e[b]=1===e[b]?null:-1});var l={addClass:"",removeClass:""};s(e,function(b,c){var d,e;1===b?(d="addClass", e=!a[c]||a[c+"-remove"]):-1===b&&(d="removeClass",e=a[c]||a[c+"-add"]);e&&(l[d].length&&(l[d]+=" "),l[d]+=c)});return l}function y(a){return a instanceof F?a[0]:a}function Sa(a,b,c){var d="";b&&(d=Y(b,"ng-",!0));c.addClass&&(d=$(d,Y(c.addClass,"-add")));c.removeClass&&(d=$(d,Y(c.removeClass,"-remove")));d.length&&(c.preparationClasses=d,a.addClass(d))}function pa(a,b){var c=b?"-"+b+"s":"";la(a,[ma,c]);return[ma,c]}function va(a,b){var c=b?"paused":"",d=aa+"PlayState";la(a,[d,c]);return[d,c]}function la(a, b){a.style[b[0]]=b[1]}function $(a,b){return a?b?a+" "+b:a:b}function Ha(a,b,c){var d=Object.create(null),e=a.getComputedStyle(b)||{};s(c,function(a,b){var c=e[a];if(c){var g=c.charAt(0);if("-"===g||"+"===g||0<=g)c=Ta(c);0===c&&(c=null);d[b]=c}});return d}function Ta(a){var b=0;a=a.split(/\s*,\s*/);s(a,function(a){"s"===a.charAt(a.length-1)&&(a=a.substring(0,a.length-1));a=parseFloat(a)||0;b=b?Math.max(a,b):a});return b}function wa(a){return 0===a||null!=a}function Ia(a,b){var c=S,d=a+"s";b?c+="Duration": d+=" linear all";return[c,d]}function Ja(){var a=Object.create(null);return{flush:function(){a=Object.create(null)},count:function(b){return(b=a[b])?b.total:0},get:function(b){return(b=a[b])&&b.value},put:function(b,c){a[b]?a[b].total++:a[b]={total:1,value:c}}}}function Ka(a,b,c){s(c,function(c){a[c]=xa(a[c])?a[c]:b.style.getPropertyValue(c)})}var S,ya,aa,za;void 0===R.ontransitionend&&void 0!==R.onwebkittransitionend?(S="WebkitTransition",ya="webkitTransitionEnd transitionend"):(S="transition",ya= "transitionend");void 0===R.onanimationend&&void 0!==R.onwebkitanimationend?(aa="WebkitAnimation",za="webkitAnimationEnd animationend"):(aa="animation",za="animationend");var qa=aa+"Delay",Aa=aa+"Duration",ma=S+"Delay",La=S+"Duration",Ma=B.$$minErr("ng"),Ua={transitionDuration:La,transitionDelay:ma,transitionProperty:S+"Property",animationDuration:Aa,animationDelay:qa,animationIterationCount:aa+"IterationCount"},Va={transitionDuration:La,transitionDelay:ma,animationDuration:Aa,animationDelay:qa}, Ba,ua,s,X,xa,ea,Ca,ba,G,J,F,P;B.module("ngAnimate",[],function(){P=B.noop;Ba=B.copy;ua=B.extend;F=B.element;s=B.forEach;X=B.isArray;G=B.isString;ba=B.isObject;J=B.isUndefined;xa=B.isDefined;Ca=B.isFunction;ea=B.isElement}).directive("ngAnimateSwap",["$animate","$rootScope",function(a,b){return{restrict:"A",transclude:"element",terminal:!0,priority:600,link:function(b,d,e,l,n){var I,g;b.$watchCollection(e.ngAnimateSwap||e["for"],function(e){I&&a.leave(I);g&&(g.$destroy(),g=null);if(e||0===e)g=b.$new(), n(g,function(b){I=b;a.enter(b,null,d)})})}}}]).directive("ngAnimateChildren",["$interpolate",function(a){return{link:function(b,c,d){function e(a){c.data("$$ngAnimateChildren","on"===a||"true"===a)}var l=d.ngAnimateChildren;G(l)&&0===l.length?c.data("$$ngAnimateChildren",!0):(e(a(l)(b)),d.$observe("ngAnimateChildren",e))}}}]).factory("$$rAFScheduler",["$$rAF",function(a){function b(a){d=d.concat(a);c()}function c(){if(d.length){for(var b=d.shift(),n=0;n<b.length;n++)b[n]();e||a(function(){e||c()})}} var d,e;d=b.queue=[];b.waitUntilQuiet=function(b){e&&e();e=a(function(){e=null;b();c()})};return b}]).provider("$$animateQueue",["$animateProvider",function(a){function b(a){if(!a)return null;a=a.split(" ");var b=Object.create(null);s(a,function(a){b[a]=!0});return b}function c(a,c){if(a&&c){var d=b(c);return a.split(" ").some(function(a){return d[a]})}}function d(a,b,c,d){return l[a].some(function(a){return a(b,c,d)})}function e(a,b){var c=0<(a.addClass||"").length,d=0<(a.removeClass||"").length; return b?c&&d:c||d}var l=this.rules={skip:[],cancel:[],join:[]};l.join.push(function(a,b,c){return!b.structural&&e(b)});l.skip.push(function(a,b,c){return!b.structural&&!e(b)});l.skip.push(function(a,b,c){return"leave"===c.event&&b.structural});l.skip.push(function(a,b,c){return c.structural&&2===c.state&&!b.structural});l.cancel.push(function(a,b,c){return c.structural&&b.structural});l.cancel.push(function(a,b,c){return 2===c.state&&b.structural});l.cancel.push(function(a,b,d){if(d.structural)return!1; a=b.addClass;b=b.removeClass;var e=d.addClass;d=d.removeClass;return J(a)&&J(b)||J(e)&&J(d)?!1:c(a,d)||c(b,e)});this.$get=["$$rAF","$rootScope","$rootElement","$document","$$HashMap","$$animation","$$AnimateRunner","$templateRequest","$$jqLite","$$forceReflow",function(b,c,g,l,C,Wa,Q,t,H,T){function O(){var a=!1;return function(b){a?b():c.$$postDigest(function(){a=!0;b()})}}function x(a,b,c){var f=y(b),d=y(a),N=[];(a=h[c])&&s(a,function(a){w.call(a.node,f)?N.push(a.callback):"leave"===c&&w.call(a.node, d)&&N.push(a.callback)});return N}function r(a,b,c){var f=ta(b);return a.filter(function(a){return!(a.node===f&&(!c||a.callback===c))})}function p(a,h,v){function r(c,f,d,h){sa(function(){var c=x(T,a,f);c.length?b(function(){s(c,function(b){b(a,d,h)});"close"!==d||a[0].parentNode||ra.off(a)}):"close"!==d||a[0].parentNode||ra.off(a)});c.progress(f,d,h)}function k(b){var c=a,f=m;f.preparationClasses&&(c.removeClass(f.preparationClasses),f.preparationClasses=null);f.activeClasses&&(c.removeClass(f.activeClasses), f.activeClasses=null);E(a,m);ha(a,m);m.domOperation();A.complete(!b)}var m=Ba(v),p,T;if(a=Oa(a))p=y(a),T=a.parent();var m=oa(m),A=new Q,sa=O();X(m.addClass)&&(m.addClass=m.addClass.join(" "));m.addClass&&!G(m.addClass)&&(m.addClass=null);X(m.removeClass)&&(m.removeClass=m.removeClass.join(" "));m.removeClass&&!G(m.removeClass)&&(m.removeClass=null);m.from&&!ba(m.from)&&(m.from=null);m.to&&!ba(m.to)&&(m.to=null);if(!p)return k(),A;v=[p.className,m.addClass,m.removeClass].join(" ");if(!Xa(v))return k(), A;var g=0<=["enter","move","leave"].indexOf(h),w=l[0].hidden,t=!f||w||N.get(p);v=!t&&z.get(p)||{};var H=!!v.state;t||H&&1===v.state||(t=!M(a,T,h));if(t)return w&&r(A,h,"start"),k(),w&&r(A,h,"close"),A;g&&K(a);w={structural:g,element:a,event:h,addClass:m.addClass,removeClass:m.removeClass,close:k,options:m,runner:A};if(H){if(d("skip",a,w,v)){if(2===v.state)return k(),A;V(a,v,w);return v.runner}if(d("cancel",a,w,v))if(2===v.state)v.runner.end();else if(v.structural)v.close();else return V(a,v,w),v.runner; else if(d("join",a,w,v))if(2===v.state)V(a,w,{});else return Sa(a,g?h:null,m),h=w.event=v.event,m=V(a,v,w),v.runner}else V(a,w,{});(H=w.structural)||(H="animate"===w.event&&0<Object.keys(w.options.to||{}).length||e(w));if(!H)return k(),ka(a),A;var C=(v.counter||0)+1;w.counter=C;L(a,1,w);c.$$postDigest(function(){var b=z.get(p),c=!b,b=b||{},f=0<(a.parent()||[]).length&&("animate"===b.event||b.structural||e(b));if(c||b.counter!==C||!f){c&&(E(a,m),ha(a,m));if(c||g&&b.event!==h)m.domOperation(),A.end(); f||ka(a)}else h=!b.structural&&e(b,!0)?"setClass":b.event,L(a,2),b=Wa(a,h,b.options),A.setHost(b),r(A,h,"start",{}),b.done(function(b){k(!b);(b=z.get(p))&&b.counter===C&&ka(y(a));r(A,h,"close",{})})});return A}function K(a){a=y(a).querySelectorAll("[data-ng-animate]");s(a,function(a){var b=parseInt(a.getAttribute("data-ng-animate"),10),c=z.get(a);if(c)switch(b){case 2:c.runner.end();case 1:z.remove(a)}})}function ka(a){a=y(a);a.removeAttribute("data-ng-animate");z.remove(a)}function k(a,b){return y(a)=== y(b)}function M(a,b,c){c=F(l[0].body);var f=k(a,c)||"HTML"===a[0].nodeName,d=k(a,g),h=!1,r,e=N.get(y(a));(a=F.data(a[0],"$ngAnimatePin"))&&(b=a);for(b=y(b);b;){d||(d=k(b,g));if(1!==b.nodeType)break;a=z.get(b)||{};if(!h){var p=N.get(b);if(!0===p&&!1!==e){e=!0;break}else!1===p&&(e=!1);h=a.structural}if(J(r)||!0===r)a=F.data(b,"$$ngAnimateChildren"),xa(a)&&(r=a);if(h&&!1===r)break;f||(f=k(b,c));if(f&&d)break;if(!d&&(a=F.data(b,"$ngAnimatePin"))){b=y(a);continue}b=b.parentNode}return(!h||r)&&!0!==e&& d&&f}function L(a,b,c){c=c||{};c.state=b;a=y(a);a.setAttribute("data-ng-animate",b);c=(b=z.get(a))?ua(b,c):c;z.put(a,c)}var z=new C,N=new C,f=null,A=c.$watch(function(){return 0===t.totalPendingRequests},function(a){a&&(A(),c.$$postDigest(function(){c.$$postDigest(function(){null===f&&(f=!0)})}))}),h=Object.create(null),sa=a.classNameFilter(),Xa=sa?function(a){return sa.test(a)}:function(){return!0},E=Z(H),w=R.Node.prototype.contains||function(a){return this===a||!!(this.compareDocumentPosition(a)& 16)},ra={on:function(a,b,c){var f=ta(b);h[a]=h[a]||[];h[a].push({node:f,callback:c});F(b).on("$destroy",function(){z.get(f)||ra.off(a,b,c)})},off:function(a,b,c){if(1!==arguments.length||G(arguments[0])){var f=h[a];f&&(h[a]=1===arguments.length?null:r(f,b,c))}else for(f in b=arguments[0],h)h[f]=r(h[f],b)},pin:function(a,b){Da(ea(a),"element","not an element");Da(ea(b),"parentElement","not an element");a.data("$ngAnimatePin",b)},push:function(a,b,c,f){c=c||{};c.domOperation=f;return p(a,b,c)},enabled:function(a, b){var c=arguments.length;if(0===c)b=!!f;else if(ea(a)){var d=y(a);1===c?b=!N.get(d):N.put(d,!b)}else b=f=!!a;return b}};return ra}]}]).provider("$$animation",["$animateProvider",function(a){var b=this.drivers=[];this.$get=["$$jqLite","$rootScope","$injector","$$AnimateRunner","$$HashMap","$$rAFScheduler",function(a,d,e,l,n,I){function g(a){function b(a){if(a.processed)return a;a.processed=!0;var d=a.domNode,p=d.parentNode;e.put(d,a);for(var K;p;){if(K=e.get(p)){K.processed||(K=b(K));break}p=p.parentNode}(K|| c).children.push(a);return a}var c={children:[]},d,e=new n;for(d=0;d<a.length;d++){var g=a[d];e.put(g.domNode,a[d]={domNode:g.domNode,fn:g.fn,children:[]})}for(d=0;d<a.length;d++)b(a[d]);return function(a){var b=[],c=[],d;for(d=0;d<a.children.length;d++)c.push(a.children[d]);a=c.length;var e=0,k=[];for(d=0;d<c.length;d++){var g=c[d];0>=a&&(a=e,e=0,b.push(k),k=[]);k.push(g.fn);g.children.forEach(function(a){e++;c.push(a)});a--}k.length&&b.push(k);return b}(c)}var u=[],C=Z(a);return function(n,Q,t){function H(a){a= a.hasAttribute("ng-animate-ref")?[a]:a.querySelectorAll("[ng-animate-ref]");var b=[];s(a,function(a){var c=a.getAttribute("ng-animate-ref");c&&c.length&&b.push(a)});return b}function T(a){var b=[],c={};s(a,function(a,d){var h=y(a.element),e=0<=["enter","move"].indexOf(a.event),h=a.structural?H(h):[];if(h.length){var k=e?"to":"from";s(h,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]||{};c[b][k]={animationID:d,element:F(a)}})}else b.push(a)});var d={},e={};s(c,function(c,k){var r=c.from, p=c.to;if(r&&p){var z=a[r.animationID],g=a[p.animationID],A=r.animationID.toString();if(!e[A]){var n=e[A]={structural:!0,beforeStart:function(){z.beforeStart();g.beforeStart()},close:function(){z.close();g.close()},classes:O(z.classes,g.classes),from:z,to:g,anchors:[]};n.classes.length?b.push(n):(b.push(z),b.push(g))}e[A].anchors.push({out:r.element,"in":p.element})}else r=r?r.animationID:p.animationID,p=r.toString(),d[p]||(d[p]=!0,b.push(a[r]))});return b}function O(a,b){a=a.split(" ");b=b.split(" "); for(var c=[],d=0;d<a.length;d++){var e=a[d];if("ng-"!==e.substring(0,3))for(var r=0;r<b.length;r++)if(e===b[r]){c.push(e);break}}return c.join(" ")}function x(a){for(var c=b.length-1;0<=c;c--){var d=e.get(b[c])(a);if(d)return d}}function r(a,b){function c(a){(a=a.data("$$animationRunner"))&&a.setHost(b)}a.from&&a.to?(c(a.from.element),c(a.to.element)):c(a.element)}function p(){var a=n.data("$$animationRunner");!a||"leave"===Q&&t.$$domOperationFired||a.end()}function K(b){n.off("$destroy",p);n.removeData("$$animationRunner"); C(n,t);ha(n,t);t.domOperation();L&&a.removeClass(n,L);n.removeClass("ng-animate");k.complete(!b)}t=oa(t);var ka=0<=["enter","move","leave"].indexOf(Q),k=new l({end:function(){K()},cancel:function(){K(!0)}});if(!b.length)return K(),k;n.data("$$animationRunner",k);var M=Ea(n.attr("class"),Ea(t.addClass,t.removeClass)),L=t.tempClasses;L&&(M+=" "+L,t.tempClasses=null);var z;ka&&(z="ng-"+Q+"-prepare",a.addClass(n,z));u.push({element:n,classes:M,event:Q,structural:ka,options:t,beforeStart:function(){n.addClass("ng-animate"); L&&a.addClass(n,L);z&&(a.removeClass(n,z),z=null)},close:K});n.on("$destroy",p);if(1<u.length)return k;d.$$postDigest(function(){var a=[];s(u,function(b){b.element.data("$$animationRunner")?a.push(b):b.close()});u.length=0;var b=T(a),c=[];s(b,function(a){c.push({domNode:y(a.from?a.from.element:a.element),fn:function(){a.beforeStart();var b,c=a.close;if((a.anchors?a.from.element||a.to.element:a.element).data("$$animationRunner")){var d=x(a);d&&(b=d.start)}b?(b=b(),b.done(function(a){c(!a)}),r(a,b)): c()}})});I(g(c))});return k}}]}]).provider("$animateCss",["$animateProvider",function(a){var b=Ja(),c=Ja();this.$get=["$window","$$jqLite","$$AnimateRunner","$timeout","$$forceReflow","$sniffer","$$rAFScheduler","$$animateQueue",function(a,e,l,n,I,g,u,C){function B(a,b){var c=a.parentNode;return(c.$$ngAnimateParentKey||(c.$$ngAnimateParentKey=++O))+"-"+a.getAttribute("class")+"-"+b}function Q(r,p,g,n){var k;0<b.count(g)&&(k=c.get(g),k||(p=Y(p,"-stagger"),e.addClass(r,p),k=Ha(a,r,n),k.animationDuration= Math.max(k.animationDuration,0),k.transitionDuration=Math.max(k.transitionDuration,0),e.removeClass(r,p),c.put(g,k)));return k||{}}function t(a){x.push(a);u.waitUntilQuiet(function(){b.flush();c.flush();for(var a=I(),d=0;d<x.length;d++)x[d](a);x.length=0})}function H(c,e,g){e=b.get(g);e||(e=Ha(a,c,Ua),"infinite"===e.animationIterationCount&&(e.animationIterationCount=1));b.put(g,e);c=e;g=c.animationDelay;e=c.transitionDelay;c.maxDelay=g&&e?Math.max(g,e):g||e;c.maxDuration=Math.max(c.animationDuration* c.animationIterationCount,c.transitionDuration);return c}var T=Z(e),O=0,x=[];return function(a,c){function d(){k()}function u(){k(!0)}function k(b){if(!(w||F&&O)){w=!0;O=!1;f.$$skipPreparationClasses||e.removeClass(a,ga);e.removeClass(a,ea);va(h,!1);pa(h,!1);s(x,function(a){h.style[a[0]]=""});T(a,f);ha(a,f);Object.keys(A).length&&s(A,function(a,b){a?h.style.setProperty(b,a):h.style.removeProperty(b)});if(f.onDone)f.onDone();fa&&fa.length&&a.off(fa.join(" "),z);var c=a.data("$$animateCss");c&&(n.cancel(c[0].timer), a.removeData("$$animateCss"));G&&G.complete(!b)}}function M(a){q.blockTransition&&pa(h,a);q.blockKeyframeAnimation&&va(h,!!a)}function L(){G=new l({end:d,cancel:u});t(P);k();return{$$willAnimate:!1,start:function(){return G},end:d}}function z(a){a.stopPropagation();var b=a.originalEvent||a;a=b.$manualTimeStamp||Date.now();b=parseFloat(b.elapsedTime.toFixed(3));Math.max(a-Z,0)>=R&&b>=m&&(F=!0,k())}function N(){function b(){if(!w){M(!1);s(x,function(a){h.style[a[0]]=a[1]});T(a,f);e.addClass(a,ea);if(q.recalculateTimingStyles){na= h.className+" "+ga;ia=B(h,na);D=H(h,na,ia);ca=D.maxDelay;J=Math.max(ca,0);m=D.maxDuration;if(0===m){k();return}q.hasTransitions=0<D.transitionDuration;q.hasAnimations=0<D.animationDuration}q.applyAnimationDelay&&(ca="boolean"!==typeof f.delay&&wa(f.delay)?parseFloat(f.delay):ca,J=Math.max(ca,0),D.animationDelay=ca,da=[qa,ca+"s"],x.push(da),h.style[da[0]]=da[1]);R=1E3*J;V=1E3*m;if(f.easing){var d,g=f.easing;q.hasTransitions&&(d=S+"TimingFunction",x.push([d,g]),h.style[d]=g);q.hasAnimations&&(d=aa+ "TimingFunction",x.push([d,g]),h.style[d]=g)}D.transitionDuration&&fa.push(ya);D.animationDuration&&fa.push(za);Z=Date.now();var p=R+1.5*V;d=Z+p;var g=a.data("$$animateCss")||[],N=!0;if(g.length){var l=g[0];(N=d>l.expectedEndTime)?n.cancel(l.timer):g.push(k)}N&&(p=n(c,p,!1),g[0]={timer:p,expectedEndTime:d},g.push(k),a.data("$$animateCss",g));if(fa.length)a.on(fa.join(" "),z);f.to&&(f.cleanupStyles&&Ka(A,h,Object.keys(f.to)),Ga(a,f))}}function c(){var b=a.data("$$animateCss");if(b){for(var d=1;d<b.length;d++)b[d](); a.removeData("$$animateCss")}}if(!w)if(h.parentNode){var d=function(a){if(F)O&&a&&(O=!1,k());else if(O=!a,D.animationDuration)if(a=va(h,O),O)x.push(a);else{var b=x,c=b.indexOf(a);0<=a&&b.splice(c,1)}},g=0<ba&&(D.transitionDuration&&0===W.transitionDuration||D.animationDuration&&0===W.animationDuration)&&Math.max(W.animationDelay,W.transitionDelay);g?n(b,Math.floor(g*ba*1E3),!1):b();v.resume=function(){d(!0)};v.pause=function(){d(!1)}}else k()}var f=c||{};f.$$prepared||(f=oa(Ba(f)));var A={},h=y(a); if(!h||!h.parentNode||!C.enabled())return L();var x=[],I=a.attr("class"),E=Na(f),w,O,F,G,v,J,R,m,V,Z,fa=[];if(0===f.duration||!g.animations&&!g.transitions)return L();var ja=f.event&&X(f.event)?f.event.join(" "):f.event,$="",U="";ja&&f.structural?$=Y(ja,"ng-",!0):ja&&($=ja);f.addClass&&(U+=Y(f.addClass,"-add"));f.removeClass&&(U.length&&(U+=" "),U+=Y(f.removeClass,"-remove"));f.applyClassesEarly&&U.length&&T(a,f);var ga=[$,U].join(" ").trim(),na=I+" "+ga,ea=Y(ga,"-active"),I=E.to&&0<Object.keys(E.to).length; if(!(0<(f.keyframeStyle||"").length||I||ga))return L();var ia,W;0<f.stagger?(E=parseFloat(f.stagger),W={transitionDelay:E,animationDelay:E,transitionDuration:0,animationDuration:0}):(ia=B(h,na),W=Q(h,ga,ia,Va));f.$$skipPreparationClasses||e.addClass(a,ga);f.transitionStyle&&(E=[S,f.transitionStyle],la(h,E),x.push(E));0<=f.duration&&(E=0<h.style[S].length,E=Ia(f.duration,E),la(h,E),x.push(E));f.keyframeStyle&&(E=[aa,f.keyframeStyle],la(h,E),x.push(E));var ba=W?0<=f.staggerIndex?f.staggerIndex:b.count(ia): 0;(ja=0===ba)&&!f.skipBlocking&&pa(h,9999);var D=H(h,na,ia),ca=D.maxDelay;J=Math.max(ca,0);m=D.maxDuration;var q={};q.hasTransitions=0<D.transitionDuration;q.hasAnimations=0<D.animationDuration;q.hasTransitionAll=q.hasTransitions&&"all"===D.transitionProperty;q.applyTransitionDuration=I&&(q.hasTransitions&&!q.hasTransitionAll||q.hasAnimations&&!q.hasTransitions);q.applyAnimationDuration=f.duration&&q.hasAnimations;q.applyTransitionDelay=wa(f.delay)&&(q.applyTransitionDuration||q.hasTransitions);q.applyAnimationDelay= wa(f.delay)&&q.hasAnimations;q.recalculateTimingStyles=0<U.length;if(q.applyTransitionDuration||q.applyAnimationDuration)m=f.duration?parseFloat(f.duration):m,q.applyTransitionDuration&&(q.hasTransitions=!0,D.transitionDuration=m,E=0<h.style[S+"Property"].length,x.push(Ia(m,E))),q.applyAnimationDuration&&(q.hasAnimations=!0,D.animationDuration=m,x.push([Aa,m+"s"]));if(0===m&&!q.recalculateTimingStyles)return L();if(null!=f.delay){var da;"boolean"!==typeof f.delay&&(da=parseFloat(f.delay),J=Math.max(da, 0));q.applyTransitionDelay&&x.push([ma,da+"s"]);q.applyAnimationDelay&&x.push([qa,da+"s"])}null==f.duration&&0<D.transitionDuration&&(q.recalculateTimingStyles=q.recalculateTimingStyles||ja);R=1E3*J;V=1E3*m;f.skipBlocking||(q.blockTransition=0<D.transitionDuration,q.blockKeyframeAnimation=0<D.animationDuration&&0<W.animationDelay&&0===W.animationDuration);f.from&&(f.cleanupStyles&&Ka(A,h,Object.keys(f.from)),Fa(a,f));q.blockTransition||q.blockKeyframeAnimation?M(m):f.skipBlocking||pa(h,!1);return{$$willAnimate:!0, end:d,start:function(){if(!w)return v={end:d,cancel:u,resume:null,pause:null},G=new l(v),t(N),G}}}}]}]).provider("$$animateCssDriver",["$$animationProvider",function(a){a.drivers.push("$$animateCssDriver");this.$get=["$animateCss","$rootScope","$$AnimateRunner","$rootElement","$sniffer","$$jqLite","$document",function(a,c,d,e,l,n,I){function g(a){return a.replace(/\bng-\S+\b/g,"")}function u(a,b){G(a)&&(a=a.split(" "));G(b)&&(b=b.split(" "));return a.filter(function(a){return-1===b.indexOf(a)}).join(" ")} function C(c,e,n){function l(a){var b={},c=y(a).getBoundingClientRect();s(["width","height","top","left"],function(a){var d=c[a];switch(a){case "top":d+=t.scrollTop;break;case "left":d+=t.scrollLeft}b[a]=Math.floor(d)+"px"});return b}function p(){var c=g(n.attr("class")||""),d=u(c,k),c=u(k,c),d=a(C,{to:l(n),addClass:"ng-anchor-in "+d,removeClass:"ng-anchor-out "+c,delay:!0});return d.$$willAnimate?d:null}function I(){C.remove();e.removeClass("ng-animate-shim");n.removeClass("ng-animate-shim")}var C= F(y(e).cloneNode(!0)),k=g(C.attr("class")||"");e.addClass("ng-animate-shim");n.addClass("ng-animate-shim");C.addClass("ng-anchor");H.append(C);var M;c=function(){var c=a(C,{addClass:"ng-anchor-out",delay:!0,from:l(e)});return c.$$willAnimate?c:null}();if(!c&&(M=p(),!M))return I();var L=c||M;return{start:function(){function a(){c&&c.end()}var b,c=L.start();c.done(function(){c=null;if(!M&&(M=p()))return c=M.start(),c.done(function(){c=null;I();b.complete()}),c;I();b.complete()});return b=new d({end:a, cancel:a})}}}function B(a,b,c,e){var g=Q(a,P),n=Q(b,P),l=[];s(e,function(a){(a=C(c,a.out,a["in"]))&&l.push(a)});if(g||n||0!==l.length)return{start:function(){function a(){s(b,function(a){a.end()})}var b=[];g&&b.push(g.start());n&&b.push(n.start());s(l,function(a){b.push(a.start())});var c=new d({end:a,cancel:a});d.all(b,function(a){c.complete(a)});return c}}}function Q(c){var d=c.element,e=c.options||{};c.structural&&(e.event=c.event,e.structural=!0,e.applyClassesEarly=!0,"leave"===c.event&&(e.onDone= e.domOperation));e.preparationClasses&&(e.event=$(e.event,e.preparationClasses));c=a(d,e);return c.$$willAnimate?c:null}if(!l.animations&&!l.transitions)return P;var t=I[0].body;c=y(e);var H=F(c.parentNode&&11===c.parentNode.nodeType||t.contains(c)?c:t);return function(a){return a.from&&a.to?B(a.from,a.to,a.classes,a.anchors):Q(a)}}]}]).provider("$$animateJs",["$animateProvider",function(a){this.$get=["$injector","$$AnimateRunner","$$jqLite",function(b,c,d){function e(c){c=X(c)?c:c.split(" ");for(var d= [],e={},l=0;l<c.length;l++){var s=c[l],B=a.$$registeredAnimations[s];B&&!e[s]&&(d.push(b.get(B)),e[s]=!0)}return d}var l=Z(d);return function(a,b,d,u){function C(){u.domOperation();l(a,u)}function B(a,b,d,e,f){switch(d){case "animate":b=[b,e.from,e.to,f];break;case "setClass":b=[b,F,G,f];break;case "addClass":b=[b,F,f];break;case "removeClass":b=[b,G,f];break;default:b=[b,f]}b.push(e);if(a=a.apply(a,b))if(Ca(a.start)&&(a=a.start()),a instanceof c)a.done(f);else if(Ca(a))return a;return P}function y(a, b,d,e,f){var g=[];s(e,function(e){var k=e[f];k&&g.push(function(){var e,f,g=!1,h=function(a){g||(g=!0,(f||P)(a),e.complete(!a))};e=new c({end:function(){h()},cancel:function(){h(!0)}});f=B(k,a,b,d,function(a){h(!1===a)});return e})});return g}function t(a,b,d,e,f){var g=y(a,b,d,e,f);if(0===g.length){var h,k;"beforeSetClass"===f?(h=y(a,"removeClass",d,e,"beforeRemoveClass"),k=y(a,"addClass",d,e,"beforeAddClass")):"setClass"===f&&(h=y(a,"removeClass",d,e,"removeClass"),k=y(a,"addClass",d,e,"addClass")); h&&(g=g.concat(h));k&&(g=g.concat(k))}if(0!==g.length)return function(a){var b=[];g.length&&s(g,function(a){b.push(a())});b.length?c.all(b,a):a();return function(a){s(b,function(b){a?b.cancel():b.end()})}}}var H=!1;3===arguments.length&&ba(d)&&(u=d,d=null);u=oa(u);d||(d=a.attr("class")||"",u.addClass&&(d+=" "+u.addClass),u.removeClass&&(d+=" "+u.removeClass));var F=u.addClass,G=u.removeClass,x=e(d),r,p;if(x.length){var K,J;"leave"===b?(J="leave",K="afterLeave"):(J="before"+b.charAt(0).toUpperCase()+ b.substr(1),K=b);"enter"!==b&&"move"!==b&&(r=t(a,b,u,x,J));p=t(a,b,u,x,K)}if(r||p){var k;return{$$willAnimate:!0,end:function(){k?k.end():(H=!0,C(),ha(a,u),k=new c,k.complete(!0));return k},start:function(){function b(c){H=!0;C();ha(a,u);k.complete(c)}if(k)return k;k=new c;var d,e=[];r&&e.push(function(a){d=r(a)});e.length?e.push(function(a){C();a(!0)}):C();p&&e.push(function(a){d=p(a)});k.setHost({end:function(){H||((d||P)(void 0),b(void 0))},cancel:function(){H||((d||P)(!0),b(!0))}});c.chain(e, b);return k}}}}}]}]).provider("$$animateJsDriver",["$$animationProvider",function(a){a.drivers.push("$$animateJsDriver");this.$get=["$$animateJs","$$AnimateRunner",function(a,c){function d(c){return a(c.element,c.event,c.classes,c.options)}return function(a){if(a.from&&a.to){var b=d(a.from),n=d(a.to);if(b||n)return{start:function(){function a(){return function(){s(d,function(a){a.end()})}}var d=[];b&&d.push(b.start());n&&d.push(n.start());c.all(d,function(a){e.complete(a)});var e=new c({end:a(),cancel:a()}); return e}}}else return d(a)}}]}])})(window,window.angular); /*! RESOURCE: /scripts/angular_1.5.11/angular-resource.min.js */ /* AngularJS v1.5.11-461c892 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(R,b){'use strict';function G(s,g){g=g||{};b.forEach(g,function(b,k){delete g[k]});for(var k in s)!s.hasOwnProperty(k)||"$"===k.charAt(0)&&"$"===k.charAt(1)||(g[k]=s[k]);return g}var y=b.$$minErr("$resource"),N=/^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;b.module("ngResource",["ng"]).provider("$resource",function(){var s=/^https?:\/\/[^/]*/,g=this;this.defaults={stripTrailingSlashes:!0,cancellable:!1,actions:{get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"}, "delete":{method:"DELETE"}}};this.$get=["$http","$log","$q","$timeout",function(k,M,H,I){function z(b,e){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,e?"%20":"+")}function B(b,e){this.template=b;this.defaults=r({},g.defaults,e);this.urlParams={}}function J(A,e,p,m){function c(a,d){var c={};d=r({},e,d);u(d,function(d,e){w(d)&&(d=d(a));var f;if(d&&d.charAt&&"@"===d.charAt(0)){f=a;var l=d.substr(1);if(null==l||""===l|| "hasOwnProperty"===l||!N.test("."+l))throw y("badmember",l);for(var l=l.split("."),h=0,g=l.length;h<g&&b.isDefined(f);h++){var q=l[h];f=null!==f?f[q]:void 0}}else f=d;c[e]=f});return c}function O(a){return a.resource}function h(a){G(a||{},this)}var s=new B(A,m);p=r({},g.defaults.actions,p);h.prototype.toJSON=function(){var a=r({},this);delete a.$promise;delete a.$resolved;delete a.$cancelRequest;return a};u(p,function(a,d){var b=/^(POST|PUT|PATCH)$/i.test(a.method),e=a.timeout,g=K(a.cancellable)? a.cancellable:s.defaults.cancellable;e&&!P(e)&&(M.debug("ngResource:\n Only numeric values are allowed as `timeout`.\n Promises are not supported in $resource, because the same value would be used for multiple requests. If you are looking for a way to cancel requests, you should use the `cancellable` option."),delete a.timeout,e=null);h[d]=function(f,l,m,A){var q={},p,v,C;switch(arguments.length){case 4:C=A,v=m;case 3:case 2:if(w(l)){if(w(f)){v=f;C=l;break}v=l;C=m}else{q=f;p=l;v=m;break}case 1:w(f)? v=f:b?p=f:q=f;break;case 0:break;default:throw y("badargs",arguments.length);}var D=this instanceof h,n=D?p:a.isArray?[]:new h(p),t={},z=a.interceptor&&a.interceptor.response||O,B=a.interceptor&&a.interceptor.responseError||void 0,x,E;u(a,function(a,d){switch(d){default:t[d]=Q(a);case "params":case "isArray":case "interceptor":case "cancellable":}});!D&&g&&(x=H.defer(),t.timeout=x.promise,e&&(E=I(x.resolve,e)));b&&(t.data=p);s.setUrlParams(t,r({},c(p,a.params||{}),q),a.url);q=k(t).then(function(f){var c= f.data;if(c){if(L(c)!==!!a.isArray)throw y("badcfg",d,a.isArray?"array":"object",L(c)?"array":"object",t.method,t.url);if(a.isArray)n.length=0,u(c,function(a){"object"===typeof a?n.push(new h(a)):n.push(a)});else{var b=n.$promise;G(c,n);n.$promise=b}}f.resource=n;return f},function(a){(C||F)(a);return H.reject(a)});q["finally"](function(){n.$resolved=!0;!D&&g&&(n.$cancelRequest=F,I.cancel(E),x=E=t.timeout=null)});q=q.then(function(a){var d=z(a);(v||F)(d,a.headers,a.status,a.statusText);return d}, B);return D?q:(n.$promise=q,n.$resolved=!1,g&&(n.$cancelRequest=x.resolve),n)};h.prototype["$"+d]=function(a,c,b){w(a)&&(b=c,c=a,a={});a=h[d].call(this,a,this,c,b);return a.$promise||a}});h.bind=function(a){a=r({},e,a);return J(A,a,p,m)};return h}var F=b.noop,u=b.forEach,r=b.extend,Q=b.copy,L=b.isArray,K=b.isDefined,w=b.isFunction,P=b.isNumber;B.prototype={setUrlParams:function(b,e,g){var m=this,c=g||m.template,k,h,r="",a=m.urlParams={};u(c.split(/\W/),function(d){if("hasOwnProperty"===d)throw y("badname"); !/^\d+$/.test(d)&&d&&(new RegExp("(^|[^\\\\]):"+d+"(\\W|$)")).test(c)&&(a[d]={isQueryParamValue:(new RegExp("\\?.*=:"+d+"(?:\\W|$)")).test(c)})});c=c.replace(/\\:/g,":");c=c.replace(s,function(a){r=a;return""});e=e||{};u(m.urlParams,function(a,b){k=e.hasOwnProperty(b)?e[b]:m.defaults[b];K(k)&&null!==k?(h=a.isQueryParamValue?z(k,!0):z(k,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+"),c=c.replace(new RegExp(":"+b+"(\\W|$)","g"),function(a,b){return h+b})):c=c.replace(new RegExp("(/?):"+ b+"(\\W|$)","g"),function(a,b,d){return"/"===d.charAt(0)?d:b+d})});m.defaults.stripTrailingSlashes&&(c=c.replace(/\/+$/,"")||"/");c=c.replace(/\/\.(?=\w+($|\?))/,".");b.url=r+c.replace(/\/\\\./,"/.");u(e,function(a,c){m.urlParams[c]||(b.params=b.params||{},b.params[c]=a)})}};return J}]})})(window,window.angular); /*! RESOURCE: /scripts/angular_1.5.11/angular-route.min.js */ /* AngularJS v1.5.11-461c892 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(E,d){'use strict';function y(t,l,g){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(b,e,a,c,k){function p(){m&&(g.cancel(m),m=null);h&&(h.$destroy(),h=null);n&&(m=g.leave(n),m.done(function(b){!1!==b&&(m=null)}),n=null)}function B(){var a=t.current&&t.current.locals;if(d.isDefined(a&&a.$template)){var a=b.$new(),c=t.current;n=k(a,function(a){g.enter(a,null,n||e).done(function(a){!1===a||!d.isDefined(A)||A&&!b.$eval(A)||l()});p()});h=c.scope=a;h.$emit("$viewContentLoaded"); h.$eval(s)}else p()}var h,n,m,A=a.autoscroll,s=a.onload||"";b.$on("$routeChangeSuccess",B);B()}}}function w(d,l,g){return{restrict:"ECA",priority:-400,link:function(b,e){var a=g.current,c=a.locals;e.html(c.$template);var k=d(e.contents());if(a.controller){c.$scope=b;var p=l(a.controller,c);a.controllerAs&&(b[a.controllerAs]=p);e.data("$ngControllerController",p);e.children().data("$ngControllerController",p)}b[a.resolveAs||"$resolve"]=c;k(b)}}}var x,C,s=d.module("ngRoute",["ng"]).provider("$route", function(){function t(b,e){return d.extend(Object.create(b),e)}function l(b,d){var a=d.caseInsensitiveMatch,c={originalPath:b,regexp:b},g=c.keys=[];b=b.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)(\*\?|[?*])?/g,function(b,a,d,c){b="?"===c||"*?"===c?"?":null;c="*"===c||"*?"===c?"*":null;g.push({name:d,optional:!!b});a=a||"";return""+(b?"":a)+"(?:"+(b?a:"")+(c&&"(.+?)"||"([^/]+)")+(b||"")+")"+(b||"")}).replace(/([/$*])/g,"\\$1");c.regexp=new RegExp("^"+b+"$",a?"i":"");return c}x=d.isArray;C=d.isObject; var g={};this.when=function(b,e){var a;a=void 0;if(x(e)){a=a||[];for(var c=0,k=e.length;c<k;c++)a[c]=e[c]}else if(C(e))for(c in a=a||{},e)if("$"!==c.charAt(0)||"$"!==c.charAt(1))a[c]=e[c];a=a||e;d.isUndefined(a.reloadOnSearch)&&(a.reloadOnSearch=!0);d.isUndefined(a.caseInsensitiveMatch)&&(a.caseInsensitiveMatch=this.caseInsensitiveMatch);g[b]=d.extend(a,b&&l(b,a));b&&(c="/"===b[b.length-1]?b.substr(0,b.length-1):b+"/",g[c]=d.extend({redirectTo:b},l(c,a)));return this};this.caseInsensitiveMatch=!1; this.otherwise=function(b){"string"===typeof b&&(b={redirectTo:b});this.when(null,b);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$templateRequest","$sce",function(b,e,a,c,k,p,l){function h(a){var f=v.current;(x=(r=y())&&f&&r.$$route===f.$$route&&d.equals(r.pathParams,f.pathParams)&&!r.reloadOnSearch&&!z)||!f&&!r||b.$broadcast("$routeChangeStart",r,f).defaultPrevented&&a&&a.preventDefault()}function n(){var u=v.current,f=r;if(x)u.params=f.params,d.copy(u.params, a),b.$broadcast("$routeUpdate",u);else if(f||u)z=!1,(v.current=f)&&f.redirectTo&&(d.isString(f.redirectTo)?e.path(w(f.redirectTo,f.params)).search(f.params).replace():e.url(f.redirectTo(f.pathParams,e.path(),e.search())).replace()),c.when(f).then(m).then(function(c){f===v.current&&(f&&(f.locals=c,d.copy(f.params,a)),b.$broadcast("$routeChangeSuccess",f,u))},function(a){f===v.current&&b.$broadcast("$routeChangeError",f,u,a)})}function m(a){if(a){var b=d.extend({},a.resolve);d.forEach(b,function(a, c){b[c]=d.isString(a)?k.get(a):k.invoke(a,null,null,c)});a=s(a);d.isDefined(a)&&(b.$template=a);return c.all(b)}}function s(a){var b,c;d.isDefined(b=a.template)?d.isFunction(b)&&(b=b(a.params)):d.isDefined(c=a.templateUrl)&&(d.isFunction(c)&&(c=c(a.params)),d.isDefined(c)&&(a.loadedTemplateUrl=l.valueOf(c),b=p(c)));return b}function y(){var a,b;d.forEach(g,function(c,g){var q;if(q=!b){var h=e.path();q=c.keys;var l={};if(c.regexp)if(h=c.regexp.exec(h)){for(var k=1,p=h.length;k<p;++k){var m=q[k-1], n=h[k];m&&n&&(l[m.name]=n)}q=l}else q=null;else q=null;q=a=q}q&&(b=t(c,{params:d.extend({},e.search(),a),pathParams:a}),b.$$route=c)});return b||g[null]&&t(g[null],{params:{},pathParams:{}})}function w(a,b){var c=[];d.forEach((a||"").split(":"),function(a,d){if(0===d)c.push(a);else{var e=a.match(/(\w+)(?:[?*])?(.*)/),g=e[1];c.push(b[g]);c.push(e[2]||"");delete b[g]}});return c.join("")}var z=!1,r,x,v={routes:g,reload:function(){z=!0;var a={defaultPrevented:!1,preventDefault:function(){this.defaultPrevented= !0;z=!1}};b.$evalAsync(function(){h(a);a.defaultPrevented||n()})},updateParams:function(a){if(this.current&&this.current.$$route)a=d.extend({},this.current.params,a),e.path(w(this.current.$$route.originalPath,a)),e.search(a);else throw D("norout");}};b.$on("$locationChangeStart",h);b.$on("$locationChangeSuccess",n);return v}]}),D=d.$$minErr("ngRoute");s.provider("$routeParams",function(){this.$get=function(){return{}}});s.directive("ngView",y);s.directive("ngView",w);y.$inject=["$route","$anchorScroll", "$animate"];w.$inject=["$compile","$controller","$route"]})(window,window.angular); /*! RESOURCE: /scripts/angular_1.5.11/angular-touch.min.js */ /* AngularJS v1.5.11-461c892 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(x,n){'use strict';function s(f,k){var e=!1,a=!1;this.ngClickOverrideEnabled=function(b){return n.isDefined(b)?(b&&!a&&(a=!0,t.$$moduleName="ngTouch",k.directive("ngClick",t),f.decorator("ngClickDirective",["$delegate",function(a){if(e)a.shift();else for(var b=a.length-1;0<=b;){if("ngTouch"===a[b].$$moduleName){a.splice(b,1);break}b--}return a}])),e=b,this):e};this.$get=function(){return{ngClickOverrideEnabled:function(){return e}}}}function v(f,k,e){p.directive(f,["$parse","$swipe",function(a, b){return function(l,u,g){function h(c){if(!d)return!1;var a=Math.abs(c.y-d.y);c=(c.x-d.x)*k;return r&&75>a&&0<c&&30<c&&.3>a/c}var m=a(g[f]),d,r,c=["touch"];n.isDefined(g.ngSwipeDisableMouse)||c.push("mouse");b.bind(u,{start:function(c,a){d=c;r=!0},cancel:function(c){r=!1},end:function(c,d){h(c)&&l.$apply(function(){u.triggerHandler(e);m(l,{$event:d})})}},c)}}])}var p=n.module("ngTouch",[]);p.provider("$touch",s);s.$inject=["$provide","$compileProvider"];p.factory("$swipe",[function(){function f(a){a= a.originalEvent||a;var b=a.touches&&a.touches.length?a.touches:[a];a=a.changedTouches&&a.changedTouches[0]||b[0];return{x:a.clientX,y:a.clientY}}function k(a,b){var l=[];n.forEach(a,function(a){(a=e[a][b])&&l.push(a)});return l.join(" ")}var e={mouse:{start:"mousedown",move:"mousemove",end:"mouseup"},touch:{start:"touchstart",move:"touchmove",end:"touchend",cancel:"touchcancel"},pointer:{start:"pointerdown",move:"pointermove",end:"pointerup",cancel:"pointercancel"}};return{bind:function(a,b,l){var e, g,h,m,d=!1;l=l||["mouse","touch","pointer"];a.on(k(l,"start"),function(c){h=f(c);d=!0;g=e=0;m=h;b.start&&b.start(h,c)});var r=k(l,"cancel");if(r)a.on(r,function(c){d=!1;b.cancel&&b.cancel(c)});a.on(k(l,"move"),function(c){if(d&&h){var a=f(c);e+=Math.abs(a.x-m.x);g+=Math.abs(a.y-m.y);m=a;10>e&&10>g||(g>e?(d=!1,b.cancel&&b.cancel(c)):(c.preventDefault(),b.move&&b.move(a,c)))}});a.on(k(l,"end"),function(c){d&&(d=!1,b.end&&b.end(f(c),c))})}}}]);var t=["$parse","$timeout","$rootElement",function(f,k,e){function a(a, d,b){for(var c=0;c<a.length;c+=2){var g=a[c+1],e=b;if(25>Math.abs(a[c]-d)&&25>Math.abs(g-e))return a.splice(c,c+2),!0}return!1}function b(b){if(!(2500<Date.now()-u)){var d=b.touches&&b.touches.length?b.touches:[b],e=d[0].clientX,d=d[0].clientY;if(!(1>e&&1>d||h&&h[0]===e&&h[1]===d)){h&&(h=null);var c=b.target;"label"===n.lowercase(c.nodeName||c[0]&&c[0].nodeName)&&(h=[e,d]);a(g,e,d)||(b.stopPropagation(),b.preventDefault(),b.target&&b.target.blur&&b.target.blur())}}}function l(a){a=a.touches&&a.touches.length? a.touches:[a];var b=a[0].clientX,e=a[0].clientY;g.push(b,e);k(function(){for(var a=0;a<g.length;a+=2)if(g[a]===b&&g[a+1]===e){g.splice(a,a+2);break}},2500,!1)}var u,g,h;return function(h,d,k){var c=f(k.ngClick),w=!1,q,p,s,t;d.on("touchstart",function(a){w=!0;q=a.target?a.target:a.srcElement;3===q.nodeType&&(q=q.parentNode);d.addClass("ng-click-active");p=Date.now();a=a.originalEvent||a;a=(a.touches&&a.touches.length?a.touches:[a])[0];s=a.clientX;t=a.clientY});d.on("touchcancel",function(a){w=!1;d.removeClass("ng-click-active")}); d.on("touchend",function(c){var h=Date.now()-p,f=c.originalEvent||c,m=(f.changedTouches&&f.changedTouches.length?f.changedTouches:f.touches&&f.touches.length?f.touches:[f])[0],f=m.clientX,m=m.clientY,v=Math.sqrt(Math.pow(f-s,2)+Math.pow(m-t,2));w&&750>h&&12>v&&(g||(e[0].addEventListener("click",b,!0),e[0].addEventListener("touchstart",l,!0),g=[]),u=Date.now(),a(g,f,m),q&&q.blur(),n.isDefined(k.disabled)&&!1!==k.disabled||d.triggerHandler("click",[c]));w=!1;d.removeClass("ng-click-active")});d.onclick= function(a){};d.on("click",function(a,b){h.$apply(function(){c(h,{$event:b||a})})});d.on("mousedown",function(a){d.addClass("ng-click-active")});d.on("mousemove mouseup",function(a){d.removeClass("ng-click-active")})}}];v("ngSwipeLeft",-1,"swipeleft");v("ngSwipeRight",1,"swiperight")})(window,window.angular); /*! RESOURCE: /scripts/angular_1.5.11/angular-cookies.min.js */ /* AngularJS v1.5.11-461c892 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(n,c){'use strict';function l(b,a,g){var d=g.baseHref(),k=b[0];return function(b,e,f){var g,h;f=f||{};h=f.expires;g=c.isDefined(f.path)?f.path:d;c.isUndefined(e)&&(h="Thu, 01 Jan 1970 00:00:00 GMT",e="");c.isString(h)&&(h=new Date(h));e=encodeURIComponent(b)+"="+encodeURIComponent(e);e=e+(g?";path="+g:"")+(f.domain?";domain="+f.domain:"");e+=h?";expires="+h.toUTCString():"";e+=f.secure?";secure":"";f=e.length+1;4096<f&&a.warn("Cookie '"+b+"' possibly not set or overflowed because it was too large ("+ f+" > 4096 bytes)!");k.cookie=e}}c.module("ngCookies",["ng"]).provider("$cookies",[function(){var b=this.defaults={};this.$get=["$$cookieReader","$$cookieWriter",function(a,g){return{get:function(d){return a()[d]},getObject:function(d){return(d=this.get(d))?c.fromJson(d):d},getAll:function(){return a()},put:function(d,a,m){g(d,a,m?c.extend({},b,m):b)},putObject:function(d,b,a){this.put(d,c.toJson(b),a)},remove:function(a,k){g(a,void 0,k?c.extend({},b,k):b)}}}]}]);c.module("ngCookies").factory("$cookieStore", ["$cookies",function(b){return{get:function(a){return b.getObject(a)},put:function(a,c){b.putObject(a,c)},remove:function(a){b.remove(a)}}}]);l.$inject=["$document","$log","$browser"];c.module("ngCookies").provider("$$cookieWriter",function(){this.$get=l})})(window,window.angular); /*! RESOURCE: /scripts/angular_1.5.11/angular-aria.min.js */ /* AngularJS v1.5.11-461c892 (c) 2010-2017 Google, Inc. http://angularjs.org License: MIT */ (function(t,p){'use strict';var b="BUTTON A INPUT TEXTAREA SELECT DETAILS SUMMARY".split(" "),l=function(a,c){if(-1!==c.indexOf(a[0].nodeName))return!0};p.module("ngAria",["ng"]).provider("$aria",function(){function a(a,b,m,h){return function(d,f,e){var q=e.$normalize(b);!c[q]||l(f,m)||e[q]||d.$watch(e[a],function(a){a=h?!a:!!a;f.attr(b,a)})}}var c={ariaHidden:!0,ariaChecked:!0,ariaReadonly:!0,ariaDisabled:!0,ariaRequired:!0,ariaInvalid:!0,ariaValue:!0,tabindex:!0,bindKeypress:!0,bindRoleForClick:!0}; this.config=function(a){c=p.extend(c,a)};this.$get=function(){return{config:function(a){return c[a]},$$watchExpr:a}}}).directive("ngShow",["$aria",function(a){return a.$$watchExpr("ngShow","aria-hidden",[],!0)}]).directive("ngHide",["$aria",function(a){return a.$$watchExpr("ngHide","aria-hidden",[],!1)}]).directive("ngValue",["$aria",function(a){return a.$$watchExpr("ngValue","aria-checked",b,!1)}]).directive("ngChecked",["$aria",function(a){return a.$$watchExpr("ngChecked","aria-checked",b,!1)}]).directive("ngReadonly", ["$aria",function(a){return a.$$watchExpr("ngReadonly","aria-readonly",b,!1)}]).directive("ngRequired",["$aria",function(a){return a.$$watchExpr("ngRequired","aria-required",b,!1)}]).directive("ngModel",["$aria",function(a){function c(c,h,d,f){return a.config(h)&&!d.attr(c)&&(f||!l(d,b))}function g(a,c){return!c.attr("role")&&c.attr("type")===a&&"INPUT"!==c[0].nodeName}function k(a,c){var d=a.type,f=a.role;return"checkbox"===(d||f)||"menuitemcheckbox"===f?"checkbox":"radio"===(d||f)||"menuitemradio"=== f?"radio":"range"===d||"progressbar"===f||"slider"===f?"range":""}return{restrict:"A",require:"ngModel",priority:200,compile:function(b,h){var d=k(h,b);return{pre:function(a,e,c,b){"checkbox"===d&&(b.$isEmpty=function(a){return!1===a})},post:function(f,e,b,n){function h(){return n.$modelValue}function k(a){e.attr("aria-checked",b.value==n.$viewValue)}function l(){e.attr("aria-checked",!n.$isEmpty(n.$viewValue))}var m=c("tabindex","tabindex",e,!1);switch(d){case "radio":case "checkbox":g(d,e)&&e.attr("role", d);c("aria-checked","ariaChecked",e,!1)&&f.$watch(h,"radio"===d?k:l);m&&e.attr("tabindex",0);break;case "range":g(d,e)&&e.attr("role","slider");if(a.config("ariaValue")){var p=!e.attr("aria-valuemin")&&(b.hasOwnProperty("min")||b.hasOwnProperty("ngMin")),r=!e.attr("aria-valuemax")&&(b.hasOwnProperty("max")||b.hasOwnProperty("ngMax")),s=!e.attr("aria-valuenow");p&&b.$observe("min",function(a){e.attr("aria-valuemin",a)});r&&b.$observe("max",function(a){e.attr("aria-valuemax",a)});s&&f.$watch(h,function(a){e.attr("aria-valuenow", a)})}m&&e.attr("tabindex",0)}!b.hasOwnProperty("ngRequired")&&n.$validators.required&&c("aria-required","ariaRequired",e,!1)&&b.$observe("required",function(){e.attr("aria-required",!!b.required)});c("aria-invalid","ariaInvalid",e,!0)&&f.$watch(function(){return n.$invalid},function(a){e.attr("aria-invalid",!!a)})}}}}}]).directive("ngDisabled",["$aria",function(a){return a.$$watchExpr("ngDisabled","aria-disabled",b,!1)}]).directive("ngMessages",function(){return{restrict:"A",require:"?ngMessages", link:function(a,b,g,k){b.attr("aria-live")||b.attr("aria-live","assertive")}}}).directive("ngClick",["$aria","$parse",function(a,c){return{restrict:"A",compile:function(g,k){var m=c(k.ngClick,null,!0);return function(c,d,f){if(!l(d,b)&&(a.config("bindRoleForClick")&&!d.attr("role")&&d.attr("role","button"),a.config("tabindex")&&!d.attr("tabindex")&&d.attr("tabindex",0),a.config("bindKeypress")&&!f.ngKeypress))d.on("keypress",function(a){function b(){m(c,{$event:a})}var d=a.which||a.keyCode;32!==d&& 13!==d||c.$apply(b)})}}}}]).directive("ngDblclick",["$aria",function(a){return function(c,g,k){!a.config("tabindex")||g.attr("tabindex")||l(g,b)||g.attr("tabindex",0)}}])})(window,window.angular); /*! RESOURCE: /scripts/app/base/_module.js */ angular.module('sn.base', ['sn.common.auth']); window.countWatchers = window.countWatchers || function (root) { var watchers = []; var f = function (element) { angular.forEach(['$scope', '$isolateScope'], function (scopeProperty) { if (element.data() && element.data().hasOwnProperty(scopeProperty)) { angular.forEach(element.data()[scopeProperty].$$watchers, function (watcher) { watchers.push(watcher); }); } }); angular.forEach(element.children(), function (childElement) { f(angular.element(childElement)); }); }; f(root); var watchersWithoutDuplicates = []; angular.forEach(watchers, function(item) { if(watchersWithoutDuplicates.indexOf(item) < 0) { watchersWithoutDuplicates.push(item); } }); console.log(watchersWithoutDuplicates.length); }; ; /*! RESOURCE: /scripts/sn/common/auth/_module.js */ angular.module('sn.common.auth', []); angular.module('sn.auth', ['sn.common.auth']); ; /*! RESOURCE: /scripts/sn/common/auth/service.authInterceptor.js */ angular.module('sn.common.auth').config(function($httpProvider) { $httpProvider.interceptors.push(function($rootScope, $q, $injector, $window, $log) { var LOG_PREFIX = '(authIntercepter) '; function error(response) { var status = response.status; if (status == 401) { var newPromise = handle401(response); if (newPromise) return newPromise; } return $q.reject(response); } function handle401(response) { if (canResendRequest(response)) { var deferredAgain = $q.defer(); var $http = $injector.get('$http'); $http(response.config).then(function success(newResponse) { deferredAgain.resolve(newResponse); }, function error(newResponse) { deferredAgain.reject(newResponse); }); return deferredAgain.promise; } $log.info(LOG_PREFIX + 'User has been logged out'); $rootScope.$broadcast("@page.login"); return null; } function canResendRequest(response) { var headers = response.headers(); var requestToken = response.config.headers['X-UserToken']; if (!requestToken) { requestToken = headers['x-usertoken-request']; } if ($window.g_ck && (requestToken !== $window.g_ck)) { $log.info(LOG_PREFIX + 'Token refreshed since request -- retrying'); response.config.headers['X-UserToken'] = $window.g_ck; return true; } if (headers['x-sessionloggedin'] != 'true' && !headers['x-rotate-guest-usertoken']) return false; var token = headers['x-usertoken-response']; if (token) { $log.info(LOG_PREFIX + 'Received new token -- retrying'); response.config.headers['X-UserToken'] = token; setToken(token); return true; } return false; } function setToken(token) { $window.g_ck = token; if (!token) { $httpProvider.defaults.headers.common["X-UserToken"] = 'token_intentionally_left_blank'; } else { $httpProvider.defaults.headers.common["X-UserToken"] = token; } if ($window.jQuery) { jQuery.ajaxSetup({ headers: { 'X-UserToken': token } }); } if ($window.Zepto) { if (!Zepto.ajaxSettings.headers) Zepto.ajaxSettings.headers = {}; Zepto.ajaxSettings.headers['X-UserToken'] = token; } } setToken($window.g_ck); return { responseError: error } }); }); ; /*! RESOURCE: /scripts/sn/common/auth/service.jsonpDecorator.js */ angular.module('sn.common.auth').config(['$provide', '$sceDelegateProvider', function($provide, $sceDelegateProvider) { var jsonpEnableInclusionList = 'true' !== 'false'; if (jsonpEnableInclusionList) { var jsonpInclusionList = 'self' || 'self'; $sceDelegateProvider.resourceUrlWhitelist(jsonpInclusionList.split(',')); } $provide.decorator('$sce', ['$delegate', function $sceDecorator($delegate) { if (jsonpEnableInclusionList) return $delegate; var originalGetTrusted = $delegate.getTrusted; function isNotEmpty(maybeTrusted) { return maybeTrusted !== null && !angular.isUndefined(maybeTrusted) && maybeTrusted !== ''; } $delegate.getTrusted = function decorateGetTrusted(type, maybeTrusted) { if (type === 'resourceUrl' && isNotEmpty(maybeTrusted) && angular.isString(maybeTrusted)) maybeTrusted = $delegate.trustAsResourceUrl(maybeTrusted); return originalGetTrusted.apply($delegate, [type, maybeTrusted]); } $delegate.getTrustedResourceUrl = function decoratedGetTrustedUrl(maybeTrusted) { return $delegate.getTrusted('resourceUrl', maybeTrusted); } return $delegate; }]); }]); ; ; /*! RESOURCE: /scripts/js_includes_amb.js */ /*! RESOURCE: /scripts/glide-amb-client-bundle.min.js */ !function(e){var n={};function t(i){if(n[i])return n[i].exports;var r=n[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,i){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:i})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=11)}([function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i,r=(i=t(1))&&i.__esModule?i:{default:i};var o=function(e){function n(n){window.console&&console.log(e+" "+n)}return{debug:function(e){"debug"===r.default.logLevel&&n("[DEBUG] "+e)},addInfoMessage:function(e){n("[INFO] "+e)},addErrorMessage:function(e){n("[ERROR] "+e)},addWarnMessage:function(e){n("[WARN] "+e)}}};n.default=o},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=n.TOKEN_MANAGEMENT_EXTENSION=n.WEBSOCKET_TYPE_NAME=void 0;n.WEBSOCKET_TYPE_NAME="websocket";n.TOKEN_MANAGEMENT_EXTENSION="tokenManagementExtension";var i={servletPath:"amb",logLevel:"info",loginWindow:"true",wsConnectTimeout:1e4,overlayStyle:"",subscribeCommandsFlow:{enable:!1,maxInflight:1,maxWait:1e4,retries:3,retryDelay:{min:2e3,max:3e5,increaseFactor:2}}};n.default=i},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i,r=(i=t(0))&&i.__esModule?i:{default:i};var o=function(e,n,t){var i,o,s=new r.default("amb.ChannelListener"),a=e;return{getCallback:function(){return o},getSubscriptionCallback:function(){return t},getID:function(){return i},setNewChannel:function(e){a.unsubscribe(this),a=e,this.subscribe(o)},subscribe:function(e){return o=e,i=a.subscribe(this),this},resubscribe:function(){return this.subscribe(o)},unsubscribe:function(){return a.unsubscribe(this),s.debug("Unsubscribed from channel: "+a.getName()),this},publish:function(e){a.publish(e)},getName:function(){return a.getName()}}};n.default=o},function(e,n,t){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.isEmptyObject=n.isObject=n.isNil=n.isNull=n.isUndefined=void 0;var r=function(e){return void 0===e};n.isUndefined=r;var o=function(e){return null===e};n.isNull=o;n.isNil=function(e){return o(e)||r(e)};var s=function(e){return null!=e&&"object"===i(e)};n.isObject=s;n.isEmptyObject=function(e){return s(e)&&0===Object.keys(e).length}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=function(e){var n=[],t=0;return{subscribe:function(e,i){var r=t++;return n.push({event:e,callback:i,id:r}),r},unsubscribe:function(e){for(var t=0;t<n.length;t++)e===n[t].id&&n.splice(t,1)},publish:function(e,n){for(var t=this._getSubscriptions(e),i=0;i<t.length;i++)t[i].callback.apply(null,n)},getEvents:function(){return e},_getSubscriptions:function(e){for(var t=[],i=0;i<n.length;i++)n[i].event===e&&t.push(n[i]);return t}}};n.default=i},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=h(t(4)),r=h(t(0)),o=function(e){if(e&&e.__esModule)return e;var n=d();if(n&&n.has(e))return n.get(e);var t={};if(null!=e){var i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){var o=i?Object.getOwnPropertyDescriptor(e,r):null;o&&(o.get||o.set)?Object.defineProperty(t,r,o):t[r]=e[r]}}t.default=e,n&&n.set(e,t);return t}(t(1)),s=h(t(6)),a=h(t(7)),u=h(t(19)),c=t(3),l=h(t(20)),f=h(t(21));function d(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return d=function(){return e},e}function h(e){return e&&e.__esModule?e:{default:e}}var g=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new u.default,t=!1,d=!1,h=new i.default({CONNECTION_INITIALIZED:"connection.initialized",CONNECTION_OPENED:"connection.opened",CONNECTION_CLOSED:"connection.closed",CONNECTION_BROKEN:"connection.broken",SESSION_LOGGED_IN:"session.logged.in",SESSION_LOGGED_OUT:"session.logged.out",SESSION_INVALIDATED:"session.invalidated",SESSION_REESTABLISHED:"session.reestablished"}),g={SESSION_LOGGED_IN:"session.logged.in",SESSION_LOGGED_OUT:"session.logged.out",SESSION_INVALIDATED:"session.invalidated"},b="closed",p={},m=new r.default("amb.ServerConnection");!function(){e.addListener("/meta/handshake",this,A),e.addListener("/meta/connect",this,G),e.addListener("/meta/subscribe",this,U),e.addListener("/meta/unsubscribe",this,U)}();var v=g.SESSION_INVALIDATED,y=null,_="true"===o.default.loginWindow,C=null,w={UNKNOWN_CLIENT:"402::Unknown client"},T=!1,S={},E=!1,x=new s.default(e,S),k=!1,O="glide.amb.session.logout.overlay.style",N="glide.session.status",I="session.touch.http",L="amb.ServerConnection.reestablish.session",M=e.getExtension(o.TOKEN_MANAGEMENT_EXTENSION),D=null;function A(e){U(e);var n=R(e,O);n&&(o.default.overlayStyle=n),v=R(e,N),function(e){if(e.ext){var n=e.ext.subscribeCommandsFlow;if(n){var t,i,r,s=o.default.subscribeCommandsFlow;if(o.default.subscribeCommandsFlow.enable=(t=n.enable,i=s.enable,r=i,(0,c.isNil)(t)||(r=!!t),r),o.default.subscribeCommandsFlow.enable){o.default.subscribeCommandsFlow.retries=P(n.retries,s.retries),o.default.subscribeCommandsFlow.maxInflight=P(n.maxInflight,s.maxInflight),o.default.subscribeCommandsFlow.maxWait=P(n.maxWait,s.maxWait);var a=n.retryDelay;if(a){var u=o.default.subscribeCommandsFlow.retryDelay;o.default.subscribeCommandsFlow.retryDelay.min=P(a.min,u.min),o.default.subscribeCommandsFlow.retryDelay.max=P(a.max,u.max),o.default.subscribeCommandsFlow.retryDelay.increaseFactor=P(a.increaseFactor,u.increaseFactor)}}o.default.subscribeCommandsFlow.enable&&(m.addInfoMessage("_initializeSubscriptionCommandSender: SubscriptionCommandSender is enabled"),null!=M&&M.updateTokenCount(o.default.subscribeCommandsFlow.maxInflight),D&&D.stop(),D=new f.default(new l.default(1e4),M))}}}(e),setTimeout(function(){e.successful&&W()},0)}function R(e,n){if((0,c.isObject)(e.ext))return e.ext[n]}function F(n,t){if(n in p)return p[n];var i=new a.default(e,n,k,t);return p[n]=i,i}function B(e){delete p[e]}function U(n){if(n.ext){!1===n.ext["glide.amb.active"]&&S.disconnect();var t=R(n,"glide.amb.client.log.level");t&&(o.default.logLevel=t,e.setLogLevel(o.default.logLevel))}}function P(e,n){var t=Math.floor(parseInt(e));return(isNaN(t)||t<0)&&(t=n),t}function j(){for(var e in m.debug("Resubscribing to all!"),p){var n=p[e];n&&n.resubscribeToCometD()}}function q(){for(var e in m.debug("Unsubscribing from all!"),p){var n=p[e];n&&n.unsubscribeFromCometD()}}function G(n){if(U(n),d)setTimeout(function(){t=!1,m.debug("Connection closed"),b="closed",X(h.getEvents().CONNECTION_CLOSED)},0);else{var i=R(n,I);o.WEBSOCKET_TYPE_NAME===e.getTransport().getType()&&!0===i&&S._touchHttpSession();var r=n.error;r&&(C=r),function(e){var n=R(e,N);n&&n!==v&&(T=!0===R(e,"glide.amb.login.window.override"),Q(n))}(n);var s=t;t=!0===n.successful,!s&&t?H():s&&!t&&(m.addErrorMessage("Connection broken"),b="broken",E=!0,X(h.getEvents().CONNECTION_BROKEN),D&&(D.stop(),D=null))}}function W(){m.debug("Connection initialized"),k=!0,b="initialized",X(h.getEvents().CONNECTION_INITIALIZED)}function H(){m.debug("Connection opened"),E?S.getLastError()===S.getErrorMessages().UNKNOWN_CLIENT&&(S.setLastError(null),S._sendSessionSetupRequest(function(e){var n=e.status;200===n&&(E=!1,x.initialize(z))})):x.initialize(z)}function z(){j(),b="opened",X(h.getEvents().CONNECTION_OPENED)}function Q(e){m.debug("session.status - "+e),function(e){return(v===g.SESSION_LOGGED_IN||v===g.SESSION_LOGGED_OUT)&&e===g.SESSION_INVALIDATED}(e)?(m.debug("INVALIDATED event fire!"),q(),X(h.getEvents().SESSION_INVALIDATED)):function(e){return v===g.SESSION_LOGGED_IN&&e===g.SESSION_LOGGED_OUT}(e)?(m.debug("LOGGED_OUT event fire!"),q(),X(h.getEvents().SESSION_LOGGED_OUT),_&&!T&&S.loginShow()):function(e){return v===g.SESSION_INVALIDATED&&e===g.SESSION_LOGGED_OUT}(e)?(m.debug("REESTABLISHED event fire!"),j(),X(h.getEvents().SESSION_REESTABLISHED)):function(e){return(v===g.SESSION_INVALIDATED||v===g.SESSION_LOGGED_OUT)&&e===g.SESSION_LOGGED_IN}(e)&&(m.debug("LOGGED_IN event fire!"),j(),X(h.getEvents().SESSION_LOGGED_IN),S.loginHide()),v=e}function X(e){try{h.publish(e)}catch(n){m.addErrorMessage("error publishing '"+e+"' - "+n)}}return S.connect=function(){t?m.debug(">>> connection exists, request satisfied"):(m.debug("Connecting to glide amb server -> "+o.default.servletURI),e.configure({url:S.getURL(o.default.servletPath),logLevel:o.default.logLevel,connectTimeout:o.default.wsConnectTimeout}),e.handshake(),n.on(L,function(){S._reestablishSession(!1)}))},S.reload=function(){e.reload()},S.abort=function(){e.getTransport().abort()},S.disconnect=function(){m.debug("Disconnecting from glide amb server.."),d=!0,e.disconnect()},S.getURL=function(e){return window.location.protocol+"//"+window.location.host+"/"+e},S.unsubscribeAll=function(){q()},S.resubscribeAll=function(){j()},S.removeChannel=function(e){B(e)},S.getEvents=function(){return h.getEvents()},S.getConnectionState=function(){return b},S.getLastError=function(){return C},S.setLastError=function(e){C=e},S.getErrorMessages=function(){return w},S.isLoggedIn=function(){return v===g.SESSION_LOGGED_IN},S.isSessionActive=function(){return v!==g.SESSION_INVALIDATED},S.getChannelRedirect=function(){return x},S.getChannel=function(e,n){return F(e,n)},S.getChannels=function(){return p},S.getState=function(){return b},S.getLoginWindowOverlayStyle=function(){return o.default.overlayStyle},S.loginShow=function(){m.debug("Show login window");var e='<iframe src="/amb_login.do" frameborder="0" height="400px" width="405px" scrolling="no"></iframe>',n='<div id="amb_disconnect_modal" tabindex="-1" aria-hidden="true" class="modal" role="dialog" style="'.concat(o.default.overlayStyle,'">\n\t\t\t\t<div class="modal-dialog small-modal" style="width:450px">\n\t\t\t\t <div class="modal-content">\n\t\t\t\t\t <header class="modal-header">\n\t\t\t\t\t\t <h4 id="small_modal1_title" class="modal-title">Login</h4>\n\t\t\t\t\t </header>\n\t\t\t\t\t <div class="modal-body">\n\t\t\t\t\t </div>\n\t\t\t\t </div>\n\t\t\t\t</div>\n\t\t\t</div>');try{var t=new GlideModal("amb_disconnect_modal");t.renderWithContent?(t.template=n,t.renderWithContent(e)):(t.setBody(e),t.render()),y=t}catch(e){m.debug(e)}},S.loginHide=function(){y&&(y.destroy(),y=null)},S.loginComplete=function(){S.reestablishSession()},S.reestablishSession=function(){S._reestablishSession(!0)},S.subscribeToEvent=function(e,n){return h.getEvents().CONNECTION_OPENED===e&&t&&n(),h.subscribe(e,n)},S.unsubscribeFromEvent=function(e){h.unsubscribe(e)},S.isLoginWindowEnabled=function(){return _},S.setLoginWindowEnabled=function(e){_=e},S.isLoginWindowOverride=function(){return T},S.getSubscriptionCommandSender=function(){return D},S._metaConnect=G,S._metaHandshake=A,S._sendSessionSetupRequest=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(){},t=function(){m.debug("sending /amb_session_setup.do!");var n=new XMLHttpRequest;return n.open("POST","/amb_session_setup.do",!0),n.setRequestHeader("Content-type","application/json;charset=UTF-8"),n.setRequestHeader("X-UserToken",window.g_ck),n.setRequestHeader("X-CometD_SessionID",e.getClientId()),n}();t.onload=function(){return n(t)},t.send()},S._onChannelRedirectSubscriptionComplete=z,S._getChannel=F,S._removeChannel=B,S._connectionInitialized=W,S._connectionOpened=H,S._reestablishSession=function(e){S._sendSessionSetupRequest(function(e){var n=e.response;n&&Q(JSON.parse(n)["glide.session.status"])}),e&&n.emit(L,L)},S._touchHttpSession=function(){var e=new XMLHttpRequest;e.open("POST","/amb",!0),e.setRequestHeader("Content-type","application/json"),e.send()},S};n.default=g},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=o(t(0)),r=o(t(2));function o(e){return e&&e.__esModule?e:{default:e}}var s=function(e,n){var t,o=e,s=new i.default("amb.ChannelRedirect");function a(e){s.debug("_onAdvice:"+e.data.clientId);var t=n.getChannel(e.data.fromChannel),i=n.getChannel(e.data.toChannel);t&&i?(function(e,n){for(var t=e.getChannelListeners(),i=0;i<t.length;i++)t[i].setNewChannel(n)}(t,i),s.debug("published channel switch event, fromChannel:"+t.getName()+", toChannel:"+i.getName())):s.debug("Could not redirect from "+e.data.fromChannel+" to "+e.data.toChannel)}return{initialize:function(e){var i="/sn/meta/channel_redirect/"+o.getClientId(),u=n.getChannel(i);t&&u===t?t.subscribeToCometD():(t&&n.removeChannel(t.getName()),t=u,new r.default(t,n,e).subscribe(a)),s.debug("ChannelRedirect initialized: "+i)},_onAdvice:a}};n.default=s},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=s(t(0)),r=t(3),o=s(t(8));function s(e){return e&&e.__esModule?e:{default:e}}var a=function(e,n,t){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){return{}},a=null,u=null,c=[],l=[],f=new i.default("amb.Channel"),d=0,h=t;function g(){return(0,o.default)().getServerConnection().getSubscriptionCommandSender()}return{subscribe:function(e){if(e.getCallback()){for(var t=0;t<c.length;t++)if(c[t]===e)return f.debug("Channel listener already in the list"),e.getID();c.push(e);var i=e.getSubscriptionCallback();if(i&&(u?i(u):l.push(i)),!a&&h)try{this.subscribeToCometD()}catch(e){return void f.addErrorMessage(e)}return++d}f.addErrorMessage("Cannot subscribe to channel: "+n+", callback not provided")},resubscribe:function(){a=null;for(var e=0;e<c.length;e++)c[e].resubscribe()},_handleResponse:function(e){for(var n=0;n<c.length;n++)c[n].getCallback()(e)},unsubscribe:function(t){if(t){for(var i=0;i<c.length;i++)if(c[i].getID()===t.getID()){c.splice(i,1);break}var r;c.length<1&&a&&"disconnecting"!==(r=e.getStatus())&&"disconnected"!==r&&this.unsubscribeFromCometD()}else f.addErrorMessage("Cannot unsubscribe from channel: "+n+", listener argument does not exist")},publish:function(t){e.publish(n,t)},subscribeToCometD:function(){f.debug("subscribeToCometD channelName : "+n+", subscription : "+a),g()?g().subscribeToChannel(this):this._subscribeToCometD(this.subscriptionCallback)},_subscribeToCometD:function(t){f.debug("_subscribeToCometD channelName : "+n);var i=s();if((0,r.isNil)(i)||(0,r.isEmptyObject)(i))a=e.subscribe(n,this._handleResponse.bind(this),t);else{var o={subscribeOptions:i};a=e.subscribe(n,this._handleResponse.bind(this),o,t)}f.debug("Successfully subscribed to channel: "+n+", Subscribe options: "+i)},subscriptionCallback:function(e){f.debug("Cometd subscription callback completed for channel: "+n),f.debug("Listener callback queue size: "+l.length),u=e,l.map(function(e){e(u)}),l=[]},unsubscribeFromCometD:function(){f.debug("unsubscribeFromCometD from : "+n+", subscription : "+a),null!==a&&(g()?g().unsubscribeToChannel(this):this._unsubscribeFromCometD())},_unsubscribeFromCometD:function(){f.debug("_unsubscribeFromCometD from : "+n+", subscription : "+a),null!==a&&(e.unsubscribe(a),a=null,u=null,f.debug("Successfully unsubscribed from channel: "+n))},resubscribeToCometD:function(){f.debug("Resubscribe to "+n),g()?g().subscribeToChannel(this):this._subscribeToCometD(this.subscriptionCallback)},getSubscribeOptionsCallback:function(){return s},getName:function(){return n},getChannelListeners:function(){return c},getListenerCallbackQueue:function(){return l},setSubscriptionCallbackResponse:function(e){u=e}}};n.default=a},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=s(t(9)),r=s(t(17)),o=s(t(18));function s(e){return e&&e.__esModule?e:{default:e}}function a(e){return e.MSInputMethodContext&&e.document.documentMode}function u(e,n){if(void 0!==e.getClientWindow&&e.getClientWindow()===n)return e;var t=function(e,n){for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t]);return e}({},e);return t.getChannel=function(t,i,r){return e.getChannel(t,i,r||n)},t.getRecordWatcherChannel=function(t,i,r,o,s){return e.getRecordWatcherChannel(t,i,r,o,s||n)},t.subscribeToEvent=function(t,i,r){return e.subscribeToEvent(t,i,r||n)},t.unsubscribeFromEvent=function(t,i){return e.unsubscribeFromEvent(t,i||n)},t.getClientWindow=function(){return n},t}var c=function(){var e=function(e){try{if(!a(e))for(;e!==e.parent&&!e.g_ambClient;)e=e.parent;if(e.g_ambClient)return e.g_ambClient}catch(e){console.log("AMB getClient() tried to access parent from an iFrame. Caught error: "+e)}return null}(window);e||function(e){var n=window.self;n.g_ambClient=e,n.addEventListener("unload",function(){n.g_ambClient.disconnect()});var t,i,r=!(!n.NOW||!n.NOW.hasOwnProperty("deferAmbConnection"))&&n.NOW.deferAmbConnection,o=n.NOW&&n.NOW.hasOwnProperty("deferredAmbConnectionTimeout")&&(t=n.NOW.deferredAmbConnectionTimeout,i=t,parseInt(i,10)===i&&t>0)?n.NOW.deferredAmbConnectionTimeout:1e4;if(r)n.setTimeout(u,o);else{var s=n.document?n.document.readyState:null;"complete"===s?u():n.addEventListener("load",u),n.setTimeout(u,1e4)}var a=!1;function u(){a||(a=!0,n.g_ambClient.connect())}}(e=u(function(e){return n=new i.default,t=function(){var e=[];function n(e,n,i){if(e&&i){var r=t(e);if(r)for(var o=r.subscriptions,s=o.length-1;s>=0;s--)o[s].id===n&&o[s].callback===i&&o.splice(s,1)}}function t(n){for(var t=0,i=e.length;t<i;t++)if(e[t].window===n)return e[t];return null}function i(n){var t={window:n,onUnload:function(){t.unloading=!0;for(var n,i=t.subscriptions;n=i.pop();)n.unsubscribe();!function(n){for(var t=0,i=e.length;t<i;t++)if(e[t].window===n.window){e.splice(t,1);break}n.subscriptions=[],n.window.removeEventListener("unload",n.onUnload),n.onUnload=null,n.window=null}(t)},unloading:!1,subscriptions:[]};return n.addEventListener("unload",t.onUnload),e.push(t),t}return{add:function(e,r,o,s){if(e&&o&&s){n(e,r,o);var a=t(e);a||(a=i(e)),a.unloading||a.subscriptions.push({id:r,callback:o,unsubscribe:s})}},remove:n}}(),s=n.getServerConnection(),e&&s.setLoginWindowEnabled(!1),{getServerConnection:function(){return s},connect:function(){n.connect()},abort:function(){n.abort()},disconnect:function(){n.disconnect()},getConnectionState:function(){return n.getConnectionState()},getState:function(){return n.getConnectionState()},getClientId:function(){return n.getClientId()},getChannel:function(e,i,r){var o=n.getChannel(e,i),a=o.subscribe,u=o.unsubscribe;return r=r||window,o.subscribe=function(e){return t.add(r,o,e,function(){o.unsubscribe(e)}),a.call(o,e),o},o.unsubscribe=function(i){t.remove(r,o,i);var a=u.call(o,i);return 0===s.getChannel(e).getChannelListeners().length&&n.removeChannel(e),a},o},getChannel0:function(e,t){return n.getChannel(e,t)},getRecordWatcherChannel:function(e,n,t,i,s){var a=r.default.stringify(o.default.parse(n)).replace(/=/g,"-");return t=t||"default",this.getChannel("/rw/"+t+"/"+e+"/"+a,i,s)},registerExtension:function(e,t){n.registerExtension(e,t)},unregisterExtension:function(e){n.unregisterExtension(e)},batch:function(e){n.batch(e)},subscribeToEvent:function(e,i,r){r=r||window;var o=n.subscribeToEvent(e,i);return t.add(r,o,!0,function(){n.unsubscribeFromEvent(o)}),o},unsubscribeFromEvent:function(e,i){i=i||window,t.remove(i,e,!0),n.unsubscribeFromEvent(e)},isLoggedIn:function(){return n.isLoggedIn()},getConnectionEvents:function(){return n.getConnectionEvents()},getEvents:function(){return n.getConnectionEvents()},reestablishSession:function(){n.reestablishSession()},loginComplete:function(){n.loginComplete()},getChannels:function(){return n.getChannels()},extendSession:function(){return n.extendSession()},getTokenManagementExtension:function(){return n.getTokenManagementExtension()}};var n,t,s}(a(window)&&null!==window.frameElement),window));return u(e,window)};n.default=c},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=f(t(13)),r=f(t(5)),o=f(t(0)),s=f(t(2)),a=f(t(14)),u=t(1),c=f(t(15)),l=f(t(16));function f(e){return e&&e.__esModule?e:{default:e}}var d=function(){var e=new i.default.CometD;e.registerTransport(u.WEBSOCKET_TYPE_NAME,new i.default.WebSocketTransport,0),e.registerTransport("long-polling",new i.default.LongPollingTransport,1),e.unregisterTransport("callback-polling");var n=new a.default;e.registerExtension("graphQLSubscription",n);var t=new c.default;e.registerExtension("sessionExtension",t);var f=new l.default;e.registerExtension(u.TOKEN_MANAGEMENT_EXTENSION,f);var d=new r.default(e),h=new o.default("amb.MessageClient"),g=!1;return{getServerConnection:function(){return d},isLoggedIn:function(){return d.isLoggedIn()},loginComplete:function(){d.loginComplete()},reestablishSession:function(){d.reestablishSession()},connect:function(){g?h.addInfoMessage(">>> connection exists, request satisfied"):(g=!0,d.connect())},reload:function(){g=!1,d.reload()},abort:function(){g=!1,d.abort()},disconnect:function(){g=!1,d.disconnect()},isConnected:function(){return g},getConnectionEvents:function(){return d.getEvents()},subscribeToEvent:function(e,n){return d.subscribeToEvent(e,n)},unsubscribeFromEvent:function(e){d.unsubscribeFromEvent(e)},getConnectionState:function(){return d.getConnectionState()},getClientId:function(){return e.getClientId()},getChannel:function(e,t){var i=t||{},r=i.subscriptionCallback,o=i.serializedGraphQLSubscription,a=i.subscribeOptionsCallback,u=d.getChannel(e,a);return n.isGraphQLChannel(e)&&(o?n.addGraphQLChannel(e,o):h.addErrorMessage("Serialized subscription not present for GraphQL channel "+e)),new s.default(u,d,r)},removeChannel:function(e){d.removeChannel(e),n.isGraphQLChannel(e)&&n.removeGraphQLChannel(e)},getChannels:function(){return d.getChannels()},extendSession:function(){t.extendSession()},getTokenManagementExtension:function(){return f},registerExtension:function(n,t){e.registerExtension(n,t)},unregisterExtension:function(n){e.unregisterExtension(n)},batch:function(n){e.batch(n)}}};n.default=d},function(e,n,t){var i;i=function(){var e=e||function(e,n){var t=Object.create||function(){function e(){}return function(n){var t;return e.prototype=n,t=new e,e.prototype=null,t}}(),i={},r=i.lib={},o=r.Base={extend:function(e){var n=t(this);return e&&n.mixIn(e),n.hasOwnProperty("init")&&this.init!==n.init||(n.init=function(){n.$super.init.apply(this,arguments)}),n.init.prototype=n,n.$super=this,n},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var n in e)e.hasOwnProperty(n)&&(this[n]=e[n]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=r.WordArray=o.extend({init:function(e,n){e=this.words=e||[],this.sigBytes=void 0!=n?n:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var n=this.words,t=e.words,i=this.sigBytes,r=e.sigBytes;if(this.clamp(),i%4)for(var o=0;o<r;o++){var s=t[o>>>2]>>>24-o%4*8&255;n[i+o>>>2]|=s<<24-(i+o)%4*8}else for(o=0;o<r;o+=4)n[i+o>>>2]=t[o>>>2];return this.sigBytes+=r,this},clamp:function(){var n=this.words,t=this.sigBytes;n[t>>>2]&=4294967295<<32-t%4*8,n.length=e.ceil(t/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(n){for(var t,i=[],r=function(n){n=n;var t=987654321,i=4294967295;return function(){var r=((t=36969*(65535&t)+(t>>16)&i)<<16)+(n=18e3*(65535&n)+(n>>16)&i)&i;return r/=4294967296,(r+=.5)*(e.random()>.5?1:-1)}},o=0;o<n;o+=4){var a=r(4294967296*(t||e.random()));t=987654071*a(),i.push(4294967296*a()|0)}return new s.init(i,n)}}),a=i.enc={},u=a.Hex={stringify:function(e){for(var n=e.words,t=e.sigBytes,i=[],r=0;r<t;r++){var o=n[r>>>2]>>>24-r%4*8&255;i.push((o>>>4).toString(16)),i.push((15&o).toString(16))}return i.join("")},parse:function(e){for(var n=e.length,t=[],i=0;i<n;i+=2)t[i>>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new s.init(t,n/2)}},c=a.Latin1={stringify:function(e){for(var n=e.words,t=e.sigBytes,i=[],r=0;r<t;r++){var o=n[r>>>2]>>>24-r%4*8&255;i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var n=e.length,t=[],i=0;i<n;i++)t[i>>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new s.init(t,n)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},f=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(n){var t=this._data,i=t.words,r=t.sigBytes,o=this.blockSize,a=r/(4*o),u=(a=n?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,c=e.min(4*u,r);if(u){for(var l=0;l<u;l+=o)this._doProcessBlock(i,l);var f=i.splice(0,u);t.sigBytes-=c}return new s.init(f,c)},clone:function(){var e=o.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0}),d=(r.Hasher=f.extend({cfg:o.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(n,t){return new e.init(t).finalize(n)}},_createHmacHelper:function(e){return function(n,t){return new d.HMAC.init(e,t).finalize(n)}}}),i.algo={});return i}(Math);return e},e.exports=i()},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i,r=(i=t(12))&&i.__esModule?i:{default:i};window.__TECTONIC__amb_client_js=r.default,window.amb=r.default;var o=r.default;n.default=o},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=d(t(1)),r=d(t(0)),o=d(t(4)),s=d(t(5)),a=d(t(6)),u=d(t(2)),c=d(t(7)),l=d(t(9)),f=d(t(8));function d(e){return e&&e.__esModule?e:{default:e}}var h={properties:i.default,Logger:r.default,EventManager:o.default,ServerConnection:s.default,ChannelRedirect:a.default,ChannelListener:u.default,Channel:c.default,MessageClient:l.default,getClient:f.default};n.default=h},function(e,n,t){var i;i=function(){var e={isString:function(e){return void 0!==e&&null!==e&&("string"==typeof e||e instanceof String)},isArray:function(e){return void 0!==e&&null!==e&&e instanceof Array},inArray:function(e,n){for(var t=0;t<n.length;++t)if(e===n[t])return t;return-1},setTimeout:function(e,n,t){return window.setTimeout(function(){try{e._debug("Invoking timed function",n),n()}catch(t){e._debug("Exception invoking timed function",n,t)}},t)},clearTimeout:function(e){window.clearTimeout(e)}},n=function(){var n,t,i;this.registered=function(e,i){n=e,t=i},this.unregistered=function(){n=null,t=null},this._debug=function(){t._debug.apply(t,arguments)},this._mixin=function(){return t._mixin.apply(t,arguments)},this.getConfiguration=function(){return t.getConfiguration()},this.getAdvice=function(){return t.getAdvice()},this.setTimeout=function(n,i){return e.setTimeout(t,n,i)},this.clearTimeout=function(n){e.clearTimeout(n)},this.convertToMessages=function(n){if(e.isString(n))try{return JSON.parse(n)}catch(e){throw this._debug("Could not convert to JSON the following string",'"'+n+'"'),e}if(e.isArray(n))return n;if(void 0===n||null===n)return[];if(n instanceof Object)return[n];throw"Conversion Error "+n+", typeof "+typeof n},this.accept=function(e,n,t){throw"Abstract"},this.getType=function(){return n},this.getURL=function(){return i},this.setURL=function(e){i=e},this.send=function(e,n){throw"Abstract"},this.reset=function(e){this._debug("Transport",n,"reset",e?"initial":"retry")},this.abort=function(){this._debug("Transport",n,"aborted")},this.toString=function(){return this.getType()}};n.derive=function(e){function n(){}return n.prototype=e,new n};var t=function(){var t=new n,i=n.derive(t),r=0,o=null,s=[],a=[];function u(e,n){if(this.transportSend(e,n),n.expired=!1,!e.sync){var t=this.getConfiguration().maxNetworkDelay,i=t;!0===n.metaConnect&&(i+=this.getAdvice().timeout),this._debug("Transport",this.getType(),"waiting at most",i,"ms for the response, maxNetworkDelay",t);var r=this;n.timeout=this.setTimeout(function(){n.expired=!0;var t="Request "+n.id+" of transport "+r.getType()+" exceeded "+i+" ms max network delay",o={reason:t},s=n.xhr;o.httpCode=r.xhrStatus(s),r.abortXHR(s),r._debug(t),r.complete(n,!1,n.metaConnect),e.onFailure(s,e.messages,o)},i)}}function c(e){var n=++r,t={id:n,metaConnect:!1,envelope:e};s.length<this.getConfiguration().maxConnections-1?(s.push(t),u.call(this,e,t)):(this._debug("Transport",this.getType(),"queueing request",n,"envelope",e),a.push([e,t]))}function l(n,t){var i=e.inArray(n,s);if(i>=0&&s.splice(i,1),a.length>0){var r=a.shift(),o=r[0],u=r[1];if(this._debug("Transport dequeued request",u.id),t)this.getConfiguration().autoBatch&&function(e){for(;a.length>0;){var n=a[0],t=n[0],i=n[1];if(t.url!==e.url||t.sync!==e.sync)break;a.shift(),e.messages=e.messages.concat(t.messages),this._debug("Coalesced",t.messages.length,"messages from request",i.id)}}.call(this,o),c.call(this,o),this._debug("Transport completed request",n.id,o);else{var l=this;this.setTimeout(function(){l.complete(u,!1,u.metaConnect);var e={reason:"Previous request failed"},n=u.xhr;e.httpCode=l.xhrStatus(n),o.onFailure(n,o.messages,e)},0)}}}return i.complete=function(e,n,t){t?function(e){var n=e.id;if(this._debug("Transport",this.getType(),"metaConnect complete, request",n),null!==o&&o.id!==n)throw"Longpoll request mismatch, completing request "+n;o=null}.call(this,e):l.call(this,e,n)},i.transportSend=function(e,n){throw"Abstract"},i.transportSuccess=function(e,n,t){n.expired||(this.clearTimeout(n.timeout),this.complete(n,!0,n.metaConnect),t&&t.length>0?e.onSuccess(t):e.onFailure(n.xhr,e.messages,{httpCode:204}))},i.transportFailure=function(e,n,t){n.expired||(this.clearTimeout(n.timeout),this.complete(n,!1,n.metaConnect),e.onFailure(n.xhr,e.messages,t))},i.send=function(e,n){n?function(e){if(null!==o)throw"Concurrent metaConnect requests not allowed, request id="+o.id+" not yet completed";var n=++r;this._debug("Transport",this.getType(),"metaConnect send, request",n,"envelope",e);var t={id:n,metaConnect:!0,envelope:e};u.call(this,e,t),o=t}.call(this,e):c.call(this,e)},i.abort=function(){t.abort();for(var e=0;e<s.length;++e){var n=s[e];n&&(this._debug("Aborting request",n),this.abortXHR(n.xhr)||this.transportFailure(n.envelope,n,{reason:"abort"}))}var i=o;i&&(this._debug("Aborting metaConnect request",i),this.abortXHR(i.xhr)||this.transportFailure(i.envelope,i,{reason:"abort"})),this.reset(!0)},i.reset=function(e){t.reset(e),o=null,s=[],a=[]},i.abortXHR=function(e){if(e)try{var n=e.readyState;return e.abort(),n!==window.XMLHttpRequest.UNSENT}catch(e){this._debug(e)}return!1},i.xhrStatus=function(e){if(e)try{return e.status}catch(e){this._debug(e)}return-1},i},i=function(){var e=new t,i=n.derive(e),r=!0;return i.accept=function(e,n,t){return r||!n},i.newXMLHttpRequest=function(){return new window.XMLHttpRequest},i.xhrSend=function(e){var n=i.newXMLHttpRequest();n.context=i.context,n.withCredentials=!0,n.open("POST",e.url,!0!==e.sync);var t=e.headers;if(t)for(var r in t)t.hasOwnProperty(r)&&n.setRequestHeader(r,t[r]);return n.setRequestHeader("Content-Type","application/json;charset=UTF-8"),n.onload=function(){200===n.status?e.onSuccess(n.responseText):e.onError(n.statusText)},n.onerror=function(){e.onError(n.statusText)},n.send(e.body),n},i.transportSend=function(e,n){this._debug("Transport",this.getType(),"sending request",n.id,"envelope",e);var t=this;try{var i=!0;n.xhr=this.xhrSend({transport:this,url:e.url,sync:e.sync,headers:this.getConfiguration().requestHeaders,body:JSON.stringify(e.messages),onSuccess:function(i){t._debug("Transport",t.getType(),"received response",i);var o=!1;try{var s=t.convertToMessages(i);0===s.length?(r=!1,t.transportFailure(e,n,{httpCode:204})):(o=!0,t.transportSuccess(e,n,s))}catch(i){if(t._debug(i),!o){r=!1;var a={exception:i};a.httpCode=t.xhrStatus(n.xhr),t.transportFailure(e,n,a)}}},onError:function(o,s){t._debug("Transport",t.getType(),"received error",o,s),r=!1;var a={reason:o,exception:s};a.httpCode=t.xhrStatus(n.xhr),i?t.setTimeout(function(){t.transportFailure(e,n,a)},0):t.transportFailure(e,n,a)}}),i=!1}catch(i){r=!1,this.setTimeout(function(){t.transportFailure(e,n,{exception:i})},0)}},i.reset=function(n){e.reset(n),r=!0},i},r=function(){var e=new t,i=n.derive(e),r=0;function o(e,n,t){var i=this;return function(){i.transportFailure(e,n,"error",t)}}return i.accept=function(e,n,t){return!0},i.jsonpSend=function(e){var n=document.getElementsByTagName("head")[0],t=document.createElement("script"),i="_cometd_jsonp_"+r++;window[i]=function(r){n.removeChild(t),delete window[i],e.onSuccess(r)};var o=e.url;o+=o.indexOf("?")<0?"?":"&",o+="jsonp="+i,o+="&message="+encodeURIComponent(e.body),t.src=o,t.async=!0!==e.sync,t.type="application/javascript",t.onerror=function(n){e.onError("jsonp "+n.type)},n.appendChild(t)},i.transportSend=function(e,n){for(var t=this,i=0,r=e.messages.length,s=[];r>0;){var a=JSON.stringify(e.messages.slice(i,i+r)),u=e.url.length+encodeURI(a).length,c=this.getConfiguration().maxURILength;if(u>c){if(1===r){var l="Bayeux message too big ("+u+" bytes, max is "+c+") for transport "+this.getType();return void this.setTimeout(o.call(this,e,n,l),0)}--r}else s.push(r),i+=r,r=e.messages.length-i}var f=e;if(s.length>1){var d=0,h=s[0];this._debug("Transport",this.getType(),"split",e.messages.length,"messages into",s.join(" + ")),(f=this._mixin(!1,{},e)).messages=e.messages.slice(d,h),f.onSuccess=e.onSuccess,f.onFailure=e.onFailure;for(var g=1;g<s.length;++g){var b=this._mixin(!1,{},e);d=h,h+=s[g],b.messages=e.messages.slice(d,h),b.onSuccess=e.onSuccess,b.onFailure=e.onFailure,this.send(b,n.metaConnect)}}this._debug("Transport",this.getType(),"sending request",n.id,"envelope",f);try{var p=!0;this.jsonpSend({transport:this,url:f.url,sync:f.sync,headers:this.getConfiguration().requestHeaders,body:JSON.stringify(f.messages),onSuccess:function(e){var i=!1;try{var r=t.convertToMessages(e);0===r.length?t.transportFailure(f,n,{httpCode:204}):(i=!0,t.transportSuccess(f,n,r))}catch(e){t._debug(e),i||t.transportFailure(f,n,{exception:e})}},onError:function(e,i){var r={reason:e,exception:i};p?t.setTimeout(function(){t.transportFailure(f,n,r)},0):t.transportFailure(f,n,r)}}),p=!1}catch(e){this.setTimeout(function(){t.transportFailure(f,n,{exception:e})},0)}},i},o=function(){var t,i=new n,r=n.derive(i),o=!0,s=!1,a=!0,u=null,c=null,l=!1,f=null;function d(e,n){e&&(this.webSocketClose(e,n.code,n.reason),this.onClose(e,n))}function h(e){return e===c||e===u}function g(e,n,t){for(var i=[],r=0;r<n.messages.length;++r){var o=n.messages[r];o.id&&i.push(o.id)}e.envelopes[i.join(",")]=[n,t],this._debug("Transport",this.getType(),"stored envelope, envelopes",e.envelopes)}function b(e,n,i){var r=JSON.stringify(n.messages);e.webSocket.send(r),this._debug("Transport",this.getType(),"sent",n,"metaConnect =",i);var o=this.getConfiguration().maxNetworkDelay,s=o;i&&(s+=this.getAdvice().timeout,l=!0);for(var a=this,u=[],c=0;c<n.messages.length;++c)!function(){var i=n.messages[c];i.id&&(u.push(i.id),e.timeouts[i.id]=a.setTimeout(function(){t._debug("Transport",a.getType(),"timing out message",i.id,"after",s,"on",e),d.call(a,e,{code:1e3,reason:"Message Timeout"})},s))}();this._debug("Transport",this.getType(),"waiting at most",s,"ms for messages",u,"maxNetworkDelay",o,", timeouts:",e.timeouts)}function p(e,n,i){try{null===e?(e=c||{envelopes:{},timeouts:{}},g.call(this,e,n,i),function(e){if(!c){var n=t.getURL().replace(/^http/,"ws");this._debug("Transport",this.getType(),"connecting to URL",n);try{var i=t.getConfiguration().protocol;e.webSocket=i?new window.WebSocket(n,i):new window.WebSocket(n),c=e}catch(e){throw o=!1,this._debug("Exception while creating WebSocket object",e),e}a=!1!==t.getConfiguration().stickyReconnect;var r=this,l=t.getConfiguration().connectTimeout;l>0&&(e.connectTimer=this.setTimeout(function(){t._debug("Transport",r.getType(),"timed out while connecting to URL",n,":",l,"ms"),d.call(r,e,{code:1e3,reason:"Connect Timeout"})},l));var f=function(n){n=n||{code:1e3},t._debug("WebSocket onclose",e,n,"connecting",c,"current",u),e.connectTimer&&r.clearTimeout(e.connectTimer),r.onClose(e,n)};e.webSocket.onopen=function(){t._debug("WebSocket onopen",e),e.connectTimer&&r.clearTimeout(e.connectTimer),h(e)?(c=null,u=e,s=!0,r.onOpen(e)):(t._warn("Closing extra WebSocket connection",this,"active connection",u),d.call(r,e,{code:1e3,reason:"Extra Connection"}))},e.webSocket.onclose=f,e.webSocket.onerror=function(){f({code:1e3,reason:"Error"})},e.webSocket.onmessage=function(n){t._debug("WebSocket onmessage",n,e),r.onMessage(e,n)},this._debug("Transport",this.getType(),"configured callbacks on",e)}}.call(this,e)):(g.call(this,e,n,i),b.call(this,e,n,i))}catch(n){var r=this;this.setTimeout(function(){d.call(r,e,{code:1e3,reason:"Exception",exception:n})},0)}}return r.reset=function(e){i.reset(e),o=!0,e&&(s=!1),a=!0,u=null,c=null,l=!1},r._notifySuccess=function(e,n){e.call(this,n)},r._notifyFailure=function(e,n,t,i){e.call(this,n,t,i)},r.onOpen=function(e){var n=e.envelopes;for(var t in this._debug("Transport",this.getType(),"opened",e,"pending messages",n),n)if(n.hasOwnProperty(t)){var i=n[t],r=i[0],o=i[1];f=r.onSuccess,b.call(this,e,r,o)}},r.onMessage=function(n,t){this._debug("Transport",this.getType(),"received websocket message",t,n);for(var i=!1,r=this.convertToMessages(t.data),o=[],s=0;s<r.length;++s){var a=r[s];if((/^\/meta\//.test(a.channel)||void 0===a.data)&&a.id){o.push(a.id);var u=n.timeouts[a.id];u&&(this.clearTimeout(u),delete n.timeouts[a.id],this._debug("Transport",this.getType(),"removed timeout for message",a.id,", timeouts",n.timeouts))}"/meta/connect"===a.channel&&(l=!1),"/meta/disconnect"!==a.channel||l||(i=!0)}for(var c=!1,d=n.envelopes,h=0;h<o.length;++h){var g=o[h];for(var b in d)if(d.hasOwnProperty(b)){var p=b.split(","),m=e.inArray(g,p);if(m>=0){c=!0,p.splice(m,1);var v=d[b][0],y=d[b][1];delete d[b],p.length>0&&(d[p.join(",")]=[v,y]);break}}}c&&this._debug("Transport",this.getType(),"removed envelope, envelopes",d),this._notifySuccess(f,r),i&&this.webSocketClose(n,1e3,"Disconnect")},r.onClose=function(e,n){this._debug("Transport",this.getType(),"closed",e,n),h(e)&&(o=a&&s,c=null,u=null);var t=e.timeouts;for(var i in e.timeouts={},t)t.hasOwnProperty(i)&&this.clearTimeout(t[i]);var r=e.envelopes;for(var f in e.envelopes={},r)if(r.hasOwnProperty(f)){var d=r[f][0];r[f][1]&&(l=!1);var g={websocketCode:n.code,reason:n.reason};n.exception&&(g.exception=n.exception),this._notifyFailure(d.onFailure,e,d.messages,g)}},r.registered=function(e,n){i.registered(e,n),t=n},r.accept=function(e,n,i){return this._debug("Transport",this.getType(),"accept, supported:",o),o&&!!window.WebSocket&&!1!==t.websocketEnabled},r.send=function(e,n){this._debug("Transport",this.getType(),"sending",e,"metaConnect =",n),p.call(this,u,e,n)},r.webSocketClose=function(e,n,t){try{e.webSocket&&e.webSocket.close(n,t)}catch(e){this._debug(e)}},r.abort=function(){i.abort(),d.call(this,u,{code:1e3,reason:"Abort"}),this.reset(!0)},r},s=["0","1","2","3","4","5","6","7","8","9","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",".","-",":","+","=","^","!","/","*","?","&","<",">","(",")","[","]","{","}","@","%","$","#"],a=[0,68,0,84,83,82,72,0,75,76,70,65,0,63,62,69,0,1,2,3,4,5,6,7,8,9,64,0,73,66,74,71,81,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,77,0,78,67,0,0,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,79,0,80,0,0];return{CometD:function(n){var t,s,a,u,c,l=this,f=n||"default",d=!1,h=new function(){var e=[],n={};this.getTransportTypes=function(){return e.slice(0)},this.findTransportTypes=function(t,i,r){for(var o=[],s=0;s<e.length;++s){var a=e[s];!0===n[a].accept(t,i,r)&&o.push(a)}return o},this.negotiateTransport=function(t,i,r,o){for(var s=0;s<e.length;++s)for(var a=e[s],u=0;u<t.length;++u)if(a===t[u]){var c=n[a];if(!0===c.accept(i,r,o))return c}return null},this.add=function(t,i,r){for(var o=!1,s=0;s<e.length;++s)if(e[s]===t){o=!0;break}return o||("number"!=typeof r?e.push(t):e.splice(r,0,t),n[t]=i),!o},this.find=function(t){for(var i=0;i<e.length;++i)if(e[i]===t)return n[t];return null},this.remove=function(t){for(var i=0;i<e.length;++i)if(e[i]===t){e.splice(i,1);var r=n[t];return delete n[t],r}return null},this.clear=function(){e=[],n={}},this.reset=function(t){for(var i=0;i<e.length;++i)n[e[i]].reset(t)}},g="disconnected",b=0,p=null,m=0,v=[],y=!1,_=0,C={},w=0,T=null,S=[],E={},x={},k={},O=!1,N=!1,I=0,L=0,M={protocol:null,stickyReconnect:!0,connectTimeout:0,maxConnections:2,backoffIncrement:1e3,maxBackoff:6e4,logLevel:"info",maxNetworkDelay:1e4,requestHeaders:{},appendMessageTypeToURL:!0,autoBatch:!1,urls:{},maxURILength:2e3,advice:{timeout:6e4,interval:0,reconnect:void 0,maxInterval:0}};function D(e,n){try{return e[n]}catch(e){return}}function A(n){return e.isString(n)}function R(e){return void 0!==e&&null!==e&&"function"==typeof e}function F(e,n){for(var t="";--n>0&&!(e>=Math.pow(10,n));)t+="0";return t+=e}function B(e,n){if(window.console){var t=window.console[e];if(R(t)){var i=new Date;[].splice.call(n,0,0,F(i.getHours(),2)+":"+F(i.getMinutes(),2)+":"+F(i.getSeconds(),2)+"."+F(i.getMilliseconds(),3)),t.apply(window.console,n)}}}function U(e){return/(^https?:\/\/)?(((\[[^\]]+\])|([^:\/\?#]+))(:(\d+))?)?([^\?#]*)(.*)?/.exec(e)}function P(e){if(e){var n=C[e.channel];n&&n[e.id]&&(delete n[e.id],l._debug("Removed",e.listener?"listener":"subscription",e))}}function j(e){e&&!e.listener&&P(e)}function q(){for(var e in C)if(C.hasOwnProperty(e)){var n=C[e];if(n)for(var t in n)n.hasOwnProperty(t)&&j(n[t])}}function G(e){g!==e&&(l._debug("Status",g,"->",e),g=e)}function W(){return"disconnecting"===g||"disconnected"===g}function H(){return""+ ++b}function z(e,n,t,i,r){try{return n.call(e,i)}catch(e){var o=l.onExtensionException;if(R(o)){l._debug("Invoking extension exception handler",t,e);try{o.call(l,e,t,r,i)}catch(e){l._info("Exception during execution of extension exception handler",t,e)}}else l._info("Exception during execution of extension",t,e);return i}}function Q(e){for(var n=S.length-1;n>=0&&void 0!==e&&null!==e;--n){var t=S[n],i=t.extension.outgoing;if(R(i)){var r=z(t.extension,i,t.name,e,!0);e=void 0===r?e:r}}return e}function X(e,n){var t=C[e];if(t)for(var i in t)if(t.hasOwnProperty(i)){var r=t[i];if(r)try{r.callback.call(r.scope,n)}catch(e){var o=l.onListenerException;if(R(o)){l._debug("Invoking listener exception handler",r,e);try{o.call(l,e,r,r.listener,n)}catch(e){l._info("Exception during execution of listener exception handler",r,e)}}else l._info("Exception during execution of listener",r,n,e)}}}function V(e,n){X(e,n);for(var t=e.split("/"),i=t.length-1,r=i;r>0;--r){var o=t.slice(0,r).join("/")+"/*";r===i&&X(o,n),X(o+="*",n)}}function K(){null!==T&&e.clearTimeout(T),T=null}function J(n,t){K();var i=E.interval+t;l._debug("Function scheduled in",i,"ms, interval =",E.interval,"backoff =",w,n),T=e.setTimeout(l,n,i)}function Y(e,n,i,r){for(var o=0;o<n.length;++o){var s=n[o],a=s.id;p&&(s.clientId=p),void 0!==(s=Q(s))&&null!==s?(s.id=a,n[o]=s):(delete x[a],n.splice(o--,1))}if(0!==n.length){var f=l.getURL();M.appendMessageTypeToURL&&(f.match(/\/$/)||(f+="/"),r&&(f+=r));var d={url:f,sync:e,messages:n,onSuccess:function(e){try{u.call(l,e)}catch(e){l._info("Exception during handling of messages",e)}},onFailure:function(e,n,t){try{var i=l.getTransport();t.connectionType=i?i.getType():"unknown",c.call(l,e,n,t)}catch(e){l._info("Exception during handling of failure",e)}}};l._debug("Send",d),t.send(d,i)}}function Z(e){m>0||!0===y?v.push(e):Y(!1,[e],!1)}function $(){w=0}function ee(){var e=v;v=[],e.length>0&&Y(!1,e,!1)}function ne(e){G("connecting"),J(function(){!function(){if(!W()){var e={id:H(),channel:"/meta/connect",connectionType:t.getType()};N||(e.advice={timeout:0}),G("connecting"),l._debug("Connect sent",e),Y(!1,[e],!0,"connect"),G("connected")}}()},e)}function te(e){e&&(E=l._mixin(!1,{},M.advice,e),l._debug("New advice",E))}function ie(e){if(K(),e&&t&&t.abort(),p=null,G("disconnected"),m=0,$(),t=null,O=!1,N=!1,v.length>0){var n=v;v=[],c.call(l,void 0,n,{reason:"Disconnected"})}}function re(e,n,t){var i=l.onTransportException;if(R(i)){l._debug("Invoking transport exception handler",e,n,t);try{i.call(l,t,e,n)}catch(e){l._info("Exception during execution of transport exception handler",e)}}}function oe(e,n){R(e)&&(n=e,e=void 0),p=null,q(),W()&&h.reset(!0),te({}),m=0,y=!0,s=e,a=n;var i=l.getURL(),r=h.findTransportTypes("1.0",d,i),o={id:H(),version:"1.0",minimumVersion:"1.0",channel:"/meta/handshake",supportedConnectionTypes:r,advice:{timeout:E.timeout,interval:E.interval}},u=l._mixin(!1,{},s,o);if(l._putCallback(u.id,n),!t&&!(t=h.negotiateTransport(r,"1.0",d,i))){var c="Could not find initial transport among: "+h.getTransportTypes();throw l._warn(c),c}l._debug("Initial transport is",t.getType()),G("handshaking"),l._debug("Handshake sent",u),Y(!1,[u],!1,"handshake")}function se(e,n){try{e.call(l,n)}catch(e){var t=l.onCallbackException;if(R(t)){l._debug("Invoking callback exception handler",e);try{t.call(l,e,n)}catch(e){l._info("Exception during execution of callback exception handler",e)}}else l._info("Exception during execution of message callback",e)}}function ae(e){var n=l._getCallback([e.id]);R(n)&&(delete x[e.id],se(n,e))}function ue(n){var t=k[n.id];if(delete k[n.id],t){l._debug("Handling remote call response for",n,"with context",t);var i=t.timeout;i&&e.clearTimeout(i);var r=t.callback;if(R(r))return se(r,n),!0}return!1}function ce(e){l._debug("Transport failure handling",e),e.transport&&(t=e.transport),e.url&&t.setURL(e.url);var n=e.action,i=e.delay||0;switch(n){case"handshake":!function(e){G("handshaking"),y=!0,J(function(){oe(s,a)},e)}(i);break;case"retry":ne(i);break;case"none":ie(!0);break;default:throw"Unknown action "+n}}function le(e,n){ae(e),V("/meta/handshake",e),V("/meta/unsuccessful",e),W()&&(n.action="none"),l.onTransportFailure.call(l,e,n,ce)}function fe(e){le(e,{cause:"failure",action:"handshake",transport:null})}function de(e,n){V("/meta/connect",e),V("/meta/unsuccessful",e),W()&&(n.action="none"),l.onTransportFailure.call(l,e,n,ce)}function he(e){N=!1,de(e,{cause:"failure",action:"retry",transport:null})}function ge(e){ie(!0),ae(e),V("/meta/disconnect",e),V("/meta/unsuccessful",e)}function be(e){ge(e)}function pe(e){var n=C[e.subscription];if(n)for(var t in n)if(n.hasOwnProperty(t)){var i=n[t];i&&!i.listener&&(delete n[t],l._debug("Removed failed subscription",i))}ae(e),V("/meta/subscribe",e),V("/meta/unsuccessful",e)}function me(e){pe(e)}function ve(e){ae(e),V("/meta/unsubscribe",e),V("/meta/unsuccessful",e)}function ye(e){ve(e)}function _e(e){ue(e)||(ae(e),V("/meta/publish",e),V("/meta/unsuccessful",e))}function Ce(e){_e(e)}function we(e){if(I=0,void 0!==(e=function(e){for(var n=0;n<S.length&&void 0!==e&&null!==e;++n){var t=S[n],i=t.extension.incoming;if(R(i)){var r=z(t.extension,i,t.name,e,!1);e=void 0===r?e:r}}return e}(e))&&null!==e)switch(te(e.advice),e.channel){case"/meta/handshake":!function(e){var n=l.getURL();if(e.successful){var i=l._isCrossDomain(U(n)[2]),r=h.negotiateTransport(e.supportedConnectionTypes,e.version,i,n);if(null===r)return e.successful=!1,void le(e,{cause:"negotiation",action:"none",transport:null});t!==r&&(l._debug("Transport",t.getType(),"->",r.getType()),t=r),p=e.clientId,y=!1,ee(),e.reestablish=O,O=!0,ae(e),V("/meta/handshake",e),L=e["x-messages"]||0;var o=W()?"none":E.reconnect||"retry";switch(o){case"retry":$(),0===L?ne(0):l._debug("Processing",L,"handshake-delivered messages");break;case"none":ie(!0);break;default:throw"Unrecognized advice action "+o}}else le(e,{cause:"unsuccessful",action:E.reconnect||"handshake",transport:t})}(e);break;case"/meta/connect":!function(e){if(N=e.successful){V("/meta/connect",e);var n=W()?"none":E.reconnect||"retry";switch(n){case"retry":$(),ne(w);break;case"none":ie(!1);break;default:throw"Unrecognized advice action "+n}}else de(e,{cause:"unsuccessful",action:E.reconnect||"retry",transport:t})}(e);break;case"/meta/disconnect":!function(e){e.successful?(ie(!1),ae(e),V("/meta/disconnect",e)):ge(e)}(e);break;case"/meta/subscribe":!function(e){e.successful?(ae(e),V("/meta/subscribe",e)):pe(e)}(e);break;case"/meta/unsubscribe":!function(e){e.successful?(ae(e),V("/meta/unsubscribe",e)):ve(e)}(e);break;default:!function(e){void 0!==e.data?ue(e)||(V(e.channel,e),L>0&&0==--L&&(l._debug("Processed last handshake-delivered message"),ne(0))):void 0===e.successful?l._warn("Unknown Bayeux Message",e):e.successful?(ae(e),V("/meta/publish",e)):_e(e)}(e)}}function Te(e){var n=C[e];if(n)for(var t in n)if(n.hasOwnProperty(t)&&n[t])return!0;return!1}function Se(e,n){var t={scope:e,method:n};if(R(e))t.scope=void 0,t.method=e;else if(A(n)){if(!e)throw"Invalid scope "+e;if(t.method=e[n],!R(t.method))throw"Invalid callback "+n+" for scope "+e}else if(!R(n))throw"Invalid callback "+n;return t}function Ee(e,n,t,i){var r=Se(n,t);l._debug("Adding",i?"listener":"subscription","on",e,"with scope",r.scope,"and callback",r.method);var o=++_,s={id:o,channel:e,scope:r.scope,callback:r.method,listener:i},a=C[e];return a||(a={},C[e]=a),a[o]=s,l._debug("Added",i?"listener":"subscription",s),s}this._mixin=function(e,n,t){for(var i=n||{},r=2;r<arguments.length;++r){var o=arguments[r];if(void 0!==o&&null!==o)for(var s in o)if(o.hasOwnProperty(s)){var a=D(o,s),u=D(i,s);if(a===n)continue;if(void 0===a)continue;if(e&&"object"==typeof a&&null!==a)if(a instanceof Array)i[s]=this._mixin(e,u instanceof Array?u:[],a);else{var c="object"!=typeof u||u instanceof Array?{}:u;i[s]=this._mixin(e,c,a)}else i[s]=a}}return i},this._warn=function(){B("warn",arguments)},this._info=function(){"warn"!==M.logLevel&&B("info",arguments)},this._debug=function(){"debug"===M.logLevel&&B("debug",arguments)},this._isCrossDomain=function(e){return!!(window.location&&window.location.host&&e)&&e!==window.location.host},this.send=Z,this._getCallback=function(e){return x[e]},this._putCallback=function(e,n){var t=this._getCallback(e);return R(n)&&(x[e]=n),t},this.onTransportFailure=function(e,n,i){this._debug("Transport failure",n,"for",e);var r=this.getTransportRegistry(),o=this.getURL(),s=this._isCrossDomain(U(o)[2]),a=r.findTransportTypes("1.0",s,o);if("none"===n.action){if("/meta/handshake"===e.channel&&!n.transport){var u="Could not negotiate transport, client=["+a+"], server=["+e.supportedConnectionTypes+"]";this._warn(u),re(t.getType(),null,{reason:u,connectionType:t.getType(),transport:t})}}else if(n.delay=this.getBackoffPeriod(),"/meta/handshake"===e.channel){if(!n.transport){var c=r.negotiateTransport(a,"1.0",s,o);c?(this._debug("Transport",t.getType(),"->",c.getType()),re(t.getType(),c.getType(),e.failure),n.action="handshake",n.transport=c):(this._warn("Could not negotiate transport, client=["+a+"]"),re(t.getType(),null,e.failure),n.action="none")}"none"!==n.action&&this.increaseBackoffPeriod()}else{var f=(new Date).getTime();if(0===I&&(I=f),"retry"===n.action){n.delay=this.increaseBackoffPeriod();var d=E.maxInterval;if(d>0){var h=E.timeout+E.interval+d;f-I+w>h&&(n.action="handshake")}}"handshake"===n.action&&(n.delay=0,r.reset(!1),this.resetBackoffPeriod())}i.call(l,n)},this.receive=we,u=function(e){l._debug("Received",e);for(var n=0;n<e.length;++n)we(e[n])},c=function(e,n,t){l._debug("handleFailure",e,n,t),t.transport=e;for(var i=0;i<n.length;++i){var r=n[i],o={id:r.id,successful:!1,channel:r.channel,failure:t};switch(t.message=r,r.channel){case"/meta/handshake":fe(o);break;case"/meta/connect":he(o);break;case"/meta/disconnect":be(o);break;case"/meta/subscribe":o.subscription=r.subscription,me(o);break;case"/meta/unsubscribe":o.subscription=r.subscription,ye(o);break;default:Ce(o)}}},this.registerTransport=function(e,n,t){var i=h.add(e,n,t);return i&&(this._debug("Registered transport",e),R(n.registered)&&n.registered(e,this)),i},this.unregisterTransport=function(e){var n=h.remove(e);return null!==n&&(this._debug("Unregistered transport",e),R(n.unregistered)&&n.unregistered()),n},this.unregisterTransports=function(){h.clear()},this.getTransportTypes=function(){return h.getTransportTypes()},this.findTransport=function(e){return h.find(e)},this.getTransportRegistry=function(){return h},this.configure=function(e){(function(e){l._debug("Configuring cometd object with",e),A(e)&&(e={url:e}),e||(e={}),M=l._mixin(!1,M,e);var n=l.getURL();if(!n)throw"Missing required configuration parameter 'url' specifying the Bayeux server URL";var t=U(n),i=t[2],r=t[8],o=t[9];if(d=l._isCrossDomain(i),M.appendMessageTypeToURL)if(void 0!==o&&o.length>0)l._info("Appending message type to URI "+r+o+" is not supported, disabling 'appendMessageTypeToURL' configuration"),M.appendMessageTypeToURL=!1;else{var s=r.split("/"),a=s.length-1;r.match(/\/$/)&&(a-=1),s[a].indexOf(".")>=0&&(l._info("Appending message type to URI "+r+" is not supported, disabling 'appendMessageTypeToURL' configuration"),M.appendMessageTypeToURL=!1)}}).call(this,e)},this.init=function(e,n){this.configure(e),this.handshake(n)},this.handshake=function(e,n){if("disconnected"!==g)throw"Illegal state: handshaken";oe(e,n)},this.disconnect=function(e,n,t){if(!W()){"boolean"!=typeof e&&(t=n,n=e,e=!1),R(n)&&(t=n,n=void 0);var i={id:H(),channel:"/meta/disconnect"},r=this._mixin(!1,{},n,i);l._putCallback(r.id,t),G("disconnecting"),Y(!0===e,[r],!1,"disconnect")}},this.startBatch=function(){++m,l._debug("Starting batch, depth",m)},this.endBatch=function(){!function(){if(--m,l._debug("Ending batch, depth",m),m<0)throw"Calls to startBatch() and endBatch() are not paired";0!==m||W()||y||ee()}()},this.batch=function(e,n){var t=Se(e,n);this.startBatch();try{t.method.call(t.scope),this.endBatch()}catch(e){throw this._info("Exception during execution of batch",e),this.endBatch(),e}},this.addListener=function(e,n,t){if(arguments.length<2)throw"Illegal arguments number: required 2, got "+arguments.length;if(!A(e))throw"Illegal argument type: channel must be a string";return Ee(e,n,t,!0)},this.removeListener=function(e){if(!(e&&e.channel&&"id"in e))throw"Invalid argument: expected subscription, not "+e;P(e)},this.clearListeners=function(){C={}},this.subscribe=function(e,n,t,i,r){if(arguments.length<2)throw"Illegal arguments number: required 2, got "+arguments.length;if(!A(e))throw"Illegal argument type: channel must be a string";if(W())throw"Illegal state: disconnected";R(n)&&(r=i,i=t,t=n,n=void 0),R(i)&&(r=i,i=void 0);var o=!Te(e),s=Ee(e,n,t,!1);if(o){var a={id:H(),channel:"/meta/subscribe",subscription:e},u=this._mixin(!1,{},i,a);l._putCallback(u.id,r),Z(u)}return s},this.unsubscribe=function(e,n,t){if(arguments.length<1)throw"Illegal arguments number: required 1, got "+arguments.length;if(W())throw"Illegal state: disconnected";R(n)&&(t=n,n=void 0),this.removeListener(e);var i=e.channel;if(!Te(i)){var r={id:H(),channel:"/meta/unsubscribe",subscription:i},o=this._mixin(!1,{},n,r);l._putCallback(o.id,t),Z(o)}},this.resubscribe=function(e,n){if(j(e),e)return this.subscribe(e.channel,e.scope,e.callback,n)},this.clearSubscriptions=function(){q()},this.publish=function(e,n,t,i){if(arguments.length<1)throw"Illegal arguments number: required 1, got "+arguments.length;if(!A(e))throw"Illegal argument type: channel must be a string";if(/^\/meta\//.test(e))throw"Illegal argument: cannot publish to meta channels";if(W())throw"Illegal state: disconnected";R(n)?(i=n,n={},t=void 0):R(t)&&(i=t,t=void 0);var r={id:H(),channel:e,data:n},o=this._mixin(!1,{},t,r);l._putCallback(o.id,i),Z(o)},this.publishBinary=function(e,n,t,i,r){R(n)?(r=n,n=new ArrayBuffer(0),t=!0,i=void 0):R(t)?(r=t,t=!0,i=void 0):R(i)&&(r=i,i=void 0);var o={meta:i,data:n,last:t};this.publish(e,o,{ext:{binary:{}}},r)},this.remoteCall=function(n,t,i,r,o){if(arguments.length<1)throw"Illegal arguments number: required 1, got "+arguments.length;if(!A(n))throw"Illegal argument type: target must be a string";if(W())throw"Illegal state: disconnected";if(R(t)?(o=t,t={},i=M.maxNetworkDelay,r=void 0):R(i)?(o=i,i=M.maxNetworkDelay,r=void 0):R(r)&&(o=r,r=void 0),"number"!=typeof i)throw"Illegal argument type: timeout must be a number";n.match(/^\//)||(n="/"+n);var s="/service"+n,a={id:H(),channel:s,data:t},u=this._mixin(!1,{},r,a),c={callback:o};i>0&&(c.timeout=e.setTimeout(l,function(){l._debug("Timing out remote call",u,"after",i,"ms"),_e({id:u.id,error:"406::timeout",successful:!1,failure:{message:u,reason:"Remote Call Timeout"}})},i),l._debug("Scheduled remote call timeout",u,"in",i,"ms")),k[u.id]=c,Z(u)},this.remoteCallBinary=function(e,n,t,i,r,o){R(n)?(o=n,n=new ArrayBuffer(0),t=!0,i=void 0,r=M.maxNetworkDelay):R(t)?(o=t,t=!0,i=void 0,r=M.maxNetworkDelay):R(i)?(o=i,i=void 0,r=M.maxNetworkDelay):R(r)&&(o=r,r=M.maxNetworkDelay);var s={meta:i,data:n,last:t};this.remoteCall(e,s,r,{ext:{binary:{}}},o)},this.getStatus=function(){return g},this.isDisconnected=W,this.setBackoffIncrement=function(e){M.backoffIncrement=e},this.getBackoffIncrement=function(){return M.backoffIncrement},this.getBackoffPeriod=function(){return w},this.increaseBackoffPeriod=function(){return w<M.maxBackoff&&(w+=M.backoffIncrement),w},this.resetBackoffPeriod=function(){$()},this.setLogLevel=function(e){M.logLevel=e},this.registerExtension=function(e,n){if(arguments.length<2)throw"Illegal arguments number: required 2, got "+arguments.length;if(!A(e))throw"Illegal argument type: extension name must be a string";for(var t=!1,i=0;i<S.length;++i)if(S[i].name===e){t=!0;break}return t?(this._info("Could not register extension with name",e,"since another extension with the same name already exists"),!1):(S.push({name:e,extension:n}),this._debug("Registered extension",e),R(n.registered)&&n.registered(e,this),!0)},this.unregisterExtension=function(e){if(!A(e))throw"Illegal argument type: extension name must be a string";for(var n=!1,t=0;t<S.length;++t){var i=S[t];if(i.name===e){S.splice(t,1),n=!0,this._debug("Unregistered extension",e);var r=i.extension;R(r.unregistered)&&r.unregistered();break}}return n},this.getExtension=function(e){for(var n=0;n<S.length;++n){var t=S[n];if(t.name===e)return t.extension}return null},this.getName=function(){return f},this.getClientId=function(){return p},this.getURL=function(){if(t){var e=t.getURL();if(e)return e;if(e=M.urls[t.getType()])return e}return M.url},this.getTransport=function(){return t},this.getConfiguration=function(){return this._mixin(!0,{},M)},this.getAdvice=function(){return this._mixin(!0,{},E)},window.WebSocket&&this.registerTransport("websocket",new o),this.registerTransport("long-polling",new i),this.registerTransport("callback-polling",new r)},Transport:n,RequestTransport:t,LongPollingTransport:i,CallbackPollingTransport:r,WebSocketTransport:o,Utils:e,Z85:{encode:function(e){var n=null;if(e instanceof ArrayBuffer?n=e:e.buffer instanceof ArrayBuffer?n=e.buffer:Array.isArray(e)&&(n=new Uint8Array(e).buffer),null==n)throw"Cannot Z85 encode "+e;for(var t=n.byteLength,i=t%4,r=4-(0===i?4:i),o=new DataView(n),a="",u=0,c=0;c<t+r;++c){var l=c>=t;if(u=256*u+(l?0:o.getUint8(c)),(c+1)%4==0){for(var f=52200625,d=5;d>0;--d){if(!l||d>r){var h=Math.floor(u/f)%85;a+=s[h]}f/=85}u=0}}return a},decode:function(e){for(var n=e.length%5,t=5-(0===n?5:n),i=0;i<t;++i)e+=s[s.length-1];for(var r=e.length,o=new ArrayBuffer(4*r/5-t),u=new DataView(o),c=0,l=0,f=0,d=0;d<r;++d){var h=e.charCodeAt(l++)-32;if(c=85*c+a[h],l%5==0){for(var g=16777216;g>=1;)f<u.byteLength&&u.setUint8(f++,Math.floor(c/g)%256),g/=256;c=0}}return o}}}},e.exports=i()},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i,r=(i=t(0))&&i.__esModule?i:{default:i};var o=function(){var e=new r.default("amb.GraphQLSubscriptionExtension"),n={};this.isGraphQLChannel=function(e){return e&&e.startsWith("/rw/graphql")},this.addGraphQLChannel=function(e,t){n[e]=t},this.removeGraphQLChannel=function(e){delete n[e]},this.getGraphQLSubscriptions=function(){return n},this.outgoing=function(t){return"/meta/subscribe"===t.channel&&this.isGraphQLChannel(t.subscription)&&(t.ext||(t.ext={}),n[t.subscription]&&(e.debug("Subscribing with GraphQL subscription:"+n[t.subscription]),t.ext.serializedGraphQLSubscription=n[t.subscription])),t}};n.default=o},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i,r=(i=t(0))&&i.__esModule?i:{default:i};var o=function(){var e=new r.default("amb.SessionExtension"),n=!1;this.extendSession=function(){n=!0},this.outgoing=function(t){return"/meta/connect"===t.channel&&n&&(t.ext||(t.ext={}),e.debug("extendSession"),t.ext.extendSession=!0,n=!1),t}};n.default=o},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=o(t(0)),r=o(t(1));function o(e){return e&&e.__esModule?e:{default:e}}var s=function(){var e=new i.default("amb.TokenManagementExtension"),n="/meta/subscribe",t="/meta/unsubscribe",o="/meta/handshake",s=r.default.subscribeCommandsFlow.maxInflight,a=[];function u(e){return e.channel==n||e.channel==t}function c(){e.debug("notifyOnAvailabilityOfToken - current tokenCount: "+s);try{a.forEach(function(e){e()})}catch(n){e.addErrorMessage("notifyOnAvailabilityOfToken - failed to call tokenEventListeners. Error Details : "+n)}}this.updateTokenCount=function(e){s=e},this.refillTokens=function(){s=r.default.subscribeCommandsFlow.maxInflight,c(),e.debug("refillTokens -- tokenCount : "+s)},this.outgoing=function(e){return function(e){return e.channel===o}(e)&&(e.ext||(e.ext={}),e.ext.supportsSubscribeCommandFlow=!0),r.default.subscribeCommandsFlow.enable?(u(e)&&s>0&&s--,e):e},this.incoming=function(e){return r.default.subscribeCommandsFlow.enable?(u(e)?(s<r.default.subscribeCommandsFlow.maxInflight&&s++,c()):function(e){if(!e.ext)return!1;var n=e.ext.received_by_glide;return!!n&&n&&u(n)}(e)&&(e=null),e):e},this.getTokenCount=function(){return s},this.addTokenAvailabilityListener=function(n){n&&(e.debug("addTokenAvailabilityListener - tokenEventListener : "+n),a.push(n))},this.removeTokenAvailabilityListener=function(n){if(n){e.debug("removeTokenAvailabilityListener - tokenEventListener : "+n);var t=a.findIndex(function(e){return n===e});-1!==t&&(e.debug("removeTokenAvailabilityListener - removing listener at index : "+t),a.splice(t,1))}}};n.default=s},function(e,n,t){var i;i=function(e){return function(){var n=e,t=n.lib.WordArray;n.enc.Base64={stringify:function(e){var n=e.words,t=e.sigBytes,i=this._map;e.clamp();for(var r=[],o=0;o<t;o+=3)for(var s=(n[o>>>2]>>>24-o%4*8&255)<<16|(n[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|n[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a<t;a++)r.push(i.charAt(s>>>6*(3-a)&63));var u=i.charAt(64);if(u)for(;r.length%4;)r.push(u);return r.join("")},parse:function(e){var n=e.length,i=this._map,r=this._reverseMap;if(!r){r=this._reverseMap=[];for(var o=0;o<i.length;o++)r[i.charCodeAt(o)]=o}var s=i.charAt(64);if(s){var a=e.indexOf(s);-1!==a&&(n=a)}return function(e,n,i){for(var r=[],o=0,s=0;s<n;s++)if(s%4){var a=i[e.charCodeAt(s-1)]<<s%4*2,u=i[e.charCodeAt(s)]>>>6-s%4*2;r[o>>>2]|=(a|u)<<24-o%4*8,o++}return t.create(r,o)}(e,n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),e.enc.Base64},e.exports=i(t(10))},function(e,n,t){var i;i=function(e){return e.enc.Utf8},e.exports=i(t(10))},function(e,n,t){"use strict";function i(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var r=function e(){!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),i(this,"emit",function(e,n){window.localStorage.setItem(e,JSON.stringify(n)),window.localStorage.removeItem(e)}),i(this,"on",function(e,n){window.addEventListener("storage",function(t){var i=t.key,r=t.newValue;i===e&&r&&n(JSON.parse(r))})})};n.default=r},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:134217727,n=[],t=Math.max(1,Math.floor(e));return{enqueue:function(e){return this.getAvailableSpace()>0&&(n.push(e),!0)},enqueueMultiple:function(e){return this.getAvailableSpace()>=e.length&&(n=n.concat(e),!0)},dequeue:function(){var e;return n.length>0&&(e=n.shift()),e},dequeueMultiple:function(e){var t;return e>=0&&n.length>=e&&(t=[],e>0&&(t=n.slice(0,e),n=n.slice(e))),t},clear:function(){n=[]},getSize:function(){return n.length},getCapacity:function(){return t},getAvailableSpace:function(){return t-n.length},getQueueBuffer:function(){return n}}};n.default=i},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=s(t(1)),r=t(3),o=s(t(0));function s(e){return e&&e.__esModule?e:{default:e}}var a=function(e,n){var t={SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe"},s=202,a=429,u=3e5,c=new o.default("amb.SubscriptionCommandSender");n.addTokenAvailabilityListener(function(){w()});var l=!i.default.subscribeCommandsFlow.enable,f=null;function d(e,n,t){return Math.min(t,Math.max(n,e))}function h(){return n.getTokenCount()>=i.default.subscribeCommandsFlow.maxInflight}function g(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(e||(0,r.isNil)(f)){var t=d(i.default.subscribeCommandsFlow.maxWait,0,u);c.debug("restartTimer - force: "+e+", timerObject : "+f+", timeInterval : "+t),b(),f=setTimeout(function(){f=null,c.debug("onTimer - stopping : "+l),l||(n.refillTokens(),w())},t)}}function b(){(0,r.isNil)(f)||(c.debug("stopTimer"),clearTimeout(f),f=null)}function p(){var e=parseInt(i.default.subscribeCommandsFlow.retryDelay.min);return e=d(e,0,u)}function m(e,n,o,s){var a;c.debug("scheduleRetry - channel : "+e.getName()+", triesLeft : "+n+", mode : "+o);var u=function(e){return d(i.default.subscribeCommandsFlow.retryDelay.increaseFactor*e,i.default.subscribeCommandsFlow.retryDelay.min,i.default.subscribeCommandsFlow.retryDelay.max)}(s);switch(o){case t.SUBSCRIBE:a=function(){return _(e,n,u)};break;case t.UNSUBSCRIBE:a=function(){return C(e,n,u)}}(0,r.isNil)(a)||setTimeout(a,s)}function v(e,t,i,r,o){c.debug("onResponse - response ".concat(JSON.stringify(e),", channel ").concat(JSON.stringify(t),", mode : ").concat(i,", \n\t\t\ttriesLeft ").concat(r,", stopping : ").concat(l,", tokenCount : ").concat(n.getTokenCount(),", isBucketFull - ").concat(h(),", retryDelay - ").concat(o)),l?t.subscriptionCallback(e):(r-=1,h()&&b(),r>0&&function(e){if(c.debug("isRetriable - response : "+e),e&&e.ext){var n=e.ext.rejected_by_glide;if(n){var t=parseInt(e.ext["glide.amb.reply.status.code"]);if(c.addWarnMessage("isRetriable - rejected_by_glide : "+n+", glide.amb.reply.status.code : "+t),!isNaN(t))return t==a||t==s}}return c.debug("isRetriable - "+!1),!1}(e)?m(t,r,i,o):t.subscriptionCallback(e),w())}function y(n){return c.debug("addItemToQueue - item : "+n),!!e.enqueue(n)&&(w(),!0)}function _(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:p();return c.debug("enqueueSubscribe - channel: "+e.getName()+", triesLeft : "+n+", stopping : "+l+", retryDelay : "+o),!!(!l&&(0,r.isObject)(e)&&((0,r.isNil)(n)&&(n=1+Math.floor(i.default.subscribeCommandsFlow.retries)),n>0))&&y(function(){c.debug("enqueueSubscribe - inside the item execution. Calling channel._subscribeToCometD - channel: "+e.getName()+", triesLeft : "+n),e._subscribeToCometD(function(i){return v(i,e,t.SUBSCRIBE,n,o)})})}function C(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:p();return c.debug("enqueueUnsubscribe - channel: "+e.getName()+", triesLeft : "+n+", stopping : "+l+", retryDelay : "+o),!!(!l&&(0,r.isObject)(e)&&((0,r.isNil)(n)&&(n=1+Math.floor(i.default.subscribeCommandsFlow.retries)),n>0))&&y(function(){e._unsubscribeFromCometD(function(i){return v(i,e,t.UNSUBSCRIBE,n,o)})})}function w(){var t=Math.min(e.getSize(),d(n.getTokenCount(),0,i.default.subscribeCommandsFlow.maxInflight));c.debug("processQueue - numberToProcess : "+t),t>0&&(e.dequeueMultiple(t).forEach(function(e){return(0,r.isNil)(e)||e()}),g(!1))}return{subscribeToChannel:function(e){return c.debug("subscribeToChannel - to : "+e.getName()),_(e)},unsubscribeToChannel:function(e){return c.debug("unsubscribeToChannel - from : "+e.getName()),C(e)},stop:function(){c.debug("stop"),c.debug("signalStop - stopping : "+l),l||(l=!0,b(),e.clear())},isStopping:function(){return l},getQueue:function(){return e},isBucketEmpty:function(){return!h()},getTimerObject:function(){return f},getTokenCountFromTokenManager:function(){return n.getTokenCount()}}};n.default=a}]); amb.getClient(); ; /*! RESOURCE: /scripts/js_includes_ngCommon.js */ /*! RESOURCE: /scripts/sn/common/js_includes_common.js */ /*! RESOURCE: /scripts/sn/common/_module.js */ angular.module('sn.common', [ 'ngSanitize', 'ngAnimate', 'sn.common.avatar', 'sn.common.controls', 'sn.common.datetime', 'sn.common.glide', 'sn.common.i18n', 'sn.common.link', 'sn.common.mention', 'sn.common.messaging', 'sn.common.notification', 'sn.common.presence', 'sn.common.stream', 'sn.common.ui', 'sn.common.user_profile', 'sn.common.util', 'sn.common.dynamicTranslation' ]); angular.module('ng.common', [ 'sn.common' ]); ; /*! RESOURCE: /scripts/sn/common/dist/templates.js */ angular.module('sn.common.dist.templates', []); ; /*! RESOURCE: /scripts/sn/common/datetime/js_includes_datetime.js */ /*! RESOURCE: /scripts/sn/common/datetime/_module.js */ angular.module('sn.common.datetime', [ 'sn.common.i18n' ]); angular.module('sn.timeAgo', [ 'sn.common.datetime' ]); ; /*! RESOURCE: /scripts/sn/common/datetime/directive.snTimeAgo.js */ angular.module('sn.common.datetime').constant('DATE_GRANULARITY', { DATETIME: 1, DATE: 2 }); angular.module('sn.common.datetime').factory('timeAgoTimer', function($interval, $rootScope, DATE_GRANULARITY) { "use strict"; var digestInterval; return function(displayGranularityType) { displayGranularityType = typeof displayGranularityType !== 'undefined' ? displayGranularityType : DATE_GRANULARITY.DATETIME; if (!digestInterval && displayGranularityType == DATE_GRANULARITY.DATETIME) digestInterval = $interval(function() { $rootScope.$broadcast('sn.TimeAgo.tick'); }, 30 * 1000); return Date.now(); }; }); angular.module('sn.common.datetime').factory('timeAgo', function(timeAgoSettings, DATE_GRANULARITY) { var service = { settings: timeAgoSettings.get(), allowFuture: function allowFuture(bool) { this.settings.allowFuture = bool; return this; }, toWords: function toWords(distanceMillis, messageGranularity, verbose) { messageGranularity = messageGranularity || DATE_GRANULARITY.DATETIME; var $l = verbose ? service.settings.strings_verbose : service.settings.strings; var seconds = Math.abs(distanceMillis) / 1000; var minutes = seconds / 60; var hours = minutes / 60; var days = hours / 24; var years = days / 365; var ago = $l.ago; if ((seconds < 45 && messageGranularity == DATE_GRANULARITY.DATETIME) || (hours < 24 && messageGranularity == DATE_GRANULARITY.DATE) || (!service.settings.allowFuture && distanceMillis < 0)) ago = '%d'; if (service.settings.allowFuture) { if (distanceMillis < 0) { ago = $l.fromNow; } } function substitute(stringOrFunction, number) { var string = angular.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction; if (!string) return ""; var value = ($l.numbers && $l.numbers[number]) || number; return string.replace(/%d/i, value); } var wantDate = messageGranularity == DATE_GRANULARITY.DATE; var wantDateTime = messageGranularity == DATE_GRANULARITY.DATETIME; var words = distanceMillis <= 0 && wantDateTime && substitute($l.justNow, 0) || distanceMillis <= 0 && wantDate && substitute($l.today, 0) || seconds < 45 && (distanceMillis >= 0 || !service.settings.allowFuture) && wantDateTime && substitute($l.justNow, Math.round(seconds)) || seconds < 45 && wantDateTime && substitute($l.seconds, Math.round(seconds)) || seconds < 90 && wantDateTime && substitute($l.minute, 1) || minutes < 45 && wantDateTime && substitute($l.minutes, Math.round(minutes)) || minutes < 90 && wantDateTime && substitute($l.hour, 1) || hours < 24 && wantDateTime && substitute($l.hours, Math.round(hours)) || hours < 24 && wantDate && substitute($l.today, 0) || hours < 42 && substitute($l.day, 1) || days < 30 && substitute($l.days, Math.ceil(days)) || days < 45 && substitute($l.month, 1) || days < 365 && substitute($l.months, Math.round(days / 30)) || years < 1.5 && substitute($l.year, 1) || substitute($l.years, Math.round(years)); return substitute(ago, words); }, parse: function(iso8601) { if (angular.isNumber(iso8601)) return new Date(parseInt(iso8601, 10)); var s = iso8601.trim(); s = s.replace(/\.\d+/,""); s = s.replace(/-/,"/").replace(/-/,"/"); s = s.replace(/T/," ").replace(/Z/," UTC"); s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); return new Date(s); } }; return service; }); angular.module('sn.common.datetime').directive("snTimeAgo", function(timeAgoSettings, $rootScope, timeAgo, timeAgoTimer, DATE_GRANULARITY, dateUtils) { "use strict"; return { restrict: "E", template: '<time title="{{ ::titleTime }}"><span aria-hidden="true">{{timeAgo}}</span><span class="sr-only">{{timeAgoVerbose}}</span></time>', scope: { timestamp: "=", local: "=" }, link: function(scope) { timeAgoSettings.ready.then(function() { timeAgoTimer(DATE_GRANULARITY.DATETIME) scope.$on('sn.TimeAgo.tick', setTimeAgo); setTimeAgo(); }); function setTimeAgo() { scope.timeAgo = timeAgoConverter(scope.timestamp, true, false); scope.timeAgoVerbose = timeAgoConverter(scope.timestamp, true, true); } function timeAgoConverter(input, noFuture, verbose) { if (!input) return; var allowFuture = !noFuture; var date = timeAgo.parse(input); if (scope.local) { scope.titleTime = input; return timeAgo.allowFuture(allowFuture).toWords(new Date() - date, 1, verbose); } if (Object.prototype.toString.call(date) !== "[object Date]" && Object.prototype.toString.call(date) !== "[object Number]") return input; else if (Object.prototype.toString.call(date) == "[object Date]" && isNaN(date.getTime())) return input; setTitleTime(date); var currentDate = new Date(); currentDate = new Date(currentDate.getUTCFullYear(), currentDate.getUTCMonth(), currentDate.getUTCDate(), currentDate.getUTCHours(), currentDate.getUTCMinutes(), currentDate.getUTCSeconds() ); var diff = currentDate - date; return timeAgo.allowFuture(allowFuture).toWords(diff, 1, verbose); } function setTitleTime(date) { var t = date.getTime(); var o = date.getTimezoneOffset(); t -= o * 60 * 1000; if (typeof g_user_date_time_format !== 'undefined' && g_user_date_time_format.indexOf('z') == -1) scope.titleTime = dateUtils.formatDate(new Date(t), g_user_date_time_format); else scope.titleTime = new Date(t).toLocaleString(); } } } }); angular.module('sn.common.datetime').directive("snTimeAgoStatic", function(timeAgoSettings, $rootScope, timeAgo, timeAgoTimer, DATE_GRANULARITY) { "use strict"; return { restrict: "E", template: '<time title="{{ ::titleTime }}">{{timeAgo}}</time>', scope: { timestamp: "@", local: "@" }, link: function(scope) { timeAgoSettings.ready.then(function() { timeAgoTimer(DATE_GRANULARITY.DATETIME) scope.$on('sn.TimeAgo.tick', setTimeAgo); setTimeAgo(); }); function setTimeAgo() { scope.timeAgo = timeAgoConverter(scope.timestamp, true); } function timeAgoConverter(input, noFuture) { if (!input) return; var allowFuture = !noFuture; var date = timeAgo.parse(input); if (scope.local) { scope.titleTime = input; return timeAgo.allowFuture(allowFuture).toWords(new Date() - date); } if (Object.prototype.toString.call(date) !== "[object Date]" && Object.prototype.toString.call(date) !== "[object Number]") return input; else if (Object.prototype.toString.call(date) == "[object Date]" && isNaN(date.getTime())) return input; setTitleTime(date); var currentDate = new Date(); currentDate = new Date(currentDate.getUTCFullYear(), currentDate.getUTCMonth(), currentDate.getUTCDate(), currentDate.getUTCHours(), currentDate.getUTCMinutes(), currentDate.getUTCSeconds() ); var diff = currentDate - date; return timeAgo.allowFuture(allowFuture).toWords(diff); } function setTitleTime(date) { var t = date.getTime(); var o = date.getTimezoneOffset(); t -= o * 60 * 1000; scope.titleTime = new Date(t).toLocaleString(); } } } }); ; /*! RESOURCE: /scripts/sn/common/datetime/directive.snDayAgo.js */ angular.module('sn.common.datetime').directive("snDayAgo", function(timeAgoSettings, $rootScope, timeAgo, timeAgoTimer, DATE_GRANULARITY) { "use strict"; return { restrict: "E", template: '<time>{{dayAgo}}</time>', scope: { date: "=" }, link: function(scope) { timeAgoSettings.ready.then(function() { setDayAgo(); }); function setDayAgo() { scope.dayAgo = dayAgoConverter(scope.date, "noFuture"); } function dayAgoConverter(input, option) { if (!input) return; var allowFuture = !((option === 'noFuture') || (option === 'no_future')); var date = timeAgo.parse(input); if ( Object.prototype.toString.call(date) !== "[object Date]" ) return input; else if ( isNaN(date.getTime()) ) return input; var diff = timeAgoTimer(DATE_GRANULARITY.DATE) - date; return timeAgo.allowFuture(allowFuture).toWords(diff, DATE_GRANULARITY.DATE); } } } }); ; /*! RESOURCE: /scripts/sn/common/datetime/snTimeAgoSettings.js */ angular.module('sn.common.datetime').provider('snTimeAgoSettings', function() { "use strict"; var INIT_NEVER = 'never'; var INIT_AUTO = 'auto'; var INIT_MANUAL = 'manual'; var _initMethod = INIT_AUTO; this.setInitializationMethod = function(init) { switch (init) { default: init = INIT_AUTO; case INIT_NEVER: case INIT_AUTO: case INIT_MANUAL: _initMethod = init; break; } }; this.$get = function(i18n, $q) { var settings = { allowFuture: true, dateOnly: false, strings: {} }; var _initialized = false; var ready = $q.defer(); function initialize() { if (_initMethod === INIT_NEVER) { return $q.reject(); } if (!_initialized) { _initialized = true; i18n.getMessages(['%d ago', '%d from now', 'just now', '%d minutes_verbose', 'about %d hours_verbose', '%d days_verbose', '%d months_verbose', '%d years_verbose', 'less than a minute', 'about a minute', '%d minutes', 'about an hour', 'about %d hours', 'today', 'a day', '%d days', 'about a month', '%d months', 'about a year', 'about a year', '%d years'], function (msgs) { settings.strings = { ago: msgs['%d ago'], fromNow: msgs['%d from now'], justNow: msgs["just now"], seconds: msgs["less than a minute"], minute: msgs["about a minute"], minutes: msgs["%d minutes"], hour: msgs["about an hour"], hours: msgs["about %d hours"], day: msgs["a day"], days: msgs["%d days"], month: msgs["about a month"], months: msgs["%d months"], year: msgs["about a year"], years: msgs["%d years"], today: msgs["today"], wordSeparator: msgs["timeago_number_separator"], numbers: [] }; settings.strings_verbose = Object.assign({}, settings.strings, { minutes: msgs["%d minutes_verbose"], hours: msgs["about %d hours_verbose"], days: msgs["%d days_verbose"], months: msgs["%d months_verbose"], years: msgs["%d years_verbose"] }); ready.resolve(); }); } return ready.promise; } if (_initMethod === INIT_AUTO) { initialize(); } return { initialize: initialize, ready: ready.promise, get: function get() { return settings; }, set: function set(translated) { settings = angular.extend(settings, translated); } }; }; }).factory('timeAgoSettings', function(snTimeAgoSettings) { return snTimeAgoSettings; }); ; ; /*! RESOURCE: /scripts/sn/common/glide/js_includes_glide.js */ /*! RESOURCE: /scripts/sn/common/glide/_module.js */ angular.module('sn.common.glide', [ 'sn.common.util' ]); ; /*! RESOURCE: /scripts/sn/common/glide/factory.glideUrlBuilder.js */ angular.module('sn.common.glide').factory('glideUrlBuilder', ['$window', function($window) { "use strict"; function GlideUrl(contextPath){ var objDef = { contextPath: '', params: {}, encodedString: '', encode: true, setFromCurrent: function() { this.setFromString($window.location.href); }, setFromString:function(href) { var pos = href.indexOf('?'); if (pos < 0) { this.contextPath = href; return; } this.contextPath = href.slice(0, pos); var hashes = href.slice(pos + 1).split('&'); var i = hashes.length; while (i--) { var pos = hashes[i].indexOf('='); this.params[hashes[i].substring(0, pos)] = hashes[i].substring(++pos); } }, setContextPath: function(c) { this.contextPath = c; }, getParam: function(p) { return this.params[p]; }, getParams: function() { return this.params; }, addParam: function(name, value) { this.params[name] = value; return this; }, addToken: function() { if (typeof g_ck != 'undefined' && g_ck != "") this.addParam('sysparm_ck', g_ck); return this; }, deleteParam: function(name) { delete this.params[name]; }, addEncodedString: function(s) { if (!s) return; if (s.substr(0, 1) != "&") this.encodedString += "&"; this.encodedString += s; return this; }, getQueryString: function(additionalParams) { var qs = this._getParamsForURL(this.params); qs += this._getParamsForURL(additionalParams); qs += this.encodedString; if (qs.length == 0) return ""; return qs.substring(1); }, _getParamsForURL: function(params) { if (!params) return ''; var url = ''; for (var n in params) { var p = params[n] || ''; url += '&' + n + '=' + (this.encode ? encodeURIComponent(p + '') : p); } return url; }, getURL: function(additionalParams) { var url = this.contextPath; var qs = this.getQueryString(additionalParams); if (qs) url += "?" + qs; return url; }, setEncode: function(b) { this.encode = b; }, toString: function() { return 'GlideURL'; } } return objDef; } return { newGlideUrl: function(contextPath) { var glideUrl = new GlideUrl(); glideUrl.setFromString(contextPath ? contextPath : ''); return glideUrl; }, refresh: function(){ $window.location.replace( $window.location.href ); }, getCancelableLink: function(link) { if ($window.NOW && $window.NOW.g_cancelPreviousTransaction) { var nextChar = link.indexOf('?') > -1 ? '&' : '?'; link += nextChar + "sysparm_cancelable=true"; } return link; } }; }]); ; /*! RESOURCE: /scripts/sn/common/glide/service.queryFilter.js */ angular.module('sn.common.glide').factory('queryFilter', function() { "use strict"; return { create : function() { var that = {}; that.conditions = []; function newCondition(field, operator, value, label, displayValue, type){ var condition = { field: field, operator: operator, value: value, displayValue: displayValue, label: label, left: null, right: null, type: null, setValue: function(value, displayValue){ this.value = value; this.displayValue = displayValue ? displayValue : value; } }; if (type) condition.type = type; return condition; } function addCondition(condition) { that.conditions.push(condition); return condition; } function removeCondition(condition) { for (var i = that.conditions.length-1; i >= 0; i--) { if (that.conditions[i] === condition) that.conditions.splice(i, 1); } } function getConditionsByField(conditions, field){ var conditionsToReturn = []; for(var condition in conditions){ if (conditions.hasOwnProperty(condition)){ if (conditions[condition].field == field) conditionsToReturn.push(conditions[condition]); } } return conditionsToReturn; } function encodeCondition(condition){ var output = ""; if (condition.hasOwnProperty("left") && condition.left){ output += encodeCondition(condition.left); } if (condition.hasOwnProperty("right") && condition.right){ var right = encodeCondition(condition.right); if (right.length > 0){ output += "^" + condition.type + right; } } if (condition.field){ output += condition.field; output += condition.operator; if (condition.value !== null && typeof condition.value !== "undefined") output += condition.value; } return output; } function createEncodedQuery() { var eq = ""; var ca = that.conditions; for (var i = 0; i < ca.length; i++) { var condition = ca[i]; if (eq.length) eq += '^'; eq += encodeCondition(condition); } eq += "^EQ"; return eq; } that.addCondition = addCondition; that.newCondition = newCondition; that.createEncodedQuery = createEncodedQuery; that.getConditionsByField = getConditionsByField; that.removeCondition = removeCondition; return that; } }; }); ; /*! RESOURCE: /scripts/sn/common/glide/service.filterExpressionParser.js */ angular.module('sn.common.glide').factory('filterExpressionParser', function() { 'use strict'; var operatorExpressions = [{ wildcardExp: '(.*)', operator: 'STARTSWITH', toExpression: function(filter) { return filter; } },{ wildcardExp: '^\\*(.*)', operator: 'LIKE', toExpression: function(filter) { return (filter === '*' ? filter : '*' + filter); } },{ wildcardExp: '^\\.(.*)', operator: 'LIKE', toExpression: function(filter) { return '.' + filter; } },{ wildcardExp: '^%(.*)', operator: 'ENDSWITH', toExpression: function(filter) { return (filter === '%' ? filter : '%' + filter); } },{ wildcardExp: '(.*)%', operator: 'LIKE', toExpression: function(filter) { return filter + '%'; } },{ wildcardExp: '^=(.*)', operator: '=', toExpression: function(filter) { return (filter === '=' ? filter : '=' + filter); } },{ wildcardExp: '^!\\*(.*)', operator: 'NOT LIKE', toExpression: function(filter) { return (filter === '!*' || filter === '!' ? filter : '!*' + filter); } },{ wildcardExp: '^!=(.*)', operator: '!=', toExpression: function(filter) { return (filter === '!=' || filter === '!' ? filter : '!=' + filter); } }]; return { getOperatorExpressionForOperator: function(operator) { for (var i = 0; i < operatorExpressions.length; i++) { var item = operatorExpressions[i]; if (item.operator === operator) return item; } throw { name: 'OperatorNotSupported', message: 'The operator ' + operator + ' is not in the list of operatorExpressions.' }; }, parse: function(val, defaultOperator) { var parsedValue = { filterText: val, operator: defaultOperator || 'STARTSWITH' }; for (var i = 1; i < operatorExpressions.length; i++) { var operatorItem = operatorExpressions[i]; var match = val.match(operatorItem.wildcardExp); if (match && match[1] !== '') { parsedValue.operator = operatorItem.operator; parsedValue.filterText = match[1]; } } return parsedValue; } }; }); ; /*! RESOURCE: /scripts/sn/common/glide/service.userPreferences.js */ angular.module('sn.common.glide').factory("userPreferences", function ($http, $q, unwrappedHTTPPromise, urlTools) { "use strict"; var preferencesCache = {}; function getPreference(preferenceName) { if (preferenceName in preferencesCache) return preferencesCache[preferenceName]; var targetURL = urlTools.getURL('user_preference', { "sysparm_pref_name": preferenceName, "sysparm_action": "get" }), deferred = $q.defer(); $http.get(targetURL).success(function (response) { deferred.resolve(response.sysparm_pref_value); }).error(function (data, status) { deferred.reject("Error getting preference " + preferenceName + ": " + status); }); preferencesCache[preferenceName] = deferred.promise; return deferred.promise; } function setPreference(preferenceName, preferenceValue) { var preferenceValueString = "" + preferenceValue; var parmsObj = { "sysparm_pref_name": preferenceName, "sysparm_action": "set" }; var useGet = preferenceValueString.length <= 1024; if (useGet) parmsObj["sysparm_pref_value"] = preferenceValueString; var targetURL = urlTools.getURL('user_preference', parmsObj); var httpPromise = useGet ? $http.get(targetURL) : $http.post(targetURL, {'sysparm_pref_value': preferenceValueString}); addToCache(preferenceName, preferenceValue); return unwrappedHTTPPromise(httpPromise); } function addToCache(preferenceName, preferenceValue){ preferencesCache[preferenceName] = $q.when(preferenceValue); } var userPreferences = { getPreference: getPreference, setPreference: setPreference, addToCache: addToCache }; return userPreferences; }); ; /*! RESOURCE: /scripts/sn/common/glide/service.nowStream.js */ angular.module('sn.common.glide').constant('nowStreamTimerInterval', 5000); angular.module('sn.common.glide').factory('nowStream', function($q, amb, $timeout, urlTools, nowStreamTimerInterval, snResource, snCustomEvent, $log) { 'use strict'; var AMB_CHANNEL = '/history/update'; amb.connect(); var Stream = function() { this.initialize.apply(this, arguments); }; Stream.prototype = { initialize: function(table, query, sys_id, processor, interval, source, includeAttachments) { this.table = table; this.query = query; this.sysparmQuery = null; this.sys_id = sys_id; this.processor = processor; this.lastTimestamp = 0; this.inflightRequest = null; this.requestImmediateUpdate = false; this.interval = interval; this.source = source; this.includeAttachments = includeAttachments; this.stopped = true; var name = AMB_CHANNEL + '/' + table + '/' + sys_id; this.ambChannel = amb.getChannel(name).subscribe(this.tap.bind(this)); }, setQuery: function(sysparmQuery) { this.sysparmQuery = sysparmQuery; }, poll: function(callback, preRequestCallback) { this.callback = callback; this.preRequestCallback = preRequestCallback; this._stopPolling(); this._startPolling(); }, tap: function() { if (!this.inflightRequest) { this._stopPolling(); this._startPolling(); } else this.requestImmediateUpdate = true; }, insert: function(field, text) { this.insertForEntry(field, text, this.table, this.sys_id); }, insertForEntry: function(field, text, table, sys_id) { return this.insertEntries([{ field: field, text: text }], table, sys_id); }, expandMentions: function (entryText, mentionIDMap) { var text = entryText; Object.getOwnPropertyNames(mentionIDMap).forEach(function(element) { var atMention = element.replace(/[.*+\-?^()|[\]\\]/g, '\\$&'); var search = new RegExp("@\\[" + atMention + "\\]", "gi"); var sysId = mentionIDMap[element]; text = text.replace(search, "@[" + sysId + ":" + element + "]"); }); return text; }, addCarriageReturns: function(entryText) { return entryText.replace(/\r*\n/g, '\r\n'); }, insertEntries: function(entries, table, sys_id, mentionIDMap) { mentionIDMap = mentionIDMap || {}; var sanitizedEntries = []; for (var i = 0; i < entries.length; i++) { var entryText = entries[i].text; if (entryText && entryText.endsWith('\n')) entryText = entryText.substring(0, entryText.length - 1); if (!entryText) continue; entries[i].text = this.addCarriageReturns(this.expandMentions(entryText, mentionIDMap)); sanitizedEntries.push(entries[i]); } if (sanitizedEntries.length === 0) return; this._isInserting = true; var url = this._getInsertURL(table, sys_id); var that = this; return snResource().post(url, { entries: sanitizedEntries }).then(this._successCallback.bind(this), function() { $log.warn('Error submitting entries', sanitizedEntries); }).then(function() { that._isInserting = false; }); }, cancel: function() { this._stopPolling(); this.ambChannel.unsubscribe(); }, _startPolling : function() { var interval = this._getInterval(); var that = this; var successCallback = this._successCallback.bind(this); that.stopped = false; function runPoll() { if (that._isInserting) { establishNextRequest(); return; } if (!that.inflightRequest) { that.inflightRequest = that._executeRequest(); that.inflightRequest.then(successCallback); that.inflightRequest.finally(function() { that.inflightRequest = null; if (that.requestImmediateUpdate) { that.requestImmediateUpdate = false; establishNextRequest(0); } else { establishNextRequest(); } }); } } function establishNextRequest(intervalOverride) { if (that.stopped) return; intervalOverride = (parseFloat(intervalOverride) >= 0) ? intervalOverride : interval; $timeout.cancel(that.timer); that.timer = $timeout(runPoll, intervalOverride); } runPoll(); }, _stopPolling : function() { if (this.timer) $timeout.cancel(this.timer); this.stopped = true; }, _executeRequest: function() { var url = this._getURL(); if (this.preRequestCallback) { this.preRequestCallback(); } return snResource().get(url); }, _getURL: function() { var params = { table: this.table, action: this._getAction(), sysparm_silent_request: true, sysparm_auto_request: true, sysparm_timestamp: this.lastTimestamp, include_attachments: this.includeAttachments }; if (this.sys_id) { params['sys_id'] = this.sys_id; } else if (this.sysparmQuery) { params['sysparm_query'] = this.sysparmQuery; } var url = urlTools.getURL(this.processor, params); if (!this.sys_id) { url += "&p=" + this.query; } return url; }, _getInsertURL: function(table, sys_id) { return urlTools.getURL(this.processor, { action: 'insert', table: table, sys_id: sys_id, sysparm_timestamp: this.timestamp || 0, sysparm_source: this.source }); }, _successCallback: function(response) { var response = response.data; if (response.entries && response.entries.length) { response.entries = this._filterOld(response.entries); if (response.entries.length > 0) { this.lastEntry = angular.copy(response.entries[0]); this.lastTimestamp = response.sys_timestamp || response.entries[0].sys_timestamp; } } this.callback.call(null, response); }, _filterOld: function(entries) { for (var i = 0; i < entries.length; i++) { if (entries[i].sys_timestamp == this.lastTimestamp) { if (this.lastEntry) { if (!angular.equals(this._makeComparable(entries[i]), this._makeComparable(this.lastEntry))) continue; if (entries[i].attachment) snCustomEvent.fire('sn.stream.attachment_state_updated', entries[i]); } } if (entries[i].sys_timestamp <= this.lastTimestamp) return entries.slice(0, i); } return entries; }, _makeComparable: function(entry) { var copy = angular.copy(entry); delete copy.short_description; delete copy.display_value; if (copy.attachment) delete copy.attachment.state; return copy; }, _getAction: function() { return this.sys_id ? 'get_new_entries' : 'get_set_entries'; }, _getInterval: function() { if (this.interval) return this.interval; else if (window.NOW && NOW.stream_poll_interval) return NOW.stream_poll_interval * 1000; else return nowStreamTimerInterval; } }; return { create: function(table, query, sys_id, processor, interval, source) { return new Stream(table, query, sys_id, processor, interval, source); } }; }); ; /*! RESOURCE: /scripts/sn/common/glide/service.nowServer.js */ angular.module('sn.common.glide').factory('nowServer', function($http, $q, userPreferences, angularProcessorUrl, urlTools) { return { getBaseURL: function () { return angularProcessorUrl; }, getPartial: function(scope, partial, parms, callback) { var url = this.getPartialURL(partial, parms); if (url === scope.url) { callback.call(); return; } var fn = scope.$on('$includeContentLoaded', function() { fn.call(); callback.call(); }); scope.url = url; }, replaceView: function($location, newView) { var p = $location.path(); var a = p.split("/"); a[1] = newView; p = a.join("/"); return p; }, getPartialURL: urlTools.getPartialURL, getURL: urlTools.getURL, urlFor : urlTools.urlFor, getPropertyURL: urlTools.getPropertyURL, setPreference: userPreferences.setPreference, getPreference: userPreferences.getPreference } }); ; ; /*! RESOURCE: /scripts/sn/common/avatar/js_includes_avatar.js */ /*! RESOURCE: /scripts/sn/common/presence/js_includes_presence.js */ /*! RESOURCE: /scripts/js_includes_ng_amb.js */ /*! RESOURCE: /scripts/js_includes_amb.js */ amb.getClient(); ; /*! RESOURCE: /scripts/app.ng.amb/app.ng.amb.js */ angular.module("ng.amb", ['sn.common.presence', 'sn.common.util']) .value("ambLogLevel", 'info') .value("ambServletURI", '/amb') .value("cometd", angular.element.cometd) .value("ambLoginWindow", 'true'); ; /*! RESOURCE: /scripts/app.ng.amb/service.AMB.js */ angular.module("ng.amb").service("amb", function (AMBOverlay, $window, $q, $log, $rootScope, $timeout) { "use strict"; var ambClient = null; var _window = $window.self; var loginWindow = null; var sameScope = false; ambClient = amb.getClient(); if (_window.g_ambClient) { sameScope = true; } if (sameScope) { var serverConnection = ambClient.getServerConnection(); serverConnection.loginShow = function() { if (!serverConnection.isLoginWindowEnabled()) return; if (loginWindow && loginWindow.isVisible()) return; if (serverConnection.isLoginWindowOverride()) return; var modalConfig = { onBeforeShow: addOverrideStyles }; loginWindow = new AMBOverlay(modalConfig); loginWindow.render(); loginWindow.show(); }; serverConnection.loginHide = function() { if (!loginWindow) return; loginWindow.hide(); loginWindow.destroy(); loginWindow = null; } } function addOverrideStyles(el) { var parent = angular.element(el.target).parent(); var backdrop = parent.find('.modal-backdrop').get(0); if (backdrop !== undefined) backdrop.style.cssText = [backdrop.style.cssText, serverConnection.getLoginWindowOverlayStyle()].join('; '); } var AUTO_CONNECT_TIMEOUT = 20 * 1000; var connected = $q.defer(); var connectionInterrupted = false; var monitorAMB = false; $timeout(startMonitoringAMB, AUTO_CONNECT_TIMEOUT); connected.promise.then(startMonitoringAMB); function startMonitoringAMB() { monitorAMB = true; } function ambInterrupted() { var state = ambClient.getState(); return monitorAMB && state !== "opened" && state !== "initialized" } var interruptionTimeout; var extendedInterruption = false; function setInterrupted(eventName) { connectionInterrupted = true; $rootScope.$broadcast(eventName); if (!interruptionTimeout) { interruptionTimeout = $timeout(function () { extendedInterruption = true; }, 30 * 1000) } connected = $q.defer(); } var connectOpenedEventId = ambClient.subscribeToEvent("connection.opened", function () { $rootScope.$broadcast("amb.connection.opened"); if (interruptionTimeout) { $timeout.cancel(interruptionTimeout); interruptionTimeout = null; } extendedInterruption = false; if(connectionInterrupted) { connectionInterrupted = false; $rootScope.$broadcast("amb.connection.recovered"); } connected.resolve(); }); var connectClosedEventId = ambClient.subscribeToEvent("connection.closed", function () { setInterrupted("amb.connection.closed"); }); var connectBrokenEventId = ambClient.subscribeToEvent("connection.broken", function () { setInterrupted("amb.connection.broken"); }); var connectSessionLoggedin = ambClient.subscribeToEvent("session.logged.in", function () { $rootScope.$broadcast("amb.session.logged.in"); }); var connectSessionReestablished = ambClient.subscribeToEvent("session.reestablished", function () { $rootScope.$broadcast("amb.session.reestablished"); }); var onUnloadWindow = function() { ambClient.unsubscribeFromEvent(connectOpenedEventId); ambClient.unsubscribeFromEvent(connectClosedEventId); ambClient.unsubscribeFromEvent(connectBrokenEventId); angular.element($window).off('unload', onUnloadWindow); }; angular.element($window).on('unload', onUnloadWindow); var defaultAmbConnectionTimeout = 10000; var shouldDeferAmbConnection = _window.NOW && _window.NOW.hasOwnProperty('deferAmbConnection') ? _window.NOW.deferAmbConnection : false; var deferredAmbConnectionTimeout = _window.NOW && _window.NOW.hasOwnProperty('deferredAmbConnectionTimeout') && isValidAmbConnectionTimeout(_window.NOW.deferredAmbConnectionTimeout) ? _window.NOW.deferredAmbConnectionTimeout : defaultAmbConnectionTimeout; if (shouldDeferAmbConnection) { $timeout(autoConnect, deferredAmbConnectionTimeout); } else { var documentReadyState = _window.document ? _window.document.readyState : null; if (documentReadyState === 'complete') autoConnect(); else _window.addEventListener('load', autoConnect); $timeout(autoConnect, defaultAmbConnectionTimeout); } function isInteger(num) { return parseInt(num, 10) === num; } function isValidAmbConnectionTimeout(timeout) { return isInteger(timeout) && timeout > 0; } var initiatedConnection = false; function autoConnect() { if (!initiatedConnection) { initiatedConnection = true; ambClient.connect(); } } return { getServerConnection: function() { return ambClient.getServerConnection(); }, connect: function() { if (initiatedConnection) { ambClient.connect(); } return connected.promise; }, get interrupted() { return ambInterrupted(); }, get extendedInterruption() { return extendedInterruption; }, get connected() { return connected.promise; }, abort: function() { ambClient.abort(); }, disconnect: function() { ambClient.disconnect(); }, getConnectionState: function () { return ambClient.getConnectionState(); }, getClientId: function () { return ambClient.getClientId(); }, getChannel: function(channelName) { return ambClient.getChannel(channelName); }, registerExtension: function(extensionName, extension) { ambClient.registerExtension(extensionName, extension); }, unregisterExtension: function(extensionName) { ambClient.unregisterExtension(extensionName); }, batch: function(batch) { ambClient.batch(batch); }, getState: function() { return ambClient.getState(); }, getFilterString: function(filter) { filter = filter. replace(/\^EQ/g, ''). replace(/\^ORDERBY(?:DESC)?[^^]*/g, ''). replace(/^GOTO/, ''); return btoa(unescape(encodeURIComponent(filter))).replace(/=/g, '-'); }, getChannelRW: function(table, filter) { var t = '/rw/default/' + table + '/' + this.getFilterString(filter); return this.getChannel(t); }, isLoggedIn: function() { return ambClient.isLoggedIn(); }, subscribeToEvent: function(event, callback) { return ambClient.subscribeToEvent(event, callback); }, getConnectionEvents: function() { return ambClient.getConnectionEvents(); }, getEvents: function() { return ambClient.getConnectionEvents(); }, loginComplete: function() { ambClient.loginComplete(); } }; }); ; /*! RESOURCE: /scripts/app.ng.amb/controller.AMBRecordWatcher.js */ angular.module("ng.amb").controller("AMBRecordWatcher", function($scope, $timeout, $window) { "use strict"; var amb = $window.top.g_ambClient; $scope.messages = []; var lastFilter; var watcherChannel; var watcher; function onMessage(message) { $scope.messages.push(message.data); } $scope.getState = function() { return amb.getState(); }; $scope.initWatcher = function() { angular.element(":focus").blur(); if(!$scope.filter || $scope.filter === lastFilter) return; lastFilter = $scope.filter; console.log("initiating watcher on " + $scope.filter); $scope.messages = []; if(watcher) { watcher.unsubscribe(); } var base64EncodeQuery = btoa($scope.filter).replace(/=/g, '-'); var channelId = '/rw/' + base64EncodeQuery; watcherChannel = amb.getChannel(channelId) watcher = watcherChannel.subscribe(onMessage); }; amb.connect(); }) ; /*! RESOURCE: /scripts/app.ng.amb/factory.snRecordWatcher.js */ angular.module("ng.amb").factory('snRecordWatcher', function($rootScope, amb, $timeout, snPresence, $log, urlTools) { "use strict"; var diagnosticLog = true; function initWatcher(table, sys_id, query) { if (!table) return; if (sys_id) var filter = "sys_id=" + sys_id; else filter = query; if (!filter) return; return initChannel(table, filter); } function initList(table, query) { if (!table) return; query = query || "sys_idISNOTEMPTY"; return initChannel(table, query); } function initTaskList(list, prevChannel) { if (prevChannel) prevChannel.unsubscribe(); var sys_ids = list.toString(); var filter = "sys_idIN" + sys_ids; return initChannel("task", filter); } function initChannel(table, filter, callbackFn) { if (isBlockedTable(table)) { $log.log("Blocked from watching", table); return null; } if (diagnosticLog) log(">>> init " + table + "?" + filter); var watcherChannel = amb.getChannelRW(table, filter); watcherChannel.subscribe(callbackFn || onMessage); amb.connect(); return watcherChannel; } function onMessage(message) { var r = message.data; var c = message.channel; if (diagnosticLog) log(">>> record " + r.operation + ": " + r.table_name + "." + r.sys_id + " " + r.display_value); $rootScope.$broadcast('record.updated', r); $rootScope.$broadcast('list.updated', r, c); } function log(message) { $log.log(message); } function isBlockedTable(table) { return table == 'sys_amb_message' || table.startsWith('sys_rw'); } return { initTaskList: initTaskList, initChannel: initChannel, init: function () { var location = urlTools.parseQueryString(window.location.search); var table = location['table'] || location['sysparm_table']; var sys_id = location['sys_id'] || location['sysparm_sys_id']; var query = location['sysparm_query']; initWatcher(table, sys_id, query); snPresence.init(table, sys_id, query); }, initList: initList, initRecord: function(table, sysId) { initWatcher(table, sysId, null); snPresence.initPresence(table, sysId); }, _initWatcher: initWatcher } }); ; /*! RESOURCE: /scripts/app.ng.amb/factory.AMBOverlay.js */ angular.module("ng.amb").factory("AMBOverlay", function($templateCache, $compile, $rootScope) { "use strict"; var showCallbacks = [], beforeShowCallbacks = [], hideCallbacks = [], isRendered = false, modal, modalScope, modalOptions; var defaults = { backdrop: 'static', keyboard: false, show: true }; function AMBOverlay(config) { config = config || {}; if(angular.isFunction(config.onBeforeShow)) beforeShowCallbacks.push(config.onBeforeShow); if(angular.isFunction(config.onShow)) showCallbacks.push(config.onShow); if(angular.isFunction(config.onHide)) hideCallbacks.push(config.onHide); function lazyRender() { if(!angular.element('html')['modal']) { var bootstrapInclude = "/scripts/bootstrap3/bootstrap.js"; ScriptLoader.getScripts([bootstrapInclude], renderModal); } else renderModal(); } function renderModal() { if(isRendered) return; modalScope = angular.extend($rootScope.$new(), config); modal = $compile($templateCache.get("amb_disconnect_modal.xml"))(modalScope); angular.element("body").append(modal); modal.on("show.bs.modal", function (e) { for(var i = 0, len = beforeShowCallbacks.length; i < len; i++) beforeShowCallbacks[i](e); }); modal.on("shown.bs.modal", function(e) { for(var i = 0, len = showCallbacks.length; i < len; i++) showCallbacks[i](e); }); modal.on("hidden.bs.modal", function(e) { for(var i = 0, len = hideCallbacks.length; i < len; i++) hideCallbacks[i](e); }); modalOptions = angular.extend({}, defaults, config); modal.modal(modalOptions); isRendered = true; } function showModal() { if(isRendered) modal.modal('show'); } function hideModal() { if(isRendered) modal.modal('hide'); } function destroyModal() { if(!isRendered) return; modal.modal('hide'); modal.remove(); modalScope.$destroy(); modalScope = void(0); isRendered = false; var pos = showCallbacks.indexOf(config.onShow); if(pos >= 0) showCallbacks.splice(pos, 1); pos = hideCallbacks.indexOf(config.onShow); if(pos >= 0) hideCallbacks.splice(pos, 1); } return { render: lazyRender, destroy: destroyModal, show: showModal, hide: hideModal, isVisible: function() { if(!isRendered) return false; return modal.visible(); } } } $templateCache.put('amb_disconnect_modal.xml', '<div id="amb_disconnect_modal" tabindex="-1" aria-hidden="true" class="modal" role="dialog">' + ' <div class="modal-dialog small-modal" style="width:450px">' + ' <div class="modal-content">' + ' <header class="modal-header">' + ' <h4 id="small_modal1_title" class="modal-title">{{title || "Login"}}</h4>' + ' </header>' + ' <div class="modal-body">' + ' <iframe class="concourse_modal" ng-src=\'{{iframe || "/amb_login.do"}}\' frameborder="0" scrolling="no" height="400px" width="405px"></iframe>' + ' </div>' + ' </div>' + ' </div>' + '</div>' ); return AMBOverlay; }); ; ; /*! RESOURCE: /scripts/sn/common/presence/snPresenceLite.js */ (function(exports, $) { 'use strict'; var PRESENCE_DISABLED = "false" === "true"; if (PRESENCE_DISABLED) { return; } if (typeof $.Deferred === "undefined") { return; } var USER_KEY = '{{SYSID}}'; var REPLACE_REGEX = new RegExp(USER_KEY, 'g'); var COLOR_ONLINE = '#71e279'; var COLOR_AWAY = '#fc8a3d'; var COLOR_OFFLINE = 'transparent'; var BASE_STYLES = [ '.sn-presence-lite { display: inline-block; width: 1rem; height: 1rem; border-radius: 50%; }' ]; var USER_STYLES = [ '.sn-presence-'+ USER_KEY +'-online [data-presence-id="'+ USER_KEY +'"] { background-color: '+ COLOR_ONLINE +'; }', '.sn-presence-'+ USER_KEY +'-away [data-presence-id="'+ USER_KEY +'"] { background-color: '+ COLOR_AWAY +'; }', '.sn-presence-'+ USER_KEY +'-offline [data-presence-id="'+ USER_KEY +'"] { background-color: '+ COLOR_OFFLINE +'; }' ]; var $head = $('head'); var stylesheet = $.Deferred(); var registeredUsers = {}; var registeredUsersLength = 0; $(function() { updateRegisteredUsers(); }); $head.ready(function() { var styleElement = document.createElement('style'); $head.append(styleElement); var $styleElement = $(styleElement); stylesheet.resolve($styleElement); }); function updateStyles(styles) { stylesheet.done(function($styleElement) { $styleElement.empty(); BASE_STYLES.forEach(function(baseStyle) { $styleElement.append(baseStyle); }); $styleElement.append(styles); }); } function getUserStyles(sysId) { var newStyles = ''; for (var i = 0, iM = USER_STYLES.length; i < iM; i++) { newStyles += USER_STYLES[i].replace(REPLACE_REGEX, sysId); } return newStyles; } function updateUserStyles() { var userKeys = Object.keys(registeredUsers); var userStyles = ""; userKeys.forEach(function(userKey) { userStyles += getUserStyles(userKey); }); updateStyles(userStyles); } exports.applyPresenceArray = applyPresenceArray; function applyPresenceArray(presenceArray) { if (!presenceArray || !presenceArray.length) { return; } var users = presenceArray.filter(function(presence) { return typeof registeredUsers[presence.user] !== "undefined"; }); updateUserPresenceStatus(users); } function updateUserPresenceStatus(users) { var presenceStatus = getBaseCSSClasses(); for (var i = 0, iM = users.length; i < iM; i++) { var presence = users[i]; var status = getNormalizedStatus(presence.status); if (status === 'offline') { continue; } presenceStatus.push('sn-presence-' + presence.user + '-' + status); } setCSSClasses(presenceStatus.join(' ')); } function getNormalizedStatus(status) { switch (status) { case 'probably offline': case 'maybe offline': return 'away'; default: return 'offline'; case 'online': case 'offline': return status; } } function updateRegisteredUsers() { var presenceIndicators = document.querySelectorAll('[data-presence-id]'); var obj = {}; for (var i = 0, iM = presenceIndicators.length; i < iM; i++) { var uid = presenceIndicators[i].getAttribute('data-presence-id'); obj[uid] = true; } if (Object.keys(obj).length === registeredUsersLength){ return; } registeredUsers = obj; registeredUsersLength = Object.keys(registeredUsers).length; updateUserStyles(); } function setCSSClasses(classes) { $('html')[0].className = classes; } function getBaseCSSClasses() { return $('html')[0].className.split(' ').filter(function(item){ return item.indexOf('sn-presence-') !== 0; }); } })(window, window.jQuery || window.Zepto); ; /*! RESOURCE: /scripts/sn/common/presence/_module.js */ angular.module('sn.common.presence', ['ng.amb', 'sn.common.glide', 'sn.common.auth']).config(function($provide) { "use strict"; $provide.constant("PRESENCE_DISABLED", "false" === "true"); }); ; /*! RESOURCE: /scripts/sn/common/presence/factory.snPresence.js */ angular.module("sn.common.presence").factory('snPresence', function($rootScope, $window, $log, amb, $timeout, $http, snRecordPresence, snTabActivity, urlTools, PRESENCE_DISABLED) { "use strict"; var REST = { PRESENCE: "/api/now/ui/presence" }; var RETRY_INTERVAL = ($window.NOW.presence_interval || 60) * 1000; var MAX_RETRY_DELAY = RETRY_INTERVAL * 10; var initialized = false; var primary = false; var presenceArray = []; var serverTimeMillis; var skew = 0; var st = 0; function init() { var location = urlTools.parseQueryString($window.location.search); var table = location['table'] || location['sysparm_table']; var sys_id = location['sys_id'] || location['sysparm_sys_id']; return initPresence(table, sys_id); } function initPresence(t, id) { if(PRESENCE_DISABLED) return; if (!initialized) { initialized = true; initRootScopes(); if (!primary) { CustomEvent.observe('sn.presence', onPresenceEvent); CustomEvent.fireTop('sn.presence.ping'); } else { presenceArray = getLocalPresence($window.localStorage.getItem('snPresence')); if (presenceArray) $timeout(schedulePresence, 100); else updatePresence(); } } return snRecordPresence.initPresence(t, id); } function isTopWindow() { var topWindow = window.self; try { while (topWindow.CustomEvent.fireEvent && topWindow !== topWindow.parent && !topWindow.parent.NOW.isPolarisWrapper && topWindow.parent.CustomEvent.fireEvent) { topWindow = topWindow.parent; } } catch (e) {} return topWindow == window.self; } function onPresenceEvent(parms) { presenceArray = parms; $timeout(broadcastPresence); } function initRootScopes() { if ($window.NOW.presence_scopes) { var ps = $window.NOW.presence_scopes; if (ps.indexOf($rootScope) == -1) ps.push($rootScope); } else { $window.NOW.presence_scopes = [$rootScope]; primary = isTopWindow(); } } function setPresence(data, st) { var rt = new Date().getTime() - st; if (rt > 500) console.log("snPresence response time " + rt + "ms"); if (data.result && data.result.presenceArray) { presenceArray = data.result.presenceArray; setLocalPresence(presenceArray); serverTimeMillis = data.result.serverTimeMillis; skew = new Date().getTime() - serverTimeMillis; var t = Math.floor(skew / 1000); if (t < -15 ) console.log(">>>>> server ahead " + Math.abs(t) + " seconds"); else if (t > 15) console.log(">>>>> browser time ahead " + t + " seconds"); } schedulePresence(); } function updatePresence(numAttempts) { presenceArray = getLocalPresence($window.localStorage.getItem('snPresence')); if (presenceArray) { determineStatus(presenceArray); $timeout(schedulePresence); return; } if (!amb.isLoggedIn() || !snTabActivity.isPrimary) { $timeout(schedulePresence); return; } var p = { user_agent: navigator.userAgent, ua_time: new Date().toISOString(), href: window.location.href, pathname: window.location.pathname, search: window.location.search, path: window.location.pathname + window.location.search }; st = new Date().getTime(); $http.post(REST.PRESENCE + '?sysparm_auto_request=true&cd=' + st, p).success(function(data) { setPresence(data, st); }).error(function(response, status) { console.log("snPresence " + status); schedulePresence(numAttempts); }) } function schedulePresence(numAttempts) { numAttempts = isFinite(numAttempts) ? numAttempts + 1 : 0; var interval = getDecayingRetryInterval(numAttempts); $timeout(function() { updatePresence(numAttempts) }, interval); determineStatus(presenceArray); broadcastPresence(); } function broadcastPresence() { if (angular.isDefined($window.applyPresenceArray)) { $window.applyPresenceArray(presenceArray); } $rootScope.$emit("sn.presence", presenceArray); if (!primary) return; CustomEvent.fireAll('sn.presence', presenceArray); } function determineStatus(presenceArray) { if (!presenceArray || !presenceArray.forEach) return; var t = new Date().getTime(); t -= skew; presenceArray.forEach(function (p) { var x = 0 + p.last_on; var y = t - x; p.status = "online"; if (y > (5 * RETRY_INTERVAL)) p.status = "offline"; else if (y > (3 * RETRY_INTERVAL)) p.status = "probably offline"; else if (y > (2.5 * RETRY_INTERVAL)) p.status = "maybe offline"; }) } function setLocalPresence(value) { var p = { saved: new $window.Date().getTime(), presenceArray: value }; $window.localStorage.setItem('snPresence', angular.toJson(p)); } function getLocalPresence(p) { if (!p) return null; try { p = angular.fromJson(p); } catch (e) { p = {}; } if (!p.presenceArray) return null; var now = new Date().getTime(); if (now - p.saved >= RETRY_INTERVAL) return null; return p.presenceArray; } function getDecayingRetryInterval(numAttempts) { return Math.min(RETRY_INTERVAL * Math.pow(2, numAttempts), MAX_RETRY_DELAY); } return { init: init, initPresence: initPresence, _getLocalPresence: getLocalPresence, _setLocalPresence: setLocalPresence, _determineStatus: determineStatus } }); ; /*! RESOURCE: /scripts/sn/common/presence/factory.snRecordPresence.js */ angular.module("sn.common.presence").factory('snRecordPresence', function($rootScope, $location, amb, $timeout, $window, PRESENCE_DISABLED, snTabActivity) { "use strict"; var statChannel; var interval = ($window.NOW.record_presence_interval || 20) * 1000; var sessions = {}; var primary = false; var currentJournalFieldName = ""; var prevJournalFieldName = ""; var table; var sys_id; function initPresence(t, id) { if(PRESENCE_DISABLED) return; if (!t || !id) return; if (t == table && id == sys_id) return; initRootScopes(); if (!primary) return; termPresence(); table = t; sys_id = id; var recordPresence = "/sn/rp/" + table + "/" + sys_id; $rootScope.me = NOW.session_id; statChannel = amb.getChannel(recordPresence); statChannel.subscribe(onStatus); amb.connected.then(function() { setStatus("entered"); $rootScope.status = "viewing"; }); return statChannel; } function initRootScopes() { if ($window.NOW.record_presence_scopes) { var ps = $window.NOW.record_presence_scopes; if (ps.indexOf($rootScope) == -1) { ps.push($rootScope); CustomEvent.observe('sn.sessions', onPresenceEvent); } } else { $window.NOW.record_presence_scopes = [$rootScope]; primary = true; } } function onPresenceEvent(sessionsToSend) { $rootScope.$emit("sn.sessions", sessionsToSend); $rootScope.$emit("sp.sessions", sessionsToSend); } function termPresence() { if (!statChannel) return; statChannel.unsubscribe(); statChannel = table = sys_id = null; } function setStatus(status) { if (status == $rootScope.status && prevJournalFieldName === currentJournalFieldName) return; prevJournalFieldName = currentJournalFieldName; $rootScope.status = status; if (Object.keys(sessions).length == 0) return; if (getStatusPrecedence(status) > 1) return; publish($rootScope.status); } function publish(status) { if (!statChannel) return; if (amb.getState() !== "opened") return; statChannel.publish({ presences: [{ status : status, session_id : NOW.session_id, user_name : NOW.user_name, user_id: NOW.user_id, user_display_name : NOW.user_display_name, user_initials : NOW.user_initials, user_avatar: NOW.user_avatar, ua : navigator.userAgent, table: table, sys_id: sys_id, field_type: currentJournalFieldName, time: new Date().toString().substring(0,24) }]}); } function onStatus(message) { message.data.presences.forEach(function(d){ if (!d.session_id || d.session_id == NOW.session_id) return; var s = sessions[d.session_id]; if (s) angular.extend(s, d); else s = sessions[d.session_id] = d; s.lastUpdated = new Date(); if (s.status == 'exited') delete sessions[d.session_id]; }); broadcastSessions(); } function broadcastSessions() { var sessionsToSend = getUniqueSessions(); $rootScope.$emit("sn.sessions", sessionsToSend); $rootScope.$emit("sp.sessions", sessionsToSend); if (primary) $timeout(function() {CustomEvent.fire('sn.sessions', sessionsToSend);}) } function getUniqueSessions() { var uniqueSessionsByUser = {}; var sessionKeys = Object.keys(sessions); sessionKeys.forEach(function(key) { var session = sessions[key]; if (session.user_id == NOW.user_id) return; if (session.user_id in uniqueSessionsByUser) { var otherSession = uniqueSessionsByUser[session.user_id]; var thisPrecedence = getStatusPrecedence(session.status); var otherPrecedence = getStatusPrecedence(otherSession.status); uniqueSessionsByUser[session.user_id] = thisPrecedence < otherPrecedence ? session : otherSession; return } uniqueSessionsByUser[session.user_id] = session; }); var uniqueSessions = {}; angular.forEach(uniqueSessionsByUser, function(item) { uniqueSessions[item.session_id] = item; }); return uniqueSessions; } function getStatusPrecedence(status) { switch (status) { case 'typing': return 0; case 'viewing': return 1; case 'entered': return 2; case 'exited': case 'probably left': return 4; case 'offline': return 5; default: return 3; } } $rootScope.$on("record.typing", function(evt, data) { currentJournalFieldName = data.field_type; setStatus(data.status); }); var idleTable, idleSysID; snTabActivity.onIdle({ onIdle: function RecordPresenceTabIdle() { idleTable = table; idleSysID = sys_id; sessions = {}; termPresence(); broadcastSessions(); }, onReturn: function RecordPresenceTabActive() { initPresence(idleTable, idleSysID, true); idleTable = idleSysID = void(0); }, delay: interval * 4 }); return { initPresence: initPresence, termPresence: termPresence } }); ; /*! RESOURCE: /scripts/sn/common/presence/directive.snPresence.js */ angular.module('sn.common.presence').directive('snPresence', function(snPresence, $rootScope, $timeout, i18n) { 'use strict'; $timeout(snPresence.init, 100); var presenceStatus = {}; i18n.getMessages(['maybe offline', 'probably offline', 'offline', 'online', 'entered', 'viewing'], function (results) { presenceStatus.maybe_offline = results['maybe offline']; presenceStatus.probably_offline = results['probably offline']; presenceStatus.offline = results['offline']; presenceStatus.online = results['online']; presenceStatus.entered = results['entered']; presenceStatus.viewing = results['viewing']; }); var presences = {}; $rootScope.$on('sn.presence', function (event, presenceArray) { angular.forEach(presences, function (p) { p.status = "offline"; }); if (!presenceArray) { return; } presenceArray.forEach(function (presence) { presences[presence.user] = presence; }); }); return { restrict: 'EA', replace: false, scope: { userId: '@?', snPresence: '=?', user: '=?', profile: '=?', displayName: '=?' }, link: function (scope, element) { if (scope.profile) { scope.user = scope.profile.userID; scope.profile.tabIndex = -1; if (scope.profile.isAccessible) scope.profile.tabIndex = 0; } if (!element.hasClass('presence')) element.addClass('presence'); function updatePresence () { var id = scope.snPresence || scope.user; if (!angular.isDefined(id) && angular.isDefined(scope.userId)) { id = scope.userId; } if (presences[id]) { var status = presences[id].status; if (status === 'maybe offline' || status === 'probably offline') { element.removeClass('presence-online presence-offline presence-away'); element.addClass('presence-away'); } else if (status == "offline" && !element.hasClass('presence-offline')) { element.removeClass('presence-online presence-away'); element.addClass('presence-offline'); } else if ( (status == "online" || status == "entered" || status == "viewing") && !element.hasClass('presence-online')) { element.removeClass('presence-offline presence-away'); element.addClass('presence-online'); } status = status.replace(/ /g,"_"); if (scope.profile) angular.element('div[user-avatar-id="' + id + '"]').attr("aria-label", scope.profile.userName + ' ' + presenceStatus[status]); else angular.element('div[user-avatar-id="' + id + '"]').attr("aria-label", scope.displayName + ' ' + presenceStatus[status]); } else { if (!element.hasClass('presence-offline')) element.addClass('presence-offline'); } } var unbind = $rootScope.$on('sn.presence', updatePresence); scope.$on('$destroy', unbind); updatePresence(); } }; }); ; /*! RESOURCE: /scripts/sn/common/presence/directive.snComposing.js */ angular.module('sn.common.presence').directive('snComposing', function(getTemplateUrl, snComposingPresence) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl("snComposing.xml"), replace: true, scope: { conversation: "=" }, controller: function($scope, $element) { var child = $element.children(); if (child && child.tooltip) child.tooltip({ 'template': '<div class="tooltip" style="white-space: pre-wrap" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', 'placement': 'top', 'container': 'body' }); $scope.snComposingPresence = snComposingPresence; } } }); ; /*! RESOURCE: /scripts/sn/common/presence/service.snComposingPresence.js */ angular.module('sn.common.presence').service('snComposingPresence', function(i18n) { "use strict"; var viewing = {}; var typing = {}; var allStrings = {}; var shortStrings = {}; var typing1="{0} is typing", typing2="{0} and {1} are typing", typingMore="{0}, {1}, and {2} more are typing", viewing1="{0} is viewing",viewing2="{0} and {1} are viewing",viewingMore="{0}, {1}, and {2} more are viewing"; i18n.getMessages( [ typing1, typing2, typingMore, viewing1, viewing2, viewingMore ], function (results) { typing1=results[typing1]; typing2=results[typing2]; typingMore=results[typingMore]; viewing1=results[viewing1]; viewing2=results[viewing2]; viewingMore=results[viewingMore]; }); function set(conversationID, newPresenceValues) { if (newPresenceValues.viewing) viewing[conversationID] = newPresenceValues.viewing; if (newPresenceValues.typing) typing[conversationID] = newPresenceValues.typing; generateAllString(conversationID, {viewing: viewing[conversationID],typing: typing[conversationID]}); generateShortString(conversationID, {viewing: viewing[conversationID],typing: typing[conversationID]}); return { viewing: viewing[conversationID], typing: typing[conversationID] } } function get(conversationID) { return { viewing: viewing[conversationID] || [], typing: typing[conversationID] || [] } } function generateAllString(conversationID, members) { var result = ""; var typingLength = members.typing.length; var viewingLength = members.viewing.length; if (typingLength < 4 && viewingLength < 4) return ""; switch (typingLength) { case 0: break; case 1: result += i18n.format(typing1, members.typing[0].name); break; case 2: result += i18n.format(typing2, members.typing[0].name, members.typing[1].name); break; default: var allButLastTyper = ""; for (var i = 0; i < typingLength; i++) { if (i < typingLength -2) allButLastTyper += members.typing[i].name + ", "; else if (i === typingLength-2) allButLastTyper += members.typing[i].name + ","; else result += i18n.format(typing2, allButLastTyper, members.typing[i].name); } } if (viewingLength > 0 && typingLength > 0) result += "\n\n"; switch (viewingLength) { case 0: break; case 1: result += i18n.format(viewing1, members.viewing[0].name); break; case 2: result += i18n.format(viewing2, members.viewing[0].name, members.viewing[1].name); break; default: var allButLastViewer = ""; for (var i = 0; i < viewingLength; i++) { if (i < viewingLength -2) allButLastViewer += members.viewing[i].name + ", "; else if (i === viewingLength - 2) allButLastViewer += members.viewing[i].name + ","; else result += i18n.format(viewing2, allButLastViewer, members.viewing[i].name); } } allStrings[conversationID] = result; } function generateShortString(conversationID, members) { var typingLength = members.typing.length; var viewingLength = members.viewing.length; var typingString = "", viewingString = ""; var inBetween = " "; switch (typingLength ) { case 0: break; case 1: typingString = i18n.format(typing1, members.typing[0].name); break; case 2: typingString = i18n.format(typing2, members.typing[0].name, members.typing[1].name); break; case 3: typingString = i18n.format(typing2, members.typing[0].name + ", " + members.typing[1].name + ",",members.typing[2].name); break; default: typingString = i18n.format(typingMore, members.typing[0].name, members.typing[1].name, (typingLength - 2)); } if (viewingLength > 0 && typingLength > 0) inBetween = ". "; switch (viewingLength) { case 0: break; case 1: viewingString = i18n.format(viewing1, members.viewing[0].name); break; case 2: viewingString = i18n.format(viewing2, members.viewing[0].name, members.viewing[1].name); break; case 3: viewingString = i18n.format(viewing2, members.viewing[0].name + ", " + members.viewing[1].name + ",", members.viewing[2].name); break; default: viewingString = i18n.format(viewingMore, members.viewing[0].name, members.viewing[1].name, (viewingLength - 2)); } shortStrings[conversationID] = typingString + inBetween + viewingString; } function getAllString(conversationID) { if ((viewing[conversationID] && viewing[conversationID].length > 3) || (typing[conversationID] && typing[conversationID].length > 3)) return allStrings[conversationID]; return ""; } function getShortString(conversationID) { return shortStrings[conversationID]; } function remove(conversationID) { delete viewing[conversationID]; } return { set: set, get: get, generateAllString: generateAllString, getAllString: getAllString, generateShortString: generateShortString, getShortString: getShortString, remove: remove } }); ; ; /*! RESOURCE: /scripts/sn/common/user_profile/js_includes_user_profile.js */ /*! RESOURCE: /scripts/sn/common/user_profile/_module.js */ angular.module("sn.common.user_profile", ['sn.common.ui']); ; /*! RESOURCE: /scripts/sn/common/user_profile/directive.snUserProfile.js */ angular.module('sn.common.user_profile').directive('snUserProfile', function(getTemplateUrl, snCustomEvent, $window, avatarProfilePersister, $timeout, $http, $injector) { "use strict"; return { replace: true, restrict: 'E', templateUrl: getTemplateUrl('snUserProfile.xml'), scope: { profile: "=", showDirectMessagePrompt: "=" }, link: function(scope, element) { scope.showDirectMessagePromptFn = function() { if ($injector.has('inSupportClient') && $injector.get('inSupportClient')) return false; if (scope.showDirectMessagePrompt) { var activeUserID = $window.NOW.user_id || ""; return !(!scope.profile || activeUserID === scope.profile.sysID || !scope.profile.hasConnectRoles || (scope.profile.document && activeUserID === scope.profile.document)); } else { return false; } }; }, controller: function($scope, snConnectService) { if ($scope.profile && $scope.profile.userID && avatarProfilePersister.getAvatar($scope.profile.userID)) { $scope.profile = avatarProfilePersister.getAvatar($scope.profile.userID); $scope.$emit("sn-user-profile.ready"); } else { $http.get('/api/now/live/profiles/sys_user.' + $scope.profile.userID).then(function (response) { angular.merge($scope.profile, response.data.result); avatarProfilePersister.setAvatar($scope.profile.userID, $scope.profile); $scope.$emit("sn-user-profile.ready"); }) } $http.get('/api/now/live/profiles/' + $scope.profile.userID + '/has_connect_roles').then(function(response) { $scope.profile.hasConnectRoles = response.data.result.hasConnectRoles; }); $scope.openDirectMessageConversation = function(evt) { if (evt && evt.keyCode === 9) return; $timeout(function () { snConnectService.openWithProfile($scope.profile); }, 0, false); angular.element('.popover').each(function() { angular.element('body').off('click.snUserAvatarPopoverClose'); angular.element(this).popover('hide'); }); }; } }; }); ; ; /*! RESOURCE: /scripts/sn/common/avatar/_module.js */ angular.module('sn.common.avatar', ['sn.common.presence', 'sn.common.messaging', 'sn.common.user_profile']).config(function($provide) { $provide.value("liveProfileID", ''); }); ; /*! RESOURCE: /scripts/sn/common/avatar/directive.snAvatarPopover.js */ angular.module('sn.common.avatar').directive('snAvatarPopover', function($http, $compile, getTemplateUrl, avatarProfilePersister, $injector) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('sn_avatar_popover.xml'), replace: true, transclude: true, scope : { members: '=', primary: '=?', showPresence: '=?', enableContextMenu: '=?', enableTooltip: '=?', enableBindOnce: '@', displayMemberCount: "=?", groupAvatar: "@", nopopover: "=", directconversation: '@', conversation: '=', primaryNonAssign: '=?' }, compile: function(tElement) { var template = tElement.html(); return function (scope, element, attrs, controller, transcludeFn) { if (scope.directconversation) { if (scope.directconversation === "true") scope.directconversation = true; else scope.directconversation = false; scope.showdirectconversation = !scope.directconversation; } else { scope.showdirectconversation = true; } if ($injector.has('inSupportClient') && $injector.get('inSupportClient')) scope.showdirectconversation = false; if (scope.primaryNonAssign) { scope.primary = angular.extend({}, scope.primary, scope.primaryNonAssign); if (scope.users && scope.users[0]) scope.users[0] = scope.primary; } function recompile () { if (scope.primaryNonAssign) { scope.primary = angular.extend({}, scope.primary, scope.primaryNonAssign); if (scope.users && scope.users[0]) scope.users[0] = scope.primary; } var newElement = $compile(template, transcludeFn)(scope); element.html(newElement); if (scope.enableTooltip) { element.tooltip({ placement: 'auto top', container: 'body' }).attr('data-original-title', scope.users[0].name).tooltip('fixTitle'); if (element.hideFix) element.hideFix(); } } if (attrs.enableBindOnce === 'false') { scope.$watch('primary', recompile); scope.$watch('primaryNonAssign', recompile); scope.$watch('members', recompile); } if (scope.enableTooltip && scope.nopopover) { var usersWatch = scope.$watch('users', function () { if (scope.users && scope.users.length === 1 && scope.users[0] && scope.users[0].name) { element.tooltip({ placement: 'auto top', container: 'body' }).attr('data-original-title', scope.users[0].name).tooltip('fixTitle'); if (element.hideFix) element.hideFix(); usersWatch(); } }); } }; }, controller: function($scope, liveProfileID, $timeout, $element, $document, snCustomEvent) { $scope.randId = Math.random(); $scope.loadEvent = 'sn-user-profile.ready'; $scope.closeEvent = ['chat:open_conversation', 'snAvatar.closePopover', 'body_clicked']; $scope.popoverConfig = { template: '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content"></div></div>' }; $scope.displayMemberCount = $scope.displayMemberCount || false; $scope.liveProfileID = liveProfileID; if ($scope.primaryNonAssign) { $scope.primary = angular.extend({}, $scope.primary, $scope.primaryNonAssign); if ($scope.users && $scope.users[0]) $scope.users[0] = $scope.primary; } $scope.$watch('members', function(newVal, oldVal) { if(newVal === oldVal) return; if ($scope.members) buildAvatar(); }); $scope.noPopover = function () { $scope.popoverCursor = ($scope.nopopover || ($scope.members && $scope.members.length > 2) ) ? "default" : "pointer"; return ($scope.nopopover || ($scope.members && $scope.members.length > 2)); } $scope.avatarType = function() { var result = []; if($scope.groupAvatar || !$scope.users) return result; if ($scope.users.length > 1) result.push("group") if ($scope.users.length === 2) result.push("avatar-duo") if ($scope.users.length === 3) result.push("avatar-trio") if ($scope.users.length >= 4) result.push("avatar-quad") if ($scope.users.length === 1 && !$scope.users[0].avatar) result.push("initials"); return result; } $scope.getBackgroundStyle = function(user) { var avatar = (user ? user.avatar : ''); if ($scope.groupAvatar) avatar = $scope.groupAvatar; if (avatar && avatar !== '') return { 'background-image' : 'url(' + avatar + ')' }; if (user && user.name) return ''; return void(0); }; $scope.stopPropCheck = function (evt) { $scope.$broadcast("snAvatar.closeOtherPopovers", $scope.randId); if (!$scope.nopopover) { evt.stopPropagation(); } }; $scope.$on("snAvatar.closeOtherPopovers", function (id) { if (id !== $scope.randId) snCustomEvent.fireTop('snAvatar.closePopover'); }); $scope.maxStringWidth = function() { var paddedWidth = parseInt($scope.avatarWidth * 0.8, 10); return $scope.users.length === 1 ? paddedWidth : paddedWidth / 2; }; function buildInitials(name) { if (!name) return "--"; var initials = name.split(" ").map(function(word) { return word.toUpperCase(); }).filter(function(word) { return word.match(/^[A-Z]/); }).map(function(word) { return word.substring(0,1); }).join(""); return (initials.length > 3) ? initials.substr(0, 3) : initials; } $scope.avatartooltip = function() { if (!$scope.enableTooltip) { return ''; } if (!$scope.users) { return ''; } var names = []; $scope.users.forEach(function(user) { if(!user) { return; } names.push(user.name); }); return names.join(', '); }; function buildAvatar() { if (typeof $scope.primary === 'string') { $http.get('/api/now/live/profiles/sys_user.' + $scope.primary).then(function (response) { $scope.users = [{ userID: $scope.primary, name: response.data.result.name, initials: buildInitials(response.data.result.name), avatar: response.data.result.avatar }]; }); return; } if ($scope.primary) { if ($scope.primary.userImage) $scope.primary.avatar = $scope.primary.userImage; if (!$scope.primary.userID && $scope.primary.sys_id) $scope.primary.userID = $scope.primary.sys_id; } $scope.isGroup = $scope.conversation && $scope.conversation.isGroup; $scope.users = [$scope.primary]; if ($scope.primary && (!$scope.members || $scope.members.length <= 0) && ($scope.primary.avatar || $scope.primary.initials) && $scope.isDocument) { $scope.users = [$scope.primary]; } else if ($scope.members && $scope.members.length > 0) { $scope.users = buildCompositeAvatar($scope.members); } $scope.presenceEnabled = $scope.showPresence && !$scope.isGroup && $scope.users.length === 1; } function buildCompositeAvatar(members) { var currentUser = window.NOW.user ? window.NOW.user.userID : window.NOW.user_id; var users = angular.isArray(members) ? members.slice() : [members]; users = users.sort(function(a, b) { var aID = a.userID || a.document; var bID = b.userID || b.document; if (a.table === "chat_queue_entry") return 1; if (aID === currentUser) return 1; else if (bID === currentUser) return -1; return 0; }); if (users.length === 2) users = [users[0]]; if (users.length > 2 && $scope.primary && $scope.primary.name && $scope.primary.table === "sys_user") { var index = -1; angular.forEach(users, function(user, i) { if (user.sys_id === $scope.primary.sys_id) { index = i; } }); if (index > -1) { users.splice(index, 1); } users.splice(1, 0, $scope.primary); } return users; } buildAvatar(); $scope.loadFullProfile = function () { if ($scope.primary && !$scope.primary.sys_id && !avatarProfilePersister.getAvatar($scope.primary.userID)) { $http.get('/api/now/live/profiles/' + $scope.primary.userID).then( function (response) { try{ angular.extend($scope.primary, response.data.result); avatarProfilePersister.setAvatar($scope.primary.userID, $scope.primary); }catch(e){} }); } } } } }); ; /*! RESOURCE: /scripts/sn/common/avatar/directive.snAvatar.js */ angular.module('sn.common.avatar') .factory('snAvatarFactory', function($http, $compile, $templateCache, $q, snCustomEvent, snConnectService) { 'use strict'; return function() { return { restrict : 'E', replace: true, transclude: true, scope : { members: '=', primary: '=', showPresence: '=?', enableContextMenu: '=?', enableTooltip: '=?', enableBindOnce: '@', displayMemberCount: "=?", groupAvatar: "@" }, compile: function(tElement) { var template = tElement.html(); return function (scope, element, attrs, controller, transcludeFn) { var newElement = $compile(template, transcludeFn)(scope); element.html(newElement); if (scope.enableTooltip) { element.tooltip({ placement: 'auto top', container: 'body' }).attr('data-original-title', scope.users[0].name).tooltip('fixTitle'); if (element.hideFix) element.hideFix(); } if (attrs.enableBindOnce === 'false') { scope.$watch('primary', recompile); scope.$watch('members', recompile); } if (scope.enableTooltip) { var usersWatch = scope.$watch('users', function () { if (scope.users && scope.users.length === 1 && scope.users[0] && scope.users[0].name) { element.tooltip({ placement: 'auto top', container: 'body' }).attr('data-original-title', scope.users[0].name).tooltip('fixTitle'); if (element.hideFix) element.hideFix(); usersWatch(); } }); } if (scope.enableContextMenu !== false) { scope.contextOptions = []; var gUser = null; try { gUser = g_user; } catch (err) {} if (scope.users && scope.users.length === 1 && scope.users[0] && (scope.users[0].userID || scope.users[0].sys_id)) { scope.contextOptions = [ ["Open user's profile", function () { if (scope.users && scope.users.length > 0) { window.open('/nav_to.do?uri=' + encodeURIComponent('sys_user.do?sys_id=' + scope.users[0].userID), '_blank'); } }]]; if ((gUser && scope.users[0].userID && scope.users[0].userID !== gUser.userID) || (scope.liveProfileID && scope.users[0] && scope.users[0].sysID !== scope.liveProfileID)) { scope.contextOptions.push(["Open a new chat", function () { snConnectService.openWithProfile(scope.users[0]); }]); } } } else { scope.contextOptions = []; } }; }, controller: function($scope, liveProfileID) { var firstBuildAvatar = true; $scope.displayMemberCount = $scope.displayMemberCount || false; $scope.liveProfileID = liveProfileID; $scope.$watch('primary', function(newValue, oldValue) { if ($scope.primary && newValue !== oldValue) { if(!firstBuildAvatar) buildAvatar(); if ($scope.contextOptions.length > 0) { $scope.contextOptions = [ ["Open user's profile", function () { if ($scope.users && $scope.users.length > 0) { window.location.href = 'sys_user.do?sys_id=' + $scope.users[0].userID || $scope.users[0].userID; } }]]; var gUser = null; try { gUser = g_user; } catch (err) { } if ((!gUser && !liveProfileID) || ($scope.users && $scope.users.length === 1 && $scope.users[0])) { if ((gUser && $scope.users[0].userID && $scope.users[0].userID !== gUser.userID) || ($scope.liveProfileID && $scope.users[0] && $scope.users[0].sysID !== $scope.liveProfileID)) { $scope.contextOptions.push(["Open a new chat", function () { snConnectService.openWithProfile($scope.users[0]); }]); } } } } }); $scope.$watch('members', function() { if ($scope.members && !firstBuildAvatar) buildAvatar(); }); $scope.avatarType = function() { var result = []; if($scope.groupAvatar || !$scope.users) return result; if ($scope.users.length > 1) result.push("group"); if ($scope.users.length === 2) result.push("avatar-duo"); if ($scope.users.length === 3) result.push("avatar-trio"); if ($scope.users.length >= 4) result.push("avatar-quad"); return result; }; $scope.getBackgroundStyle = function(user) { var avatar = (user ? user.avatar : ''); if ($scope.groupAvatar) avatar = $scope.groupAvatar; if (avatar && avatar !== '') return { 'background-image' : 'url(' + avatar + ')' }; if (user && user.name) return ''; return void(0); }; $scope.maxStringWidth = function() { var paddedWidth = parseInt($scope.avatarWidth * 0.8, 10); return $scope.users.length === 1 ? paddedWidth : paddedWidth / 2; }; function buildInitials(name) { if (!name) return "--"; var initialMatchRegex = /^[A-ZÀ-Ÿ]|^[\u3040-\u309f]|^[\u30a0-\u30ff]|^[\uff66-\uff9f]|^[\u4e00-\u9faf]/; var initials = name.split(" ").map(function(word) { return word.toUpperCase(); }).filter(function(word) { return word.match(initialMatchRegex); }).map(function(word) { return word.substring(0,1); }).join(""); return (initials.length > 3) ? initials.substr(0, 3) : initials; } $scope.avatartooltip = function() { if (!$scope.enableTooltip) { return ''; } if (!$scope.users) { return ''; } var names = []; $scope.users.forEach(function(user) { if(!user) { return; } names.push(user.name); }); return names.join(', '); }; function setPresence(){ $scope.presenceEnabled = $scope.showPresence && !$scope.isDocument && $scope.users.length === 1; return $scope.presenceEnabled; } function buildAvatar() { if(firstBuildAvatar) firstBuildAvatar = false; if (typeof $scope.primary === 'string') { return $http.get('/api/now/live/profiles/sys_user.' + $scope.primary).then(function (response) { $scope.users = [{ userID: $scope.primary, name: response.data.result.name, initials: buildInitials(response.data.result.name), avatar: response.data.result.avatar }]; return setPresence(); }); } if ($scope.primary) { if ($scope.primary.userImage) $scope.primary.avatar = $scope.primary.userImage; if (!$scope.primary.userID && $scope.primary.sys_id) $scope.primary.userID = $scope.primary.sys_id; } $scope.isDocument = $scope.primary && $scope.primary.table && $scope.primary.table !== "sys_user" && $scope.primary.table !== "chat_queue_entry"; $scope.users = [$scope.primary]; if ($scope.primary && (!$scope.members || $scope.members.length <= 0) && ($scope.primary.avatar || $scope.primary.initials) && $scope.isDocument) { $scope.users = [$scope.primary]; } else if ($scope.members && $scope.members.length > 0) { $scope.users = buildCompositeAvatar($scope.members); } return $q.when(setPresence()); } function buildCompositeAvatar(members) { var currentUser = window.NOW.user ? window.NOW.user.userID : window.NOW.user_id; var users = angular.isArray(members) ? members.slice() : [members]; users = users.sort(function(a, b) { var aID = a.userID || a.document; var bID = b.userID || b.document; if (a.table === "chat_queue_entry") return 1; if (aID === currentUser) return 1; else if (bID === currentUser) return -1; return 0; }); if (users.length === 2) users = [users[0]]; if (users.length > 2 && $scope.primary && $scope.primary.name && $scope.primary.table === "sys_user") { var index = -1; angular.forEach(users, function(user, i) { if (user.sys_id === $scope.primary.sys_id) { index = i; } }); if (index > -1) { users.splice(index, 1); } users.splice(1, 0, $scope.primary); } return users; } buildAvatar(); } } } }) .directive('snAvatar', function (snAvatarFactory, getTemplateUrl){ var directive = snAvatarFactory(); directive.templateUrl = getTemplateUrl('sn_avatar.xml'); return directive; }) .directive('snAvatarOnce', function (snAvatarFactory, getTemplateUrl) { var directive = snAvatarFactory(); directive.templateUrl = getTemplateUrl('sn_avatar_once.xml'); return directive; }); ; /*! RESOURCE: /scripts/sn/common/avatar/service.avatarProfilePersister.js */ angular.module('sn.common.avatar').service('avatarProfilePersister', function () { "use strict"; var avatars = {}; function setAvatar (id, payload) { avatars[id] = payload; } function getAvatar (id) { return avatars[id]; } return { setAvatar: setAvatar, getAvatar: getAvatar } }); ; /*! RESOURCE: /scripts/sn/common/avatar/directive.snUserAvatar.js */ angular.module('sn.common.avatar').directive('snUserAvatar', function(getTemplateUrl) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl('sn_user_avatar.xml'), replace: true, scope: { profile: '=?', userId: '=?', avatarUrl: '=?', initials: '=?', enablePresence: '@', disablePopover: '=?', directConversationButton: '=?', userName: '=?', isAccessible: '=?' }, link: function (scope, element) { scope.evaluatedProfile = undefined; scope.backgroundStyle = undefined; scope.enablePresence = scope.enablePresence !== 'false'; if (scope.profile) { scope.evaluatedProfile = scope.profile; scope.userId = scope.profile.userID || ""; scope.avatarUrl = scope.profile.avatar || ""; scope.initials = scope.profile.initials || ""; scope.backgroundStyle = scope.getBackgroundStyle(); } else if (scope.userId || scope.avatarUrl || scope.initials || scope.userName) { scope.evaluatedProfile = scope.profile = { 'userID': scope.userId || "", 'avatar': scope.avatarUrl || "", 'initials': scope.initials || "", 'userName': scope.userName || "", 'isAccessible': scope.isAccessible || false }; scope.backgroundStyle = scope.getBackgroundStyle(); } else { var unwatch = scope.$watch('profile', function (newVal) { if (newVal) { scope.evaluatedProfile = newVal; scope.backgroundStyle = scope.getBackgroundStyle(); unwatch(); } }) } scope.directConversationButton = scope.directConversationButton !== 'false' && scope.directConversationButton !== false; scope.template = '<sn-user-profile tabindex="-1" id="sn-bootstrap-popover" profile="evaluatedProfile" show-direct-message-prompt="::directConversationButton" class="avatar-popover avatar-popover-padding"></sn-user-profile>'; scope.ariaRole = scope.disablePopover ? 'presentation' : 'button'; }, controller: function($scope) { $scope.getBackgroundStyle = function() { if ( ($scope.avatarUrl && $scope.avatarUrl !== '') || $scope.evaluatedProfile && $scope.evaluatedProfile.avatar !== '' ) return {"background-image": 'url(' + ($scope.avatarUrl || $scope.evaluatedProfile.avatar) + ')'}; return {"background-image": ""}; }; } } }); ; /*! RESOURCE: /scripts/sn/common/avatar/directive.snGroupAvatar.js */ angular.module('sn.common.avatar').directive('snGroupAvatar', function($http, $compile, getTemplateUrl, avatarProfilePersister) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('sn_group_avatar.xml'), replace: true, transclude: true, scope : { members: '=', primary: '=?', groupAvatar: "@" }, controller: function($scope, liveProfileID) { $scope.liveProfileID = liveProfileID; $scope.$watch('members', function(newVal, oldVal) { if(newVal === oldVal) return; if ($scope.members) $scope.users = buildCompositeAvatar($scope.members); }); $scope.avatarType = function() { var result = []; if($scope.groupAvatar || !$scope.users) return result; if ($scope.users.length > 1) result.push("group") if ($scope.users.length === 2) result.push("sn-avatar_duo") if ($scope.users.length === 3) result.push("sn-avatar_trio") if ($scope.users.length >= 4) result.push("sn-avatar_quad") return result; }; $scope.getBackgroundStyle = function(user) { var avatar = (user ? user.avatar : ''); if ($scope.groupAvatar) avatar = $scope.groupAvatar; if (avatar && avatar !== '') return {"background-image" : "url(" + avatar + ")"}; return {}; }; $scope.users = buildCompositeAvatar($scope.members); function buildCompositeAvatar(members) { var currentUser = window.NOW.user ? window.NOW.user.userID : window.NOW.user_id; var users = angular.isArray(members) ? members.slice() : [members]; users = users.sort(function(a, b) { var aID = a.userID || a.document; var bID = b.userID || b.document; if (a.table === "chat_queue_entry") return 1; if (aID === currentUser) return 1; else if (bID === currentUser) return -1; return 0; }); if (users.length === 2) users = [users[0]]; if (users.length > 2 && $scope.primary && $scope.primary.name && $scope.primary.table === "sys_user") { var index = -1; angular.forEach(users, function(user, i) { if (user.sys_id === $scope.primary.sys_id) { index = i; } }); if (index > -1) { users.splice(index, 1); } users.splice(1, 0, $scope.primary); } return users; } } } }); ; ; /*! RESOURCE: /scripts/sn/common/controls/js_includes_controls.js */ /*! RESOURCE: /scripts/sn/common/controls/_module.js */ angular.module('sn.common.controls', ['sn.common.util']); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snChoiceList.js */ angular.module('sn.common.controls').directive('snChoiceList', function(i18n, $timeout) { "use strict"; return { restrict : 'E', replace : true, scope : { snModel: "=", snTextField: "@", snValueField: "@", snOptions: "=?", snItems: "=?", snOnChange: "&", snDisabled: "=", snDialogName: "=" }, template : '<select ng-disabled="snDisabled" ' + ' ng-model="model" ' + ' ng-options="item[snValueField] as item[snTextField] for item in snItems">' + ' <option value="" ng-show="snOptions.placeholder">{{snOptions.placeholder}}</option>' + '</select>', link : function (scope, element, attrs) { if (scope.snDialogName) scope.$on("dialog." + scope.snDialogName + ".close", function() { $timeout(function() { $(element).select2("destroy"); }) }); $(element).css("opacity", 0); var config = { width: "100%" }; if (angular.isFunction(element.select2)) { i18n.getMessage('No matches found', function(msg) { config.formatNoMatches = function() { return msg; }; }); } if (scope.snOptions){ if (scope.snOptions.placeholder){ config.placeholder = scope.snOptions.placeholder; config.placeholderOption = "first"; } if (scope.snOptions.allowClear){ config.allowClear = scope.snOptions.allowClear; } if (scope.snOptions.hideSearch && scope.snOptions.hideSearch === true){ config.minimumResultsForSearch = -1; } } function init(){ scope.model = scope.snModel; render(); } function render(){ if (!attrs){ $timeout(function(){render();}); return; } $timeout(function(){ $(element).css("opacity", 1); $(element).select2("destroy"); $(element).select2(config); }); } init(); scope.$watch("snItems", function(newValue, oldValue){ if (newValue !== oldValue){ init(); } }, true); scope.$watch("snModel", function(newValue){ if (newValue !== undefined && newValue !== scope.model){ init(); } }); scope.$watch("model", function(newValue, oldValue){ if (newValue !== oldValue){ scope.snModel = newValue; if (scope.snOnChange) scope.snOnChange({selectedValue:newValue}); } }); scope.$on('$destroy', function() { $(element).select2("destroy"); }); }, controller : function($scope) { } } }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snHtmlContentWrapper.js */ angular.module('sn.common.controls').directive('snHtmlContentWrapper', function() { function link(scope, element, attrs) { attrs.$observe("content", function(content) { encapsulate(element[0], content, attrs.uniqueId); }); } function createDefaultCssLink() { var link = document.createElement("link"); link.href = "styles/activity_encapsulated.css"; link.rel = "stylesheet"; link.type = "text/css"; return link; } function createBaseElement() { var base = document.createElement("base"); base.setAttribute("target", "_blank") return base; } function encapsulate(root, content, uniqueId) { var defaultCssLink = createDefaultCssLink(); var style = document.createElement('style'); style.innerHTML = ':host img {max-width: 100%; height: auto; overflow: hidden;}'; if (document.head.createShadowRoot || document.head.attachShadow) { var shadow = root.shadowRoot || (document.head.attachShadow ? root.attachShadow({mode: 'open'}) : root.createShadowRoot()); var contentDiv = document.createElement('div'); contentDiv.innerHTML = content; shadow.innerHTML = contentDiv.outerHTML; shadow.appendChild(defaultCssLink); shadow.appendChild(style); } else { var iframeId = "activity-iframe-" + uniqueId; var existingIframe = document.getElementById(iframeId); if (existingIframe) { existingIframe.contentDocument.write(content); existingIframe.contentWindow.document.head.appendChild(defaultCssLink); existingIframe.setAttribute("height", existingIframe.contentWindow.document.body.scrollHeight + 'px') } else { var rootEl = $j(root); var iframe = document.createElement("iframe"); iframe.setAttribute("id", iframeId); iframe.setAttribute("style", "border:none;display:block;width:100%"); iframe.setAttribute("class", "html-content"); iframe.setAttribute("scrolling", "no"); iframe.setAttribute("height", "0"); iframe.setAttribute("sandbox", "allow-same-origin"); root.appendChild(iframe); var doc = iframe.contentWindow.document; doc.open(); doc.write(content); doc.close(); iframe.contentWindow.document.head.appendChild(defaultCssLink); iframe.contentWindow.document.head.appendChild(createBaseElement()); iframe.height = doc.body.scrollHeight + 'px'; var parentTab = rootEl.closest(".tabs2_section"); var parentSectionId = parentTab.attr("data-section-id"); var setIFrameHeightFn = function(tab) { var openedTab = $j(".tabs2_section." + tab); if (openedTab.length > 0 && openedTab.attr("data-section-id") === parentSectionId) { iframe.contentWindow.document.head.appendChild(defaultCssLink); iframe.height = doc.body.scrollHeight + 'px'; CustomEvent.un("tab.activated", setIFrameHeightFn); } }; CustomEvent.observe("tab.activated", setIFrameHeightFn); } } } return { link: link, restrict: 'E', replace: true }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snReferencePicker.js */ angular.module('sn.common.controls').directive('snReferencePicker', function($timeout, $http, urlTools, filterExpressionParser, escapeHtml, i18n) { "use strict"; return { restrict: 'E', replace: true, scope: { ed: "=?", field: "=", refTable: "=?", refId: "=?", snOptions: "=?", atfQualifier: "=?", snOnChange: "&", snOnBlur: "&", snOnClose: "&", snOnOpen: '&', minimumInputLength : "@", snDisabled: "=", snPageSize: "@", dropdownCssClass: "@", formatResultCssClass: "&", overlay: "=", additionalDisplayColumns: "@", displayColumn: "@", recordValues: '&', getGlideForm: '&glideForm', domain: "@", snSelectWidth: '@', }, template: '<input type="text" name="{{field.name}}" ng-disabled="snDisabled" style="min-width: 150px;" ng-model="field.displayValue" ' + 'sn-atf-settable="true" sn-atf-component-value="{{field.value}}" sn-atf-data-type="reference"' + 'sn-atf-data-type-params=\'{"reference" : "{{ed.reference}}", "reference_qual" : "{{atfQualifier || ed.qualifier}}", ' + '"valueField" : "sys_id", "displayField" : "{{ed.searchField}}"}\' ng-attr-sn-atf-disabled="{{ snDisabled || undefined }}" />', link: function(scope, element, attrs, ctrl) { scope.ed = scope.ed || scope.field.ed; scope.selectWidth = scope.snSelectWidth || '100%'; element.css("opacity", 0); var fireReadyEvent = true; var g_form; if (angular.isDefined(scope.getGlideForm)) g_form = scope.getGlideForm(); var fieldAttributes = {}; if (angular.isDefined(scope.field) && angular.isDefined(scope.field.attributes) && typeof scope.ed.attributes == 'undefined') if (Array.isArray(scope.field.attributes)) fieldAttributes = scope.field.attributes; else fieldAttributes = parseAttributes(scope.field.attributes); else fieldAttributes = parseAttributes(scope.ed.attributes); if (!angular.isDefined(scope.additionalDisplayColumns) && angular.isDefined(fieldAttributes['ref_ac_columns'])) scope.additionalDisplayColumns = fieldAttributes['ref_ac_columns']; var atfQualifier = scope.ed.qualifier || ''; if (scope.ed.dependent_field && scope.ed.dependent_value && scope.ed.dependent_table && !(scope.ed.reference == 'sys_user' && scope.ed.dependent_field.indexOf('group') != -1)) { if (atfQualifier) atfQualifier += "^"; atfQualifier += scope.ed.dependent_field + "=" + scope.ed.dependent_value; } scope.atfQualifier = atfQualifier; var select2AjaxHelpers = { formatSelection: function(item) { return escapeHtml(getDisplayValue(item)); }, formatResult: function(item) { var displayValues = getDisplayValues(item); if (displayValues.length == 1) return escapeHtml(displayValues[0]); if (displayValues.length > 1) { var width = 100 / displayValues.length; var markup = ""; for (var i = 0; i < displayValues.length; i++) markup += "<div style='width: " + width + "%;' class='select2-result-cell'>" + escapeHtml(displayValues[i]) + "</div>"; return markup; } return ""; }, search: function(queryParams) { if ('sysparm_include_variables' in queryParams.data) { var url = urlTools.getURL('ref_list_data', queryParams.data); return $http.get(url).then(queryParams.success); }else { var urlQueryParameters = {}; if (queryParams.data['sysparm_for_impersonation']) { urlQueryParameters['sysparm_for_impersonation'] = true; } var url = urlTools.getURL('ref_list_data', urlQueryParameters); return $http.post(url, queryParams.data).then(queryParams.success); } }, initSelection: function(elem, callback) { if (scope.field && scope.field.displayValue) callback({ sys_id: scope.field.value, name: scope.field.displayValue }); } }; var config = { width : scope.selectWidth, minimumInputLength: scope.minimumInputLength ? parseInt(scope.minimumInputLength, 10) : 0, overlay: scope.overlay, containerCssClass : 'select2-reference ng-form-element', placeholder : ' ', formatSearching: '', allowClear: attrs.allowClear !== 'false', clearAriaLabel: (scope.snOptions) ? scope.snOptions.clearAriaLabel : "", id: function(item) { return item.sys_id; }, sortResults: (scope.snOptions && scope.snOptions.sortResults) ? scope.snOptions.sortResults : undefined, ajax: { quietMillis: NOW.ac_wait_time, data: function(filterText, page) { var q = _getReferenceQuery(filterText); var params = { start: (scope.pageSize * (page - 1)), count: scope.pageSize, sysparm_target_table: scope.refTable, sysparm_target_sys_id: scope.refId, sysparm_target_field: scope.ed.dependent_field || scope.ed.name, table: scope.ed.reference, qualifier: scope.ed.qualifier, sysparm_for_impersonation: !!scope.ed.for_impersonation, data_adapter: scope.ed.data_adapter, attributes: scope.ed.attributes, dependent_field: scope.ed.dependent_field, dependent_table: scope.ed.dependent_table, dependent_value: scope.ed.dependent_value, p: scope.ed.reference + ';q:' + q + ';r:' + scope.ed.qualifier }; if (scope.domain) { params.sysparm_domain = scope.domain; } if (angular.isDefined(scope.field) && scope.field['_cat_variable'] === true){ delete params['sysparm_target_table']; params['sysparm_include_variables'] = true; params['variable_ids'] = scope.field.sys_id; var getFieldSequence = g_form.$private.options('getFieldSequence'); if (getFieldSequence) { params['variable_sequence1'] = getFieldSequence(); } var itemSysId = g_form.$private.options('itemSysId'); params['sysparm_id'] = itemSysId; var getFieldParams = g_form.$private.options('getFieldParams'); if (getFieldParams) { angular.extend(params, getFieldParams()); } } if (scope.recordValues) params.sysparm_record_values = scope.recordValues(); return params; }, results: function(data, page) { return ctrl.filterResults(data, page, scope.pageSize); }, transport: select2AjaxHelpers.search }, formatSelection: select2AjaxHelpers.formatSelection, formatResult: select2AjaxHelpers.formatResult, initSelection: select2AjaxHelpers.initSelection, dropdownCssClass: attrs.dropdownCssClass, formatResultCssClass: scope.formatResultCssClass || null }; if (scope.snOptions) { if (scope.snOptions.placeholder) { config.placeholder = scope.snOptions.placeholder; } if (scope.snOptions.width) { config.width = scope.snOptions.width; } } function _getReferenceQuery(filterText) { var filterExpression = filterExpressionParser.parse(filterText, scope.ed.defaultOperator); var colToSearch = getReferenceColumnsToSearch(); var excludedValues = getExcludedValues(); return colToSearch.map(function(column) { return column + filterExpression.operator + filterExpression.filterText + '^' + column + 'ISNOTEMPTY' + excludedValues; }).join("^NQ"); } function getReferenceColumnsToSearch() { var colName = ['name']; if (scope.ed.searchField) { colName = scope.ed.searchField.split(";"); } else if (fieldAttributes['ref_ac_columns_search'] == 'true' && 'ref_ac_columns' in fieldAttributes && fieldAttributes['ref_ac_columns'] != '') { colName = fieldAttributes['ref_ac_columns'].split(';'); } else if (fieldAttributes['ref_ac_order_by']) { colName = [fieldAttributes['ref_ac_order_by']]; } return colName; } function getExcludedValues () { if (scope.ed.excludeValues && scope.ed.excludeValues != '') { return '^sys_idNOT IN' + scope.ed.excludeValues; } return ''; } function parseAttributes(strAttributes) { var attributeArray = (strAttributes && strAttributes.length ? strAttributes.split(',') : []); var attributeObj = {}; for (var i = 0; i < attributeArray.length; i++) { if (attributeArray[i].length > 0) { var attribute = attributeArray[i].split('='); attributeObj[attribute[0]] = attribute.length > 1 ? attribute[1] : ''; } } return attributeObj; } function init() { scope.model = scope.snModel; render(); } function render() { $timeout(function() { i18n.getMessage('Searching...', function(searchingMsg) { config.formatSearching = function() { return searchingMsg; }; }); element.css("opacity", 1); element.select2("destroy"); var select2 = element.select2(config).select2('val', []); select2.bind("change", select2Change); select2.bind("select2-removed", select2Change); select2.bind("select2-blur", function() { scope.$apply(function() { scope.snOnBlur(); }); }); select2.bind("select2-close", function() { scope.$apply(function() { scope.snOnClose(); }); }); select2.bind("select2-open", function() { scope.$apply(function() { if (scope.snOnOpen) scope.snOnOpen(); }); }); select2.bind('select2-focus', function() { redirectLabel(element); }); select2.bind('sn-atf-setvalue', setValueATF); if (fireReadyEvent) { scope.$emit('select2.ready', element); fireReadyEvent = false; } }); } function select2Change(e) { e.stopImmediatePropagation(); if (e.added) { if (scope.$$phase || scope.$root.$$phase) return; var selectedItem = e.added; var value = selectedItem.sys_id; var displayValue = value ? getDisplayValue(selectedItem) : ''; if (scope.snOptions && scope.snOptions.useGlideForm === true) { g_form.setValue(scope.field.name, value, displayValue); scope.rowSelected(); e.displayValue = displayValue; triggerSnOnChange(); } else { scope.$apply(function() { scope.field.value = value; scope.field.displayValue = displayValue; scope.rowSelected(); e.displayValue = displayValue; triggerSnOnChange(); }); } } else if (e.removed) { if (scope.snOptions && scope.snOptions.useGlideForm === true) { g_form.clearValue(scope.field.name); triggerSnOnChange(); } else { scope.$apply(function() { scope.field.displayValue = ''; scope.field.value = ''; triggerSnOnChange(); }); } } $timeout(function() { element.parent().find(".select2-focusser").focus(); }, 0, false); function triggerSnOnChange(){ if (scope.snOnChange) scope.snOnChange(e); } } function redirectLabel($select2) { if (NOW.select2LabelWorkaround) NOW.select2LabelWorkaround($select2); } function getDisplayValue(selectedItem) { var displayValue = ''; if (selectedItem && selectedItem.sys_id) { if (scope.displayColumn && typeof selectedItem[scope.displayColumn] != "undefined") displayValue = selectedItem[scope.displayColumn]; else if (selectedItem.$$displayValue) displayValue = selectedItem.$$displayValue; else if (selectedItem.name) displayValue = selectedItem.name; else if (selectedItem.title) displayValue = selectedItem.title; } return displayValue; } function getDisplayValues(selectedItem) { var displayValues = []; if (selectedItem && selectedItem.sys_id) { var current = ""; if (scope.displayColumn && typeof selectedItem[scope.displayColumn] != "undefined") current = selectedItem[scope.displayColumn]; else if (selectedItem.$$displayValue) current = selectedItem.$$displayValue; else if (selectedItem.name) current = selectedItem.name; else if (selectedItem.title) current = selectedItem.title; displayValues.push(current); } if (scope.additionalDisplayColumns) { var columns = scope.additionalDisplayColumns.split(","); for (var i = 0; i < columns.length; i++) { var column = columns[i]; if (selectedItem[column]) displayValues.push(selectedItem[column]); } } return displayValues; } function setValueATF(e) { e.stopImmediatePropagation(); var changeEventParameters = { type: "change" }; if (scope.field.value) changeEventParameters.removed = element.select2("data"); var newValue = e.detail && e.detail.newValue; if (newValue) { var params = config.ajax.data('', 1); if (params.qualifier) params.qualifier += "^"; else params.qualifier = ""; params.qualifier += "sys_id=" + newValue; var data = { data: params, dataType: "json", error: atfHandleNoResults, success: function (answer) { if (answer.data.items && answer.data.items.length == 1) { var valueToSet = answer.data.items[0].sys_id; changeEventParameters.added = answer.data.items[0]; $timeout(function() { element.val(valueToSet); element.triggerHandler(changeEventParameters); }, 0, false); } else atfHandleNoResults(); }, }; select2AjaxHelpers.search(data); } else { element.val(""); element.triggerHandler(changeEventParameters); } function atfHandleNoResults() { i18n.getMessage( "Unable to set reference picker to value {0}", function(errorMessage) { throw new Error(i18n.format(errorMessage, newValue)); } ); } } scope.$watch("field.displayValue", function(newValue, oldValue) { if (newValue != oldValue && newValue !== scope.model) { init(); } }); scope.$on("snReferencePicker.activate", function(evt, parms) { $timeout(function() { element.select2("open"); }) }); init(); }, controller: function($scope, $rootScope) { $scope.pageSize = 20; if ($scope.snPageSize) $scope.pageSize = parseInt($scope.snPageSize); $scope.rowSelected = function() { $rootScope.$broadcast("@page.reference.selected", { field: $scope.field, ed: $scope.ed }); }; this.filterResults = function(data, page) { return { results: data.data.items, more: (page * $scope.pageSize < data.data.total) }; }; } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snRecordPicker.js */ angular.module('sn.common.controls').directive('snRecordPicker', function($timeout, $http, urlTools, filterExpressionParser, escapeHtml, i18n) { "use strict"; var cache = {}; function cleanLabel(val) { if (val && typeof val == "object") return typeof val.display_value == "string" ? val.display_value.trim() : ""; return typeof val == "string" ? val.trim() : val; } return { restrict: 'E', replace: true, scope: { field: '=', table: '=', defaultQuery: '=?', startswith: '=?', searchFields: '=?', valueField: '=?', displayField: '=?', displayFields: '=?', pageSize: '=?', onChange: '&', snDisabled: '=', multiple: '=?', options: '=?', placeholder: '@' }, template: '<input type="text" ng-disabled="snDisabled" style="min-width: 150px;" name="{{field.name}}" ng-model="field.value"' + ' sn-atf-data-type="reference" sn-atf-data-type-params=\'{"reference" : "{{table}}", "reference_qual" : "{{defaultQuery}}",' + ' "valueField" : "{{valueField}}", "displayField" : "{{displayField}}"}\' sn-atf-class="builtin:ATF.BaseSNRecordPicker" aria-hidden="true" sn-atf-component-value="{{field}}"/>', controller: function($scope) { if (!angular.isNumber($scope.pageSize)) $scope.pageSize = 20; if (!angular.isDefined($scope.valueField)) $scope.valueField = 'sys_id'; this.filterResults = function(data, page) { return { results: data.data.result, more: (page * $scope.pageSize < parseInt(data.headers('x-total-count'), 10)) }; }; }, link: function(scope, element, attrs, ctrl) { var TOKENIZER = '####'; var isExecuting = false; var remove = i18n.getMessage("Remove"); function getRemoveItem(label){ return jQuery("<span class='sr-only' />").text(remove + " " + label); }; var select2Helpers = { formatSelection: function(item) { return escapeHtml(getDisplayValue(item)); }, formatResult: function(item) { var displayFields = getdisplayFields(item); if (displayFields.length == 1) return escapeHtml(cleanLabel(displayFields[0])); if (displayFields.length > 1) { var markup = escapeHtml(cleanLabel(displayFields[0])); var width = 100 / (displayFields.length - 1); markup += "<div>"; for (var i = 1; i < displayFields.length; i++) markup += "<div style='width: " + width + "%;' class='select2-additional-display-field'>" + escapeHtml(cleanLabel(displayFields[i])) + "</div>"; markup += "</div>"; return markup; } return ""; }, search: function(queryParams) { var url = '/api/now/table/' + scope.table + '?' + urlTools.encodeURIParameters(queryParams.data); if (scope.options && scope.options.cache && cache[url]) return queryParams.success(cache[url]); return $http.get(url).then(function(response) { if (scope.options && scope.options.cache) { cache[url] = response; } return queryParams.success(response) }); }, initSelection: function(elem, callback) { if (scope.field.displayValue) { if (scope.multiple){ var items = [], sel; var values = scope.field.value.split(','); var displayValues = scope.field.displayValue.split(TOKENIZER); for(var i=0; i<values.length; i++){ sel = {}; sel[scope.valueField] = values[i]; sel[scope.displayField] = displayValues[i]; items.push(sel); } callback(items); } else { var sel = {}; sel[scope.valueField] = scope.field.value; sel[scope.displayField] = scope.field.displayValue; callback(sel); } } else callback([]); }, formatSelectionCssClass: function(item, el) { var anchorEl = el.parent().find("a"); if (anchorEl.length) { anchorEl.removeAttr("tabindex"); anchorEl.addClass("fa fa-times"); anchorEl.append(getRemoveItem(item[scope.displayField])); } } }; var config = { width : '100%', containerCssClass : 'select2-reference ng-form-element', placeholder : scope.placeholder || ' ', formatSearching: '', allowClear: (scope.options && typeof scope.options.allowClear !== "undefined") ? scope.options.allowClear : true, id: function(item) { return item[scope.valueField]; }, ajax: { quietMillis: NOW.ac_wait_time, data: function(filterText, page) { var fields = [scope.valueField, 'name', 'title']; if (scope.displayField) fields.push(scope.displayField); if (scope.displayFields) fields.push(scope.displayFields); var params = { sysparm_offset: (scope.pageSize * (page - 1)), sysparm_limit: scope.pageSize, sysparm_query: buildQuery(filterText, scope.searchFields, scope.defaultQuery), sysparm_fields: fields.join(','), sysparm_display_value: true }; return params; }, results: function(data, page) { return ctrl.filterResults(data, page, scope.pageSize); }, transport: select2Helpers.search }, formatSelection: select2Helpers.formatSelection, formatResult: select2Helpers.formatResult, formatResultCssClass: function(){ return ''; }, initSelection: select2Helpers.initSelection, multiple: scope.multiple, formatSelectionCssClass: select2Helpers.formatSelectionCssClass }; function buildQuery(filterText, searchFields, defaultQuery) { var queryParts = []; var operator = "CONTAINS"; if (scope.startswith) operator = "STARTSWITH"; if (filterText.startsWith("*")) { filterText = filterText.substring(1); operator = "CONTAINS"; } if (defaultQuery) queryParts.push(defaultQuery); var filterExpression = filterExpressionParser.parse(filterText, operator); if (searchFields != null) { var fields = searchFields.split(','); if (filterExpression.filterText != '') { var OR = ""; for (var i = 0; i < fields.length; i++) { queryParts.push(OR + fields[i] + filterExpression.operator + filterExpression.filterText); OR = "OR"; } } for (var i = 0; i < fields.length; i++) queryParts.push('ORDERBY' + fields[i]); queryParts.push('EQ'); } return queryParts.join('^'); } scope.field = scope.field || {}; if (scope.field.displayValue && scope.multiple) scope.field.displayValue = scope.field.displayValue.replace(/,/g, TOKENIZER); var initTimeout = null; var value = scope.field.value; var oldValue = scope.field.value; var $select; function init() { element.css("opacity", 0); $timeout.cancel(initTimeout); initTimeout = $timeout(function() { i18n.getMessage('Searching...', function(searchingMsg) { config.formatSearching = function() { return searchingMsg; }; }); element.css("opacity", 1); element.select2("destroy"); $select = element.select2(config); $select.bind("change", onChanged); $select.bind("select2-selecting", onSelecting); $select.bind("select2-removing", onRemoving); $select.bind("sn-atf-setvalue", onAtfSetValue); scope.$emit('select2.ready', element); updateAriaExpanded(false); }); } function onAtfSetValue(e) { var valueToSet = e.detail ? e.detail.newValue : null; if (scope.multiple) { var data = element.select2("data"); for (var i = 0; i < data.length; i++) { element.triggerHandler({ type: "select2-removing", choice: data[i] }); } if (!valueToSet) return; var selected = {}; selected[scope.valueField] = valueToSet.value; if (scope.displayField) selected[scope.displayField] = valueToSet.displayValue; element.triggerHandler({ type: "select2-selecting", choice: selected }); return; } var changeEventParameters = { type: "change" }; if (scope.field.value) changeEventParameters.removed = element.select2("data"); if (valueToSet) { var added = {}; added[scope.valueField] = valueToSet.value; if (scope.displayField) added[scope.displayField] = valueToSet.displayValue; changeEventParameters.added = added; element.val(valueToSet.value); scope.field.displayValue = valueToSet.displayValue; } else element.val(""); element.triggerHandler(changeEventParameters); } function onSelecting(e) { isExecuting = true; oldValue = scope.field.value; var selectedItem = e.choice; if (scope.multiple && selectedItem[scope.valueField] != '') { var values = !scope.field.value ? [] : scope.field.value.split(','); var displayValues = !scope.field.displayValue ? [] : scope.field.displayValue.split(TOKENIZER); values.push(selectedItem[scope.valueField]); displayValues.push(getDisplayValue(selectedItem)); scope.field.value = values.join(','); scope.field.displayValue = displayValues.join(TOKENIZER); e.preventDefault(); $select.select2('val', values).select2('close'); scope.$apply(function() { callChange(oldValue, e); }); } } function onRemoving(e) { isExecuting = true; oldValue = scope.field.value; var removed = e.choice; if (scope.multiple){ var values = scope.field.value.split(','); var displayValues = scope.field.displayValue.split(TOKENIZER); for(var i = values.length-1; i>=0; i--){ if (removed[scope.valueField] == values[i]) { values.splice(i, 1); displayValues.splice(i, 1); break; } } scope.field.value = values.join(','); scope.field.displayValue = displayValues.join(TOKENIZER); e.preventDefault(); $select.select2('val', scope.field.value.split(',')); scope.$apply(function() { callChange(oldValue, e); }); } } function callChange(oldValue, e) { var f = scope.field; var p = { field: f, newValue: f.value, oldValue: oldValue, displayValue: f.displayValue } scope.$emit("field.change", p); scope.$emit("field.change." + f.name, p); if (scope.onChange) try { scope.onChange(e); } catch(ex) { console.log("directive.snRecordPicker error in onChange") console.log(ex) } isExecuting = false; } function onChanged(e) { e.stopImmediatePropagation(); if (scope.$$phase || scope.$root.$$phase) { console.warn('in digest, returning early'); return; } if (e.added) { var selectedItem = e.added; if (!scope.multiple){ scope.field.value = selectedItem[scope.valueField]; if (scope.field.value) { scope.field.displayValue = getDisplayValue(selectedItem); } else scope.field.displayValue = ''; } } else if (e.removed) { if (!scope.multiple) { scope.field.displayValue = ''; scope.field.value = ''; } } scope.$apply(function() { callChange(oldValue, e); }); } function getDisplayValue(selectedItem) { var displayValue = selectedItem[scope.valueField]; if (selectedItem) { if (scope.displayField && angular.isDefined(selectedItem[scope.displayField])) displayValue = selectedItem[scope.displayField]; else if (selectedItem.name) displayValue = selectedItem.name; else if (selectedItem.title) displayValue = selectedItem.title; } return cleanLabel(displayValue); } function getdisplayFields(selectedItem) { var displayFields = []; if (selectedItem && selectedItem[scope.valueField]) { var current = ""; if (scope.displayField && angular.isDefined(selectedItem[scope.displayField])) current = selectedItem[scope.displayField]; else if (selectedItem.name) current = selectedItem.name; else if (selectedItem.title) current = selectedItem.title; displayFields.push(current); } if (scope.displayFields) { var columns = scope.displayFields.split(","); for (var i = 0; i < columns.length; i++) { var column = columns[i]; if (selectedItem[column]) displayFields.push(selectedItem[column]); } } return displayFields; } scope.$watch("field.value", function(newValue) { if (isExecuting) return; if (angular.isDefined(newValue) && $select) { if (scope.multiple) $select.select2('val', newValue.split(',')).select2('close'); else $select.select2('val', newValue).select2('close'); } }); function updateAriaExpanded(isOpen) { if (scope.multiple) element.parent().find(".select2-choices input[role='combobox']").attr("aria-expanded", isOpen); else element.parent().find(".select2-focusser").attr("aria-expanded", isOpen); } element.bind("select2-open", function() { updateAriaExpanded(true); }); element.bind("select2-close", function() { updateAriaExpanded(false); }); if (attrs.displayValue) { attrs.$observe('displayValue', function(value){ scope.field.value = value; }); } init(); } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snSelectBasic.js */ angular.module('sn.common.controls').directive('snSelectBasic', function($timeout,i18n) { return { restrict: 'C', priority: 1, require: '?ngModel', scope: { 'snAllowClear': '@', 'snSelectWidth': '@', 'snChoices': '=?' }, link: function (scope, element, attrs, ngModel) { if (angular.isFunction(element.select2)) { var config = { allowClear: scope.selectAllowClear, width: scope.selectWidth }; i18n.getMessage('Searching...', function(searchingMsg) { config.formatSearching = function() { return searchingMsg; }; }); i18n.getMessage('No matches found', function(msg) { config.formatNoMatches = function() { return msg; }; }); i18n.getMessage('Loading more results...', function(msg) { config.formatLoadMore = function() { return msg; }; }); element.css("opacity", 0); scope.selectWidth = scope.snSelectWidth || '100%'; scope.selectAllowClear = scope.snAllowClear === "true"; $timeout(function(){ element.css("opacity", 1); element.select2(config); if (ngModel === null) return; ngModel.$render = function(){ element.select2('val', ngModel.$viewValue); element.val(ngModel.$viewValue); }; element.parent().find(".select2-focusser").attr("aria-expanded", false); }); element.on('change', function() { scope.$evalAsync(setModelValue); }); scope.$watch('snChoices', function(newValue, oldValue){ if (angular.isDefined(newValue) && newValue != oldValue) { $timeout(function(){ setModelValue(); }); } }, true); function setModelValue(){ if (ngModel === null) return; ngModel.$setViewValue(element.val()); }; element.on("select2-open", function() { if (element.data('select2').search.val() === " ") element.select2("search", ""); element.parent().find(".select2-focusser").attr("aria-expanded", true); }); element.on("select2-close", function() { element.parent().find(".select2-focusser").attr("aria-expanded", false); }); } } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snTableReference.js */ angular.module('sn.common.controls').directive('snTableReference', function($timeout) { "use strict"; return { restrict: 'E', replace: true, scope: { field: "=", snChange: "&", snDisabled: "=" }, template: '<select ng-disabled="snDisabled" style="min-width: 150px;" name="{{::field.name}}" ng-model="fieldValue" ng-model-options="{getterSetter: true}" ng-options="choice.value as choice.label for choice in field.choices"></select>', controller: function($scope){ $scope.fieldValue = function(selected){ if (angular.isDefined(selected)) { $scope.snChange({ newValue: selected }); } return $scope.field.value; } }, link: function(scope, element) { var initTimeout = null; var fireReadyEvent = true; var field = scope.field; var isOpen = false; element.css("opacity", 0); function render() { var select2Focusser = element.parent().find('.select2-focusser'); $timeout.cancel(initTimeout); initTimeout = $timeout(function() { element.css("opacity", 1); element.select2("destroy"); element.select2(); if (select2Focusser.length > 0) setAccessibilityRoles(); if (fireReadyEvent) { scope.$emit('select2.ready', element); fireReadyEvent = false; } }); } element.bind("select2-open", function(){ isOpen = true; element.parent().find('.select2-focusser').attr('aria-expanded', isOpen); }); element.bind("select2-close", function(){ isOpen = false; element.parent().find('.select2-focusser').attr('aria-expanded', isOpen); }); scope.$on('select2.ready', function() { setAccessibilityRoles(); }); function setAccessibilityRoles() { var select2Results = element.parent().find('ul.select2-results'); var select2Focusser = element.parent().find('.select2-focusser'); var select2Choice = element.parent().find(".select2-choice"); select2Focusser.removeAttr('aria-labelledby'); select2Focusser.attr('aria-label', getAriaLabel()); select2Focusser.attr('aria-required', field.isMandatory()); select2Focusser.attr('aria-expanded', isOpen); select2Focusser.attr('aria-owns', select2Results.attr('id')); select2Choice.attr("aria-hidden", true); } function getAriaLabel() { var displayValue = ''; var label = ''; label += field.label; displayValue = element.parent().find('.select2-choice .select2-chosen').text(); if (displayValue) { label += (" " + displayValue); } return label; } scope.$watch("field.displayValue", function(newValue, oldValue) { if (newValue !== undefined && newValue != oldValue) { render(); } }); render(); } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snFieldReference.js */ angular.module('sn.common.controls').directive('snFieldReference', function($timeout, $http, nowServer) { "use strict"; return { restrict: 'E', replace: true, scope: { field: "=", snChange: "&", snDisabled: "=", getGlideForm: '&glideForm' }, template: '<select ng-disabled="snDisabled" name="{{field.name}}" style="min-width: 150px;" ng-model="fieldValue" ng-model-options="{getterSetter: true}" ng-options="choice.name as choice.label for choice in field.choices"></select>', controller: function($scope){ $scope.fieldValue = function(selected){ if (angular.isDefined(selected)) $scope.snChange({ newValue: selected }); return $scope.field.value; } $scope.$watch('field.dependentValue', function(newVal, oldVal){ if (!angular.isDefined(newVal)) return; var src = nowServer.getURL('table_fields', 'exclude_formatters=true&fd_table=' + newVal); $http.post(src).success(function(response) { $scope.field.choices = response; $scope.render(); }); }); }, link: function(scope, element) { var initTimeout = null; var fireReadyEvent = true; scope.render = function() { $timeout.cancel(initTimeout); initTimeout = $timeout(function() { element.select2("destroy"); element.select2(); if (fireReadyEvent) { scope.$emit('select2.ready', element); fireReadyEvent = false; } }); }; scope.$watch("field.displayValue", function(newValue, oldValue) { if (newValue !== undefined && newValue != oldValue) { scope.render(); } }); scope.render(); } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snSyncWith.js */ angular.module("sn.common.controls").directive('snSyncWith', function() { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attr) { var journalField = scope.$eval(attr.snSyncWith); var journalValue = scope.$eval(attr.ngModel); if(attr.snSyncWithValueInFn) scope.$eval(attr.ngModel + "=" + attr.snSyncWithValueInFn, {text: scope.value}); scope.$watch(function() { return scope.$eval(attr.snSyncWith); }, function(nv, ov) { if (nv !== journalField) journalField = nv; }); scope.$watch(function() { return scope.$eval(attr.ngModel); }, function(nv, ov) { if (nv !== ov) journalValue = nv; }); if (!window.g_form) return; scope.$watch(function(){ return journalValue; }, function (n, o) { if (n !== o) setFieldValue(); }); function setFieldValue() { setValue(journalField, journalValue); } function setValue(field, value) { value = !!value ? value : ''; var control = g_form.getControl(field); if(attr.snSyncWithValueOutFn) value = scope.$eval(attr.snSyncWithValueOutFn, {text: value}) control.value = value; onChange(control.id); } scope.$watch(function(){ return journalField; }, function(newValue, oldValue) { if (newValue !== oldValue){ if (oldValue) setValue(oldValue, ''); if (newValue) setFieldValue(); } }, true); } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.contenteditable.js */ angular.module('sn.common.controls').directive('contenteditable', function($timeout, $sanitize) { return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { var changehandler = scope.changehandler; scope.usenewline = scope.usenewline + "" != "false"; var newLine = "\n"; var nodeBR = "BR"; var nodeDIV = "DIV"; var nodeText = "#text"; var nbspRegExp = new RegExp(String.fromCharCode(160), "g"); if (!scope.usenewline) elem.keypress(function(event) { if (event.which == "13") { if (scope.entercallback) scope.entercallback(elem); event.preventDefault(); } }); function processNodes(nodes) { var val = ""; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var follow = true; switch (node.nodeName) { case nodeText: val += node.nodeValue.replace(nbspRegExp, " "); break; case nodeDIV: val += newLine; if (node.childNodes.length == 1 && node.childNodes[0].nodeName == nodeBR) follow = false; break; case nodeBR: val += scope.usenewline ? newLine : ""; } if (follow) val += processNodes(node.childNodes) } return val; } function readHtml() { var val = processNodes(elem[0].childNodes); ctrl.$setViewValue(val); } function writeHtml() { var val = ctrl.$viewValue; if (!val || val === null) val = ""; val = val.replace(/\n/gi, scope.usenewline ? "<br/>" : ""); val = val.replace(/ /gi, " "); try { if (attrs.contenteditableEscapeHtml == "true") val = $sanitize(val); } catch (err) { var replacement = {'&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/'}; val = val.replace(/[&<>"'\/]/g, function (pattern) {return replacement[pattern]}); }; elem.html(val); } function processPlaceholder() { if (elem[0].dataset) { if (elem[0].textContent) elem[0].dataset.divPlaceholderContent = 'true'; else if (elem[0].dataset.divPlaceholderContent) delete(elem[0].dataset.divPlaceholderContent); } } elem.bind('keyup', function() { scope.$apply(function() { readHtml(); processPlaceholder(); }); }); function selectText(elem) { var range; var selection; if (document.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(elem); range.select(); } else if (window.getSelection) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(elem); selection.removeAllRanges(); selection.addRange(range); } } elem.bind('focus', function() { if (scope[attrs.tracker] && scope[attrs.tracker]['isDefault_' + attrs.trackeratt]) $timeout(function() { selectText(elem[0]); }); elem.original = ctrl.$viewValue; }); elem.bind('blur', function() { scope.$apply(function() { readHtml(); processPlaceholder(); if (elem.original != ctrl.$viewValue && changehandler) { if (scope[attrs.tracker] && typeof scope[attrs.tracker]['isDefault_' + attrs.trackeratt] != "undefined") scope[attrs.tracker]['isDefault_' + attrs.trackeratt] = false; changehandler(scope[attrs.tracker], attrs.trackeratt); } }); }); elem.bind('paste', function() { scope.$apply(function() { setTimeout(function() { readHtml(); writeHtml(); }, 0); return false; }); }); ctrl.$render = function() { writeHtml(); }; scope.$watch('field.readonly', function(){ elem[0].contentEditable = !scope.$eval('field.readonly'); }); scope.$watch( function () { return { val: elem[0].textContent }; }, function (newValue, oldValue) { if (newValue.val != oldValue.val) processPlaceholder(); }, true); writeHtml(); } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snGlyph.js */ angular.module("sn.common.controls").directive("snGlyph", function() { "use strict"; return { restrict : 'E', replace : true, scope : { char : "@", }, template : '<span class="glyphicon glyphicon-{{char}}" />', link : function(scope) {} } }); angular.module("sn.common.controls").directive('fa', function () { return { restrict: 'E', template: '<span class="fa" aria-hidden="true"></span>', replace: true, link: function (scope, element, attrs) { 'use strict'; var currentClasses = {}; function _observeStringAttr (attr, baseClass) { var className; attrs.$observe(attr, function () { baseClass = baseClass || 'fa-' + attr; element.removeClass(currentClasses[attr]); if (attrs[attr]) { className = [baseClass, attrs[attr]].join('-'); element.addClass(className); currentClasses[attr] = className; } }); } _observeStringAttr('name', 'fa'); _observeStringAttr('rotate'); _observeStringAttr('flip'); _observeStringAttr('stack'); attrs.$observe('size', function () { var className; element.removeClass(currentClasses.size); if (attrs.size === 'large') { className = 'fa-lg'; } else if (!isNaN(parseInt(attrs.size, 10))) { className = 'fa-' + attrs.size + 'x'; } element.addClass(className); currentClasses.size = className; }); attrs.$observe('stack', function () { var className; element.removeClass(currentClasses.stack); if (attrs.stack === 'large') { className = 'fa-stack-lg'; } else if (!isNaN(parseInt(attrs.stack, 10))) { className = 'fa-stack-' + attrs.stack + 'x'; } element.addClass(className); currentClasses.stack = className; }); function _observeBooleanAttr (attr, className) { var value; attrs.$observe(attr, function () { className = className || 'fa-' + attr; value = attr in attrs && attrs[attr] !== 'false' && attrs[attr] !== false; element.toggleClass(className, value); }); } _observeBooleanAttr('border'); _observeBooleanAttr('fw'); _observeBooleanAttr('inverse'); _observeBooleanAttr('spin'); element.toggleClass('fa-li', element.parent() && element.parent().prop('tagName') === 'LI' && element.parent().parent() && element.parent().parent().hasClass('fa-ul') && element.parent().children()[0] === element[0] && attrs.list !== 'false' && attrs.list !== false ); attrs.$observe('alt', function () { var altText = attrs.alt, altElem = element.next(), altElemClass = 'fa-alt-text'; if (altText) { element.removeAttr('alt'); if (!altElem || !altElem.hasClass(altElemClass)) { element.after('<span class="sr-only fa-alt-text"></span>'); altElem = element.next(); } altElem.text(altText); } else if (altElem && altElem.hasClass(altElemClass)) { altElem.remove(); } }); } }; }) .directive('faStack', function () { return { restrict: 'E', transclude: true, template: '<span ng-transclude class="fa-stack fa-lg"></span>', replace: true, link: function (scope, element, attrs) { var currentClasses = {}; function _observeStringAttr (attr, baseClass) { var className; attrs.$observe(attr, function () { baseClass = baseClass || 'fa-' + attr; element.removeClass(currentClasses[attr]); if (attrs[attr]) { className = [baseClass, attrs[attr]].join('-'); element.addClass(className); currentClasses[attr] = className; } }); } _observeStringAttr('size'); attrs.$observe('size', function () { var className; element.removeClass(currentClasses.size); if (attrs.size === 'large') { className = 'fa-lg'; } else if (!isNaN(parseInt(attrs.size, 10))) { className = 'fa-' + attrs.size + 'x'; } element.addClass(className); currentClasses.size = className; }); } }; }); ; /*! RESOURCE: /scripts/sn/common/controls/directive.snImageUploader.js */ angular.module('sn.common.controls').directive('snImageUploader', function($window, $rootScope, $timeout, getTemplateUrl, i18n, snAttachmentHandler) { var DRAG_IMAGE_SELECT = i18n.getMessage('Drag image or click to select'); return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('directive.snImageUploader'), transclude: true, scope: { readOnly: '@', tableName: '@', sysId: '@', fieldName: '@', onUpload: '&', onDelete: '&', uploadMessage: '@', src: '=' }, controller: function($scope) { $scope.uploading = false; $scope.getTitle = function() { if($scope.readOnly !== 'true') return DRAG_IMAGE_SELECT; return ''; } }, link: function(scope, element) { function isValidImage(file) { if (file.type.indexOf('image') != 0) { $alert(i18n.getMessage('Please select an image')); return false; } if (file.type.indexOf('tiff') > 0) { $alert(i18n.getMessage('Please select a common image format such as gif, jpeg or png')); return false; } return true; } function $alert(message) { alert(message); } scope.onFileSelect = function($files) { if (scope.readOnly === 'true') return; if ($files.length == 0) return; var file = $files[0]; if(!isValidImage(file)) return; var uploadParams = { sysparm_fieldname: scope.fieldName }; scope.uploading = true; snAttachmentHandler.create(scope.tableName, scope.sysId).uploadAttachment(file, uploadParams).then(function(response) { $timeout(function() { scope.uploading = false; }); if (scope.onUpload) scope.onUpload(response); $rootScope.$broadcast("snImageUploader:complete", scope.sysId, response); }); } scope.openFileSelector = function($event) { $event.stopPropagation(); var input = element.find('input[type=file]'); input.click(); } scope.activateUpload = function($event) { if (scope.readOnly !== 'true') scope.openFileSelector($event); else scope.showUpload = !scope.showUpload; } scope.deleteAttachment = function () { var sys_id = scope.src.split(".")[0]; snAttachmentHandler.deleteAttachment(sys_id).then(function () { scope.src = null; if (scope.onDelete) scope.onDelete(); $rootScope.$broadcast("snImageUploader:delete", scope.sysId, sys_id); }); } } } }); ; ; /*! RESOURCE: /scripts/sn/common/i18n/js_includes_i18n.js */ /*! RESOURCE: /scripts/sn/common/i18n/_module.js */ angular.module('sn.common.i18n', ['sn.common.glide']); angular.module('sn.i18n', ['sn.common.i18n']); ; /*! RESOURCE: /scripts/sn/common/i18n/directive.snBindI18n.js */ angular.module('sn.common.i18n').directive('snBindI18n', function(i18n, $sanitize) { return { restrict: 'A', link : function(scope, iElem, iAttrs) { i18n.getMessage(iAttrs.snBindI18n, function(translatedValue) { var sanitizedValue = $sanitize(translatedValue); iElem.append(sanitizedValue); }); } } }); ; /*! RESOURCE: /scripts/sn/common/i18n/directive.message.js */ angular.module('sn.common.i18n').directive('nowMessage', function(i18n) { return { restrict: 'E', priority: 0, template: '', replace: true, compile: function(element, attrs, transclude) { var value = element.attr('value'); if (!attrs.key || !value) return; i18n.loadMessage(attrs.key, value); } }; }); ; /*! RESOURCE: /scripts/sn/common/i18n/service.i18n.js */ angular.module('sn.common.i18n').provider('i18n', function() { var messageMap = {}; function loadMessage(msgKey, msgValue) { messageMap[msgKey] = msgValue; } this.preloadMessages = function(messages) { angular.forEach(messages, function(key, val) { loadMessage(key, val); }); }; function interpolate(param) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = param[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; } ); } if (!String.prototype.withValues) String.prototype.withValues = interpolate; this.$get = function(nowServer, $http, $window, $log) { var isDebug = $window.NOW ? $window.NOW.i18n_debug : true; function debug(msg) { if (!isDebug) return; $log.log('i18n: ' + msg); } function getMessageFromServer( msgKey, callback) { getMessagesFromServer([msgKey], function() { if (callback) callback(messageMap[msgKey]); }); } function getMessagesFromServer( msgArray, callback, msgArrayFull) { var url = nowServer.getURL('message'); $http.post(url, { messages: msgArray }).success(function(response) { var messages = response.messages; for (var i in messages) { loadMessage(i, messages[i]); } var returnMessages = {}, allMessages = msgArrayFull || msgArray; for (var j = 0; j < allMessages.length; j++) { var key = allMessages[j]; returnMessages[key] = messageMap[key]; } if (callback) callback(returnMessages); }); } return { getMessage: function( msgKey, callback) { debug('getMessage: Checking for ' + msgKey); if (messageMap.hasOwnProperty(msgKey)) { var message = messageMap[msgKey]; if (typeof(callback) == 'function') callback(message); debug('getMessage: Found: ' + msgKey + ', message: ' + message); return message; } debug('getMessage: Not found: ' + msgKey + ', querying server'); getMessageFromServer(msgKey, callback); msgKey.withValues = interpolate; if (typeof(callback) != 'function') $log.warn('getMessage (key="' + msgKey + '"): synchronous use not supported in Mobile or Service Portal unless message is already cached'); return msgKey; }, format: function(message) { if(arguments.length == 1) return message; if(arguments.length == 2 && (typeof arguments[1] === 'object')) return interpolate.call(message, arguments[1]); return interpolate.call(message, [].slice.call(arguments, 1)); }, getMessages: function( msgArray, callback) { debug('getMessages: Checking for ' + msgArray.join(',')); var results = {}, needMessage = [], needServerRequest = false; for (var i = 0; i < msgArray.length; i++) { var key = msgArray[i]; if (!messageMap.hasOwnProperty(key)) { debug('getMessages: Did not find ' + key); needMessage.push(key); needServerRequest = true; results[key] = key; continue; } results[key] = messageMap[key]; debug('getMessages: Found ' + key + ', message: ' + results[key]); } if (needServerRequest) { debug('getMessages: Querying server for ' + needMessage.join(',')); getMessagesFromServer(needMessage, callback, msgArray); } else if (typeof(callback) == 'function') { debug('getMessages: Found all messages'); callback(results); } return results; }, clearMessages: function() { debug('clearMessages: clearing messages'); messageMap = {}; }, loadMessage: function(msgKey, msgValue) { loadMessage(msgKey, msgValue); debug('loadMessage: loaded key: ' + msgKey + ', value: ' + msgValue); }, preloadMessages: function() { var that = this angular.element('now-message').each(function() { var elem = angular.element(this); that.loadMessage(elem.attr('key'), elem.attr('value')); }) } }; }; }); ; ; /*! RESOURCE: /scripts/sn/common/link/js_includes_link.js */ /*! RESOURCE: /scripts/sn/common/link/_module.js */ angular.module("sn.common.link", []); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContent.js */ angular.module('sn.common.link').directive('snLinkContent', function($compile, linkContentTypes) { 'use strict'; return { restrict: 'E', replace: true, template: "<span />", scope: { link: "=" }, link: function(scope, elem) { scope.isShowing = function() { return (scope.link.isActive || scope.link.isUnauthorized) && !scope.link.isPending; }; var linkDirective = linkContentTypes.forType(scope.link); elem.attr(linkDirective, ""); elem.attr('ng-if', 'isShowing()'); $compile(elem)(scope); } } }); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContentYoutube.js */ angular.module('sn.common.link').directive('snLinkContentYoutube', function(getTemplateUrl, $sce, inFrameSet) { 'use strict'; return { restrict: 'A', replace: true, templateUrl: getTemplateUrl('snLinkContentYoutube.xml'), scope: { link: "=" }, controller: function($scope) { $scope.playerActive = false; $scope.width = (inFrameSet) ? '248px' : '500px'; $scope.height = (inFrameSet) ? '139px' : '281px'; $scope.showPlayer = function() { $scope.playerActive = true; }; $scope.getVideoEmbedLink = function() { if ($scope.link.embedLink) { var videoLink = $scope.link.embedLink + "?autoplay=1"; return $sce.trustAsHtml("<iframe width='" + $scope.width + "' height='" + $scope.height + "' autoplay='1' frameborder='0' allowfullscreen='' src='" + videoLink + "'></iframe>"); } }; } } }); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContentSoundcloud.js */ angular.module('sn.common.link').directive('snLinkContentSoundcloud', function(getTemplateUrl, $sce, inFrameSet) { 'use strict'; return { restrict: 'A', replace: true, templateUrl: getTemplateUrl('snLinkContentSoundcloud.xml'), scope: { link: "=" }, controller: function($scope) { $scope.playerActive = false; $scope.width = (inFrameSet) ? '248px' : '500px'; $scope.height = (inFrameSet) ? '139px' : '281px'; $scope.showPlayer = function() { $scope.playerActive = true; }; $scope.getVideoEmbedLink = function() { if ($scope.link.embedLink) { var videoLink = $scope.link.embedLink + "&auto_play=true"; var width = (inFrameSet) ? 248 : 500; return $sce.trustAsHtml("<iframe width='" + $scope.width + "' height='" + $scope.height + "' autoplay='1' frameborder='0' allowfullscreen='' src='" + videoLink + "'></iframe>"); } }; } } }); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContentArticle.js */ angular.module('sn.common.link').directive('snLinkContentArticle', function(getTemplateUrl) { 'use strict'; return { restrict: 'A', replace: true, templateUrl: getTemplateUrl('snLinkContentArticle.xml'), scope: { link: "=" }, controller: function($scope) { $scope.backgroundImageStyle = $scope.link.imageLink ? {"background-image": 'url(' + $scope.link.imageLink + ')'} : {}; $scope.isVisible = function() { var link = $scope.link; return !!link.shortDescription || !!link.imageLink; }; $scope.hasDescription = function() { var link = $scope.link; return link.shortDescription && (link.shortDescription !== link.title); }; } } }); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContentError.js */ angular.module('sn.common.link').directive('snLinkContentError', function(getTemplateUrl) { 'use strict'; return { restrict: 'A', replace: true, templateUrl: getTemplateUrl('snLinkContentError.xml'), scope: { link: "=" }, controller: function($scope) { } } }); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContentImage.js */ angular.module('sn.common.link').directive('snLinkContentImage', function(getTemplateUrl) { 'use strict'; return { restrict: 'A', replace: true, templateUrl: getTemplateUrl('snLinkContentImage.xml'), scope: { link: "=" }, controller: function($scope) { } } }); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContentAttachment.js */ angular.module('sn.common.link').directive('snLinkContentAttachment', function(getTemplateUrl) { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: getTemplateUrl('snLinkContentAttachment.xml'), scope: { attachment: '=', link: '=' }, controller: function($scope, $element, snCustomEvent) { $scope.attachmentFile = $scope.attachment || $scope.link.attachment; $scope.calcImageSize = function() { var imageWidth = $scope.width; var imageHeight = $scope.height; var MAX_IMAGE_SIZE = $element.width() < 298 ? $element.width() : 298; if (imageHeight < 0 || imageWidth < 0) return ""; if (imageHeight > imageWidth) { if (imageHeight >= MAX_IMAGE_SIZE) { imageWidth *= MAX_IMAGE_SIZE / imageHeight; imageHeight = MAX_IMAGE_SIZE; } } else { if (imageWidth >= MAX_IMAGE_SIZE) { imageHeight *= MAX_IMAGE_SIZE / imageWidth; imageWidth = MAX_IMAGE_SIZE } } return "height: " + imageHeight + "px; width: " + imageWidth + "px;"; }; $scope.aspectRatioClass = function() { return ($scope.height > $scope.width) ? 'limit-height' : 'limit-width'; }; $scope.showImage = function(event) { if (event.keyCode === 9) return; snCustomEvent.fire('sn.attachment.preview', event, $scope.attachmentFile.rawData); }; } } }); ; /*! RESOURCE: /scripts/sn/common/link/directive.snLinkContentRecord.js */ angular.module('sn.common.link').directive('snLinkContentRecord', function(getTemplateUrl) { 'use strict'; return { restrict: 'A', replace: true, templateUrl: getTemplateUrl('snLinkContentRecord.xml'), scope: { link: '=' }, controller: function($scope) { $scope.isTitleVisible = function() { return !$scope.isDescriptionVisible() && $scope.link.title; }; $scope.isDescriptionVisible = function() { return $scope.link.shortDescription; }; $scope.hasNoHeader = function() { return !$scope.isTitleVisible() && !$scope.isDescriptionVisible(); }; $scope.isUnassigned = function() { return $scope.link.isTask && !$scope.link.avatarID; }; } } }); ; /*! RESOURCE: /scripts/sn/common/link/provider.linkContentTypes.js */ angular.module('sn.common.link').provider('linkContentTypes', function linkContentTypesProvider() { "use strict"; var linkDirectiveMap = { 'record' : "sn-link-content-record", 'attachment' : "sn-link-content-attachment", 'video' : "sn-link-content-youtube", 'music.song': "sn-link-content-soundcloud", 'link' : 'sn-link-content-article', 'article': 'sn-link-content-article', 'website': 'sn-link-content-article', 'image': 'sn-link-content-image' }; this.$get = function linkContentTypesFactory() { return { forType: function(link) { if (link.isUnauthorized) return "sn-link-content-error"; return linkDirectiveMap[link.type] || "no-card"; } } }; }); ; ; /*! RESOURCE: /scripts/sn/common/mention/js_includes_mention.js */ /*! RESOURCE: /scripts/sn/common/mention/_module.js */ angular.module("sn.common.mention", []); ; /*! RESOURCE: /scripts/sn/common/mention/directive.snMentionPopover.js */ angular.module('sn.common.mention').directive("snMentionPopover", function(getTemplateUrl, $timeout) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snMentionPopover.xml'), link: function(scope, elem, $attrs) { elem.detach().appendTo(document.body); scope.dontPositionManually = scope.$eval($attrs.dontpositionmanually) || false; scope.onClick = function(event) { if (!angular.element(event.target).closest("#mention-popover").length || angular.element(event.target).closest("#direct-message-popover-trigger").length) { scope.$evalAsync(function() { scope.$parent.showPopover = false; scope.$emit("snMentionPopover.showPopoverIsFalse"); if (scope.dontPositionManually && !(scope.$eval($attrs.snavatarpopover))) { elem.remove(); } else { scope.$broadcast("sn-avatar-popover-destroy"); } angular.element('.popover').each(function () { var object = angular.element(this); if (object.popover) { object.popover('hide'); } }) }); } }; scope.clickListener = $timeout(function() { angular.element('html').on('click.mentionPopover', scope.onClick); }, 0, false); scope.$on('sn-bootstrap-popover.close-other-popovers', scope.onClick); function setPopoverPosition(clickX, clickY) { var topPosition; var leftPosition; var windowHeight = window.innerHeight; var windowWidth = window.innerWidth; if (((clickY - (elem.height() / 2))) < 10) topPosition = 10; else topPosition = ((clickY + (elem.height() / 2)) > windowHeight) ? windowHeight - elem.height() - 15 : clickY - (elem.height() / 2); leftPosition = ((clickX + 20 + (elem.width())) > windowWidth) ? windowWidth - elem.width() - 15: clickX + 20; elem.css("top", topPosition + "px").css("left", leftPosition + "px"); } if (!scope.dontPositionManually) { $timeout(function () { var clickX = (scope.$parent && scope.$parent.clickEvent && scope.$parent.clickEvent.pageX) ? scope.$parent.clickEvent.pageX : clickX || 300; var clickY = (scope.$parent && scope.$parent.clickEvent && scope.$parent.clickEvent.pageY) ? scope.$parent.clickEvent.pageY : clickY || 300; setPopoverPosition(clickX, clickY); elem.velocity({ opacity: 1 }, { duration: 100, easing: "cubic" }); }); } }, controller: function($scope, $element, $attrs) { $scope.profile = $scope.$eval($attrs.profile); $scope.$on("$destroy", function() { angular.element('html').off('click.mentionPopover', $scope.onClick); $element.remove(); }); } } }); ; /*! RESOURCE: /scripts/sn/common/mention/service.snMention.js */ angular.module("sn.common.mention").factory("snMention", function(liveProfileID, $q, $http) { "use strict"; var MENTION_PATH = "/api/now/form/mention/record"; var USER_PATH = '/api/now/ui/user/'; var avatarCache = {}; function retrieveMembers(table, document, term) { if(!term || !document || !table) { var deferred = $q.defer(); deferred.resolve([]); return deferred.promise; } return $http( { url: MENTION_PATH + "/" + table + "/" + document, method: "GET", params: { term: term } }).then(function(response) { var members = response.data.result; var promises = []; angular.forEach(members, function(user) { if (avatarCache[user.sys_id]) { user.initials = avatarCache[user.sys_id].initials; user.avatar = avatarCache[user.sys_id].avatar; } else { var promise = $http.get(USER_PATH + user.sys_id).success(function(response) { user.initials = response.result.user_initials; user.avatar = response.result.user_avatar; avatarCache[user.sys_id] = {initials: user.initials, avatar: user.avatar}; }); promises.push(promise); } }); return $q.all(promises).then(function() { return members; }); }) } return { retrieveMembers: retrieveMembers } }); ; ; /*! RESOURCE: /scripts/sn/common/messaging/js_includes_messaging.js */ /*! RESOURCE: /scripts/doctype/CustomEventManager.js */ var NOW = NOW || {}; var CustomEventManager = (function (existingCustomEvent) { "use strict"; var events = (existingCustomEvent && existingCustomEvent.events) || {}; var isFiringFlag = false; var trace = false; var suppressEvents = false; var NOW_MSG = 'NOW.PostMessage'; function observe(eventName, fn){ if (trace) jslog("$CustomEventManager observing: " + eventName); on(eventName, fn); } function on(name, func) { if (!func || typeof func !== 'function') return; if (typeof name === 'undefined') return; if (!events[name]) events[name] = []; events[name].push(func); } function un(name, func) { if (!events[name]) return; var idx = -1; for (var i = 0; i < events[name].length; i++) { if (events[name][i] === func) { idx = i; break; } } if (idx >= 0) events[name].splice(idx, 1) } function unAll(name) { if (events[name]) delete events[name]; } function fire(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); return fireEvent.apply(null, arguments); } function fireUp(eventName, args){ var win = window; while (win){ try { if (win.CustomEvent.fireEvent.apply(null, arguments) === false) return; win = win.parent === win ? null : win.parent; }catch(e){ return; } } } function fireEvent() { if (suppressEvents) return true; var args = Array.prototype.slice.apply(arguments); var name = args.shift(); var eventList = events[name]; if (!eventList) return true; var event = eventList.slice(); isFiringFlag = true; for (var i = 0, l = event.length; i < l; i++) { var ev = event[i]; if (!ev) continue; if (ev.apply(null, args) === false) { isFiringFlag = false; return false; } } isFiringFlag = false; return true; } function isFiring() { return isFiringFlag; } function forward(name, element, func) { on(name, func); element.addEventListener(name, function(e) { fireEvent(e.type, this, e); }.bind(api)); } function isOriginInWhiteList(origin, whitelistStr) { if (!whitelistStr) { return false; } var delimiterRegex = /[\n, ]/; var whitelist = whitelistStr.split(delimiterRegex) .filter(function(whiteListedOrigin) { return whiteListedOrigin; }) .map(function(whiteListedOrigin) { return whiteListedOrigin.toLowerCase(); }); if (~whitelist.indexOf(origin.toLowerCase())) { return true; } return false; } function shouldProcessMessage(sourceOrigin) { if (!window.g_concourse_onmessage_enforce_same_origin || sourceOrigin === window.location.origin) { return true; } return isOriginInWhiteList(sourceOrigin, window.g_concourse_onmessage_enforce_same_origin_whitelist); } function registerPostMessageEvent() { if (NOW.registeredPostMessageEvent) { return; } if (!window.postMessage) { return; } window.addEventListener('message', function (event) { if (!shouldProcessMessage(event.origin)) { console.warn('Incoming message ignored due to origin mismatch.'); return; } var nowMessageJSON = event.data; var nowMessage; try { nowMessage = JSON.parse(nowMessageJSON.toString()); } catch (e) { return; } if (!nowMessage.type == NOW_MSG) { return; } fire(nowMessage.eventName, nowMessage.args); }, false); NOW.registeredPostMessageEvent = true; } function doPostMessage(win, event, msg, targetOrigin) { var nowMessage = {type: NOW_MSG, eventName: event, args: msg}; var nowMessageJSON; if (!win || !win.postMessage) { return } nowMessageJSON = JSON.stringify(nowMessage); win.postMessage(nowMessageJSON, targetOrigin); } function fireTop(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); fireEvent.apply(null, arguments); var t = getTopWindow(); if (t !== null && window !== t) t.CustomEvent.fire(eventName, args); } function fireAll(eventName, args) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); var topWindow = getTopWindow(); if (topWindow !== window.self) CustomEvent.fireEvent(eventName, args); notifyAllFrom(topWindow); function notifyAllFrom(rootFrame) { var childFrame; rootFrame.CustomEvent.fireEvent(eventName, args); for (var i = 0; i < rootFrame.frames.length; i++) { try { childFrame = rootFrame.frames[i]; if (!childFrame) continue; if (childFrame.CustomEvent && typeof childFrame.CustomEvent.fireEvent === "function") { notifyAllFrom(childFrame); } } catch(e) { } } } } function fireToWindow(targetWindow, eventName, args, usePostMessage, targetOrigin) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + args.length); if (usePostMessage) { doPostMessage(targetWindow, eventName, args, targetOrigin); } else { targetWindow.CustomEvent.fireEvent(eventName, args); } } function getTopWindow() { var topWindow = window.self; try { while (topWindow.CustomEvent.fireEvent && topWindow !== topWindow.parent && topWindow.parent.CustomEvent.fireEvent) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } function isTopWindow() { return getTopWindow() == window.self; } function jslog(msg, src, dateTime) { try { if (!src) { var path = window.self.location.pathname; src = path.substring(path.lastIndexOf('/') + 1); } if (window.self.opener && window != window.self.opener) { if (window.self.opener.jslog) { window.self.opener.jslog(msg, src, dateTime); } } else if (parent && parent.jslog && jslog != parent.jslog) { parent.jslog(msg, src, dateTime); } else { if (window.console && window.console.log) console.log(msg); } } catch (e) { } } var api = { set trace(value) { trace = !!value; }, get trace() { return trace; }, set suppressEvents(value) { suppressEvents = !!value; }, get suppressEvents() { return suppressEvents; }, get events() { return events; }, set events(value) { events = value; }, on: on, un: un, unAll: unAll, forward: forward, isFiring: isFiring, fireEvent: fireEvent, observe: observe, fire: fire, fireTop: fireTop, fireAll: fireAll, fireToWindow: fireToWindow, isTopWindow: isTopWindow, fireUp: fireUp, toString: function() { return 'CustomEventManager'; } }; registerPostMessageEvent(); return api; })(NOW.CustomEvent); NOW.CustomEvent = CustomEventManager; if (typeof CustomEvent !== "undefined") { CustomEvent.observe = NOW.CustomEvent.observe.bind(NOW.CustomEvent); CustomEvent.fire = NOW.CustomEvent.fire.bind(NOW.CustomEvent); CustomEvent.fireUp = NOW.CustomEvent.fireUp.bind(NOW.CustomEvent); CustomEvent.fireTop = NOW.CustomEvent.fireTop.bind(NOW.CustomEvent); CustomEvent.fireAll = NOW.CustomEvent.fireAll.bind(NOW.CustomEvent); CustomEvent.fireToWindow = NOW.CustomEvent.fireToWindow.bind(NOW.CustomEvent); CustomEvent.on = NOW.CustomEvent.on.bind(NOW.CustomEvent); CustomEvent.un = NOW.CustomEvent.un.bind(NOW.CustomEvent); CustomEvent.unAll = NOW.CustomEvent.unAll.bind(NOW.CustomEvent); CustomEvent.forward = NOW.CustomEvent.forward.bind(NOW.CustomEvent); CustomEvent.isFiring = NOW.CustomEvent.isFiring.bind(NOW.CustomEvent); CustomEvent.fireEvent = NOW.CustomEvent.fireEvent.bind(NOW.CustomEvent); CustomEvent.events = NOW.CustomEvent.events; CustomEvent.isTopWindow = NOW.CustomEvent.isTopWindow.bind(NOW.CustomEvent); } else { window.CustomEvent = NOW.CustomEvent; } ; /*! RESOURCE: /scripts/sn/common/messaging/_module.js */ angular.module('sn.common.messaging', []); angular.module('sn.messaging', ['sn.common.messaging']); ; /*! RESOURCE: /scripts/sn/common/messaging/service.snCustomEvent.js */ angular.module('sn.common.messaging').factory('snCustomEvent', function() { "use strict"; if (typeof NOW.CustomEvent === 'undefined') throw "CustomEvent not found in NOW global"; return NOW.CustomEvent; }); ; ; /*! RESOURCE: /scripts/sn/common/notification/js_includes_notification.js */ /*! RESOURCE: /scripts/sn/common/notification/_module.js */ angular.module('sn.common.notification', ['sn.common.util', 'ngSanitize', 'sn.common.i18n']); ; /*! RESOURCE: /scripts/sn/common/notification/factory.notificationWrapper.js */ angular.module("sn.common.notification").factory("snNotificationWrapper", function($window, $timeout) { "use strict"; function assignHandler(notification, handlerName, options){ if (typeof options[handlerName] === "function") notification[handlerName.toLowerCase()] = options[handlerName]; } return function NotificationWrapper(title, options) { var defaults = { dir: 'auto', lang: 'en_US', decay: true, lifespan: 4000, body: "", tag: "", icon: '/native_notification_icon.png' }; var optionsOnClick = options.onClick; options.onClick = function() { if(angular.isFunction($window.focus)) $window.focus(); if(typeof optionsOnClick === "function") optionsOnClick(); } var result = {}; options = angular.extend(defaults, options); var previousOnClose = options.onClose; options.onClose = function() { if(angular.isFunction(result.onclose)) result.onclose(); if(angular.isFunction(previousOnClose)) previousOnClose(); } var notification = new $window.Notification(title, options); assignHandler(notification, "onShow", options); assignHandler(notification, "onClick", options); assignHandler(notification, "onError", options); assignHandler(notification, "onClose", options); if (options.decay && options.lifespan > 0) $timeout(function() { notification.close(); }, options.lifespan) result.close = function() { notification.close(); } return result; } }) ; /*! RESOURCE: /scripts/sn/common/notification/service.snNotifier.js */ angular.module("sn.common.notification").factory("snNotifier", function ($window, snNotificationWrapper) { "use strict"; return function(settings) { function requestNotificationPermission() { if($window.Notification && $window.Notification.permission === "default") $window.Notification.requestPermission(); } function canUseNativeNotifications() { return ($window.Notification && $window.Notification.permission === "granted"); } var currentNotifications = []; settings = angular.extend({ notifyMethods: ["native", "glide"] }, settings); var methods = { 'native': nativeNotify, 'glide': glideNotify }; function nativeNotify(title, options) { if(canUseNativeNotifications()) { var newNotification = snNotificationWrapper(title, options); newNotification.onclose = function () { stopTrackingNotification(newNotification) }; currentNotifications.push(newNotification); return true; } return false; } function glideNotify(title, options) { return false; } function stopTrackingNotification(newNotification) { var index = currentNotifications.indexOf(newNotification); if(index > -1) currentNotifications.splice(index, 1); } function notify(title, options) { if(typeof options === "string") options = {body: options}; options = options || {}; for(var i = 0, len = settings.notifyMethods.length; i < len; i++) if(typeof settings.notifyMethods[i] == "string") { if(methods[settings.notifyMethods[i]](title, options)) break; } else { if(settings.notifyMethods[i](title, options)) break; } } function clearAllNotifications() { while(currentNotifications.length > 0) currentNotifications.pop().close(); } return { notify: notify, canUseNativeNotifications: canUseNativeNotifications, clearAllNotifications: clearAllNotifications, requestNotificationPermission: requestNotificationPermission } } }); ; /*! RESOURCE: /scripts/sn/common/notification/directive.snNotification.js */ angular.module('sn.common.notification').directive('snNotification', function($timeout, $rootScope) { "use strict"; return { restrict: 'E', replace: true, template: '<div class="notification-container"></div>', link: function(scope, element) { scope.addNotification = function(payload) { if (!payload) payload = {}; if (!payload.text) payload.text = ''; if (!payload.classes) payload.classes = ''; if (!payload.duration) payload.duration = 5000; angular.element('<div/>').qtip({ content: { text: payload.text, title: { button: false } }, position: { target: [0, 0], container: angular.element('.notification-container') }, show: { event: false, ready: true, effect: function () { angular.element(this).stop(0, 1).animate({ height: 'toggle' }, 400, 'swing'); }, delay: 0, persistent: false }, hide: { event: false, effect: function (api) { angular.element(this).stop(0, 1).animate({ height: 'toggle' }, 400, 'swing'); } }, style: { classes: 'jgrowl' + ' ' + payload.classes, tip: false }, events: { render: function (event, api) { if (!api.options.show.persistent) { angular.element(this).bind('mouseover mouseout', function(e) { clearTimeout(api.timer); if (e.type !== 'mouseover') { api.timer = setTimeout(function() { api.hide(e); }, payload.duration); } }) .triggerHandler('mouseout'); } } } }); }, scope.$on('notification.notify', function(event, payload) { scope.addNotification(payload); }); } }; }); ; /*! RESOURCE: /scripts/sn/common/notification/service.snNotification.js */ angular.module('sn.common.notification').factory('snNotification', function($document, $templateCache, $compile, $rootScope, $timeout, $q, getTemplateUrl, $http, i18n) { 'use strict'; var openNotifications = [], timeouts = {}, options = { top: 20, gap: 10, duration: 5000 }, a11yContainer, a11yDuration = 5000; return { show: function(type, message, duration, onClick, container) { return createNotificationElement(type, message).then(function(element) { return displayAndDestroyNotification(element, container, duration); }); }, showScreenReaderOnly: function(type, message, duration, onClick, container) { return createNotificationElement(type, message, true).then(function(element) { return displayAndDestroyNotification(element, container, duration); }); }, hide: hide, setOptions: function(opts) { if (angular.isObject(opts)) angular.extend(options, opts); } }; function displayAndDestroyNotification(element, container, duration) { displayNotification(element, container); checkAndSetDestroyDuration(element, duration); return element; } function getTemplate() { var templateName = 'sn_notification.xml', template = $templateCache.get(templateName), deferred = $q.defer(); if (!template) { var url = getTemplateUrl(templateName); $http.get(url).then(function(result) { $templateCache.put(templateName, result.data); deferred.resolve(result.data); }, function(reason) { return $q.reject(reason); }); } else deferred.resolve(template); return deferred.promise; } function createNotificationElement(type, message, screenReaderOnly) { var thisScope, thisElement; var icon = 'icon-info'; screenReaderOnly = typeof(screenReaderOnly) === 'undefined' ? false : screenReaderOnly; if (type == 'error') { icon = 'icon-cross-circle'; } else if (type == 'warning') { icon = 'icon-alert'; } else if (type == 'success') { icon = 'icon-check-circle'; } return getTemplate().then(function(template) { thisScope = $rootScope.$new(); thisScope.type = type; thisScope.message = message; thisScope.icon = icon; thisScope.screenReaderOnly = screenReaderOnly; thisElement = $compile(template)(thisScope); return angular.element(thisElement[0]); }); } function displayNotification(element, container) { if( !a11yContainer ) { a11yContainer = angular.element('<div class="notification-a11y-container sr-only" aria-live="assertive">'); $document.find('body').append(a11yContainer); } var container = $document.find(container || 'body'), id = 'elm' + Date.now(), pos; container.append(element); pos = options.top + openNotifications.length * getElementHeight(element); positionElement(element, pos); element.addClass('visible'); element.attr('id', id); element.find('button').bind('click', function(e) { hideElement(element); }); openNotifications.push(element); if (options.duration > 0) timeouts[id] = $timeout(function () { hideNext(); }, options.duration); $timeout(function() { var srElement = angular.element('<div>').text(element.text()); a11yContainer.append(srElement); $timeout(function() { srElement.remove(); }, a11yDuration, false); }, 0, false) } function hide(element) { $timeout.cancel(timeouts[element.attr('id')]); element.removeClass('visible'); element.addClass('hidden'); element.find('button').eq(0).unbind(); element.scope().$destroy(); element.remove(); repositionAll(); } function hideElement(element) { var index = openNotifications.indexOf(element); openNotifications.splice(index, 1); hide(element); } function hideNext() { var element = openNotifications.shift(); if (element) hide(element); } function getElementHeight(element) { return element[0].offsetHeight + options.gap; } function positionElement(element, pos) { element[0].style.top = pos + 'px'; } function repositionAll() { var pos = options.top; openNotifications.forEach(function(element) { positionElement(element, pos); pos += getElementHeight(element); }); } function checkAndSetDestroyDuration(element, duration){ if (duration){ timeouts[element.attr('id')] = $timeout(function(){ hideElement(element); }, duration); } } }); ; ; /*! RESOURCE: /scripts/sn/common/presence/js_includes_presence.js */ /*! RESOURCE: /scripts/js_includes_ng_amb.js */ /*! RESOURCE: /scripts/js_includes_amb.js */ amb.getClient(); ; /*! RESOURCE: /scripts/app.ng.amb/app.ng.amb.js */ angular.module("ng.amb", ['sn.common.presence', 'sn.common.util']) .value("ambLogLevel", 'info') .value("ambServletURI", '/amb') .value("cometd", angular.element.cometd) .value("ambLoginWindow", 'true'); ; /*! RESOURCE: /scripts/app.ng.amb/service.AMB.js */ angular.module("ng.amb").service("amb", function (AMBOverlay, $window, $q, $log, $rootScope, $timeout) { "use strict"; var ambClient = null; var _window = $window.self; var loginWindow = null; var sameScope = false; ambClient = amb.getClient(); if (_window.g_ambClient) { sameScope = true; } if (sameScope) { var serverConnection = ambClient.getServerConnection(); serverConnection.loginShow = function() { if (!serverConnection.isLoginWindowEnabled()) return; if (loginWindow && loginWindow.isVisible()) return; if (serverConnection.isLoginWindowOverride()) return; var modalConfig = { onBeforeShow: addOverrideStyles }; loginWindow = new AMBOverlay(modalConfig); loginWindow.render(); loginWindow.show(); }; serverConnection.loginHide = function() { if (!loginWindow) return; loginWindow.hide(); loginWindow.destroy(); loginWindow = null; } } function addOverrideStyles(el) { var parent = angular.element(el.target).parent(); var backdrop = parent.find('.modal-backdrop').get(0); if (backdrop !== undefined) backdrop.style.cssText = [backdrop.style.cssText, serverConnection.getLoginWindowOverlayStyle()].join('; '); } var AUTO_CONNECT_TIMEOUT = 20 * 1000; var connected = $q.defer(); var connectionInterrupted = false; var monitorAMB = false; $timeout(startMonitoringAMB, AUTO_CONNECT_TIMEOUT); connected.promise.then(startMonitoringAMB); function startMonitoringAMB() { monitorAMB = true; } function ambInterrupted() { var state = ambClient.getState(); return monitorAMB && state !== "opened" && state !== "initialized" } var interruptionTimeout; var extendedInterruption = false; function setInterrupted(eventName) { connectionInterrupted = true; $rootScope.$broadcast(eventName); if (!interruptionTimeout) { interruptionTimeout = $timeout(function () { extendedInterruption = true; }, 30 * 1000) } connected = $q.defer(); } var connectOpenedEventId = ambClient.subscribeToEvent("connection.opened", function () { $rootScope.$broadcast("amb.connection.opened"); if (interruptionTimeout) { $timeout.cancel(interruptionTimeout); interruptionTimeout = null; } extendedInterruption = false; if(connectionInterrupted) { connectionInterrupted = false; $rootScope.$broadcast("amb.connection.recovered"); } connected.resolve(); }); var connectClosedEventId = ambClient.subscribeToEvent("connection.closed", function () { setInterrupted("amb.connection.closed"); }); var connectBrokenEventId = ambClient.subscribeToEvent("connection.broken", function () { setInterrupted("amb.connection.broken"); }); var connectSessionLoggedin = ambClient.subscribeToEvent("session.logged.in", function () { $rootScope.$broadcast("amb.session.logged.in"); }); var connectSessionReestablished = ambClient.subscribeToEvent("session.reestablished", function () { $rootScope.$broadcast("amb.session.reestablished"); }); var onUnloadWindow = function() { ambClient.unsubscribeFromEvent(connectOpenedEventId); ambClient.unsubscribeFromEvent(connectClosedEventId); ambClient.unsubscribeFromEvent(connectBrokenEventId); angular.element($window).off('unload', onUnloadWindow); }; angular.element($window).on('unload', onUnloadWindow); var defaultAmbConnectionTimeout = 10000; var shouldDeferAmbConnection = _window.NOW && _window.NOW.hasOwnProperty('deferAmbConnection') ? _window.NOW.deferAmbConnection : false; var deferredAmbConnectionTimeout = _window.NOW && _window.NOW.hasOwnProperty('deferredAmbConnectionTimeout') && isValidAmbConnectionTimeout(_window.NOW.deferredAmbConnectionTimeout) ? _window.NOW.deferredAmbConnectionTimeout : defaultAmbConnectionTimeout; if (shouldDeferAmbConnection) { $timeout(autoConnect, deferredAmbConnectionTimeout); } else { var documentReadyState = _window.document ? _window.document.readyState : null; if (documentReadyState === 'complete') autoConnect(); else _window.addEventListener('load', autoConnect); $timeout(autoConnect, defaultAmbConnectionTimeout); } function isInteger(num) { return parseInt(num, 10) === num; } function isValidAmbConnectionTimeout(timeout) { return isInteger(timeout) && timeout > 0; } var initiatedConnection = false; function autoConnect() { if (!initiatedConnection) { initiatedConnection = true; ambClient.connect(); } } return { getServerConnection: function() { return ambClient.getServerConnection(); }, connect: function() { if (initiatedConnection) { ambClient.connect(); } return connected.promise; }, get interrupted() { return ambInterrupted(); }, get extendedInterruption() { return extendedInterruption; }, get connected() { return connected.promise; }, abort: function() { ambClient.abort(); }, disconnect: function() { ambClient.disconnect(); }, getConnectionState: function () { return ambClient.getConnectionState(); }, getClientId: function () { return ambClient.getClientId(); }, getChannel: function(channelName) { return ambClient.getChannel(channelName); }, registerExtension: function(extensionName, extension) { ambClient.registerExtension(extensionName, extension); }, unregisterExtension: function(extensionName) { ambClient.unregisterExtension(extensionName); }, batch: function(batch) { ambClient.batch(batch); }, getState: function() { return ambClient.getState(); }, getFilterString: function(filter) { filter = filter. replace(/\^EQ/g, ''). replace(/\^ORDERBY(?:DESC)?[^^]*/g, ''). replace(/^GOTO/, ''); return btoa(unescape(encodeURIComponent(filter))).replace(/=/g, '-'); }, getChannelRW: function(table, filter) { var t = '/rw/default/' + table + '/' + this.getFilterString(filter); return this.getChannel(t); }, isLoggedIn: function() { return ambClient.isLoggedIn(); }, subscribeToEvent: function(event, callback) { return ambClient.subscribeToEvent(event, callback); }, getConnectionEvents: function() { return ambClient.getConnectionEvents(); }, getEvents: function() { return ambClient.getConnectionEvents(); }, loginComplete: function() { ambClient.loginComplete(); } }; }); ; /*! RESOURCE: /scripts/app.ng.amb/controller.AMBRecordWatcher.js */ angular.module("ng.amb").controller("AMBRecordWatcher", function($scope, $timeout, $window) { "use strict"; var amb = $window.top.g_ambClient; $scope.messages = []; var lastFilter; var watcherChannel; var watcher; function onMessage(message) { $scope.messages.push(message.data); } $scope.getState = function() { return amb.getState(); }; $scope.initWatcher = function() { angular.element(":focus").blur(); if(!$scope.filter || $scope.filter === lastFilter) return; lastFilter = $scope.filter; console.log("initiating watcher on " + $scope.filter); $scope.messages = []; if(watcher) { watcher.unsubscribe(); } var base64EncodeQuery = btoa($scope.filter).replace(/=/g, '-'); var channelId = '/rw/' + base64EncodeQuery; watcherChannel = amb.getChannel(channelId) watcher = watcherChannel.subscribe(onMessage); }; amb.connect(); }) ; /*! RESOURCE: /scripts/app.ng.amb/factory.snRecordWatcher.js */ angular.module("ng.amb").factory('snRecordWatcher', function($rootScope, amb, $timeout, snPresence, $log, urlTools) { "use strict"; var diagnosticLog = true; function initWatcher(table, sys_id, query) { if (!table) return; if (sys_id) var filter = "sys_id=" + sys_id; else filter = query; if (!filter) return; return initChannel(table, filter); } function initList(table, query) { if (!table) return; query = query || "sys_idISNOTEMPTY"; return initChannel(table, query); } function initTaskList(list, prevChannel) { if (prevChannel) prevChannel.unsubscribe(); var sys_ids = list.toString(); var filter = "sys_idIN" + sys_ids; return initChannel("task", filter); } function initChannel(table, filter, callbackFn) { if (isBlockedTable(table)) { $log.log("Blocked from watching", table); return null; } if (diagnosticLog) log(">>> init " + table + "?" + filter); var watcherChannel = amb.getChannelRW(table, filter); watcherChannel.subscribe(callbackFn || onMessage); amb.connect(); return watcherChannel; } function onMessage(message) { var r = message.data; var c = message.channel; if (diagnosticLog) log(">>> record " + r.operation + ": " + r.table_name + "." + r.sys_id + " " + r.display_value); $rootScope.$broadcast('record.updated', r); $rootScope.$broadcast('list.updated', r, c); } function log(message) { $log.log(message); } function isBlockedTable(table) { return table == 'sys_amb_message' || table.startsWith('sys_rw'); } return { initTaskList: initTaskList, initChannel: initChannel, init: function () { var location = urlTools.parseQueryString(window.location.search); var table = location['table'] || location['sysparm_table']; var sys_id = location['sys_id'] || location['sysparm_sys_id']; var query = location['sysparm_query']; initWatcher(table, sys_id, query); snPresence.init(table, sys_id, query); }, initList: initList, initRecord: function(table, sysId) { initWatcher(table, sysId, null); snPresence.initPresence(table, sysId); }, _initWatcher: initWatcher } }); ; /*! RESOURCE: /scripts/app.ng.amb/factory.AMBOverlay.js */ angular.module("ng.amb").factory("AMBOverlay", function($templateCache, $compile, $rootScope) { "use strict"; var showCallbacks = [], beforeShowCallbacks = [], hideCallbacks = [], isRendered = false, modal, modalScope, modalOptions; var defaults = { backdrop: 'static', keyboard: false, show: true }; function AMBOverlay(config) { config = config || {}; if(angular.isFunction(config.onBeforeShow)) beforeShowCallbacks.push(config.onBeforeShow); if(angular.isFunction(config.onShow)) showCallbacks.push(config.onShow); if(angular.isFunction(config.onHide)) hideCallbacks.push(config.onHide); function lazyRender() { if(!angular.element('html')['modal']) { var bootstrapInclude = "/scripts/bootstrap3/bootstrap.js"; ScriptLoader.getScripts([bootstrapInclude], renderModal); } else renderModal(); } function renderModal() { if(isRendered) return; modalScope = angular.extend($rootScope.$new(), config); modal = $compile($templateCache.get("amb_disconnect_modal.xml"))(modalScope); angular.element("body").append(modal); modal.on("show.bs.modal", function (e) { for(var i = 0, len = beforeShowCallbacks.length; i < len; i++) beforeShowCallbacks[i](e); }); modal.on("shown.bs.modal", function(e) { for(var i = 0, len = showCallbacks.length; i < len; i++) showCallbacks[i](e); }); modal.on("hidden.bs.modal", function(e) { for(var i = 0, len = hideCallbacks.length; i < len; i++) hideCallbacks[i](e); }); modalOptions = angular.extend({}, defaults, config); modal.modal(modalOptions); isRendered = true; } function showModal() { if(isRendered) modal.modal('show'); } function hideModal() { if(isRendered) modal.modal('hide'); } function destroyModal() { if(!isRendered) return; modal.modal('hide'); modal.remove(); modalScope.$destroy(); modalScope = void(0); isRendered = false; var pos = showCallbacks.indexOf(config.onShow); if(pos >= 0) showCallbacks.splice(pos, 1); pos = hideCallbacks.indexOf(config.onShow); if(pos >= 0) hideCallbacks.splice(pos, 1); } return { render: lazyRender, destroy: destroyModal, show: showModal, hide: hideModal, isVisible: function() { if(!isRendered) return false; return modal.visible(); } } } $templateCache.put('amb_disconnect_modal.xml', '<div id="amb_disconnect_modal" tabindex="-1" aria-hidden="true" class="modal" role="dialog">' + ' <div class="modal-dialog small-modal" style="width:450px">' + ' <div class="modal-content">' + ' <header class="modal-header">' + ' <h4 id="small_modal1_title" class="modal-title">{{title || "Login"}}</h4>' + ' </header>' + ' <div class="modal-body">' + ' <iframe class="concourse_modal" ng-src=\'{{iframe || "/amb_login.do"}}\' frameborder="0" scrolling="no" height="400px" width="405px"></iframe>' + ' </div>' + ' </div>' + ' </div>' + '</div>' ); return AMBOverlay; }); ; ; /*! RESOURCE: /scripts/sn/common/presence/snPresenceLite.js */ (function(exports, $) { 'use strict'; var PRESENCE_DISABLED = "false" === "true"; if (PRESENCE_DISABLED) { return; } if (typeof $.Deferred === "undefined") { return; } var USER_KEY = '{{SYSID}}'; var REPLACE_REGEX = new RegExp(USER_KEY, 'g'); var COLOR_ONLINE = '#71e279'; var COLOR_AWAY = '#fc8a3d'; var COLOR_OFFLINE = 'transparent'; var BASE_STYLES = [ '.sn-presence-lite { display: inline-block; width: 1rem; height: 1rem; border-radius: 50%; }' ]; var USER_STYLES = [ '.sn-presence-'+ USER_KEY +'-online [data-presence-id="'+ USER_KEY +'"] { background-color: '+ COLOR_ONLINE +'; }', '.sn-presence-'+ USER_KEY +'-away [data-presence-id="'+ USER_KEY +'"] { background-color: '+ COLOR_AWAY +'; }', '.sn-presence-'+ USER_KEY +'-offline [data-presence-id="'+ USER_KEY +'"] { background-color: '+ COLOR_OFFLINE +'; }' ]; var $head = $('head'); var stylesheet = $.Deferred(); var registeredUsers = {}; var registeredUsersLength = 0; $(function() { updateRegisteredUsers(); }); $head.ready(function() { var styleElement = document.createElement('style'); $head.append(styleElement); var $styleElement = $(styleElement); stylesheet.resolve($styleElement); }); function updateStyles(styles) { stylesheet.done(function($styleElement) { $styleElement.empty(); BASE_STYLES.forEach(function(baseStyle) { $styleElement.append(baseStyle); }); $styleElement.append(styles); }); } function getUserStyles(sysId) { var newStyles = ''; for (var i = 0, iM = USER_STYLES.length; i < iM; i++) { newStyles += USER_STYLES[i].replace(REPLACE_REGEX, sysId); } return newStyles; } function updateUserStyles() { var userKeys = Object.keys(registeredUsers); var userStyles = ""; userKeys.forEach(function(userKey) { userStyles += getUserStyles(userKey); }); updateStyles(userStyles); } exports.applyPresenceArray = applyPresenceArray; function applyPresenceArray(presenceArray) { if (!presenceArray || !presenceArray.length) { return; } var users = presenceArray.filter(function(presence) { return typeof registeredUsers[presence.user] !== "undefined"; }); updateUserPresenceStatus(users); } function updateUserPresenceStatus(users) { var presenceStatus = getBaseCSSClasses(); for (var i = 0, iM = users.length; i < iM; i++) { var presence = users[i]; var status = getNormalizedStatus(presence.status); if (status === 'offline') { continue; } presenceStatus.push('sn-presence-' + presence.user + '-' + status); } setCSSClasses(presenceStatus.join(' ')); } function getNormalizedStatus(status) { switch (status) { case 'probably offline': case 'maybe offline': return 'away'; default: return 'offline'; case 'online': case 'offline': return status; } } function updateRegisteredUsers() { var presenceIndicators = document.querySelectorAll('[data-presence-id]'); var obj = {}; for (var i = 0, iM = presenceIndicators.length; i < iM; i++) { var uid = presenceIndicators[i].getAttribute('data-presence-id'); obj[uid] = true; } if (Object.keys(obj).length === registeredUsersLength){ return; } registeredUsers = obj; registeredUsersLength = Object.keys(registeredUsers).length; updateUserStyles(); } function setCSSClasses(classes) { $('html')[0].className = classes; } function getBaseCSSClasses() { return $('html')[0].className.split(' ').filter(function(item){ return item.indexOf('sn-presence-') !== 0; }); } })(window, window.jQuery || window.Zepto); ; /*! RESOURCE: /scripts/sn/common/presence/_module.js */ angular.module('sn.common.presence', ['ng.amb', 'sn.common.glide', 'sn.common.auth']).config(function($provide) { "use strict"; $provide.constant("PRESENCE_DISABLED", "false" === "true"); }); ; /*! RESOURCE: /scripts/sn/common/presence/factory.snPresence.js */ angular.module("sn.common.presence").factory('snPresence', function($rootScope, $window, $log, amb, $timeout, $http, snRecordPresence, snTabActivity, urlTools, PRESENCE_DISABLED) { "use strict"; var REST = { PRESENCE: "/api/now/ui/presence" }; var RETRY_INTERVAL = ($window.NOW.presence_interval || 60) * 1000; var MAX_RETRY_DELAY = RETRY_INTERVAL * 10; var initialized = false; var primary = false; var presenceArray = []; var serverTimeMillis; var skew = 0; var st = 0; function init() { var location = urlTools.parseQueryString($window.location.search); var table = location['table'] || location['sysparm_table']; var sys_id = location['sys_id'] || location['sysparm_sys_id']; return initPresence(table, sys_id); } function initPresence(t, id) { if(PRESENCE_DISABLED) return; if (!initialized) { initialized = true; initRootScopes(); if (!primary) { CustomEvent.observe('sn.presence', onPresenceEvent); CustomEvent.fireTop('sn.presence.ping'); } else { presenceArray = getLocalPresence($window.localStorage.getItem('snPresence')); if (presenceArray) $timeout(schedulePresence, 100); else updatePresence(); } } return snRecordPresence.initPresence(t, id); } function isTopWindow() { var topWindow = window.self; try { while (topWindow.CustomEvent.fireEvent && topWindow !== topWindow.parent && !topWindow.parent.NOW.isPolarisWrapper && topWindow.parent.CustomEvent.fireEvent) { topWindow = topWindow.parent; } } catch (e) {} return topWindow == window.self; } function onPresenceEvent(parms) { presenceArray = parms; $timeout(broadcastPresence); } function initRootScopes() { if ($window.NOW.presence_scopes) { var ps = $window.NOW.presence_scopes; if (ps.indexOf($rootScope) == -1) ps.push($rootScope); } else { $window.NOW.presence_scopes = [$rootScope]; primary = isTopWindow(); } } function setPresence(data, st) { var rt = new Date().getTime() - st; if (rt > 500) console.log("snPresence response time " + rt + "ms"); if (data.result && data.result.presenceArray) { presenceArray = data.result.presenceArray; setLocalPresence(presenceArray); serverTimeMillis = data.result.serverTimeMillis; skew = new Date().getTime() - serverTimeMillis; var t = Math.floor(skew / 1000); if (t < -15 ) console.log(">>>>> server ahead " + Math.abs(t) + " seconds"); else if (t > 15) console.log(">>>>> browser time ahead " + t + " seconds"); } schedulePresence(); } function updatePresence(numAttempts) { presenceArray = getLocalPresence($window.localStorage.getItem('snPresence')); if (presenceArray) { determineStatus(presenceArray); $timeout(schedulePresence); return; } if (!amb.isLoggedIn() || !snTabActivity.isPrimary) { $timeout(schedulePresence); return; } var p = { user_agent: navigator.userAgent, ua_time: new Date().toISOString(), href: window.location.href, pathname: window.location.pathname, search: window.location.search, path: window.location.pathname + window.location.search }; st = new Date().getTime(); $http.post(REST.PRESENCE + '?sysparm_auto_request=true&cd=' + st, p).success(function(data) { setPresence(data, st); }).error(function(response, status) { console.log("snPresence " + status); schedulePresence(numAttempts); }) } function schedulePresence(numAttempts) { numAttempts = isFinite(numAttempts) ? numAttempts + 1 : 0; var interval = getDecayingRetryInterval(numAttempts); $timeout(function() { updatePresence(numAttempts) }, interval); determineStatus(presenceArray); broadcastPresence(); } function broadcastPresence() { if (angular.isDefined($window.applyPresenceArray)) { $window.applyPresenceArray(presenceArray); } $rootScope.$emit("sn.presence", presenceArray); if (!primary) return; CustomEvent.fireAll('sn.presence', presenceArray); } function determineStatus(presenceArray) { if (!presenceArray || !presenceArray.forEach) return; var t = new Date().getTime(); t -= skew; presenceArray.forEach(function (p) { var x = 0 + p.last_on; var y = t - x; p.status = "online"; if (y > (5 * RETRY_INTERVAL)) p.status = "offline"; else if (y > (3 * RETRY_INTERVAL)) p.status = "probably offline"; else if (y > (2.5 * RETRY_INTERVAL)) p.status = "maybe offline"; }) } function setLocalPresence(value) { var p = { saved: new $window.Date().getTime(), presenceArray: value }; $window.localStorage.setItem('snPresence', angular.toJson(p)); } function getLocalPresence(p) { if (!p) return null; try { p = angular.fromJson(p); } catch (e) { p = {}; } if (!p.presenceArray) return null; var now = new Date().getTime(); if (now - p.saved >= RETRY_INTERVAL) return null; return p.presenceArray; } function getDecayingRetryInterval(numAttempts) { return Math.min(RETRY_INTERVAL * Math.pow(2, numAttempts), MAX_RETRY_DELAY); } return { init: init, initPresence: initPresence, _getLocalPresence: getLocalPresence, _setLocalPresence: setLocalPresence, _determineStatus: determineStatus } }); ; /*! RESOURCE: /scripts/sn/common/presence/factory.snRecordPresence.js */ angular.module("sn.common.presence").factory('snRecordPresence', function($rootScope, $location, amb, $timeout, $window, PRESENCE_DISABLED, snTabActivity) { "use strict"; var statChannel; var interval = ($window.NOW.record_presence_interval || 20) * 1000; var sessions = {}; var primary = false; var currentJournalFieldName = ""; var prevJournalFieldName = ""; var table; var sys_id; function initPresence(t, id) { if(PRESENCE_DISABLED) return; if (!t || !id) return; if (t == table && id == sys_id) return; initRootScopes(); if (!primary) return; termPresence(); table = t; sys_id = id; var recordPresence = "/sn/rp/" + table + "/" + sys_id; $rootScope.me = NOW.session_id; statChannel = amb.getChannel(recordPresence); statChannel.subscribe(onStatus); amb.connected.then(function() { setStatus("entered"); $rootScope.status = "viewing"; }); return statChannel; } function initRootScopes() { if ($window.NOW.record_presence_scopes) { var ps = $window.NOW.record_presence_scopes; if (ps.indexOf($rootScope) == -1) { ps.push($rootScope); CustomEvent.observe('sn.sessions', onPresenceEvent); } } else { $window.NOW.record_presence_scopes = [$rootScope]; primary = true; } } function onPresenceEvent(sessionsToSend) { $rootScope.$emit("sn.sessions", sessionsToSend); $rootScope.$emit("sp.sessions", sessionsToSend); } function termPresence() { if (!statChannel) return; statChannel.unsubscribe(); statChannel = table = sys_id = null; } function setStatus(status) { if (status == $rootScope.status && prevJournalFieldName === currentJournalFieldName) return; prevJournalFieldName = currentJournalFieldName; $rootScope.status = status; if (Object.keys(sessions).length == 0) return; if (getStatusPrecedence(status) > 1) return; publish($rootScope.status); } function publish(status) { if (!statChannel) return; if (amb.getState() !== "opened") return; statChannel.publish({ presences: [{ status : status, session_id : NOW.session_id, user_name : NOW.user_name, user_id: NOW.user_id, user_display_name : NOW.user_display_name, user_initials : NOW.user_initials, user_avatar: NOW.user_avatar, ua : navigator.userAgent, table: table, sys_id: sys_id, field_type: currentJournalFieldName, time: new Date().toString().substring(0,24) }]}); } function onStatus(message) { message.data.presences.forEach(function(d){ if (!d.session_id || d.session_id == NOW.session_id) return; var s = sessions[d.session_id]; if (s) angular.extend(s, d); else s = sessions[d.session_id] = d; s.lastUpdated = new Date(); if (s.status == 'exited') delete sessions[d.session_id]; }); broadcastSessions(); } function broadcastSessions() { var sessionsToSend = getUniqueSessions(); $rootScope.$emit("sn.sessions", sessionsToSend); $rootScope.$emit("sp.sessions", sessionsToSend); if (primary) $timeout(function() {CustomEvent.fire('sn.sessions', sessionsToSend);}) } function getUniqueSessions() { var uniqueSessionsByUser = {}; var sessionKeys = Object.keys(sessions); sessionKeys.forEach(function(key) { var session = sessions[key]; if (session.user_id == NOW.user_id) return; if (session.user_id in uniqueSessionsByUser) { var otherSession = uniqueSessionsByUser[session.user_id]; var thisPrecedence = getStatusPrecedence(session.status); var otherPrecedence = getStatusPrecedence(otherSession.status); uniqueSessionsByUser[session.user_id] = thisPrecedence < otherPrecedence ? session : otherSession; return } uniqueSessionsByUser[session.user_id] = session; }); var uniqueSessions = {}; angular.forEach(uniqueSessionsByUser, function(item) { uniqueSessions[item.session_id] = item; }); return uniqueSessions; } function getStatusPrecedence(status) { switch (status) { case 'typing': return 0; case 'viewing': return 1; case 'entered': return 2; case 'exited': case 'probably left': return 4; case 'offline': return 5; default: return 3; } } $rootScope.$on("record.typing", function(evt, data) { currentJournalFieldName = data.field_type; setStatus(data.status); }); var idleTable, idleSysID; snTabActivity.onIdle({ onIdle: function RecordPresenceTabIdle() { idleTable = table; idleSysID = sys_id; sessions = {}; termPresence(); broadcastSessions(); }, onReturn: function RecordPresenceTabActive() { initPresence(idleTable, idleSysID, true); idleTable = idleSysID = void(0); }, delay: interval * 4 }); return { initPresence: initPresence, termPresence: termPresence } }); ; /*! RESOURCE: /scripts/sn/common/presence/directive.snPresence.js */ angular.module('sn.common.presence').directive('snPresence', function(snPresence, $rootScope, $timeout, i18n) { 'use strict'; $timeout(snPresence.init, 100); var presenceStatus = {}; i18n.getMessages(['maybe offline', 'probably offline', 'offline', 'online', 'entered', 'viewing'], function (results) { presenceStatus.maybe_offline = results['maybe offline']; presenceStatus.probably_offline = results['probably offline']; presenceStatus.offline = results['offline']; presenceStatus.online = results['online']; presenceStatus.entered = results['entered']; presenceStatus.viewing = results['viewing']; }); var presences = {}; $rootScope.$on('sn.presence', function (event, presenceArray) { angular.forEach(presences, function (p) { p.status = "offline"; }); if (!presenceArray) { return; } presenceArray.forEach(function (presence) { presences[presence.user] = presence; }); }); return { restrict: 'EA', replace: false, scope: { userId: '@?', snPresence: '=?', user: '=?', profile: '=?', displayName: '=?' }, link: function (scope, element) { if (scope.profile) { scope.user = scope.profile.userID; scope.profile.tabIndex = -1; if (scope.profile.isAccessible) scope.profile.tabIndex = 0; } if (!element.hasClass('presence')) element.addClass('presence'); function updatePresence () { var id = scope.snPresence || scope.user; if (!angular.isDefined(id) && angular.isDefined(scope.userId)) { id = scope.userId; } if (presences[id]) { var status = presences[id].status; if (status === 'maybe offline' || status === 'probably offline') { element.removeClass('presence-online presence-offline presence-away'); element.addClass('presence-away'); } else if (status == "offline" && !element.hasClass('presence-offline')) { element.removeClass('presence-online presence-away'); element.addClass('presence-offline'); } else if ( (status == "online" || status == "entered" || status == "viewing") && !element.hasClass('presence-online')) { element.removeClass('presence-offline presence-away'); element.addClass('presence-online'); } status = status.replace(/ /g,"_"); if (scope.profile) angular.element('div[user-avatar-id="' + id + '"]').attr("aria-label", scope.profile.userName + ' ' + presenceStatus[status]); else angular.element('div[user-avatar-id="' + id + '"]').attr("aria-label", scope.displayName + ' ' + presenceStatus[status]); } else { if (!element.hasClass('presence-offline')) element.addClass('presence-offline'); } } var unbind = $rootScope.$on('sn.presence', updatePresence); scope.$on('$destroy', unbind); updatePresence(); } }; }); ; /*! RESOURCE: /scripts/sn/common/presence/directive.snComposing.js */ angular.module('sn.common.presence').directive('snComposing', function(getTemplateUrl, snComposingPresence) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl("snComposing.xml"), replace: true, scope: { conversation: "=" }, controller: function($scope, $element) { var child = $element.children(); if (child && child.tooltip) child.tooltip({ 'template': '<div class="tooltip" style="white-space: pre-wrap" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', 'placement': 'top', 'container': 'body' }); $scope.snComposingPresence = snComposingPresence; } } }); ; /*! RESOURCE: /scripts/sn/common/presence/service.snComposingPresence.js */ angular.module('sn.common.presence').service('snComposingPresence', function(i18n) { "use strict"; var viewing = {}; var typing = {}; var allStrings = {}; var shortStrings = {}; var typing1="{0} is typing", typing2="{0} and {1} are typing", typingMore="{0}, {1}, and {2} more are typing", viewing1="{0} is viewing",viewing2="{0} and {1} are viewing",viewingMore="{0}, {1}, and {2} more are viewing"; i18n.getMessages( [ typing1, typing2, typingMore, viewing1, viewing2, viewingMore ], function (results) { typing1=results[typing1]; typing2=results[typing2]; typingMore=results[typingMore]; viewing1=results[viewing1]; viewing2=results[viewing2]; viewingMore=results[viewingMore]; }); function set(conversationID, newPresenceValues) { if (newPresenceValues.viewing) viewing[conversationID] = newPresenceValues.viewing; if (newPresenceValues.typing) typing[conversationID] = newPresenceValues.typing; generateAllString(conversationID, {viewing: viewing[conversationID],typing: typing[conversationID]}); generateShortString(conversationID, {viewing: viewing[conversationID],typing: typing[conversationID]}); return { viewing: viewing[conversationID], typing: typing[conversationID] } } function get(conversationID) { return { viewing: viewing[conversationID] || [], typing: typing[conversationID] || [] } } function generateAllString(conversationID, members) { var result = ""; var typingLength = members.typing.length; var viewingLength = members.viewing.length; if (typingLength < 4 && viewingLength < 4) return ""; switch (typingLength) { case 0: break; case 1: result += i18n.format(typing1, members.typing[0].name); break; case 2: result += i18n.format(typing2, members.typing[0].name, members.typing[1].name); break; default: var allButLastTyper = ""; for (var i = 0; i < typingLength; i++) { if (i < typingLength -2) allButLastTyper += members.typing[i].name + ", "; else if (i === typingLength-2) allButLastTyper += members.typing[i].name + ","; else result += i18n.format(typing2, allButLastTyper, members.typing[i].name); } } if (viewingLength > 0 && typingLength > 0) result += "\n\n"; switch (viewingLength) { case 0: break; case 1: result += i18n.format(viewing1, members.viewing[0].name); break; case 2: result += i18n.format(viewing2, members.viewing[0].name, members.viewing[1].name); break; default: var allButLastViewer = ""; for (var i = 0; i < viewingLength; i++) { if (i < viewingLength -2) allButLastViewer += members.viewing[i].name + ", "; else if (i === viewingLength - 2) allButLastViewer += members.viewing[i].name + ","; else result += i18n.format(viewing2, allButLastViewer, members.viewing[i].name); } } allStrings[conversationID] = result; } function generateShortString(conversationID, members) { var typingLength = members.typing.length; var viewingLength = members.viewing.length; var typingString = "", viewingString = ""; var inBetween = " "; switch (typingLength ) { case 0: break; case 1: typingString = i18n.format(typing1, members.typing[0].name); break; case 2: typingString = i18n.format(typing2, members.typing[0].name, members.typing[1].name); break; case 3: typingString = i18n.format(typing2, members.typing[0].name + ", " + members.typing[1].name + ",",members.typing[2].name); break; default: typingString = i18n.format(typingMore, members.typing[0].name, members.typing[1].name, (typingLength - 2)); } if (viewingLength > 0 && typingLength > 0) inBetween = ". "; switch (viewingLength) { case 0: break; case 1: viewingString = i18n.format(viewing1, members.viewing[0].name); break; case 2: viewingString = i18n.format(viewing2, members.viewing[0].name, members.viewing[1].name); break; case 3: viewingString = i18n.format(viewing2, members.viewing[0].name + ", " + members.viewing[1].name + ",", members.viewing[2].name); break; default: viewingString = i18n.format(viewingMore, members.viewing[0].name, members.viewing[1].name, (viewingLength - 2)); } shortStrings[conversationID] = typingString + inBetween + viewingString; } function getAllString(conversationID) { if ((viewing[conversationID] && viewing[conversationID].length > 3) || (typing[conversationID] && typing[conversationID].length > 3)) return allStrings[conversationID]; return ""; } function getShortString(conversationID) { return shortStrings[conversationID]; } function remove(conversationID) { delete viewing[conversationID]; } return { set: set, get: get, generateAllString: generateAllString, getAllString: getAllString, generateShortString: generateShortString, getShortString: getShortString, remove: remove } }); ; ; /*! RESOURCE: /scripts/sn/common/user_profile/js_includes_user_profile.js */ /*! RESOURCE: /scripts/sn/common/user_profile/_module.js */ angular.module("sn.common.user_profile", ['sn.common.ui']); ; /*! RESOURCE: /scripts/sn/common/user_profile/directive.snUserProfile.js */ angular.module('sn.common.user_profile').directive('snUserProfile', function(getTemplateUrl, snCustomEvent, $window, avatarProfilePersister, $timeout, $http, $injector) { "use strict"; return { replace: true, restrict: 'E', templateUrl: getTemplateUrl('snUserProfile.xml'), scope: { profile: "=", showDirectMessagePrompt: "=" }, link: function(scope, element) { scope.showDirectMessagePromptFn = function() { if ($injector.has('inSupportClient') && $injector.get('inSupportClient')) return false; if (scope.showDirectMessagePrompt) { var activeUserID = $window.NOW.user_id || ""; return !(!scope.profile || activeUserID === scope.profile.sysID || !scope.profile.hasConnectRoles || (scope.profile.document && activeUserID === scope.profile.document)); } else { return false; } }; }, controller: function($scope, snConnectService) { if ($scope.profile && $scope.profile.userID && avatarProfilePersister.getAvatar($scope.profile.userID)) { $scope.profile = avatarProfilePersister.getAvatar($scope.profile.userID); $scope.$emit("sn-user-profile.ready"); } else { $http.get('/api/now/live/profiles/sys_user.' + $scope.profile.userID).then(function (response) { angular.merge($scope.profile, response.data.result); avatarProfilePersister.setAvatar($scope.profile.userID, $scope.profile); $scope.$emit("sn-user-profile.ready"); }) } $http.get('/api/now/live/profiles/' + $scope.profile.userID + '/has_connect_roles').then(function(response) { $scope.profile.hasConnectRoles = response.data.result.hasConnectRoles; }); $scope.openDirectMessageConversation = function(evt) { if (evt && evt.keyCode === 9) return; $timeout(function () { snConnectService.openWithProfile($scope.profile); }, 0, false); angular.element('.popover').each(function() { angular.element('body').off('click.snUserAvatarPopoverClose'); angular.element(this).popover('hide'); }); }; } }; }); ; ; /*! RESOURCE: /scripts/sn/common/util/js_includes_util.js */ /*! RESOURCE: /scripts/thirdparty/autosizer/autosizer.min.js */ /*! Autosize 4.0.0 license: MIT http://www.jacklmoore.com/autosize */ !function(e,t){if("function"==typeof define&&define.amd)define(["exports","module"],t);else if("undefined"!=typeof exports&&"undefined"!=typeof module)t(exports,module);else{var n={exports:{}};t(n.exports,n),e.autosize=n.exports}}(this,function(e,t){"use strict";function n(e){function t(){var t=window.getComputedStyle(e,null);"vertical"===t.resize?e.style.resize="none":"both"===t.resize&&(e.style.resize="horizontal"),s="content-box"===t.boxSizing?-(parseFloat(t.paddingTop)+parseFloat(t.paddingBottom)):parseFloat(t.borderTopWidth)+parseFloat(t.borderBottomWidth),isNaN(s)&&(s=0),l()}function n(t){var n=e.style.width;e.style.width="0px",e.offsetWidth,e.style.width=n,e.style.overflowY=t}function o(e){for(var t=[];e&&e.parentNode&&e.parentNode instanceof Element;)e.parentNode.scrollTop&&t.push({node:e.parentNode,scrollTop:e.parentNode.scrollTop}),e=e.parentNode;return t}function r(){var t=e.style.height,n=o(e),r=document.documentElement&&document.documentElement.scrollTop;e.style.height="";var i=e.scrollHeight+s;return 0===e.scrollHeight?void(e.style.height=t):(e.style.height=i+"px",u=e.clientWidth,n.forEach(function(e){e.node.scrollTop=e.scrollTop}),void(r&&(document.documentElement.scrollTop=r)))}function l(){r();var t=Math.round(parseFloat(e.style.height)),o=window.getComputedStyle(e,null),i="content-box"===o.boxSizing?Math.round(parseFloat(o.height)):e.offsetHeight;if(i!==t?"hidden"===o.overflowY&&(n("scroll"),r(),i="content-box"===o.boxSizing?Math.round(parseFloat(window.getComputedStyle(e,null).height)):e.offsetHeight):"hidden"!==o.overflowY&&(n("hidden"),r(),i="content-box"===o.boxSizing?Math.round(parseFloat(window.getComputedStyle(e,null).height)):e.offsetHeight),a!==i){a=i;var l=d("autosize:resized");try{e.dispatchEvent(l)}catch(e){}}}if(e&&e.nodeName&&"TEXTAREA"===e.nodeName&&!i.has(e)){var s=null,u=e.clientWidth,a=null,c=function(){e.clientWidth!==u&&l()},p=function(t){window.removeEventListener("resize",c,!1),e.removeEventListener("input",l,!1),e.removeEventListener("keyup",l,!1),e.removeEventListener("autosize:destroy",p,!1),e.removeEventListener("autosize:update",l,!1),Object.keys(t).forEach(function(n){e.style[n]=t[n]}),i.delete(e)}.bind(e,{height:e.style.height,resize:e.style.resize,overflowY:e.style.overflowY,overflowX:e.style.overflowX,wordWrap:e.style.wordWrap});e.addEventListener("autosize:destroy",p,!1),"onpropertychange"in e&&"oninput"in e&&e.addEventListener("keyup",l,!1),window.addEventListener("resize",c,!1),e.addEventListener("input",l,!1),e.addEventListener("autosize:update",l,!1),e.style.overflowX="hidden",e.style.wordWrap="break-word",i.set(e,{destroy:p,update:l}),t()}}function o(e){var t=i.get(e);t&&t.destroy()}function r(e){var t=i.get(e);t&&t.update()}var i="function"==typeof Map?new Map:function(){var e=[],t=[];return{has:function(t){return e.indexOf(t)>-1},get:function(n){return t[e.indexOf(n)]},set:function(n,o){e.indexOf(n)===-1&&(e.push(n),t.push(o))},delete:function(n){var o=e.indexOf(n);o>-1&&(e.splice(o,1),t.splice(o,1))}}}(),d=function(e){return new Event(e,{bubbles:!0})};try{new Event("test")}catch(e){d=function(e){var t=document.createEvent("Event");return t.initEvent(e,!0,!1),t}}var l=null;"undefined"==typeof window||"function"!=typeof window.getComputedStyle?(l=function(e){return e},l.destroy=function(e){return e},l.update=function(e){return e}):(l=function(e,t){return e&&Array.prototype.forEach.call(e.length?e:[e],function(e){return n(e,t)}),e},l.destroy=function(e){return e&&Array.prototype.forEach.call(e.length?e:[e],o),e},l.update=function(e){return e&&Array.prototype.forEach.call(e.length?e:[e],r),e}),t.exports=l}); /*! RESOURCE: /scripts/sn/common/util/_module.js */ angular.module('sn.common.util', ['sn.common.auth']); angular.module('sn.util', ['sn.common.util']); ; /*! RESOURCE: /scripts/sn/common/util/factory.escapeHtml.js */ angular.module('sn.common.util').factory('escapeHtml', function() { return function(value) { if (typeof value !== 'string') { return ''; } return value .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/'/g, ''') .replace(/"/g, '"') .replace(/\//g, '/'); }; }); ; /*! RESOURCE: /scripts/sn/common/util/service.dateUtils.js */ angular.module('sn.common.util').factory('dateUtils', function(){ var dateUtils = { SYS_DATE_FORMAT: "yyyy-MM-dd", SYS_TIME_FORMAT: "HH:mm:ss", SYS_DATE_TIME_FORMAT: "yyyy-MM-dd HH:mm:ss", MONTH_NAMES: new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'), DAY_NAMES: new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat'), LZ: function (x) {return(x<0||x>9?"":"0")+x}, isDate: function (val,format) { var date=this.getDateFromFormat(val,format); if (date==0) { return false; } return true; }, compareDates: function (date1,dateformat1,date2,dateformat2) { var d1=this.getDateFromFormat(date1,dateformat1); var d2=this.getDateFromFormat(date2,dateformat2); if (d1==0 || d2==0) { return -1; } else if (d1 > d2) { return 1; } return 0; }, formatDateServer: function(date, format) { var ga = new GlideAjax("DateTimeUtils"); ga.addParam("sysparm_name", "formatCalendarDate"); var browserOffset = date.getTimezoneOffset() * 60000; var utcTime = date.getTime() - browserOffset; var userDateTime = utcTime - g_tz_offset; ga.addParam("sysparm_value", userDateTime); ga.getXMLWait(); return ga.getAnswer(); }, formatDate: function(date,format) { if (format.indexOf("z") > 0) return this.formatDateServer(date, format); format=format+""; var result=""; var i_format=0; var c=""; var token=""; var y=date.getYear()+""; var M=date.getMonth()+1; var d=date.getDate(); var E=date.getDay(); var H=date.getHours(); var m=date.getMinutes(); var s=date.getSeconds(); var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k; var value=new Object(); value["M"]=M; value["MM"]=this.LZ(M); value["MMM"]=this.MONTH_NAMES[M+11]; value["NNN"]=this.MONTH_NAMES[M+11]; value["MMMM"]=this.MONTH_NAMES[M-1]; value["d"]=d; value["dd"]=this.LZ(d); value["E"]=this.DAY_NAMES[E+7]; value["EE"]=this.DAY_NAMES[E]; value["H"]=H; value["HH"]=this.LZ(H); if (format.indexOf('w') != -1) { var wk = date.getWeek(); if (wk >= 52 && M == 1) { y = date.getYear(); y--; y = y + ""; } if (wk == 1 && M == 12) { y = date.getYear(); y++; y = y + ""; } value["w"] = wk; value["ww"] = this.LZ(wk); } var dayOfWeek = (7 + (E + 1) - (g_first_day_of_week - 1)) % 7; if (dayOfWeek == 0) dayOfWeek = 7; value["D"] = dayOfWeek; if (y.length < 4) { y=""+(y-0+1900); } value["y"]=""+y; value["yyyy"]=y; value["yy"]=y.substring(2,4); if (H==0) { value["h"]=12; } else if (H>12){ value["h"]=H-12; } else { value["h"]=H; } value["hh"]=this.LZ(value["h"]); if (H>11) { value["K"]=H-12; } else { value["K"]=H; } value["k"]=H+1; value["KK"]=this.LZ(value["K"]); value["kk"]=this.LZ(value["k"]); if (H > 11) { value["a"]="PM"; } else { value["a"]="AM"; } value["m"]=m; value["mm"]=this.LZ(m); value["s"]=s; value["ss"]=this.LZ(s); while (i_format < format.length) { c=format.charAt(i_format); token=""; while ((format.charAt(i_format)==c) && (i_format < format.length)) { token += format.charAt(i_format++); } if (value[token] != null) { result=result + value[token]; } else { result=result + token; } } return result; }, _isInteger: function (val) { var digits="1234567890"; for (var i=0; i < val.length; i++) { if (digits.indexOf(val.charAt(i))==-1) { return false; } } return true; }, _getInt: function (str,i,minlength,maxlength) { for (var x=maxlength; x>=minlength; x--) { var token=str.substring(i,i+x); if (token.length < minlength) { return null; } if (this._isInteger(token)) { return token; } } return null; }, getDateFromFormat: function (val,format) { val=val+""; format=format+""; var i_val=0; var i_format=0; var c=""; var token=""; var token2=""; var x,y; var now=new Date(); var year=now.getYear(); var month=now.getMonth()+1; var date=0; var hh=now.getHours(); var mm=now.getMinutes(); var ss=now.getSeconds(); var ampm=""; var week = false; while (i_format < format.length) { c=format.charAt(i_format); token=""; while ((format.charAt(i_format)==c) && (i_format < format.length)) { token += format.charAt(i_format++); } if (token=="yyyy" || token=="yy" || token=="y") { if (token=="yyyy") { x=4;y=4; } if (token=="yy") { x=2;y=2; } if (token=="y") { x=2;y=4; } year=this._getInt(val,i_val,x,y); if (year==null) { return 0; } i_val += year.length; if (year.length==2) { if (year > 70) { year=1900+(year-0); } else { year=2000+(year-0); } } } else if (token=="MMM"||token=="NNN"){ month=0; for (var i=0; i<this.MONTH_NAMES.length; i++) { var month_name=this.MONTH_NAMES[i]; if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) { if (token=="MMM"||(token=="NNN"&&i>11)) { month=i+1; if (month>12) { month -= 12; } i_val += month_name.length; break; } } } if ((month < 1)||(month>12)){return 0;} } else if (token=="EE"||token=="E") { for (var i=0; i<this.DAY_NAMES.length; i++) { var day_name=this.DAY_NAMES[i]; if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) { if (week) { if (i==0 || i == 7) date+=6; else if (i== 2 || i == 9) date+=1; else if (i== 3 || i == 10) date+=2; else if (i == 4 || i == 11) date+=3; else if (i == 5 || i == 12) date +=4; else if (i == 6 || i== 13) date+=5; } i_val += day_name.length; break; } } } else if (token=="MM"||token=="M") { month=this._getInt(val,i_val,token.length,2); if(month==null||(month<1)||(month>12)){return 0;} i_val+=month.length;} else if (token=="dd"||token=="d") { date=this._getInt(val,i_val,token.length,2); if(date==null||(date<1)||(date>31)){return 0;} i_val+=date.length;} else if (token=="hh"||token=="h") { hh=this._getInt(val,i_val,token.length,2); if(hh==null||(hh<1)||(hh>12)){return 0;} i_val+=hh.length;} else if (token=="HH"||token=="H") { hh=this._getInt(val,i_val,token.length,2); if(hh==null||(hh<0)||(hh>23)){return 0;} i_val+=hh.length;} else if (token=="KK"||token=="K") { hh=this._getInt(val,i_val,token.length,2); if(hh==null||(hh<0)||(hh>11)){return 0;} i_val+=hh.length;} else if (token=="kk"||token=="k") { hh=this._getInt(val,i_val,token.length,2); if(hh==null||(hh<1)||(hh>24)){return 0;} i_val+=hh.length;hh--;} else if (token=="mm"||token=="m") { mm=this._getInt(val,i_val,token.length,2); if(mm==null||(mm<0)||(mm>59)){return 0;} i_val+=mm.length;} else if (token=="ss"||token=="s") { ss=this._getInt(val,i_val,token.length,2); if(ss==null||(ss<0)||(ss>59)){return 0;} i_val+=ss.length;} else if (token=="a") { if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";} else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";} else {return 0;} i_val+=2;} else if (token == "w" || token == "ww") { var weekNum = this._getInt(val,i_val,token.length, 2); week = true; if (weekNum != null) { var temp = new Date(year, 0, 1, 0, 0, 0); temp.setWeek(parseInt(weekNum, 10)); year = temp.getFullYear(); month = temp.getMonth()+1; date = temp.getDate(); } weekNum += ""; i_val += weekNum.length; } else if (token=="D") { if (week) { var day = this._getInt(val,i_val,token.length, 1); if ((day == null) || (day <= 0) || (day > 7)) return 0; var temp = new Date(year, month-1, date, hh, mm, ss); var dayOfWeek = temp.getDay(); day = parseInt(day, 10); day = (day + g_first_day_of_week - 1) % 7; if (day == 0) day = 7; day--; if (day < dayOfWeek) day = 7 - (dayOfWeek - day); else day -= dayOfWeek; if (day > 0) { temp.setDate(temp.getDate() + day); year = temp.getFullYear(); month = temp.getMonth() + 1; date = temp.getDate(); } i_val++; } } else if (token =="z") i_val+=3; else { if (val.substring(i_val,i_val+token.length)!=token) {return 0;} else {i_val+=token.length;} } } if (i_val != val.length) { return 0; } if (month==2) { if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { if (date > 29){ return 0; } } else { if (date > 28) { return 0; } } } if ((month==4)||(month==6)||(month==9)||(month==11)) { if (date > 30) { return 0; } } if (hh<12 && ampm=="PM") { hh=hh-0+12; } else if (hh>11 && ampm=="AM") { hh-=12; } var newdate=new Date(year,month-1,date,hh,mm,ss); return newdate.getTime(); }, parseDate: function (val) { var preferEuro=(arguments.length==2)?arguments[1]:false; generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d'); monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d'); dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M'); yearFirst =new Array( 'yyyyw.F', 'yyw.F'); var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst', 'yearFirst'); var d=null; for (var i=0; i<checkList.length; i++) { var l=window[checkList[i]]; for (var j=0; j<l.length; j++) { d=this.getDateFromFormat(val,l[j]); if (d!=0) { return new Date(d); } } } return null; } }; Date.prototype.getWeek = function() { var newYear = new Date(this.getFullYear(),0,1); var day = newYear.getDay() - (g_first_day_of_week - 1); day = (day >= 0 ? day : day + 7); var dayNum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1; var weekNum; if (day < 4) { weekNum = Math.floor((dayNum+day-1)/7) +1; if (weekNum > 52) weekNum = this._checkNextYear(weekNum); return weekNum; } weekNum = Math.floor((dayNum+day-1)/7); if (weekNum < 1) weekNum = this._lastWeekOfYear(); else if (weekNum > 52) weekNum = this._checkNextYear(weekNum); return weekNum; }; Date.prototype._lastWeekOfYear = function() { var newYear = new Date(this.getFullYear() - 1,0,1); var endOfYear = new Date(this.getFullYear() - 1,11,31); var day = newYear.getDay() - (g_first_day_of_week - 1); var dayNum = Math.floor((endOfYear.getTime() - newYear.getTime() - (endOfYear.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1; return day < 4 ? Math.floor((dayNum+day-1)/7) + 1 : Math.floor((dayNum+day-1)/7); }; Date.prototype._checkNextYear = function() { var nYear = new Date(this.getFullYear() + 1,0,1); var nDay = nYear.getDay() - (g_first_day_of_week-1); nDay = nDay >= 0 ? nDay : nDay + 7; return nDay < 4 ? 1 : 53; }; Date.prototype.setWeek = function(weekNum) { weekNum--; var startOfYear = new Date(this.getFullYear(), 0, 1); var day = startOfYear.getDay() - (g_first_day_of_week - 1); if (day > 0 && day < 4) { this.setFullYear(startOfYear.getFullYear() - 1); this.setDate(31 - day + 1); this.setMonth(11); } else if (day > 3) this.setDate(startOfYear.getDate() + (7-day)); this.setDate(this.getDate() + (7 * weekNum)); }; return dateUtils; }) ; /*! RESOURCE: /scripts/sn/common/util/service.debounceFn.js */ angular.module("sn.common.util").service("debounceFn", function () { "use strict"; function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } return { debounce: debounce } }); ; /*! RESOURCE: /scripts/sn/common/util/factory.unwrappedHTTPPromise.js */ angular.module('sn.common.util').factory("unwrappedHTTPPromise", function ($q) { "use strict"; function isGenericPromise(promise){ return (typeof promise.then === "function" && promise.success === undefined && promise.error === undefined); } return function(httpPromise){ if(isGenericPromise(httpPromise)) return httpPromise; var deferred = $q.defer(); httpPromise.success(function(data){ deferred.resolve(data); }).error(function(data, status){ deferred.reject({ data: data, status: status }) }); return deferred.promise; }; }); ; /*! RESOURCE: /scripts/sn/common/util/service.urlTools.js */ angular.module('sn.common.util').constant('angularProcessorUrl', 'angular.do?sysparm_type='); angular.module('sn.common.util').factory("urlTools", function(getTemplateUrl, angularProcessorUrl) { "use strict"; function getPartialURL(name, parameters) { var url = getTemplateUrl(name); if (parameters) { if (typeof parameters !== 'string') { parameters = encodeURIParameters(parameters); } if (parameters.length) { url += "&" + parameters; } } if (window.NOW && window.NOW.ng_cache_defeat) url += "&t=" + new Date().getTime(); return url; } function getURL(name, parameters) { if (parameters && typeof parameters === 'object') return urlFor(name, parameters); var url = angularProcessorUrl; url += name; if (parameters) url += "&" + parameters; return url; } function urlFor(route, parameters) { var p = encodeURIParameters(parameters); return angularProcessorUrl + route + (p.length ? '&' + p : ''); } function getPropertyURL(name) { var url = angularProcessorUrl + "get_property&name=" + name; url += "&t=" + new Date().getTime(); return url; } function encodeURIParameters(parameters) { var s = []; for (var parameter in parameters) { if (parameters.hasOwnProperty(parameter)) { var key = encodeURIComponent(parameter); var value = parameters[parameter] ? encodeURIComponent(parameters[parameter]) : ''; s.push(key + "=" + value); } } return s.join('&'); } function parseQueryString(qs) { qs = qs || ''; if (qs.charAt(0) === '?') { qs = qs.substr(1); } var a = qs.split('&'); if (a === "") { return {}; } if(a && a[0].indexOf('http') != -1) a[0] = a[0].split("?")[1]; var b = {}; for (var i = 0; i < a.length; i++) { var p = a[i].split('=', 2); if (p.length == 1) { b[p[0]] = ""; } else { b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } } return b; } var urlPattern = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)/; var hostnameGroupIndex = 4; function isUrlExternal(url) { var matchResult = url.match(urlPattern); if (matchResult && matchResult[hostnameGroupIndex] && matchResult[hostnameGroupIndex].length > 0) return true; return false; } return { getPartialURL: getPartialURL, getURL: getURL, urlFor: urlFor, getPropertyURL: getPropertyURL, encodeURIParameters: encodeURIParameters, parseQueryString: parseQueryString, isUrlExternal: isUrlExternal }; }); ; /*! RESOURCE: /scripts/sn/common/util/service.getTemplateUrl.js */ angular.module('sn.common.util').provider('getTemplateUrl', function(angularProcessorUrl) { 'use strict'; var _handlerId = 0; var _handlers = {}; this.registerHandler = function(handler) { var registeredId = _handlerId; _handlers[_handlerId] = handler; _handlerId++; return function() { delete _handlers[registeredId]; }; }; this.$get = function() { return getTemplateUrl; }; function getTemplateUrl(templatePath) { if (_handlerId > 0) { var path; var handled = false; angular.forEach(_handlers, function(handler) { if (!handled) { var handlerPath = handler(templatePath); if (typeof handlerPath !== 'undefined') { path = handlerPath; handled = true; } } }); if (handled) { return path; } } return angularProcessorUrl + 'get_partial&name=' + templatePath; } }); ; /*! RESOURCE: /scripts/sn/common/util/service.snTabActivity.js */ angular.module("sn.common.util").service("snTabActivity", function ($window, $timeout, $rootElement, $document) { "use strict"; var activeEvents = ["keydown", "DOMMouseScroll", "mousewheel", "mousedown", "touchstart", "mousemove", "mouseenter", "input", "focus", "scroll"], defaultIdle = 75000, isPrimary = true, idleTime = 0, isVisible = true, idleTimeout = void(0), pageIdleTimeout = void(0), hasActed = false, appName = $rootElement.attr('ng-app') || "", storageKey = "sn.tabs." + appName + ".activeTab"; var callbacks = { "tab.primary": [], "tab.secondary": [], "activity.active": [], "activity.idle": [{delay: defaultIdle, cb: function(){}}] }; $window.tabGUID = $window.tabGUID || createGUID(); function getActiveEvents() { return activeEvents.join(".snTabActivity ") + ".snTabActivity"; } function setAppName (an) { appName = an; storageKey = "sn.tabs." + appName + ".activeTab"; makePrimary(true); } function createGUID(l) { l = l || 32; var strResult = ''; while (strResult.length < l) strResult += (((1+Math.random()+new Date().getTime())*0x10000)|0).toString(16).substring(1); return strResult.substr(0, l); } function ngObjectIndexOf(arr, obj) { for (var i = 0, len = arr.length; i < len; i++) if (angular.equals(arr[i], obj)) return i; return -1; } var detectedApi, apis = [{ eventName: 'visibilitychange', propertyName: 'hidden' },{ eventName: 'mozvisibilitychange', propertyName: 'mozHidden' },{ eventName: 'msvisibilitychange', propertyName: 'msHidden' },{ eventName: 'webkitvisibilitychange', propertyName: 'webkitHidden' }]; apis.some(function(api) { if (angular.isDefined($document[0][api.propertyName])) { detectedApi = api; return true; } }); if(detectedApi) $document.on(detectedApi.eventName, function() { if(!$document[0][detectedApi.propertyName]) { makePrimary(); isVisible = true; } else { if(!idleTimeout && !idleTime) waitForIdle(0); isVisible = false; } }); angular.element($window).on({ "mouseleave": function(e) { var destination = angular.isUndefined(e.toElement) ? e.relatedTarget : e.toElement; if (destination === null && $document[0].hasFocus()) { waitForIdle(0); } }, "blur": function(e) { makePrimary(true); isVisible = false; resetIdleTime(); }, "storage": function(e) { if(e.originalEvent.key !== storageKey) return; if($window.localStorage.getItem(storageKey) !== $window.tabGUID) makeSecondary(); } }); function waitForIdle(index, delayOffset) { var callback = callbacks['activity.idle'][index]; var numCallbacks = callbacks['activity.idle'].length; delayOffset = delayOffset || callback.delay; angular.element($window).off(getActiveEvents()); angular.element($window).one(getActiveEvents(), setActive); if(index >= numCallbacks) return; if(idleTimeout) $timeout.cancel(idleTimeout); idleTimeout = $timeout(function() { idleTime = callback.delay; callback.cb(); $timeout.cancel(idleTimeout); idleTimeout = void(0); angular.element($window).off(getActiveEvents()); angular.element($window).one(getActiveEvents(), setActive); for( var i = index + 1; i < numCallbacks; i++ ) { var nextDelay = callbacks['activity.idle'][i].delay; if(nextDelay <= callback.delay) callbacks['activity.idle'][i].cb(); else { waitForIdle(i, nextDelay - callback.delay); break; } } }, delayOffset, false); } function setActive() { angular.element($window).off(getActiveEvents()); if(idleTimeout) { $timeout.cancel(idleTimeout); idleTimeout = void(0); } var activeCallbacks = callbacks['activity.active']; activeCallbacks.some(function(callback) { if(callback.delay <= idleTime) callback.cb(); else return true; }); idleTime = 0; makePrimary(); if(pageIdleTimeout) { $timeout.cancel(pageIdleTimeout); pageIdleTimeout = void(0); } var minDelay = callbacks['activity.idle'][0].delay; hasActed = false; if(!pageIdleTimeout) pageIdleTimeout = $timeout(pageIdleHandler, minDelay, false); listenForActivity(); } function pageIdleHandler() { if(idleTimeout) return; var minDelay = callbacks['activity.idle'][0].delay; if(hasActed) { hasActed = false; if(pageIdleTimeout) $timeout.cancel(pageIdleTimeout); pageIdleTimeout = $timeout(pageIdleHandler, minDelay, false); listenForActivity(); return; } var delayOffset = minDelay; if(callbacks['activity.idle'].length > 1) delayOffset = callbacks['activity.idle'][1].delay - minDelay; idleTime = minDelay; callbacks['activity.idle'][0].cb(); waitForIdle(1, delayOffset); pageIdleTimeout = void(0); } function listenForActivity() { angular.element($window).off(getActiveEvents()); angular.element($window).one(getActiveEvents(), onActivity); angular.element("#gsft_main").on("load.snTabActivity", function() { var src = angular.element(this).attr('src'); if(src.indexOf("/") == 0 || src.indexOf($window.location.origin) == 0 || src.indexOf('http') == -1) { var iframeWindow = this.contentWindow ? this.contentWindow : this.contentDocument.defaultView; angular.element(iframeWindow).off(getActiveEvents()); angular.element(iframeWindow).one(getActiveEvents(), onActivity); } }); angular.element('iframe').each(function(idx, iframe) { var src = angular.element(iframe).attr('src'); if (!src) return; if(src.indexOf("/") == 0 || src.indexOf($window.location.origin) == 0 || src.indexOf('http') == -1) { var iframeWindow = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.defaultView; try { angular.element(iframeWindow).off(getActiveEvents()); angular.element(iframeWindow).one(getActiveEvents(), onActivity); } catch(e) { return; } } }); } function onActivity() { hasActed = true; makePrimary(); } function makePrimary(initial) { var oldGuid = $window.localStorage.getItem(storageKey); isPrimary = true; isVisible = true; $timeout.cancel(idleTimeout); idleTimeout = void(0); if(canUseStorage() && oldGuid !== $window.tabGUID && !initial) for(var i = 0, len = callbacks["tab.primary"].length; i < len; i++) callbacks["tab.primary"][i].cb(); try { $window.localStorage.setItem(storageKey, $window.tabGUID); } catch (ignored) { } if(idleTime && $document[0].hasFocus()) setActive(); } function makeSecondary() { isPrimary = false; isVisible = false; for(var i = 0, len = callbacks["tab.secondary"].length; i < len; i++) callbacks["tab.secondary"][i].cb(); } function registerCallback(event, callback, scope) { var cbObject = angular.isObject(callback) ? callback : {delay: defaultIdle, cb: callback}; if(callbacks[event]) { callbacks[event].push(cbObject); callbacks[event].sort(function(a, b) { return a.delay - b.delay; }) } function destroyCallback() { if (callbacks[event]) { var pos = ngObjectIndexOf(callbacks[event], cbObject); if (pos !== -1) callbacks[event].splice(pos, 1); } } if(scope) scope.$on("$destroy", function() { destroyCallback(); }); return destroyCallback; } function registerIdleCallback(options, onIdle, onReturn, scope) { var delay = options, onIdleDestroy, onReturnDestroy; if(angular.isObject(options)) { delay = options.delay; onIdle = options.onIdle || onIdle; onReturn = options.onReturn || onReturn; scope = options.scope || scope; } if(angular.isFunction(onIdle)) onIdleDestroy = registerCallback("activity.idle", {delay: delay, cb: onIdle}); else if (angular.isFunction(onReturn)) { onIdleDestroy = registerCallback("activity.idle", {delay: delay, cb: function(){}}); } if(angular.isFunction(onReturn)) onReturnDestroy = registerCallback("activity.active", {delay: delay, cb: onReturn}); function destroyAll() { if(angular.isFunction(onIdleDestroy)) onIdleDestroy(); if(angular.isFunction(onReturnDestroy)) onReturnDestroy(); } if(scope) scope.$on("$destroy", function() { destroyAll(); }); return destroyAll; } function canUseStorage() { var canWe = false; try { $window.localStorage.setItem(storageKey, $window.tabGUID); canWe = true; } catch (ignored) { } return canWe; } function resetIdleTime() { if(idleTime > 0) { idleTime = 0; if(pageIdleTimeout) { $timeout.cancel(pageIdleTimeout); pageIdleTimeout = void(0); } } waitForIdle(0); } makePrimary(true); listenForActivity(); pageIdleTimeout = $timeout(pageIdleHandler, defaultIdle, false); return { on: registerCallback, onIdle: registerIdleCallback, setAppName: setAppName, get isPrimary() { return isPrimary; }, get isIdle() { return idleTime > 0; }, get idleTime() { return idleTime; }, get isVisible() { return isVisible; }, get appName() { return appName; }, get defaultIdleTime() { return defaultIdle }, isActive: function() { return this.idleTime < this.defaultIdleTime && this.isVisible; }, resetIdleTime: resetIdleTime } }); ; /*! RESOURCE: /scripts/sn/common/util/factory.ArraySynchronizer.js */ angular.module("sn.common.util").factory("ArraySynchronizer", function() { 'use strict'; function ArraySynchronizer(){} function index(key, arr) { var result = {}; var keys = []; result.orderedKeys = keys; angular.forEach(arr, function(item) { var keyValue = item[key]; result[keyValue] = item; keys.push(keyValue); }); return result; } function sortByKeyAndModel(arr, key, model) { arr.sort(function(a, b) { var aIndex = model.indexOf(a[key]); var bIndex = model.indexOf(b[key]); if(aIndex > bIndex) return 1; else if (aIndex < bIndex) return -1; return 0; }); } ArraySynchronizer.prototype = { add: function(syncField, dest, source, end) { end = end || "bottom"; var destIndex = index(syncField, dest); var sourceIndex = index(syncField, source); angular.forEach(sourceIndex.orderedKeys, function(key) { if(destIndex.orderedKeys.indexOf(key) === -1) { if(end === "bottom") { dest.push(sourceIndex[key]); } else { dest.unshift(sourceIndex[key]); } } }); }, synchronize: function(syncField, dest, source, deepKeySyncArray) { var destIndex = index(syncField, dest); var sourceIndex = index(syncField, source); deepKeySyncArray = (typeof deepKeySyncArray === "undefined") ? [] : deepKeySyncArray; for(var i = destIndex.orderedKeys.length - 1; i >= 0; i--) { var key = destIndex.orderedKeys[i]; if(sourceIndex.orderedKeys.indexOf(key) === -1) { destIndex.orderedKeys.splice(i, 1); dest.splice(i, 1); } if (deepKeySyncArray.length > 0) { angular.forEach(deepKeySyncArray, function(deepKey) { if (sourceIndex[key] && destIndex[key][deepKey] !== sourceIndex[key][deepKey]) { destIndex[key][deepKey] = sourceIndex[key][deepKey]; } }); } } angular.forEach(sourceIndex.orderedKeys, function(key) { if(destIndex.orderedKeys.indexOf(key) === -1) dest.push(sourceIndex[key]); }); sortByKeyAndModel(dest, syncField, sourceIndex.orderedKeys); } }; return ArraySynchronizer; }); ; /*! RESOURCE: /scripts/sn/common/util/directive.snBindOnce.js */ angular.module("sn.common.util").directive("snBindOnce", function($sanitize) { "use strict"; return { restrict: "A", link: function(scope, element, attrs) { var value = scope.$eval(attrs.snBindOnce); var sanitizedValue = $sanitize(value); element.append(sanitizedValue); } } }) ; /*! RESOURCE: /scripts/sn/common/util/directive.snCloak.js */ angular.module("sn.common.util").directive("snCloak", function() { "use strict"; return { restrict: "A", compile: function(element, attr) { return function() { attr.$set('snCloak', undefined); element.removeClass('sn-cloak'); } } }; }) ; /*! RESOURCE: /scripts/sn/common/util/service.md5.js */ angular.module('sn.common.util').factory('md5', function() { 'use strict'; var md5cycle = function(x, k) { var a = x[0], b = x[1], c = x[2], d = x[3]; a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586); c = ff(c, d, a, b, k[2], 17, 606105819); b = ff(b, c, d, a, k[3], 22, -1044525330); a = ff(a, b, c, d, k[4], 7, -176418897); d = ff(d, a, b, c, k[5], 12, 1200080426); c = ff(c, d, a, b, k[6], 17, -1473231341); b = ff(b, c, d, a, k[7], 22, -45705983); a = ff(a, b, c, d, k[8], 7, 1770035416); d = ff(d, a, b, c, k[9], 12, -1958414417); c = ff(c, d, a, b, k[10], 17, -42063); b = ff(b, c, d, a, k[11], 22, -1990404162); a = ff(a, b, c, d, k[12], 7, 1804603682); d = ff(d, a, b, c, k[13], 12, -40341101); c = ff(c, d, a, b, k[14], 17, -1502002290); b = ff(b, c, d, a, k[15], 22, 1236535329); a = gg(a, b, c, d, k[1], 5, -165796510); d = gg(d, a, b, c, k[6], 9, -1069501632); c = gg(c, d, a, b, k[11], 14, 643717713); b = gg(b, c, d, a, k[0], 20, -373897302); a = gg(a, b, c, d, k[5], 5, -701558691); d = gg(d, a, b, c, k[10], 9, 38016083); c = gg(c, d, a, b, k[15], 14, -660478335); b = gg(b, c, d, a, k[4], 20, -405537848); a = gg(a, b, c, d, k[9], 5, 568446438); d = gg(d, a, b, c, k[14], 9, -1019803690); c = gg(c, d, a, b, k[3], 14, -187363961); b = gg(b, c, d, a, k[8], 20, 1163531501); a = gg(a, b, c, d, k[13], 5, -1444681467); d = gg(d, a, b, c, k[2], 9, -51403784); c = gg(c, d, a, b, k[7], 14, 1735328473); b = gg(b, c, d, a, k[12], 20, -1926607734); a = hh(a, b, c, d, k[5], 4, -378558); d = hh(d, a, b, c, k[8], 11, -2022574463); c = hh(c, d, a, b, k[11], 16, 1839030562); b = hh(b, c, d, a, k[14], 23, -35309556); a = hh(a, b, c, d, k[1], 4, -1530992060); d = hh(d, a, b, c, k[4], 11, 1272893353); c = hh(c, d, a, b, k[7], 16, -155497632); b = hh(b, c, d, a, k[10], 23, -1094730640); a = hh(a, b, c, d, k[13], 4, 681279174); d = hh(d, a, b, c, k[0], 11, -358537222); c = hh(c, d, a, b, k[3], 16, -722521979); b = hh(b, c, d, a, k[6], 23, 76029189); a = hh(a, b, c, d, k[9], 4, -640364487); d = hh(d, a, b, c, k[12], 11, -421815835); c = hh(c, d, a, b, k[15], 16, 530742520); b = hh(b, c, d, a, k[2], 23, -995338651); a = ii(a, b, c, d, k[0], 6, -198630844); d = ii(d, a, b, c, k[7], 10, 1126891415); c = ii(c, d, a, b, k[14], 15, -1416354905); b = ii(b, c, d, a, k[5], 21, -57434055); a = ii(a, b, c, d, k[12], 6, 1700485571); d = ii(d, a, b, c, k[3], 10, -1894986606); c = ii(c, d, a, b, k[10], 15, -1051523); b = ii(b, c, d, a, k[1], 21, -2054922799); a = ii(a, b, c, d, k[8], 6, 1873313359); d = ii(d, a, b, c, k[15], 10, -30611744); c = ii(c, d, a, b, k[6], 15, -1560198380); b = ii(b, c, d, a, k[13], 21, 1309151649); a = ii(a, b, c, d, k[4], 6, -145523070); d = ii(d, a, b, c, k[11], 10, -1120210379); c = ii(c, d, a, b, k[2], 15, 718787259); b = ii(b, c, d, a, k[9], 21, -343485551); x[0] = add32(a, x[0]); x[1] = add32(b, x[1]); x[2] = add32(c, x[2]); x[3] = add32(d, x[3]); }; var cmn = function(q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32((a << s) | (a >>> (32 - s)), b); }; var ff = function(a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t); }; var gg = function(a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t); }; var hh = function(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); }; var ii = function(a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t); }; var md51 = function(s) { var txt = ''; var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i; for (i=64; i<=s.length; i+=64) { md5cycle(state, md5blk(s.substring(i-64, i))); } s = s.substring(i-64); var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; for (i=0; i<s.length; i++) tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3); tail[i>>2] |= 0x80 << ((i%4) << 3); if (i > 55) { md5cycle(state, tail); for (i=0; i<16; i++) tail[i] = 0; } tail[14] = n*8; md5cycle(state, tail); return state; }; var md5blk = function(s) { var md5blks = [], i; for (i=0; i<64; i+=4) { md5blks[i>>2] = s.charCodeAt(i) + (s.charCodeAt(i+1) << 8) + (s.charCodeAt(i+2) << 16) + (s.charCodeAt(i+3) << 24); } return md5blks; }; var hex_chr = '0123456789abcdef'.split(''); var rhex = function(n) { var s='', j=0; for(; j<4; j++) s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; return s; }; var hex = function(x) { for (var i=0; i<x.length; i++) x[i] = rhex(x[i]); return x.join(''); }; var add32 = function(a, b) { return (a + b) & 0xFFFFFFFF; }; return function(s) { return hex(md51(s)); }; }); ; /*! RESOURCE: /scripts/sn/common/util/service.priorityQueue.js */ angular.module('sn.common.util').factory('priorityQueue', function() { 'use strict'; return function(comparator) { var items = []; var compare = comparator || function(a, b) { return a - b; }; var swap = function(a, b) { var temp = items[a]; items[a] = items[b]; items[b] = temp; }; var bubbleUp = function(pos) { var parent; while (pos > 0) { parent = (pos - 1) >> 1; if (compare(items[pos], items[parent]) >= 0) break; swap(parent, pos); pos = parent; } }; var bubbleDown = function(pos) { var left, right, min, last = items.length - 1; while (true) { left = (pos << 1) + 1; right = left + 1; min = pos; if (left <= last && compare(items[left], items[min]) < 0) min = left; if (right <= last && compare(items[right], items[min]) < 0) min = right; if (min === pos) break; swap(min, pos); pos = min; } }; return { add: function(item) { items.push(item); bubbleUp(items.length - 1); }, poll: function() { var first = items[0], last = items.pop(); if (items.length > 0) { items[0] = last; bubbleDown(0); } return first; }, peek: function() { return items[0]; }, clear: function() { items = []; }, inspect: function() { return angular.toJson(items, true); }, get size() { return items.length; }, get all() { return items; }, set comparator(fn) { compare = fn; } }; }; }); ; /*! RESOURCE: /scripts/sn/common/util/service.snResource.js */ angular.module('sn.common.util').factory('snResource', function($http, $q, priorityQueue, md5) { 'use strict'; var methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'jsonp', 'trace'], queue = priorityQueue(function(a, b) { return a.timestamp - b.timestamp; }), resource = {}, pendingRequests = [], inFlightRequests = []; return function() { var requestInterceptors = $http.defaults.transformRequest, responseInterceptors = $http.defaults.transformResponse; var next = function() { var request = queue.peek(); pendingRequests.shift(); inFlightRequests.push(request.hash); $http(request.config).then(function(response) { request.deferred.resolve(response); }, function(reason) { request.deferred.reject(reason); }).finally(function() { queue.poll(); inFlightRequests.shift(); if (queue.size > 0) next(); }); }; angular.forEach(methods, function(method) { resource[method] = function(url, data) { var deferredRequest = $q.defer(), promise = deferredRequest.promise, deferredAbort = $q.defer(), config = { method: method, url: url, data: data, transformRequest: requestInterceptors, transformResponse: responseInterceptors, timeout: deferredAbort.promise }, hash = md5(JSON.stringify(config)); pendingRequests.push(hash); queue.add({ config: config, deferred: deferredRequest, timestamp: Date.now(), hash: hash }); if (queue.size === 1) next(); promise.abort = function() { deferredAbort.resolve('Request cancelled'); }; return promise; }; }); resource.addRequestInterceptor = function(fn) { requestInterceptors = requestInterceptors.concat([fn]); }; resource.addResponseInterceptor = function(fn) { responseInterceptors = responseInterceptors.concat([fn]); }; resource.queueSize = function() { return queue.size; }; resource.queuedRequests = function() { return queue.all; }; return resource; }; }); ; /*! RESOURCE: /scripts/sn/common/util/service.snConnect.js */ angular.module("sn.common.util").service("snConnectService", function ($http, snCustomEvent) { "use strict"; var connectPaths = ["/$c.do", "/$chat.do"]; function canOpenInFrameset() { return window.top.NOW.collaborationFrameset; } function isInConnect() { var parentPath = getParentPath(); return connectPaths.some(function(path) { return parentPath == path; }); } function getParentPath() { try { return window.top.location.pathname; } catch(IGNORED) { return ""; } } function openWithProfile(profile) { if (isInConnect() || canOpenInFrameset()) snCustomEvent.fireTop('chat:open_conversation', profile); else window.open("$c.do#/with/" + profile.sys_id, "_blank"); } return { openWithProfile: openWithProfile } }); ; /*! RESOURCE: /scripts/sn/common/util/snPolyfill.js */ (function(){ "use strict"; polyfill(String.prototype, 'startsWith', function(prefix) { return this.indexOf(prefix) === 0; }); polyfill(String.prototype, 'endsWith', function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }); polyfill(Number, 'isNaN', function(value) { return value !== value; }); polyfill(window, 'btoa', function (input) { var str = String(input); var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; for ( var block, charCode, idx = 0, map = chars, output = ''; str.charAt(idx | 0) || (map = '=', idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8) ) { charCode = str.charCodeAt(idx += 3/4); if (charCode > 0xFF) { throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); } block = block << 8 | charCode; } return output; }); function polyfill(obj, slot, fn) { if (obj[slot] === void(0)) { obj[slot] = fn; } } window.console = window.console || { log: function(){} }; })(); ; /*! RESOURCE: /scripts/sn/common/util/directive.snFocus.js */ angular.module('sn.common.util').directive('snFocus', function($timeout) { 'use strict'; return function(scope, element, attrs) { scope.$watch(attrs.snFocus, function(value) { if (value !== true) return; $timeout(function() { element[0].focus(); }); }); }; }); ; /*! RESOURCE: /scripts/sn/common/util/directive.snResizeHeight.js */ angular.module('sn.common.util').directive('snResizeHeight', function($window) { 'use strict'; return { restrict : 'A', link : function(scope, elem, attrs) { if (typeof $window.autosize === 'undefined') { return; } $window.autosize(elem); function _update() { $window.autosize.update(elem); } function _destroy() { $window.autosize.destroy(elem); } if (typeof attrs.disableValueWatcher === "undefined") { scope.$watch(function() { return elem.val(); }, function valueWatcher(newValue, oldValue) { if (newValue === oldValue) { return; } _update(); }); } elem.on('input.resize', _update()); scope.$on('$destroy', function() { _destroy(); }); if (attrs.snTextareaAutosizer === 'trim') { elem.on('blur', function() { elem.val(elem.val().trim()); _update(); }) } } } }); ; /*! RESOURCE: /scripts/sn/common/util/directive.snBlurOnEnter.js */ angular.module('sn.common.util').directive('snBlurOnEnter', function() { 'use strict'; return function(scope, element) { element.bind("keydown keypress", function(event) { if (event.which !== 13) return; element.blur(); event.preventDefault(); }); }; }); ; /*! RESOURCE: /scripts/sn/common/util/directive.snStickyHeaders.js */ angular.module('sn.common.util').directive('snStickyHeaders', function() { "use strict"; return { restrict : 'A', transclude: false, replace: false, link: function (scope, element, attrs) { element.addClass('sticky-headers'); var containers; var scrollContainer = element.find('[sn-sticky-scroll-container]'); scrollContainer.addClass('sticky-scroll-container'); function refreshHeaders () { if (attrs.snStickyHeaders !== 'false') { angular.forEach(containers, function (container) { var stickyContainer = angular.element(container); var stickyHeader = stickyContainer.find('[sn-sticky-header]'); var stickyOffset = stickyContainer.position().top + stickyContainer.outerHeight(); stickyContainer.addClass('sticky-container'); if (stickyOffset < stickyContainer.outerHeight() && stickyOffset > -stickyHeader.outerHeight()) { stickyContainer.css('padding-top', stickyHeader.outerHeight()); stickyHeader.css('width', stickyHeader.outerWidth()); stickyHeader.removeClass('sticky-header-disabled').addClass('sticky-header-enabled'); } else { stickyContainer.css('padding-top', ''); stickyHeader.css('width', ''); stickyHeader.removeClass('sticky-header-enabled').addClass('sticky-header-disabled'); } }); } else { element.find('[sn-sticky-container]').removeClass('sticky-container'); element.find('[sn-sticky-container]').css('padding-top', ''); element.find('[sn-sticky-header]').css('width', ''); element.find('[sn-sticky-header]').removeClass('sticky-header-enabled').addClass('sticky-header-disabled'); } } scope.$watch(function () { scrollContainer.find('[sn-sticky-header]').addClass('sticky-header'); containers = element.find('[sn-sticky-container]'); return attrs.snStickyHeaders; }, refreshHeaders); scope.$watch(function () { return scrollContainer[0].scrollHeight; }, refreshHeaders); scrollContainer.on('scroll', refreshHeaders); } }; }); ; /*! RESOURCE: /scripts/sn/common/util/directive.snBanner.js */ angular.module('sn.common.util').directive('snBanner', function(getTemplateUrl, $window, $http) { 'use strict'; function isIOS () { var match = navigator.userAgent.match(/iPhone; CPU iPhone OS ([0-9_]*)/); return !!match; }; function isNative () { return (navigator.userAgent.match(/SnMobile/i) || navigator.userAgent.match(/ServiceNow/i)) }; var isBannerClosed = function() { var localStorageTime = $window.localStorage.getItem('mobileBannerDismissed'); var isBannerClosedFlag = false; var SECONDS_IN_A_DAY = 86400000; if(localStorageTime) { if(((Date.now() - localStorageTime)/SECONDS_IN_A_DAY) < 1) { isBannerClosedFlag = true; } else { $window.localStorage.removeItem('mobileBannerDismissed'); } } return isBannerClosedFlag; }; var setBannerClosedTime = function() { $window.localStorage.setItem('mobileBannerDismissed', Date.now()); }; var emitBannerState = function(state, $scope) { $scope.$emit(state); } return { restrict: 'E', templateUrl: getTemplateUrl('sn_banner.xml'), scope: { bannerApiUrl: '=' }, controller: function($scope) { $scope.isIOS = isIOS(); $scope.closeBanner = function() { $scope.banner.show = false; setBannerClosedTime(); emitBannerState('banner.closed', $scope); }; $scope.openUrl = function() { $window.open($scope.banner.nativeAppUrl, '_blank'); }; $scope.$watch('bannerApiUrl', function(newVal, oldVal) { if (newVal && newVal !== oldVal) { setBanner(newVal); } }); function setBanner(bannerApiUrl) { $scope.banner = {}; if (isBannerClosed()) { $scope.banner.show = false; return; } if (isNative()) { $scope.banner.show = false; return; }; $http.get(bannerApiUrl) .then(function(response) { var data = response.data; if (data.BannerDetails) { $scope.banner.show = true; $scope.banner.icon = data.BannerDetails.IconPath; $scope.banner.name = data.BannerDetails.Name; $scope.banner.description = data.BannerDetails.Description; $scope.banner.nativeAppUrl = data.BannerDetails.Ulink; emitBannerState('banner.opened', $scope); } else { $scope.banner.show = false; emitBannerState('banner.closed', $scope); } }); } } } }); ; ; /*! RESOURCE: /scripts/sn/common/ui/js_includes_ui.js */ /*! RESOURCE: /scripts/sn/common/ui/_module.js */ angular.module('sn.common.ui', ['sn.common.messaging']); ; /*! RESOURCE: /scripts/sn/common/ui/popover/js_includes_ui_popover.js */ /*! RESOURCE: /scripts/sn/common/ui/popover/_module.js */ angular.module('sn.common.ui.popover', []); ; /*! RESOURCE: /scripts/sn/common/ui/popover/directive.snBindPopoverSelection.js */ angular.module('sn.common.ui.popover').directive('snBindPopoverSelection', function(snCustomEvent) { "use strict"; return { restrict: "A", controller: function($scope, $element, $attrs , snCustomEvent) { snCustomEvent.observe('list.record_select', recordSelectDataHandler); function recordSelectDataHandler(data, event) { if (!data || !event) return; event.stopPropagation(); var ref = ($scope.field) ? $scope.field.ref : $attrs.ref; if (data.ref === ref) { if (window.g_form) { if ($attrs.addOption) { addGlideListChoice('select_0' + $attrs.ref, data.value, data.displayValue); } else { var fieldValue = typeof $attrs.ref === 'undefined' ? data.ref : $attrs.ref; window.g_form._setValue(fieldValue, data.value, data.displayValue); clearDerivedFields(data.value); } } if ($scope.field) { $scope.field.value = data.value; $scope.field.displayValue = data.displayValue; } } } function clearDerivedFields(value) { if (window.DerivedFields) { var df = new DerivedFields($scope.field ? $scope.field.ref : $attrs.ref); df.clearRelated(); df.updateRelated(value); } } } }; }); ; /*! RESOURCE: /scripts/sn/common/ui/popover/directive.snComplexPopover.js */ angular.module('sn.common.ui.popover').directive('snComplexPopover', function(getTemplateUrl, $q, $http, $templateCache, $compile, $timeout){ "use strict"; return { restrict: 'E', replace:true, templateUrl: function(elem, attrs){ return getTemplateUrl(attrs.buttonTemplate); }, controller: function($scope, $element, $attrs, $q, $document, snCustomEvent, snComplexPopoverService){ $scope.type = $attrs.complexPopoverType || "complex_popover"; if ($scope.closeEvent){ snCustomEvent.observe($scope.closeEvent, destroyPopover); $scope.$on($scope.closeEvent, destroyPopover); } $scope.$parent.$on('$destroy', destroyPopover); $scope.$on('$destroy', function() { snCustomEvent.un($scope.closeEvent, destroyPopover); }); var newScope; var open; var popover; var content; var popoverDefaults = { container: 'body', html: true, placement: 'auto', trigger: 'manual', template: '<div class="complex_popover popover" role="dialog"><div class="arrow"></div><div class="popover-content"></div></div>' }; var popoverConfig = angular.extend(popoverDefaults, $scope.popoverConfig); $scope.loading = false; $scope.initialized = false; $scope.popOverDisplaying = false; $scope.togglePopover = function(event) { if (!open){ showPopover(event); } else { destroyPopover(); } $scope.popOverDisplaying = !$scope.popOverDisplaying; }; function showPopover(e) { if ($scope.loading) return; $scope.$toggleButton = angular.element(e.target); $scope.loading = true; $scope.$emit('list.toggleLoadingState', true); _getTemplate() .then(_insertTemplate) .then(_createPopover) .then(_bindHtml) .then(function(){ $scope.initialized = true; if (!$scope.loadEvent) _openPopover(); }); } function destroyPopover() { if (!newScope) return; $scope.$toggleButton.on('hidden.bs.popover', function(){ open = false; $scope.$toggleButton.data('bs.popover').$element.removeData('bs.popover').off('.popover'); $scope.$toggleButton = null; snCustomEvent.fire('hidden.complexpopover.' + $scope.ref); }); $scope.$toggleButton.popover('hide'); snCustomEvent.fire('hide.complexpopover.' + $scope.ref, $scope.$toggleButton); newScope.$broadcast('$destroy'); newScope.$destroy(); newScope = null; $scope.initialized = false; angular.element(popoverConfig.container).off({ 'keydown': keyDownHandler }); angular.element(window).off({ 'click': complexHtmlHandler }); } function _getTemplate() { return snComplexPopoverService.getTemplate(getTemplateUrl($attrs.template)); } function _createPopover() { $scope.$toggleButton.popover(popoverConfig); return $q.when(true); } function _insertTemplate(response) { newScope = $scope.$new(); if ($scope.loadEvent) newScope.$on($scope.loadEvent, _openPopover); content = $compile(response.data)(newScope); popoverConfig.content = content; newScope.open = true; snCustomEvent.fire('inserted.complexpopover.' + $scope.ref, $scope.$toggleButton); return $q.when(true); } function _bindHtml() { angular.element(popoverConfig.container).on({ 'keydown': keyDownHandler }); angular.element(window).on({ 'click': complexHtmlHandler }); return $q.when(true); } function complexHtmlHandler(e) { var parentComplexPopoverScope = angular.element(e.target).parents('.popover-content').children().scope(); if (parentComplexPopoverScope && (parentComplexPopoverScope.type = "complex_popover") && $scope.type === "complex_popover") return; if (!open || angular.element(e.target).parents('html').length === 0) return; if ($scope.initialized && !$scope.loading && !$scope.$toggleButton.is(e.target) && content.parents('.popover').has(angular.element(e.target)).length === 0) { _eventClosePopover(e); destroyPopover(e); } } function keyDownHandler(e) { if (e.keyCode != 27) return; if (!open || angular.element(e.target).parents('html').length === 0) return; if ($scope.initialized && !$scope.loading && !$scope.$toggleButton.is(e.target) && content.parents('.popover').has(angular.element(e.target)).length > 0) { _eventClosePopover(e); destroyPopover(); } } function _eventClosePopover(e) { e.preventDefault(); e.stopPropagation(); } function createAndActivateFocusTrap(popover) { var deferred = $q.defer(); if (!window.focusTrap) { deferred.reject('Focus trap not found'); } else { if (!$scope.focusTrap) { $scope.focusTrap = window.focusTrap(popover, { clickOutsideDeactivates: true }); } try { $scope.focusTrap.activate({ onActivate: function() { deferred.resolve(); } }); } catch(e) { console.warn("Unable to activate focus trap", e); } } return deferred.promise; } function deactivateAndDestroyFocusTrap() { var deferred = $q.defer(); if (!$scope.focusTrap) { deferred.reject("Focus trap not found"); } else { try { $scope.focusTrap.deactivate({ returnFocus: false, onDeactivate: function () { deferred.resolve(); } }); } catch (e) { console.warn("Unable to deactivate focus trap", e); } $scope.focusTrap = null; } return deferred.promise; } function _openPopover() { if (open) { return; } open = true; $timeout(function() { $scope.$toggleButton.popover('show'); $scope.loading = false; snCustomEvent.fire('show.complexpopover.' + $scope.ref, $scope.$toggleButton); $scope.$toggleButton.on('shown.bs.popover', function(evt) { var popoverObject = angular.element(evt.target).data('bs.popover'), $tooltip, popover; $tooltip = popoverObject && popoverObject.$tip; popover = $tooltip && $tooltip[0]; if (popover) { createAndActivateFocusTrap(popover); } snCustomEvent.fire('shown.complexpopover.' + $scope.ref, $scope.$toggleButton); }); $scope.$toggleButton.on('hide.bs.popover', function () { deactivateAndDestroyFocusTrap().finally(function() { $scope.$toggleButton.focus(); }); }); }, 0 ); } } }; }); ; /*! RESOURCE: /scripts/sn/common/ui/popover/service.snComplexPopoverService.js */ angular.module('sn.common.ui.popover').service('snComplexPopoverService', function($http, $q, $templateCache){ "use strict"; return { getTemplate: getTemplate }; function getTemplate(template){ return $http.get(template, {cache: $templateCache}); } }); ; ; /*! RESOURCE: /scripts/sn/common/ui/directive.snConfirmModal.js */ angular.module('sn.common.ui').directive('snConfirmModal', function(getTemplateUrl) { return { templateUrl: getTemplateUrl('sn_confirm_modal.xml'), restrict: 'E', replace: true, transclude: true, scope: { config: '=?', modalName: '@', title: '@?', message: '@?', cancelButton: '@?', okButton: '@?', alertButton: '@?', cancel: '&?', ok: '&?', alert: '&?' }, link: function (scope, element) { element.find('.modal').remove(); }, controller: function($scope, $rootScope) { $scope.config = $scope.config || {}; function Button(fn, text) { return { fn: fn, text: text } } var buttons = { 'cancelButton': new Button('cancel', 'Cancel'), 'okButton': new Button('ok', 'OK'), 'alertButton': new Button('alert', 'Close'), getText: function(type) { var button = this[type]; if (button && $scope.get(button.fn)) return button.text; } }; $scope.get = function(type) { if ($scope.config[type]) return $scope.config[type]; if (!$scope[type]) { var text = buttons.getText(type); if (text) return $scope.config[type] = text; } return $scope.config[type] = $scope[type]; }; if(!$scope.get('modalName')) $scope.config.modalName = 'confirm-modal'; function call(type) { var action = $scope.get(type); if (action) { if (angular.isFunction(action)) action(); return true; } return !!buttons.getText(type); } $scope.cancelPressed = close('cancel'); $scope.okPressed = close('ok'); $scope.alertPressed = close('alert'); function close (type) { return function () { actionClosed = true; $rootScope.$broadcast('dialog.' + $scope.config.modalName + '.close'); call(type); } } var actionClosed; $scope.$on('dialog.' + $scope.get('modalName') + '.opened', function() { actionClosed = false; $scope.isOpen = true; }); $scope.$on('dialog.' + $scope.get('modalName') + '.closed', function() { $scope.isOpen = false; if (actionClosed) return; if (call('cancel')) return; if (call('alert')) return; call('ok'); }); } }; }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snContextMenu.js */ angular.module('sn.common.ui').directive('contextMenu', function ($document, $window, snCustomEvent) { var $contextMenu, $ul; var scrollHeight = angular.element("body").get(0).scrollHeight; var contextMenuItemHeight = 0; var $triggeringElement; var _focusTrap; function setContextMenuPosition(event, $ul){ if (!event.pageX && event.originalEvent.changedTouches) event = event.originalEvent.changedTouches[0]; if (contextMenuItemHeight === 0) contextMenuItemHeight = 24; var cmWidth = 150; var cmHeight = contextMenuItemHeight * $ul.children().length; var pageX = event.pageX; var pageY = event.pageY; if (!pageX) { var rect = event.target.getBoundingClientRect(); pageX = rect.left + angular.element(event.target).width(); pageY = rect.top + angular.element(event.target).height(); } var startX = pageX + cmWidth >= $window.innerWidth ? pageX - cmWidth : pageX; var startY = pageY + cmHeight >= $window.innerHeight ? pageY - cmHeight : pageY; $ul.css({ display: 'block', position: 'absolute', left: startX, top: startY }); } function renderContextMenuItems($scope, event, options) { $ul.empty(); angular.forEach(options, function (item) { var $li = angular.element('<li role="presentation">'); if (item === null) { $li.addClass('divider'); } else { var $a = angular.element('<a role="menuitem" href="javascript:void(0)">'); $a.text(typeof item[0] == 'string' ? item[0] : item[0].call($scope, $scope)); $li.append($a); $li.on('click', function ($event) { $event.preventDefault(); $scope.$apply(function () { _clearContextMenus(event); item[1].call($scope, $scope); }); }); } $ul.append($li); }); setContextMenuPosition(event, $ul); } var renderContextMenu = function ($scope, event, options) { angular.element(event.currentTarget).addClass('context'); $contextMenu = angular.element('<div>', { 'class': 'dropdown clearfix context-dropdown open' }); $contextMenu.on('click', function (e) { if (angular.element(e.target).hasClass('dropdown')) { _clearContextMenus(event); } }); $contextMenu.on('contextmenu', function (event) { event.preventDefault(); _clearContextMenus(event); }); $contextMenu.on('keydown', function(event) { if (event.keyCode != 27 && event.keyCode != 9) return; event.preventDefault(); _clearContextMenus(event); }); $contextMenu.css({ position: 'absolute', top: 0, height: angular.element("body").get(0).scrollHeight, left: 0, right: 0, zIndex: 9999 }); $document.find('body').append($contextMenu); $ul = angular.element('<ul>', { 'class': 'dropdown-menu', 'role': 'menu' }); renderContextMenuItems($scope, event, options); $contextMenu.append($ul); $triggeringElement = document.activeElement; activateFocusTrap(); $contextMenu.data('resizeHandler', function() { scrollHeight = angular.element("body").get(0).scrollHeight; $contextMenu.css('height', scrollHeight); }); snCustomEvent.observe('partial.page.reload', $contextMenu.data('resizeHandler')); }; function _clearContextMenus(event){ if (!event) return; angular.element(event.currentTarget).removeClass('context'); var els = angular.element(".context-dropdown"); angular.forEach(els, function(el){ snCustomEvent.un('partial.page.reload', angular.element(el).data('resizeHandler')); angular.element(el).remove(); }); deactivateFocusTrap(); } function activateFocusTrap() { if (_focusTrap || !window.focusTrap) return; _focusTrap = focusTrap($contextMenu[0], { focusOutsideDeactivates: true, clickOutsideDeactivates: true }); _focusTrap.activate(); } function deactivateFocusTrap() { if (!_focusTrap || !window.focusTrap) return; _focusTrap.deactivate(); _focusTrap = null; } return function (scope, element, attrs) { element.on('contextmenu', function (event) { if (event.ctrlKey) return; if (angular.element(element).attr('context-type')) return; showMenu(event); }); element.on('click', handleClick); element.on('keydown', function(event) { if (event.keyCode == 32) { handleSpace(event); } else if (event.keyCode === 13) { handleClick(event); } }); var doubleTapTimeout, doubleTapActive = false, doubleTapStartPosition; element.on('touchstart', function(event) { doubleTapStartPosition = { x: event.originalEvent.changedTouches[0].screenX, y: event.originalEvent.changedTouches[0].screenY }; }); element.on('touchend', function(event) { var distX = Math.abs(event.originalEvent.changedTouches[0].screenX - doubleTapStartPosition.x); var distY = Math.abs(event.originalEvent.changedTouches[0].screenY - doubleTapStartPosition.y); if (distX > 15 || distY > 15) { doubleTapStartPosition = null; return; } if (doubleTapActive) { doubleTapActive = false; clearTimeout(doubleTapTimeout); showMenu(event); event.preventDefault(); return; } doubleTapActive = true; event.preventDefault(); doubleTapTimeout = setTimeout(function() { doubleTapActive = false; if (event.target) event.target.click(); }, 300); }); function handleSpace(evt) { var $target = angular.element(evt.target); if ($target.is('button, [role=button]')) { handleClick(evt); return; } if (!$target.hasClass('list-edit-cursor')) return; showMenu(evt); } function handleClick(event) { var $el = angular.element(element); var $target = angular.element(event.target); if (!$el.attr('context-type') && !$target.hasClass('context-menu-click')) return; showMenu(event); } function showMenu(evt) { scope.$apply(function () { applyMenu(evt); clearWindowSelection(); }); } function clearWindowSelection() { if (window.getSelection) if (window.getSelection().empty) window.getSelection().empty(); else if (window.getSelection().removeAllRanges) window.getSelection().removeAllRanges(); else if (document.selection) document.selection.empty(); } function applyMenu(event) { var tagName = event.target.tagName; if (tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'BUTTON') { return; } var menu = scope.$eval(attrs.contextMenu, { event: event }); if (menu instanceof Array) { if (menu.length > 0) { event.stopPropagation(); event.preventDefault(); scope.$watch(function(){ return menu; }, function(newValue, oldValue){ if (newValue !== oldValue) renderContextMenuItems(scope, event, menu);}, true); renderContextMenu(scope, event, menu); } } else if (typeof menu !== 'undefined' && typeof menu.then === 'function' ) { event.stopPropagation(); event.preventDefault(); menu.then(function(response) { var contextMenu = response; if (contextMenu.length > 0) { scope.$watch(function() { return contextMenu; }, function(newValue, oldValue) { if (newValue !== oldValue) renderContextMenuItems(scope, event, contextMenu); }, true); renderContextMenu(scope, event, contextMenu); } else { throw '"' + attrs.contextMenu + '" is not an array or promise'; } }); } else { throw '"' + attrs.contextMenu + '" is not an array or promise'; } } }; }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snDialog.js */ angular.module("sn.common.ui").directive("snDialog", function($timeout, $rootScope, $document) { "use strict"; return { restrict: "AE", transclude: true, scope: { modal: "=?", disableAutoFocus: "=?", classCheck: "=" }, replace: true, template: '<dialog ng-keydown="escape($event)"><div ng-click="onClickClose()" title="Close" class="close-button icon-button icon-cross" tabindex="-1"></div></dialog>', link: function(scope, element, attrs, ctrl, transcludeFn) { var transcludeScope = {}; var _focusTrap = null; scope.isOpen = function() { return element[0].open; }; transcludeFn(element.scope().$new(), function(a, b) { element.prepend('<i class="sn-dialog-focus-trap-boundary" tabindex="0" ></i>'); element.append(a); element.append('<i class="sn-dialog-focus-trap-boundary" tabindex="0" ></i>'); transcludeScope = b; }); element.click(function(event) { event.stopPropagation(); if (event.offsetX < 0 || event.offsetX > element[0].offsetWidth || event.offsetY < 0 || event.offsetY > element[0].offsetHeight) if (!scope.classCheck) scope.onClickClose(); else { var classes = scope.classCheck.split(","); var found = false; for (var i = 0; i < classes.length; i++) if (angular.element(event.target).closest(classes[i]).length > 0) found = true; if (!found) scope.onClickClose(); } }); scope.show = function() { var d = element[0]; if (!d.showModal || true) { dialogPolyfill.registerDialog(d); d.setDisableAutoFocus(scope.disableAutoFocus); } if (scope.modal) d.showModal(); else d.show(); if(!angular.element(d).hasClass('sn-alert')) { $timeout(function() { if (d.dialogPolyfillInfo && d.dialogPolyfillInfo.backdrop) { angular.element(d.dialogPolyfillInfo.backdrop).one('click', function(event) { if (!scope.classCheck || angular.element(event.srcElement).closest(scope.classCheck).length == 0) scope.onClickClose(); }) } else { $document.on('click', function(event) { if (!scope.classCheck || angular.element(event.srcElement).closest(scope.classCheck).length == 0) scope.onClickClose(); }) } }); } element.find('.btn-primary').eq(0).focus(); }; scope.setPosition = function(data) { var contextData = scope.getContextData(data); if (contextData && element && element[0]) { if (contextData.position) { element[0].style.top = contextData.position.top + "px"; element[0].style.left = contextData.position.left + "px"; element[0].style.margin = "0px"; } if (contextData.dimensions) { element[0].style.width = contextData.dimensions.width + "px"; element[0].style.height = contextData.dimensions.height + "px"; } } } scope.$on("dialog." + attrs.name + ".move", function(event, data) { scope.setPosition(data); }) scope.$on("dialog." + attrs.name + ".show", function(event, data) { scope.setPosition(data); scope.setKeyEvents(data); if (scope.isOpen() === true) scope.close(); else scope.show(); angular.element(".sn-dialog-menu").each(function(index, value) { var name = angular.element(this).attr('name'); if(name != attrs.name && !angular.element(this).attr('open')) { return true; } if(name != attrs.name && angular.element(this).attr('open')) { $rootScope.$broadcast("dialog." + name + ".close"); } }); activateFocusTrap(); }) scope.onClickClose = function() { if (scope.isOpen()) $rootScope.$broadcast("dialog." + attrs.name + ".close"); } scope.escape = function($event) { if ($event.keyCode === 27) { scope.onClickClose(); } }; scope.close = function() { var d = element[0]; d.close(); scope.removeListeners(); deactivateFocusTrap(); } scope.ok = function(contextData) { contextData.ok(); scope.removeListeners(); } scope.cancel = function(contextData) { contextData.cancel(); scope.removeListeners(); } scope.removeListeners = function() { element[0].removeEventListener("ok", scope.handleContextOk, false); element[0].removeEventListener("cancel", scope.handleContextCancel, false); } scope.setKeyEvents = function(data) { var contextData = scope.getContextData(data); if (contextData && contextData.cancel) { scope.handleContextOk = function() { scope.ok(contextData); } scope.handleContextCancel = function() { scope.cancel(contextData); } element[0].addEventListener("ok", scope.handleContextOk, false); element[0].addEventListener("cancel", scope.handleContextCancel, false); } } scope.getContextData = function(data) { var context = attrs.context; var contextData = null; if (context && data && context in data) { contextData = data[context]; transcludeScope[context] = contextData; } return contextData; } scope.$on("dialog." + attrs.name + ".close", scope.close); function focusTrap(element) { var getSentinelElements = function() { var boundarySelector = '.sn-dialog-focus-trap-boundary'; var sentinelNodes = element.querySelectorAll(boundarySelector); return sentinelNodes; } var getTabbableElements = function (elm, selector) { var tabbables = window.tabbable ? window.tabbable(elm, selector) : []; return tabbables; }; var focusElement = function (reverse) { return function (e) { var selectors = 'iframe, input, select, a[href], textarea, button, [tabindex]:not(.sn-dialog-focus-trap-boundary), [contenteditable]:not([contenteditable="false"])'; var tabbables = getTabbableElements(element, selectors); if (tabbables.length === 0) return; var newTarget = reverse ? tabbables[tabbables.length - 1] : tabbables[0]; if (newTarget.tagName == "IFRAME") { var frameElements = getTabbableElements( newTarget.contentDocument ); if (frameElements.length > 0) newTarget = reverse ? frameElements[frameElements.length - 1] : frameElements[0]; } newTarget.focus(); }; }; var sentinelElements = getSentinelElements(); var topSentinelElement = sentinelElements[0]; var bottomSentinelElement = sentinelElements[1]; var nodeFocusedBeforeActivation = null; var forwardTrap = focusElement(true); var reverseTrap = focusElement(false); var activate = function () { nodeFocusedBeforeActivation = document.activeElement; topSentinelElement.addEventListener("focusin", forwardTrap); bottomSentinelElement.addEventListener("focusin", reverseTrap); }; var deactivate = function () { if(nodeFocusedBeforeActivation) nodeFocusedBeforeActivation.focus(); topSentinelElement.removeEventListener("focusin", forwardTrap); bottomSentinelElement.removeEventListener("focusin", reverseTrap); }; return { activate: activate, deactivate: deactivate, }; } function activateFocusTrap() { if (_focusTrap) return; _focusTrap = focusTrap(element[0]); _focusTrap.activate(); } function deactivateFocusTrap() { if (!_focusTrap) return; _focusTrap.deactivate(); _focusTrap = null; } } } }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snFlyout.js */ angular.module('sn.common.ui').directive('snFlyout', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', transclude: true, replace: 'true', templateUrl: getTemplateUrl('sn_flyout.xml'), scope: true, link: function($scope, element, attrs) { $scope.open = false; $scope.more = false; $scope.position = attrs.position || 'left'; $scope.flyoutControl = attrs.control; $scope.register = attrs.register; var body = angular.element('.flyout-body', element); var header = angular.element('.flyout-header', element); var tabs = angular.element('.flyout-tabs', element); var distance = 0; var position = $scope.position; var options = {duration: 800, easing: 'easeOutBounce'} var animation = {}; if ($scope.flyoutControl) { $('.flyout-handle', element).hide(); var controls = angular.element('#' + $scope.flyoutControl); controls.click(function() { angular.element(this).trigger("snFlyout.open"); }); controls.on('snFlyout.open', function() { $scope.$apply(function() { $scope.open = !$scope.open; }); }); } var animate = function() { element.velocity(animation, options); } var setup = function() { animation[position] = -distance; if ($scope.open) element.css(position, 0); else element.css(position, -distance); } var calculatePosition = function() { if ($scope.open) { animation[position] = 0; } else { if ($scope.position === 'left' || $scope.position === 'right') animation[position] = -body.outerWidth(); else animation[position] = -body.outerHeight(); } } $scope.$watch('open', function(newValue, oldValue) { if(newValue === oldValue) return; calculatePosition(); animate(); }); $scope.$watch('more', function(newValue, oldValue) { if (newValue === oldValue) return; var moreAnimation = {}; if ($scope.more) { element.addClass('fly-double'); moreAnimation = {width: body.outerWidth() * 2}; } else { element.removeClass('fly-double'); moreAnimation = {width: body.outerWidth() / 2}; } body.velocity(moreAnimation, options); header.velocity(moreAnimation, options); }); if ($scope.position === 'left' || $scope.position === 'right') { $scope.$watch(element[0].offsetWidth, function() { element.addClass('fly-from-' + $scope.position); distance = body.outerWidth(); setup(); }); } else if ($scope.position === 'top' || $scope.position === 'bottom') { $scope.$watch(element[0].offsetWidth, function() { element.addClass('fly-from-' + $scope.position); distance = body.outerHeight() + header.outerHeight(); setup(); }); } $scope.$on($scope.register + ".bounceTabByIndex", function(event, index) { $scope.bounceTab(index); }); $scope.$on($scope.register + ".bounceTab", function(event, tab) { $scope.bounceTab($scope.tabs.indexOf(tab)); }); $scope.$on($scope.register + ".selectTabByIndex", function(event, index) { $scope.selectTab($scope.tabs[index]); }); $scope.$on($scope.register + ".selectTab", function(event, tab) { $scope.selectTab(tab); }); }, controller: function($scope, $element) { $scope.tabs = []; var baseColor, highLightColor; $scope.selectTab = function(tab) { if ($scope.selectedTab) $scope.selectedTab.selected = false; tab.selected = true; $scope.selectedTab = tab; normalizeTab($scope.tabs.indexOf(tab)); } function expandTab(tabElem) { tabElem.queue("tabBounce", function(next) { tabElem.velocity({ width: ["2.5rem", "2.125rem"], backgroundColorRed: [highLightColor[0], baseColor[0]], backgroundColorGreen: [highLightColor[1], baseColor[1]], backgroundColorBlue: [highLightColor[2], baseColor[2]] },{ easing: "easeInExpo", duration: 250 }); next(); }); } function contractTab(tabElem) { tabElem.queue("tabBounce", function(next) { tabElem.velocity({ width: ["2.125rem","2.5rem"], backgroundColorRed: [baseColor[0], highLightColor[0]], backgroundColorGreen: [baseColor[1], highLightColor[1]], backgroundColorBlue: [baseColor[2], highLightColor[2]] },{ easing: "easeInExpo", duration: 250 }); next(); }); } $scope.bounceTab = function(index) { if(index >= $scope.tabs.length || index < 0) return; var tabScope = $scope.tabs[index]; if(!tabScope.selected) { var tabElem = $element.find('.flyout-tab').eq(index); if(!baseColor) { baseColor = tabElem.css('backgroundColor').match(/[0-9]+/g); for( var i = 0; i < baseColor.length; i++) baseColor[i] = parseInt(baseColor[i], 10); } if(!highLightColor) highLightColor = invertColor(baseColor); if(tabScope.highlighted) contractTab(tabElem); for(var i = 0; i < 2; i++) { expandTab(tabElem); contractTab(tabElem); } expandTab(tabElem); tabElem.dequeue("tabBounce"); tabScope.highlighted = true; } } $scope.toggleOpen = function() { $scope.open = !$scope.open; } this.addTab = function(tab) { $scope.tabs.push(tab); if($scope.tabs.length === 1) $scope.selectTab(tab) } function normalizeTab(index) { if(index < 0 || index >= $scope.tabs.length || !$scope.tabs[index].highlighted) return; var tabElem = $element.find('.flyout-tab').eq(index); tabElem.velocity({ width: ["2.125rem", "2.5rem"] },{ easing: "easeInExpo", duration: 250 }); tabElem.css('backgroundColor', ''); $scope.tabs[index].highlighted = false; } function invertColor(rgb) { if(typeof rgb === "string") var color = rgb.match(/[0-9]+/g); else var color = rgb.slice(0); for(var i = 0; i < color.length; i++) color[i] = 255 - parseInt(color[i], 10); return color; } } } }).directive("snFlyoutTab", function() { "use strict"; return { restrict: "E", require: "^snFlyout", replace: true, scope: true, transclude: true, template: "<div ng-show='selected' ng-transclude='' style='height: 100%'></div>", link: function(scope, element, attrs, flyoutCtrl) { flyoutCtrl.addTab(scope); } } }) ; /*! RESOURCE: /scripts/sn/common/ui/directive.snModal.js */ angular.module("sn.common.ui").directive("snModal", function($timeout, $rootScope) { "use strict"; return { restrict: "AE", transclude: true, scope: {}, replace: true, template: '<div tabindex="-1" aria-modal="true" aria-hidden="true" class="modal" role="dialog"></div>', link: function(scope, element, attrs, ctrl, transcludeFn) { var transcludeScope = {}; transcludeFn(element.scope().$new(), function(a, b) { element.append(a); element.append('<i class="focus-trap-boundary-south" tabindex="0"></i>'); transcludeScope = b; }); scope.$on("dialog." + attrs.name + ".show", function(event, data) { if (!isOpen()) show(data); }); scope.$on("dialog." + attrs.name + ".close", function() { if (isOpen()) close(); }); function eventFn(eventName) { return function (e) { $rootScope.$broadcast("dialog." + attrs.name + "." + eventName, e); } } var events = { 'shown.bs.modal' : eventFn("opened"), 'hide.bs.modal' : eventFn("hide"), 'hidden.bs.modal' : eventFn("closed") }; function show(data) { var context = attrs.context; var contextData = null; if (context && data && context in data) { contextData = data[context]; transcludeScope[context] = contextData; } $timeout(function() { angular.element('.sn-popover-basic').each(function () { var $this = angular.element(this); if (angular.element($this.attr('data-target')).is(':visible')) { $this.popover('hide'); } }); }); element.modal('show'); element.attr('aria-hidden', 'false'); for (var event in events) if(events.hasOwnProperty(event)) element.on(event, events[event]); if (attrs.moveBackdrop == 'true') moveBackdrop(element); } function close() { element.modal('hide'); element.attr('aria-hidden', 'true'); for (var event in events) if(events.hasOwnProperty(event)) element.off(event, events[event]); } function isOpen() { return element.hasClass('in'); } function moveBackdrop(element) { var backdrop = element.data('bs.modal').$backdrop; if (!backdrop) return; element.after(backdrop.remove()); } } } }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snModalShow.js */ angular.module('sn.common.ui').directive('snModalShow', function() { "use strict"; return { restrict: 'A', link: function(scope, element, attrs) { element.click(function() { showDialog(); }); function showDialog() { scope.$broadcast('dialog.' + attrs.snModalShow + '.show'); } } } }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snTabs.js */ angular.module('sn.common.ui').directive('snTabs', function() { 'use strict'; return { restrict: 'E', transclude: true, replace: 'true', scope: { tabData: '=' }, link: function($scope, element, attrs) { $scope.tabClass = attrs.tabClass; $scope.register = attrs.register; attrs.$observe('register', function(value) { $scope.register = value; $scope.setupListeners(); }); $scope.bounceTab = function() { angular.element() } }, controller: 'snTabs' } }).controller('snTabs', function($scope, $rootScope) { $scope.selectedTabIndex = 0; $scope.tabData[$scope.selectedTabIndex].selected = true; $scope.setupListeners = function() { $scope.$on($scope.register + '.selectTabByIndex', function(event, index) { $scope.selectTabByIndex(event, index); }); } $scope.selectTabByIndex = function(event, index) { if (index === $scope.selectedTabIndex) return; if (event.stopPropagation) event.stopPropagation(); $scope.tabData[$scope.selectedTabIndex].selected = false; $scope.tabData[index].selected = true; $scope.selectedTabIndex = index; $rootScope.$broadcast($scope.register + '.selectTabByIndex', $scope.selectedTabIndex); } }).directive('snTab', function() { 'use strict'; return { restrict: 'E', transclude: true, replace: 'true', scope: { tabData: '=', index: '=' }, template: '', controller: 'snTab', link: function($scope, element, attrs) { $scope.register = attrs.register; attrs.$observe('register', function(value) { $scope.register = value; $scope.setupListeners(); }); $scope.bounceTab = function() { alert('Bounce Tab at Index: ' + $scope.index); } } } }).controller('snTab', function($scope) { $scope.selectTabByIndex = function(index) { $scope.$emit($scope.register + '.selectTabByIndex', index); } $scope.setupListeners = function() { $scope.$on($scope.register + '.showTabActivity', function(event, index, type) { $scope.showTabActivity(index, type); }); } $scope.showTabActivity = function(index, type) { if ($scope.index !== index) return; switch (type) { case 'message': break; case 'error': break; default: $scope.bounceTab(); } } }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snTextExpander.js */ angular.module('sn.common.ui').directive('snTextExpander', function(getTemplateUrl, $timeout) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('sn_text_expander.xml'), scope: { maxHeight: '&', value: '=' }, link: function compile(scope, element, attrs) { var container = angular.element(element).find('.textblock-content-container'); var content = angular.element(element).find('.textblock-content'); if (scope.maxHeight() === undefined) { scope.maxHeight = function () { return 100; } } container.css('overflow-y', 'hidden'); container.css('max-height', scope.maxHeight() + 'px'); }, controller: function ($scope, $element) { var container = $element.find('.textblock-content-container'); var content = $element.find('.textblock-content'); $scope.value = $scope.value || ''; $scope.toggleExpand = function () { $scope.showMore = !$scope.showMore; if ($scope.showMore) { container.css('max-height', content.height()); } else { container.css('max-height', $scope.maxHeight()); } }; $timeout(function () { if (content.height() > $scope.maxHeight()) { $scope.showToggle = true; $scope.showMore = false; } }); } }; }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snAttachmentPreview.js */ angular.module('sn.common.ui').directive('snAttachmentPreview', function(getTemplateUrl, snCustomEvent) { return { restrict: 'E', templateUrl: getTemplateUrl('sn_attachment_preview.xml'), controller: function($scope) { snCustomEvent.observe('sn.attachment.preview', function(evt, attachment) { if (evt.stopPropagation) evt.stopPropagation(); if (evt.preventDefault) evt.preventDefault(); $scope.image = attachment; $scope.$broadcast('dialog.attachment_preview.show'); return false; }); } } }); ; /*! RESOURCE: /scripts/sn/common/ui/service.progressDialog.js */ angular.module('sn.common.ui').factory('progressDialog', ['$rootScope', '$compile', '$timeout', '$http', '$templateCache', 'nowServer', 'i18n', function($rootScope, $compile, $timeout, $http, $templateCache, nowServer, i18n) { 'use strict'; i18n.getMessages(['Close']); return { STATES : ["Pending", "Running", "Succeeded", "Failed", "Cancelled" ], STATUS_IMAGES : ["images/workflow_skipped.gif", "images/loading_anim2.gifx", "images/progress_success.png", "images/progress_failure.png", 'images/request_cancelled.gif' ], EXPAND_IMAGE : "images/icons/filter_hide.gif", COLLAPSE_IMAGE : "images/icons/filter_reveal.gif", BACK_IMAGE : "images/activity_filter_off.gif", TIMEOUT_INTERVAL : 750, _findChildMessage: function( statusObject ) { if ( !statusObject.children ) return null; for ( var i = 0; i < statusObject.children.length; i++ ) { var child = statusObject.children[i]; if ( child.state == '1' ) { var msg = child.message; var submsg = this._findChildMessage( child ); if ( submsg == null ) return msg; else return null; } else if ( child.state == '0' ) { return null; } else { } } return null; }, create: function(scope, elemid, title, startCallback, endCallback, closeCallback) { var namespace = this; var progressItem = scope.$new(true); progressItem.id = elemid + "_progressDialog"; progressItem.overlayVisible = true; progressItem.state = 0; progressItem.message = ''; progressItem.percentComplete = 0; progressItem.enableChildMessages = false; if (!title) title = ''; progressItem.title = title; progressItem.button_close = i18n.getMessage('Close'); var overlayElement; overlayElement = $compile( '<div id="{{id}}" ng-show="overlayVisible" class="modal modal-mask" role="dialog" tabindex="-1">' + '<div class="modal-dialog m_progress_overlay_content">' + '<div class="modal-content">' + '<header class="modal-header">' + '<h4 class="modal-title">{{title}}</h4>' + '</header>' + '<div class="modal-body">' + '<div class="progress" ng-class="{\'progress-danger\': (state == 3)}">' + '<div class="progress-bar" ng-class="{\'progress-bar-danger\': (state == 3)}" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{percentComplete}}" ng-style="{width: percentComplete + \'%\'}">' + '</div>' + '</div>' + '<div>{{message}}<span style="float: right;" ng-show="state==1 || state == 2">{{percentComplete}}%</span></div>' + '</div>' + '<footer class="modal-footer">' + '<button class="btn btn-default sn-button sn-button-normal" ng-click="close()" ng-show="state > 1">{{button_close}}</button>' + '</footer>' + '</div>' + '</div>' + '</div>')(progressItem); $("body")[0].appendChild(overlayElement[0]); progressItem.setEnableChildMessages = function( enableChildren ) { progressItem.enableChildMessages = enableChildren; } progressItem.start = function( src, dataArray ) { $http.post(src, dataArray).success(function(response) { progressItem.trackerId = response.sys_id; try { if ( startCallback ) startCallback(response); } catch(e) { } $timeout(progressItem.checkProgress.bind(progressItem)); }) .error(function(response, status, headers, config) { progressItem.state = '3'; if (endCallback) endCallback( response ); }); }; progressItem.checkProgress = function() { var src = nowServer.getURL('progress_status', {sysparm_execution_id: this.trackerId}); $http.post(src).success(function(response) { if ( $.isEmptyObject(response) ) { progressItem.state = '3'; if (endCallback) endCallback( response ); return; } progressItem.update( response ); if (response.status == 'error' || response.state == '') { progressItem.state = '3'; if ( response.message ) progressItem.message = response.message; else progressItem.message = response; if (endCallback) endCallback( response ); return; } if ( response.state == '0' || response.state == '1' ) { $timeout(progressItem.checkProgress.bind(progressItem), namespace.TIMEOUT_INTERVAL); } else { if (endCallback) endCallback( response ); } }) .error(function(response, status, headers, config) { progressItem.state = '3'; progressItem.message = response; if (endCallback) endCallback( response ); }); }; progressItem.update = function( statusObject ) { var msg = statusObject.message; if ( progressItem.enableChildMessages ) { var childMsg = namespace._findChildMessage( statusObject ); if ( childMsg != null ) msg = childMsg; } this.message = msg; this.state = statusObject.state; this.percentComplete = statusObject.percent_complete; }; progressItem.close = function(ev) { try { if (closeCallback) closeCallback(); } catch(e) { } $("body")[0].removeChild($("#" + this.id)[0]); delete namespace.progressItem; }; return progressItem; } } }]); ; /*! RESOURCE: /scripts/sn/common/ui/factory.paneManager.js */ angular.module("sn.common.ui").factory("paneManager", ['$timeout', 'userPreferences', 'snCustomEvent', function($timeout, userPreferences, snCustomEvent) { "use strict"; var paneIndex = {}; function registerPane(paneName) { if (!paneName in paneIndex) { paneIndex[paneName] = false; } userPreferences.getPreference(paneName + '.opened').then(function(value) { var isOpen = value !== 'false'; if (isOpen) { togglePane(paneName, false); } }); } function togglePane(paneName, autoFocusPane) { for (var currentPane in paneIndex) { if (paneName != currentPane && paneIndex[currentPane]) { CustomEvent.fireTop(currentPane + '.toggle'); saveState(currentPane, false); } } snCustomEvent.fireTop(paneName + '.toggle', false, autoFocusPane); saveState(paneName, !paneIndex[paneName]); }; function saveState(paneName, state) { paneIndex[paneName] = state; userPreferences.setPreference(paneName + '.opened', state); } return { registerPane : registerPane, togglePane : togglePane }; }]); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snBootstrapPopover.js */ angular.module('sn.common.ui').directive('snBootstrapPopover', function ($timeout, $compile, $rootScope) { 'use strict'; return { restrict: 'A', link: function (scope, element) { element.on('click.snBootstrapPopover', function (event) { $rootScope.$broadcast('sn-bootstrap-popover.close-other-popovers'); createPopover(event); }); element.on('keypress.snBootstrapPopover', function (event) { if (event.keyCode != 13 && event.keyCode != 32) return; if (event.keyCode === 32 ) { event.preventDefault(); } scope.$broadcast('sn-bootstrap-popover.close-other-popovers'); createPopover(event); }); var popoverOpen = false; function _hidePopover() { popoverOpen = false; var api = element.data('bs.popover'); if (api) { api.hide(); element.off('.popover').removeData('bs.popover'); element.data('bs.popover', void(0)); element.focus(); } } function _openPopover() { $timeout(function () { popoverOpen = true; element.on('hidden.bs.popover', function () { _hidePopover(); popoverOpen = false; }); element.popover('show'); var popoverBody = angular.element(document.getElementById('sn-bootstrap-popover')); popoverBody.focus(); popoverBody.on('keydown', function (e) { if (e.keyCode === 27) { popoverBody.off('keydown'); _hidePopover(); } }); }, 0, false); } function createPopover (evt) { angular.element('.popover').each(function () { var object = angular.element(this); if (!object.is(evt.target) && object.has(evt.target).length === 0 && angular.element('.popover').has(evt.target).length === 0) { _hidePopover(); object.popover('hide'); } }); if (scope.disablePopover || evt.keyCode === 9) return; if (popoverOpen) { _hidePopover(); return; } var childScope = scope.$new(); evt.stopPropagation(); element.attr('data-toggle', 'popover'); element.attr('data-trigger','focus'); element.attr('tabindex',0); angular.element(element).popover({ container: 'body', placement: 'auto top', html: true, trigger: 'manual', content: $compile(scope.template)(childScope) }); var wait = element.attr('popover-wait-event'); if (wait) scope.$on(wait, _openPopover); else _openPopover(); var bodyClickEvent = angular.element('body').on('click.snBootstrapPopover.body', function (evt) { angular.element('.popover').each(function () { var object = angular.element(this); if (!object.is(evt.target) && object.has(evt.target).length === 0 && angular.element('.popover').has(evt.target).length === 0) { bodyClickEvent.off(); _hidePopover(); childScope.$destroy(); } }) }); element.on('$destroy', function () { bodyClickEvent.off(); _hidePopover(); childScope.$destroy(); }) }; } } }); ; /*! RESOURCE: /scripts/sn/common/ui/directive.snFocusEsc.js */ angular.module('sn.common.ui').directive('snFocusEsc', function($document) { 'use strict'; return { restrict: 'A', scope: false, link: function (scope, element, attrs) { $document.on('keyup', function($event) { if ($event.keyCode === 27 ) { var focusedElement = $event.target; if (focusedElement && element[0].contains(focusedElement)) { scope.$eval(attrs.snFocusEsc); } } }); } }; }); ; ; /*! RESOURCE: /scripts/sn/common/stream/js_includes_stream.js */ /*! RESOURCE: /scripts/thirdparty/ment.io/mentio.js */ (function() { 'use strict'; angular.module('mentio', []) .directive('mentio', ['mentioUtil', '$document', '$compile', '$log', '$timeout', function (mentioUtil, $document, $compile, $log, $timeout) { return { restrict: 'A', scope: { macros: '=mentioMacros', search: '&mentioSearch', select: '&mentioSelect', items: '=mentioItems', typedTerm: '=mentioTypedTerm', altId: '=mentioId', iframeElement: '=mentioIframeElement', requireLeadingSpace: '=mentioRequireLeadingSpace', suppressTrailingSpace: '=mentioSuppressTrailingSpace', selectNotFound: '=mentioSelectNotFound', trimTerm: '=mentioTrimTerm', ngModel: '=' }, controller: ["$scope", "$timeout", "$attrs", function($scope, $timeout, $attrs) { $scope.query = function (triggerChar, triggerText) { var remoteScope = $scope.triggerCharMap[triggerChar]; if ($scope.trimTerm === undefined || $scope.trimTerm) { triggerText = triggerText.trim(); } remoteScope.showMenu(); remoteScope.search({ term: triggerText }); remoteScope.typedTerm = triggerText; }; $scope.defaultSearch = function(locals) { var results = []; angular.forEach($scope.items, function(item) { if (item.label.toUpperCase().indexOf(locals.term.toUpperCase()) >= 0) { results.push(item); } }); $scope.localItems = results; }; $scope.bridgeSearch = function(termString) { var searchFn = $attrs.mentioSearch ? $scope.search : $scope.defaultSearch; searchFn({ term: termString }); }; $scope.defaultSelect = function(locals) { return $scope.defaultTriggerChar + locals.item.label; }; $scope.bridgeSelect = function(itemVar) { var selectFn = $attrs.mentioSelect ? $scope.select : $scope.defaultSelect; return selectFn({ item: itemVar }); }; $scope.setTriggerText = function(text) { if ($scope.syncTriggerText) { $scope.typedTerm = ($scope.trimTerm === undefined || $scope.trimTerm) ? text.trim() : text; } }; $scope.context = function() { if ($scope.iframeElement) { return {iframe: $scope.iframeElement}; } }; $scope.replaceText = function (text, hasTrailingSpace) { $scope.hideAll(); mentioUtil.replaceTriggerText($scope.context(), $scope.targetElement, $scope.targetElementPath, $scope.targetElementSelectedOffset, $scope.triggerCharSet, text, $scope.requireLeadingSpace, hasTrailingSpace, $scope.suppressTrailingSpace); if (!hasTrailingSpace) { $scope.setTriggerText(''); angular.element($scope.targetElement).triggerHandler('change'); if ($scope.isContentEditable()) { $scope.contentEditableMenuPasted = true; var timer = $timeout(function() { $scope.contentEditableMenuPasted = false; }, 200); $scope.$on('$destroy', function() { $timeout.cancel(timer); }); } } }; $scope.hideAll = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { $scope.triggerCharMap[key].hideMenu(); } } }; $scope.getActiveMenuScope = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { if ($scope.triggerCharMap[key].visible) { return $scope.triggerCharMap[key]; } } } return null; }; $scope.selectActive = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { if ($scope.triggerCharMap[key].visible) { $scope.triggerCharMap[key].selectActive(); } } } }; $scope.isActive = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { if ($scope.triggerCharMap[key].visible) { return true; } } } return false; }; $scope.isContentEditable = function() { return ($scope.targetElement.nodeName !== 'INPUT' && $scope.targetElement.nodeName !== 'TEXTAREA'); }; $scope.replaceMacro = function(macro, hasTrailingSpace) { if (!hasTrailingSpace) { $scope.replacingMacro = true; $scope.timer = $timeout(function() { mentioUtil.replaceMacroText($scope.context(), $scope.targetElement, $scope.targetElementPath, $scope.targetElementSelectedOffset, $scope.macros, $scope.macros[macro]); angular.element($scope.targetElement).triggerHandler('change'); $scope.replacingMacro = false; }, 300); $scope.$on('$destroy', function() { $timeout.cancel($scope.timer); }); } else { mentioUtil.replaceMacroText($scope.context(), $scope.targetElement, $scope.targetElementPath, $scope.targetElementSelectedOffset, $scope.macros, $scope.macros[macro]); } }; $scope.addMenu = function(menuScope) { if (menuScope.parentScope && $scope.triggerCharMap.hasOwnProperty(menuScope.triggerChar)) { return; } $scope.triggerCharMap[menuScope.triggerChar] = menuScope; if ($scope.triggerCharSet === undefined) { $scope.triggerCharSet = []; } $scope.triggerCharSet.push(menuScope.triggerChar); menuScope.setParent($scope); }; $scope.$on( 'menuCreated', function (event, data) { if ( $attrs.id !== undefined || $attrs.mentioId !== undefined ) { if ( $attrs.id === data.targetElement || ( $attrs.mentioId !== undefined && $scope.altId === data.targetElement ) ) { $scope.addMenu(data.scope); } } } ); $document.on( 'click', function () { if ($scope.isActive()) { $scope.$apply(function () { $scope.hideAll(); }); } } ); $document.on( 'keydown keypress paste', function (event) { var activeMenuScope = $scope.getActiveMenuScope(); if (activeMenuScope) { if (event.which === 9 || event.which === 13) { event.preventDefault(); activeMenuScope.selectActive(); } if (event.which === 27) { event.preventDefault(); activeMenuScope.$apply(function () { activeMenuScope.hideMenu(); }); } if (event.which === 40) { event.preventDefault(); activeMenuScope.$apply(function () { activeMenuScope.activateNextItem(); }); activeMenuScope.adjustScroll(1); } if (event.which === 38) { event.preventDefault(); activeMenuScope.$apply(function () { activeMenuScope.activatePreviousItem(); }); activeMenuScope.adjustScroll(-1); } if (event.which === 37 || event.which === 39) { event.preventDefault(); } } } ); }], link: function (scope, element, attrs, $timeout) { scope.triggerCharMap = {}; scope.targetElement = element; scope.scrollBarParents = element.parents().filter(function() { var overflow = angular.element(this).css("overflow"); return this.scrollHeight > this.clientHeight && overflow !== "hidden" && overflow !== "visible"; }); scope.scrollPosition = null; attrs.$set('autocomplete','off'); if (attrs.mentioItems) { scope.localItems = []; scope.parentScope = scope; var itemsRef = attrs.mentioSearch ? ' mentio-items="items"' : ' mentio-items="localItems"'; scope.defaultTriggerChar = attrs.mentioTriggerChar ? scope.$eval(attrs.mentioTriggerChar) : '@'; var html = '<mentio-menu' + ' mentio-search="bridgeSearch(term)"' + ' mentio-select="bridgeSelect(item)"' + itemsRef; if (attrs.mentioTemplateUrl) { html = html + ' mentio-template-url="' + attrs.mentioTemplateUrl + '"'; } html = html + ' mentio-trigger-char="\'' + scope.defaultTriggerChar + '\'"' + ' mentio-parent-scope="parentScope"' + '/>'; var linkFn = $compile(html); var el = linkFn(scope); element.parent().append(el); scope.$on('$destroy', function() { el.remove(); }); } if (attrs.mentioTypedTerm) { scope.syncTriggerText = true; } function keyHandler(event) { function stopEvent(event) { event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); } var activeMenuScope = scope.getActiveMenuScope(); if (activeMenuScope) { if (event.which === 9 || event.which === 13) { stopEvent(event); activeMenuScope.selectActive(); return false; } if (event.which === 27) { stopEvent(event); activeMenuScope.$apply(function () { activeMenuScope.hideMenu(); }); return false; } if (event.which === 40) { stopEvent(event); activeMenuScope.$apply(function () { activeMenuScope.activateNextItem(); }); activeMenuScope.adjustScroll(1); return false; } if (event.which === 38) { stopEvent(event); activeMenuScope.$apply(function () { activeMenuScope.activatePreviousItem(); }); activeMenuScope.adjustScroll(-1); return false; } if (event.which === 37 || event.which === 39) { stopEvent(event); return false; } } } scope.$watch( 'iframeElement', function(newValue) { if (newValue) { var iframeDocument = newValue.contentWindow.document; iframeDocument.addEventListener('click', function () { if (scope.isActive()) { scope.$apply(function () { scope.hideAll(); }); } } ); iframeDocument.addEventListener('keydown', keyHandler, true ); scope.$on ( '$destroy', function() { iframeDocument.removeEventListener ( 'keydown', keyHandler ); }); } } ); scope.$watch( 'ngModel', function (newValue) { if ((!newValue || newValue === '') && !scope.isActive()) { return; } if (scope.triggerCharSet === undefined) { $log.warn('Error, no mentio-items attribute was provided, ' + 'and no separate mentio-menus were specified. Nothing to do.'); return; } if (scope.contentEditableMenuPasted) { scope.contentEditableMenuPasted = false; return; } if (scope.replacingMacro) { $timeout.cancel(scope.timer); scope.replacingMacro = false; } var isActive = scope.isActive(); var isContentEditable = scope.isContentEditable(); var mentionInfo = mentioUtil.getTriggerInfo(scope.context(), scope.triggerCharSet, scope.requireLeadingSpace, isActive); if (mentionInfo !== undefined && ( !isActive || (isActive && ( (isContentEditable && mentionInfo.mentionTriggerChar === scope.currentMentionTriggerChar) || (!isContentEditable && mentionInfo.mentionPosition === scope.currentMentionPosition) ) ) ) ) { if (mentionInfo.mentionSelectedElement) { scope.targetElement = mentionInfo.mentionSelectedElement; scope.targetElementPath = mentionInfo.mentionSelectedPath; scope.targetElementSelectedOffset = mentionInfo.mentionSelectedOffset; } scope.setTriggerText(mentionInfo.mentionText); scope.currentMentionPosition = mentionInfo.mentionPosition; scope.currentMentionTriggerChar = mentionInfo.mentionTriggerChar; scope.query(mentionInfo.mentionTriggerChar, mentionInfo.mentionText); } else { var currentTypedTerm = scope.typedTerm; scope.setTriggerText(''); scope.hideAll(); var macroMatchInfo = mentioUtil.getMacroMatch(scope.context(), scope.macros); if (macroMatchInfo !== undefined) { scope.targetElement = macroMatchInfo.macroSelectedElement; scope.targetElementPath = macroMatchInfo.macroSelectedPath; scope.targetElementSelectedOffset = macroMatchInfo.macroSelectedOffset; scope.replaceMacro(macroMatchInfo.macroText, macroMatchInfo.macroHasTrailingSpace); } else if (scope.selectNotFound && currentTypedTerm && currentTypedTerm !== '') { var lastScope = scope.triggerCharMap[scope.currentMentionTriggerChar]; if (lastScope) { var text = lastScope.select({ item: {label: currentTypedTerm} }); if (typeof text.then === 'function') { text.then(scope.replaceText); } else { scope.replaceText(text, true); } } } } } ); } }; }]) .directive('mentioMenu', ['mentioUtil', '$rootScope', '$log', '$window', '$document', '$timeout', function (mentioUtil, $rootScope, $log, $window, $document, $timeout) { return { restrict: 'E', scope: { search: '&mentioSearch', select: '&mentioSelect', items: '=mentioItems', triggerChar: '=mentioTriggerChar', forElem: '=mentioFor', parentScope: '=mentioParentScope' }, templateUrl: function(tElement, tAttrs) { return tAttrs.mentioTemplateUrl !== undefined ? tAttrs.mentioTemplateUrl : 'mentio-menu.tpl.html'; }, controller: ["$scope", function ($scope) { $scope.visible = false; this.activate = $scope.activate = function (item) { $scope.activeItem = item; }; this.isActive = $scope.isActive = function (item) { return $scope.activeItem === item; }; this.selectItem = $scope.selectItem = function (item) { if (item.termLengthIsZero) { item.name = $scope.triggerChar + $scope.typedTerm } var text = $scope.select({ item: item }); if (typeof text.then === 'function') { text.then($scope.parentMentio.replaceText); } else { $scope.parentMentio.replaceText(text); } }; $scope.activateNextItem = function () { var index = $scope.items.indexOf($scope.activeItem); this.activate($scope.items[(index + 1) % $scope.items.length]); }; $scope.activatePreviousItem = function () { var index = $scope.items.indexOf($scope.activeItem); this.activate($scope.items[index === 0 ? $scope.items.length - 1 : index - 1]); }; $scope.isFirstItemActive = function () { var index = $scope.items.indexOf($scope.activeItem); return index === 0; }; $scope.isLastItemActive = function () { var index = $scope.items.indexOf($scope.activeItem); return index === ($scope.items.length - 1); }; $scope.selectActive = function () { $scope.selectItem($scope.activeItem); }; $scope.isVisible = function () { return $scope.visible; }; $scope.showMenu = function () { if (!$scope.visible) { $scope.menuElement.css("visibility", "visible"); $scope.requestVisiblePendingSearch = true; } }; $scope.setParent = function (scope) { $scope.parentMentio = scope; $scope.targetElement = scope.targetElement; }; var scopeDuplicate = $scope; $rootScope.$on('mentio.closeMenu', function () { scopeDuplicate.hideMenu(); }) }], link: function (scope, element) { element[0].parentNode.removeChild(element[0]); $document[0].body.appendChild(element[0]); scope.menuElement = element; scope.menuElement.css("visibility", "hidden"); if (scope.parentScope) { scope.parentScope.addMenu(scope); } else { if (!scope.forElem) { $log.error('mentio-menu requires a target element in tbe mentio-for attribute'); return; } if (!scope.triggerChar) { $log.error('mentio-menu requires a trigger char'); return; } $rootScope.$broadcast('menuCreated', { targetElement : scope.forElem, scope : scope }); } angular.element($window).bind( 'resize', function () { if (scope.isVisible()) { var triggerCharSet = []; triggerCharSet.push(scope.triggerChar); mentioUtil.popUnderMention(scope.parentMentio.context(), triggerCharSet, element, scope.requireLeadingSpace); } } ); scope.$watch('items', function (items) { if (items && items.length > 0) { scope.activate(items[0]); if (!scope.visible && scope.requestVisiblePendingSearch) { scope.visible = true; scope.requestVisiblePendingSearch = false; } $timeout(function() { var menu = element.find(".dropdown-menu"); if(menu.length > 0 && menu.offset().top < 0) menu.addClass("reverse"); }, 0, false); } else { scope.activate({ termLengthIsZero: true }); } }); scope.$watch('isVisible()', function (visible) { if (visible) { var triggerCharSet = []; triggerCharSet.push(scope.triggerChar); mentioUtil.popUnderMention(scope.parentMentio.context(), triggerCharSet, element, scope.requireLeadingSpace); } else { element.find(".dropdown-menu").removeClass("reverse"); } }); var prevScroll; scope.parentMentio.scrollBarParents.each(function() { angular.element(this).on("scroll.mentio", function() { if (!prevScroll) prevScroll = this.scrollTop; var scrollDiff = prevScroll - this.scrollTop; prevScroll = this.scrollTop; if (element[0].style["position"] === "absolute") { element[0].style["z-index"] = 9; element[0].style.top = (parseInt(element[0].style.top) + scrollDiff) + "px"; } }); }); scope.parentMentio.$on('$destroy', function () { element.remove(); }); scope.hideMenu = function () { scope.visible = false; element.css('display', 'none'); }; scope.adjustScroll = function (direction) { var menuEl = element[0]; var menuItemsList = menuEl.querySelector('ul'); var menuItem = menuEl.querySelector('[mentio-menu-item].active'); if (scope.isFirstItemActive()) { return menuItemsList.scrollTop = 0; } else if(scope.isLastItemActive()) { return menuItemsList.scrollTop = menuItemsList.scrollHeight; } if (direction === 1) { menuItemsList.scrollTop += menuItem.offsetHeight; } else { menuItemsList.scrollTop -= menuItem.offsetHeight; } }; } }; }]) .directive('mentioMenuItem', function () { return { restrict: 'A', scope: { item: '=mentioMenuItem' }, require: '^mentioMenu', link: function (scope, element, attrs, controller) { scope.$watch(function () { return controller.isActive(scope.item); }, function (active) { if (active) { element.addClass('active'); } else { element.removeClass('active'); } }); element.bind('mouseenter', function () { scope.$apply(function () { controller.activate(scope.item); }); }); element.bind('click', function () { controller.selectItem(scope.item); return false; }); } }; }) .filter('unsafe', ["$sce", function($sce) { return function (val) { return $sce.trustAsHtml(val); }; }]) .filter('mentioHighlight', function() { function escapeRegexp (queryToEscape) { return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } return function (matchItem, query, hightlightClass) { if (query) { var replaceText = hightlightClass ? '<span class="' + hightlightClass + '">$&</span>' : '<strong>$&</strong>'; return ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), replaceText); } else { return matchItem; } }; }); 'use strict'; angular.module('mentio') .factory('mentioUtil', ["$window", "$location", "$anchorScroll", "$timeout", function ($window, $location, $anchorScroll, $timeout) { function popUnderMention (ctx, triggerCharSet, selectionEl, requireLeadingSpace) { var coordinates; var mentionInfo = getTriggerInfo(ctx, triggerCharSet, requireLeadingSpace, false); if (mentionInfo !== undefined) { if (selectedElementIsTextAreaOrInput(ctx)) { coordinates = getTextAreaOrInputUnderlinePosition(ctx, getDocument(ctx).activeElement, mentionInfo.mentionPosition); } else { coordinates = getContentEditableCaretPosition(ctx, mentionInfo.mentionPosition); } selectionEl.css({ top: coordinates.top + 'px', left: coordinates.left + 'px', position: 'absolute', zIndex: 5000, display: 'block' }); $timeout(function(){ scrollIntoView(ctx, selectionEl); },0); } else { selectionEl.css({ display: 'none' }); } } function scrollIntoView(ctx, elem) { var reasonableBuffer = 20; var maxScrollDisplacement = 100; var clientRect; var e = elem[0]; while (clientRect === undefined || clientRect.height === 0) { clientRect = e.getBoundingClientRect(); if (clientRect.height === 0) { e = e.childNodes[0]; if (e === undefined || !e.getBoundingClientRect) { return; } } } var elemTop = clientRect.top; var elemBottom = elemTop + clientRect.height; if(elemTop < 0) { $window.scrollTo(0, $window.pageYOffset + clientRect.top - reasonableBuffer); } else if (elemBottom > $window.innerHeight) { var maxY = $window.pageYOffset + clientRect.top - reasonableBuffer; if (maxY - $window.pageYOffset > maxScrollDisplacement) { maxY = $window.pageYOffset + maxScrollDisplacement; } var targetY = $window.pageYOffset - ($window.innerHeight - elemBottom); if (targetY > maxY) { targetY = maxY; } $window.scrollTo(0, targetY); } } function selectedElementIsTextAreaOrInput (ctx) { var element = getDocument(ctx).activeElement; if (element !== null) { var nodeName = element.nodeName; var type = element.getAttribute('type'); return (nodeName === 'INPUT' && type === 'text') || nodeName === 'TEXTAREA'; } return false; } function selectElement (ctx, targetElement, path, offset) { var range; var elem = targetElement; if (path) { for (var i = 0; i < path.length; i++) { elem = elem.childNodes[path[i]]; if (elem === undefined) { return; } while (elem.length < offset) { offset -= elem.length; elem = elem.nextSibling; } if (elem.childNodes.length === 0 && !elem.length) { elem = elem.previousSibling; } } } var sel = getWindowSelection(ctx); range = getDocument(ctx).createRange(); range.setStart(elem, offset); range.setEnd(elem, offset); range.collapse(true); try{sel.removeAllRanges();}catch(error){} sel.addRange(range); targetElement.focus(); } function pasteHtml (ctx, html, startPos, endPos) { var range, sel; sel = getWindowSelection(ctx); range = getDocument(ctx).createRange(); range.setStart(sel.anchorNode, startPos); range.setEnd(sel.anchorNode, endPos); range.deleteContents(); var el = getDocument(ctx).createElement('div'); el.innerHTML = html; var frag = getDocument(ctx).createDocumentFragment(), node, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } range.insertNode(frag); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } function resetSelection (ctx, targetElement, path, offset) { var nodeName = targetElement.nodeName; if (nodeName === 'INPUT' || nodeName === 'TEXTAREA') { if (targetElement !== getDocument(ctx).activeElement) { targetElement.focus(); } } else { selectElement(ctx, targetElement, path, offset); } } function replaceMacroText (ctx, targetElement, path, offset, macros, text) { resetSelection(ctx, targetElement, path, offset); var macroMatchInfo = getMacroMatch(ctx, macros); if (macroMatchInfo.macroHasTrailingSpace) { macroMatchInfo.macroText = macroMatchInfo.macroText + '\xA0'; text = text + '\xA0'; } if (macroMatchInfo !== undefined) { var element = getDocument(ctx).activeElement; if (selectedElementIsTextAreaOrInput(ctx)) { var startPos = macroMatchInfo.macroPosition; var endPos = macroMatchInfo.macroPosition + macroMatchInfo.macroText.length; element.value = element.value.substring(0, startPos) + text + element.value.substring(endPos, element.value.length); element.selectionStart = startPos + text.length; element.selectionEnd = startPos + text.length; } else { pasteHtml(ctx, text, macroMatchInfo.macroPosition, macroMatchInfo.macroPosition + macroMatchInfo.macroText.length); } } } function replaceTriggerText (ctx, targetElement, path, offset, triggerCharSet, text, requireLeadingSpace, hasTrailingSpace, suppressTrailingSpace) { resetSelection(ctx, targetElement, path, offset); var mentionInfo = getTriggerInfo(ctx, triggerCharSet, requireLeadingSpace, true, hasTrailingSpace); if (mentionInfo !== undefined) { if (selectedElementIsTextAreaOrInput()) { var myField = getDocument(ctx).activeElement; if (!suppressTrailingSpace) { text = text + ' '; } var startPos = mentionInfo.mentionPosition; var endPos = mentionInfo.mentionPosition + mentionInfo.mentionText.length + 1; myField.value = myField.value.substring(0, startPos) + text + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + text.length; myField.selectionEnd = startPos + text.length; } else { if (!suppressTrailingSpace) { text = text + '\xA0'; } pasteHtml(ctx, text, mentionInfo.mentionPosition, mentionInfo.mentionPosition + mentionInfo.mentionText.length + 1); } } } function getNodePositionInParent (ctx, elem) { if (elem.parentNode === null) { return 0; } for (var i = 0; i < elem.parentNode.childNodes.length; i++) { var node = elem.parentNode.childNodes[i]; if (node === elem) { return i; } } } function getMacroMatch (ctx, macros) { var selected, path = [], offset; if (selectedElementIsTextAreaOrInput(ctx)) { selected = getDocument(ctx).activeElement; } else { var selectionInfo = getContentEditableSelectedPath(ctx); if (selectionInfo) { selected = selectionInfo.selected; path = selectionInfo.path; offset = selectionInfo.offset; } } var effectiveRange = getTextPrecedingCurrentSelection(ctx); if (effectiveRange !== undefined && effectiveRange !== null) { var matchInfo; var hasTrailingSpace = false; if (effectiveRange.length > 0 && (effectiveRange.charAt(effectiveRange.length - 1) === '\xA0' || effectiveRange.charAt(effectiveRange.length - 1) === ' ')) { hasTrailingSpace = true; effectiveRange = effectiveRange.substring(0, effectiveRange.length-1); } angular.forEach(macros, function (macro, c) { var idx = effectiveRange.toUpperCase().lastIndexOf(c.toUpperCase()); if (idx >= 0 && c.length + idx === effectiveRange.length) { var prevCharPos = idx - 1; if (idx === 0 || effectiveRange.charAt(prevCharPos) === '\xA0' || effectiveRange.charAt(prevCharPos) === ' ' ) { matchInfo = { macroPosition: idx, macroText: c, macroSelectedElement: selected, macroSelectedPath: path, macroSelectedOffset: offset, macroHasTrailingSpace: hasTrailingSpace }; } } }); if (matchInfo) { return matchInfo; } } } function getContentEditableSelectedPath(ctx) { var sel = getWindowSelection(ctx); var selected = sel.anchorNode; var path = []; var offset; if (selected != null) { var i; var ce = selected.contentEditable; while (selected !== null && ce !== 'true') { i = getNodePositionInParent(ctx, selected); path.push(i); selected = selected.parentNode; if (selected !== null) { ce = selected.contentEditable; } } path.reverse(); offset = sel.getRangeAt(0).startOffset; return { selected: selected, path: path, offset: offset }; } } function getTriggerInfo (ctx, triggerCharSet, requireLeadingSpace, menuAlreadyActive, hasTrailingSpace) { var selected, path, offset; if (selectedElementIsTextAreaOrInput(ctx)) { selected = getDocument(ctx).activeElement; } else { var selectionInfo = getContentEditableSelectedPath(ctx); if (selectionInfo) { selected = selectionInfo.selected; path = selectionInfo.path; offset = selectionInfo.offset; } } var effectiveRange = getTextPrecedingCurrentSelection(ctx); if (effectiveRange !== undefined && effectiveRange !== null) { var mostRecentTriggerCharPos = -1; var triggerChar; triggerCharSet.forEach(function(c) { var idx = effectiveRange.lastIndexOf(c); if (idx > mostRecentTriggerCharPos) { mostRecentTriggerCharPos = idx; triggerChar = c; } }); if (mostRecentTriggerCharPos >= 0 && ( mostRecentTriggerCharPos === 0 || !requireLeadingSpace || /[\xA0\s]/g.test ( effectiveRange.substring( mostRecentTriggerCharPos - 1, mostRecentTriggerCharPos) ) ) ) { var currentTriggerSnippet = effectiveRange.substring(mostRecentTriggerCharPos + 1, effectiveRange.length); triggerChar = effectiveRange.substring(mostRecentTriggerCharPos, mostRecentTriggerCharPos+1); var firstSnippetChar = currentTriggerSnippet.substring(0,1); var leadingSpace = currentTriggerSnippet.length > 0 && ( firstSnippetChar === ' ' || firstSnippetChar === '\xA0' ); if (hasTrailingSpace) { currentTriggerSnippet = currentTriggerSnippet.trim(); } if (!leadingSpace && (menuAlreadyActive || !(/[\xA0\s]/g.test(currentTriggerSnippet)))) { return { mentionPosition: mostRecentTriggerCharPos, mentionText: currentTriggerSnippet, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset, mentionTriggerChar: triggerChar }; } } } } function getWindowSelection(ctx) { if (!ctx) { return window.getSelection(); } else { return ctx.iframe.contentWindow.getSelection(); } } function getDocument(ctx) { if (!ctx) { return document; } else { return ctx.iframe.contentWindow.document; } } function getTextPrecedingCurrentSelection (ctx) { var text; if (selectedElementIsTextAreaOrInput(ctx)) { var textComponent = getDocument(ctx).activeElement; var startPos = textComponent.selectionStart; text = textComponent.value.substring(0, startPos); } else { var selectedElem = getWindowSelection(ctx).anchorNode; if (selectedElem != null) { var workingNodeContent = selectedElem.textContent; var selectStartOffset = getWindowSelection(ctx).getRangeAt(0).startOffset; if (selectStartOffset >= 0) { text = workingNodeContent.substring(0, selectStartOffset); } } } return text; } function getContentEditableCaretPosition (ctx, selectedNodePosition) { var markerTextChar = '\ufeff'; var markerEl, markerId = 'sel_' + new Date().getTime() + '_' + Math.random().toString().substr(2); var range; var sel = getWindowSelection(ctx); var prevRange = sel.getRangeAt(0); range = getDocument(ctx).createRange(); range.setStart(sel.anchorNode, selectedNodePosition); range.setEnd(sel.anchorNode, selectedNodePosition); range.collapse(false); markerEl = getDocument(ctx).createElement('span'); markerEl.id = markerId; markerEl.appendChild(getDocument(ctx).createTextNode(markerTextChar)); range.insertNode(markerEl); sel.removeAllRanges(); sel.addRange(prevRange); var coordinates = { left: 0, top: markerEl.offsetHeight }; localToGlobalCoordinates(ctx, markerEl, coordinates); markerEl.parentNode.removeChild(markerEl); return coordinates; } function localToGlobalCoordinates(ctx, element, coordinates) { var obj = element; var iframe = ctx ? ctx.iframe : null; while(obj) { coordinates.left += obj.offsetLeft; coordinates.top += obj.offsetTop; if (obj !== getDocument().body) { coordinates.top -= obj.scrollTop; coordinates.left -= obj.scrollLeft; } obj = obj.offsetParent; if (!obj && iframe) { obj = iframe; iframe = null; } } } function getTextAreaOrInputUnderlinePosition (ctx, element, position) { var properties = [ 'direction', 'boxSizing', 'width', 'height', 'overflowX', 'overflowY', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent', 'textDecoration', 'letterSpacing', 'wordSpacing' ]; var isFirefox = (window.mozInnerScreenX !== null); var div = getDocument(ctx).createElement('div'); div.id = 'input-textarea-caret-position-mirror-div'; getDocument(ctx).body.appendChild(div); var style = div.style; var computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle; style.whiteSpace = 'pre-wrap'; if (element.nodeName !== 'INPUT') { style.wordWrap = 'break-word'; } style.position = 'absolute'; style.visibility = 'hidden'; properties.forEach(function (prop) { style[prop] = computed[prop]; }); if (isFirefox) { style.width = (parseInt(computed.width) - 2) + 'px'; if (element.scrollHeight > parseInt(computed.height)) style.overflowY = 'scroll'; } else { style.overflow = 'hidden'; } div.textContent = element.value.substring(0, position); if (element.nodeName === 'INPUT') { div.textContent = div.textContent.replace(/\s/g, '\u00a0'); } var span = getDocument(ctx).createElement('span'); span.textContent = element.value.substring(position) || '.'; div.appendChild(span); var coordinates = { top: span.offsetTop + parseInt(computed.borderTopWidth) + parseInt(computed.fontSize), left: span.offsetLeft + parseInt(computed.borderLeftWidth) }; localToGlobalCoordinates(ctx, element, coordinates); getDocument(ctx).body.removeChild(div); return coordinates; } return { popUnderMention: popUnderMention, replaceMacroText: replaceMacroText, replaceTriggerText: replaceTriggerText, getMacroMatch: getMacroMatch, getTriggerInfo: getTriggerInfo, selectElement: selectElement, getTextAreaOrInputUnderlinePosition: getTextAreaOrInputUnderlinePosition, getTextPrecedingCurrentSelection: getTextPrecedingCurrentSelection, getContentEditableSelectedPath: getContentEditableSelectedPath, getNodePositionInParent: getNodePositionInParent, getContentEditableCaretPosition: getContentEditableCaretPosition, pasteHtml: pasteHtml, resetSelection: resetSelection, scrollIntoView: scrollIntoView }; }]); angular.module("mentio").run(["$templateCache", function($templateCache) {$templateCache.put("mentio-menu.tpl.html","<style>\n.scrollable-menu {\n height: auto;\n max-height: 300px;\n overflow: auto;\n}\n\n.menu-highlighted {\n font-weight: bold;\n}\n</style>\n<ul class=\"dropdown-menu scrollable-menu\" style=\"display:block\">\n <li mentio-menu-item=\"item\" ng-repeat=\"item in items track by $index\">\n <a class=\"text-primary\" ng-bind-html=\"item.label | mentioHighlight:typedTerm:\'menu-highlighted\' | unsafe\"></a>\n </li>\n</ul>");}]); })(); ; /*! RESOURCE: /scripts/sn/common/stream/_module.js */ (function() { var moduleDeps = [ 'sn.base', 'ng.amb', 'sn.messaging', 'sn.common.glide', 'ngSanitize', 'sn.common.avatar', 'sn.common.ui.popover', 'mentio', 'sn.common.controls', 'sn.common.user_profile', 'sn.common.datetime', 'sn.common.mention', 'sn.common.ui', 'sn.common.dynamicTranslation']; if (angular.version.major == 1 && angular.version.minor >= 3) moduleDeps.push('ngAria'); angular.module("sn.common.stream", moduleDeps); angular.module("sn.stream.direct", [ 'sn.common.stream']); })(); ; /*! RESOURCE: /scripts/sn/common/stream/controller.Stream.js */ angular.module("sn.common.stream").controller("Stream", function($rootScope, $scope, snRecordWatcher, $timeout) { var isForm = NOW.sysId.length > 0; $scope.showCommentsAndWorkNotes = isForm; $scope.sessions = {}; $scope.recordStreamOpen = false; $scope.streamHidden = true; $scope.recordSysId = ''; $scope.recordDisplayValue = ''; $rootScope.$on('sn.sessions', onSessions); $timeout(function() { var query = isForm ? "sys_id=" + NOW.sysId : NOW.tableQuery || "sys_idISNOTEMPTY"; snRecordWatcher.initChannel(NOW.targetTable, query, function(message) { $rootScope.$broadcast("sn.stream.tap", message.data); }); }, 100); $scope.controls = { showRecord : function($event, entry, sysId) { if (sysId !== '') return; if ($event.currentTarget != $event.target && $event.target.tagName == 'A') return; $scope.recordSysId = entry.document_id; $scope.recordDisplayValue = entry.display_value; $scope.recordStreamOpen = true; $scope.streamHidden = true; }, openRecord : function() { var targetFrame = window.self; var url = NOW.targetTable + ".do?sys_id=" + $scope.recordSysId; if (NOW.linkTarget == 'form_pane') { url += "&sysparm_clear_stack=true"; window.parent.CustomEvent.fireTop( "glide:nav_open_url", { url : url, openInForm : true }); return; } if (NOW.streamLinkTarget == 'parent' || NOW.concourse == 'true') targetFrame = window.parent; targetFrame.location = url; } }; $scope.sessionCount = function() { $scope.sessions.length = Object.keys($scope.sessions.data).length; return $scope.sessions.length; }; function onSessions(name, sessions) { $scope.sessions.data = sessions; $scope.sessionCount(); } $scope.toggleEmailIframe = function(email, event){ email.expanded = !email.expanded; event.preventDefault(); }; $scope.showListStream = function () { $scope.recordStreamOpen = false; $scope.recordHidden = false; $scope.streamHidden = false; angular.element('div.list-stream-record').velocity('snTransition.streamSlideRight', { duration: 400 }); angular.element('[streamType="list"]').velocity('snTransition.slideIn', { duration: 400, complete: function (element) { angular.element(element).css({display: 'block'}); } }); }; $scope.$watch(function () { return angular.element('div.list-stream-record').length }, function (newValue, oldValue) { if (newValue == 1) { angular.element('div.list-stream-record').delay(100).velocity('snTransition.streamSlideLeft', { begin: function (element) { angular.element(element).css({visibility: 'visible'}); angular.element('.list-stream-record-header').css({visibility: 'visible'}); }, duration: 400, complete: function (element) { angular.element(element).css({transform: "translateX(0)"}); angular.element(element).scrollTop(0); angular.element(element).css({transform: "initial"}); angular.element('.return-to-stream').focus(); } }); } }); }); ; /*! RESOURCE: /scripts/sn/common/stream/controller.snStream.js */ angular.module("sn.common.stream").controller("snStream", function($rootScope, $scope, $attrs, $http, nowStream, snRecordPresence, snCustomEvent, userPreferences, $window, $q, $timeout, $sce, snMention, i18n, getTemplateUrl, $injector, dynamicTranslation) { "use strict"; if (angular.isDefined($attrs.isInline)) { bindInlineStreamAttributes(); } var globalMembers = NOW.recordMembers || {}; function putGlobalMember(sysId, name, initials, avatar) { if (!sysId || !name || !initials) return; if (!globalMembers[sysId]) { globalMembers[sysId] = { "name": name, "initials": initials, "sys_id": sysId, "record_is_visible": true, "avatar": avatar }; return; } if ((globalMembers[sysId].avatar === undefined || globalMembers[sysId].avatar === "") && avatar) globalMembers[sysId].avatar = avatar; } function getMembersFromPageContext(members, term) { var matching = [], matchingSysIds = []; var memberKeys = Object.keys(globalMembers); term = term.toLowerCase().trim(); memberKeys.forEach(function(sysId) { var member = globalMembers[sysId]; if ((typeof member.name !== "undefined" && member.name.toLowerCase().indexOf(term) == 0) || (typeof member.last_name !== "undefined" && member.last_name.toLowerCase().indexOf(term) == 0)) { matching.push(member); matchingSysIds.push(sysId); } }); members.forEach(function(member) { if (globalMembers[member.sys_id] && globalMembers[member.sys_id].avatar === undefined) globalMembers[member.sys_id].avatar = member.avatar; if (matchingSysIds.indexOf(member.sys_id) === -1) matching.push(member); }); return matching; } function bindInlineStreamAttributes() { var streamAttributes = {}; if ($attrs.table) { streamAttributes.table = $attrs.table; } if ($attrs.query) { streamAttributes.query = $attrs.query; } if ($attrs.sysId) { streamAttributes.sysId = $attrs.sysId; } if ($attrs.active) { streamAttributes.active = ($attrs.active == "true"); } if ($attrs.template) { streamAttributes.template = $attrs.template; } if ($attrs.preferredInput) { streamAttributes.preferredInput = $attrs.preferredInput; } if ($attrs.useMultipleInputs) { streamAttributes.useMultipleInputs = ($attrs.useMultipleInputs == "true"); } if ($attrs.expandEntries) { streamAttributes.expandEntries = ($attrs.expandEntries == "true"); } if ($attrs.pageSize) { streamAttributes.pageSize = parseInt($attrs.pageSize, 10); } if ($attrs.truncate) { streamAttributes.truncate = ($attrs.truncate == "true"); } if ($attrs.attachments) { streamAttributes.attachments = ($attrs.attachments == "true"); } if ($attrs.showCommentsAndWorkNotes) { streamAttributes.attachments = ($attrs.showCommentsAndWorkNotes == "true"); } angular.extend($scope, streamAttributes) } var stream; var processor = $attrs.processor || "list_history"; var interval; var FROM_LIST = 'from_list'; var FROM_FORM = 'from_form'; var source = $scope.sysId ? FROM_FORM : FROM_LIST; var _firstPoll = true; var _firstPollTimeout; var fieldsInitialized = false; var primaryJournalFieldOrder = ["comments", "work_notes"]; var primaryJournalField = null; $scope.defaultShowCommentsAndWorkNotes = ($scope.sysId != null && !angular.isUndefined($scope.sysId) && $scope.sysId.length > 0); $scope.canWriteWorkNotes = false; $scope.inputTypeValue = ""; $scope.entryTemplate = getTemplateUrl($attrs.template || "list_stream_entry"); $scope.isFormStream = $attrs.template === "record_stream_entry.xml"; $scope.allFields = null; $scope.fields = {}; $scope.fieldColor = "transparent"; $scope.multipleInputs = $scope.useMultipleInputs; $scope.checkbox = {}; $scope.attachmentAdviceRequired = $window.NOW.attachmentAdviceRequired; var infectedAttachmnentMsg = "The file {0} did not pass security scan and cannot be downloaded"; i18n.getMessage(infectedAttachmnentMsg, function(message) { infectedAttachmnentMsg = message; }); var typing = '{0} is typing', viewing = '{0} is viewing', entered = '{0} has entered'; var probablyLeft = '{0} has probably left', exited = '{0} has exited', offline = '{0} is offline', auditMessage = '{0} was {1}', was ="was"; i18n.getMessages( [ typing, viewing, entered, probablyLeft, exited, offline, was, auditMessage ], function (results) { typing = results[typing]; viewing = results[viewing]; entered = results[entered]; probablyLeft = results[probablyLeft]; exited = results[exited]; offline = results[offline]; was = results[was]; $scope.auditMessageParts = buildAuditMessageParts(results[auditMessage],was); } ); function buildAuditMessageParts(auditMessage, was) { var tMessagePattern = /^([^{]*)\{([01])\}([^{]*)\{([01])\}(.*)$/; var messageParts = tMessagePattern.exec(auditMessage); var auditMessageParts = messageParts ? { prefix: messageParts[1].trim(), newValPosition: messageParts[2], middle: messageParts[3].trim(), oldValPosition: messageParts[4], postfix: messageParts[5].trim() } : { prefix: '', newValPosition: "0", middle: was, oldValPosition: "1", postfix: '' }; return auditMessageParts; } $scope.parsePresence = function (sessionData) { var status = sessionData.status; var name = sessionData.user_display_name; switch (status) { case 'typing': return i18n.format(typing, name); case 'viewing': return i18n.format(viewing, name); case 'entered': return i18n.format(entered, name); case 'probably left': return i18n.format(probablyLeft, name); case 'exited': return i18n.format(exited, name); case 'offline': return i18n.format(offline, name); default: return ''; } }; $scope.members = []; $scope.members.loading = true; var mentionMap = {}; $scope.selectAtMention = function(item) { if(item.termLengthIsZero) return (item.name || "") + "\n"; mentionMap[item.name] = item.sys_id; return "@[" + item.name + "]"; }; var typingTimer; $scope.searchMembersAsync = function(term) { $scope.members = getMembersFromPageContext([], term); $scope.members.loading = true; $timeout.cancel(typingTimer); if (term.length === 0) { $scope.members = [{ termLengthIsZero: true }]; $scope.members.loading = false; } else { typingTimer = $timeout(function() { snMention.retrieveMembers($scope.table, $scope.sysId, term).then(function(members) { $scope.members = getMembersFromPageContext(members, term); $scope.members.loading = false; }, function () { $scope.members = getMembersFromPageContext([{ termLengthIsZero: true }], term); $scope.members.loading = false; }); }, 500); } }; $scope.expandMentions = function(text) { return stream.expandMentions(text, mentionMap) }; $scope.reduceMentions = function(text) { if(!text) return text; var regexMentionParts = /[@\w\d\s/\']+/gi; text = text.replace(/@\[[\w\d\s]+:[@\w\d\s/\']+\]/gi, function (mention) { var mentionParts = mention.match(regexMentionParts); if (mentionParts.length === 3) { var name = mentionParts[2]; mentionMap[name] = mentionParts[1]; return "@[" + name + "]"; } return mentionParts; }); return text; }; $scope.parseMentions = function(entry) { var regexMentionParts = /[\w\d\s/\']+/gi; entry = entry.replace(/@\[[\w\d\s]+:[\w\d\s/\']+\]/gi, function (mention) { var mentionParts = mention.match(regexMentionParts); if (mentionParts.length === 2) { return '<a class="at-mention at-mention-user-' + mentionParts[0] + '">@' + mentionParts[1] + '</a>'; } return mentionParts; }); return entry; }; $scope.parseLinks = function(text) { var regexLinks = /@L\[([^|]+?)\|([^\]]*)]/gi; return text.replace(regexLinks, "<a href='$1' target='_blank'>$2</a>"); }; $scope.trustAsHtml = function(text) { return $sce.trustAsHtml(text); }; $scope.parseSpecial = function(text) { var parsedText = $scope.parseLinks(text); parsedText = $scope.parseMentions(parsedText); return $scope.trustAsHtml(parsedText); }; $scope.containsHTML = function(text) { return /<([a-z][a-z0-9]*)\b[^>]*>[\s\S]*<\/\1>/mi.test(text); }; $scope.isHTMLField = function(change) { return change.field_type === 'html' || change.field_type === 'translated_html'; }; $scope.shouldEncapsulate = function(journal) { return $scope.isHTMLField(journal) || $scope.containsHTML(journal.sanitized_new_value) }; $scope.getFullEntryValue = function(entry, event) { event.stopPropagation(); var index = getEntryIndex(entry); var journal = $scope.entries[index].entries.journal[0]; journal.loading = true; $http.get('/api/now/ui/stream_entry/full_entry', { params: { sysparm_sys_id: journal.sys_id } }).then(function (response) { journal.sanitized_new_value = journal.new_value = response.data.result.replace(/\n/g, '<br/>'); journal.is_truncated = false; journal.loading = false; journal.showMore = true; }); }; function getEntryIndex(entry) { for (var i = 0, l = $scope.entries.length; i < l; i++) { if (entry === $scope.entries[i]) { return i; } } } $scope.$watch('active', function(n, o) { if (n === o) return; if ($scope.active) startPolling(); else cancelStream(); }); $scope.defaultControls = { getTitle: function(entry) { if(entry && entry.short_description) { return entry.short_description; } else if(entry && entry.shortDescription) { return entry.shortDescription; } }, showCreatedBy: function() { return true; }, hideCommentLabel: function() { return false; }, showRecord: function($event, entry) { }, showRecordLink: function() { return true; } }; if ($scope.controls) { for (var attr in $scope.controls) $scope.defaultControls[attr] = $scope.controls[attr]; } $scope.controls = $scope.defaultControls; if ($scope.showCommentsAndWorkNotes === undefined) { $scope.showCommentsAndWorkNotes = $scope.defaultShowCommentsAndWorkNotes; } snCustomEvent.observe('sn.stream.change_input_display', function(table, display) { if (table != $scope.table) return; $scope.showCommentsAndWorkNotes = display; $scope.$apply(); }); snCustomEvent.observe('sn.stream.attachment_state_updated', function(entry) { $scope.entries.forEach(function(e) { if (e.attachment && e.attachment.sys_id === entry.attachment.sys_id) { e.attachment.state = entry.attachment.state; } }); }); $scope.$on("$destroy", function() { cancelStream(); }); $scope.$on('sn.stream.interval', function($event, time) { interval = time; reschedulePoll(); }); $scope.$on("sn.stream.tap", function() { if (stream) stream.tap(); else startPolling(); }); $scope.$on('window_visibility_change', function($event, hidden) { interval = (hidden) ? 120000 : undefined; reschedulePoll(); }); snCustomEvent.observe('sn.stream.clearOnSilentSubmit', function(){ clearInputs(); }); $scope.$on("sn.stream.refresh", function(event, data) { stream._successCallback(data.response); }); $scope.$on("sn.stream.reload", function() { startPolling(); }); snCustomEvent.observe('sn.stream.toggle_multiple_inputs', function() { $scope.useMultipleInputs = true; }); $scope.$on('sn.stream.input_value', function(otherScope, type, value) { setMultipleInputs(); if(!$scope.multipleInputs) { $scope.inputType = type; $scope.inputTypeValue = value; } }); $scope.$watchCollection('[table, query, sysId]', startPolling); $scope.changeInputType = function(field) { if (!primaryJournalField){ angular.forEach($scope.fields, function(item) { if (item.isPrimary) primaryJournalField = item.name; }); } $scope.inputType = field.checked ? field.name : primaryJournalField; userPreferences.setPreference('glide.ui.' + $scope.table + '.stream_input', $scope.inputType); }; $scope.selectedInputType = function(value) { if (angular.isDefined(value)) { $scope.inputType = value; userPreferences.setPreference('glide.ui.' + $scope.table + '.stream_input', $scope.inputType); } return $scope.inputType; }; $scope.$watch('inputType', function() { if (!$scope.inputType || !$scope.preferredInput) return; $scope.preferredInput = $scope.inputType; }); $scope.submitCheck = function(event){ var key = event.keyCode || event.which; if (key === 13) { $scope.postJournalEntryForCurrent(event); } }; $scope.postJournalEntry = function(type, entry, event) { type = type || primaryJournalFieldOrder[0]; event.stopPropagation(); var requestTable = $scope.table || "board:" + $scope.board.sys_id; stream.insertForEntry(type, entry.journalText, requestTable, entry.document_id); entry.journalText = ""; entry.commentBoxVisible = false; snRecordPresence.termPresence(); }; $scope.postJournalEntryForCurrent = function(event) { event.stopPropagation(); var entries = []; if ($scope.multipleInputs) { angular.forEach($scope.fields, function(item) { if (!item.value) return; entries.push({ field: item.name, text: item.value }); }) } else { entries.push({ field: $scope.inputType, text: $scope.inputTypeValue }) } var request = stream.insertEntries(entries, $scope.table, $scope.sysId, mentionMap); if (request) { request.then(function () { for (var i = 0; i < entries.length; i++) { fireClearEvent(entries[i].field); } }); } clearInputs(); return false; }; $scope.doesFormHasMandatoryJournalFields = function() { if (window.g_form) { var fields = Object.values($scope.fields); for (var index = 0; index < fields.length; index++) { if (fields[index].mandatory) return true; } } return false; }; function fireInsertEvent(name, value) { snCustomEvent.fire('sn.stream.insert', name, value); } function fireClearEvent(name) { snCustomEvent.fire('sn.stream.clear', name); } function clearInputs() { $scope.inputTypeValue = ""; angular.forEach($scope.fields, function(item) { if (item.value) item.filled = true; item.value = ""; }); } $scope.showCommentBox = function(entry, event) { event.stopPropagation(); if (entry !== $scope.selectedEntry) $scope.closeEntry(); $scope.selectedEntry = entry; entry.commentBoxVisible = !entry.commentBoxVisible; if (entry.commentBoxVisible) { snRecordPresence.initPresence($scope.table, entry.document_id); } }; $scope.showMore = function(journal, event) { event.stopPropagation(); journal.showMore = true; }; $scope.showLess = function(journal, event) { event.stopPropagation(); journal.showMore = false; }; $scope.closeEntry = function() { if ($scope.selectedEntry) $scope.selectedEntry.commentBoxVisible = false; }; $scope.handleListASAttachmentClick = function(evt, entry) { evt.stopPropagation(); $scope.handleASAttachmentClick(evt, entry); }; $scope.handleListASAttachmentKeydown = function(evt, entry) { if (evt.keyCode === 13 || evt.keyCode === 32) { evt.stopPropagation(); $scope.handleASAttachmentClick(evt, entry); } } $scope.handleASAttachmentClick = function(evt, entry) { var attachment = entry.attachment; if (attachment.state === 'available' || !$scope.attachmentAdviceRequired) { previewOrDownloadAttachment(evt, entry, false); } else if (attachment.state === 'not_available') { evt.preventDefault(); $scope.showAttachmentUnAvailabilityMessage(attachment.file_name); } else { evt.preventDefault(); getAttachmentAvailability(attachment.sys_id) .then(function(res) { entry.attachment.state = res.state; previewOrDownloadAttachment(evt, entry, true); }, function(res) { entry.attachment.state = res.state; if (res.forceDownload) { downloadAttachment(evt.currentTarget); } else { $scope.showAttachmentUnAvailabilityMessage(attachment.file_name, res.message); } }); } }; function getAttachmentAvailability(attachmentSysId) { var deferred = $q.defer(); $http.get('/api/now/as_attachment/getAvailability/' + attachmentSysId) .then(function (response) { var _res = response.data.result; if (_res && _res.availability) { if (_res.availability === 'available') { deferred.resolve({state : _res.availability}); } else { deferred.reject({ state : _res.availability, message : _res.message }); } } else { deferred.reject({ state: "", forceDownload : true}); } }, function() { deferred.reject({ state: "", forceDownload : true}); }); return deferred.promise; } function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } $scope.showAttachmentUnAvailabilityMessage = function(fileName, customMsg) { var errMsg = customMsg || i18n.format(infectedAttachmnentMsg, escapeHtml(fileName)); if (typeof g_form !== "undefined") { g_form.addErrorMessage(errMsg); } else if (typeof window.parent.GlideUI !== "undefined") { var topWindow = window.parent; topWindow.CustomEvent.fireTop(topWindow.GlideUI.UI_NOTIFICATION + '.error', new topWindow.GlideUINotification({type : 'error',text : errMsg })); } else if (window.NOW && window.NOW.CustomEvent) { window.NOW.CustomEvent.fire('stream.attachment.unavailable', errMsg); } }; function downloadAttachment(ele) { var link = document.createElement('a'); link.href = ele.getAttribute('href'); link.download = ele.getAttribute('file-name'); var event = (typeof window.MouseEvent === "function") ? new MouseEvent("click") : document.createEvent('Event'); event.initEvent('click', true, true); link.dispatchEvent(event); } function previewOrDownloadAttachment(evt, entry, isAsync) { if (!$scope.isFormStream) { evt.preventDefault(); if (isAsync && entry.type === 'attachment-image') return; openAttachment(entry.attachment.sys_id); return; } if (entry.type === 'attachment-image') { if (snCustomEvent.events['sn.attachment.preview'] && !isAsync) { snCustomEvent.fire('sn.attachment.preview', evt, entry.attachment); } } else if((entry.attachment.extension === 'mp4' || entry.attachment.extension === 'webm') && typeof GlideVideoPlayer !== "undefined") { evt.preventDefault(); entry.attachment.playVideo = true; } else if (isAsync) { downloadAttachment(evt.currentTarget); } } function openAttachment(sysId) { var url = "/sys_attachment.do?view=true&sys_id=" + sysId; var newTab = window.open(url, '_blank'); newTab.focus(); } $rootScope.$on('sn.sessions', function(someOtherScope, sessions) { if ($scope.selectedEntry && $scope.selectedEntry.commentBoxVisible) $scope.selectedEntry.sessions = sessions; }); $scope.$watch("inputTypeValue", function(n, o) { if (n !== o) { emitTyping($scope.inputTypeValue); } }); $scope.$watch("selectedEntry.journalText", function(newValue) { if ($scope.selectedEntry) emitTyping(newValue || ""); }); var multipleInputWatcher = function(){}; $scope.$watch('useMultipleInputs', function() { if($scope.useMultipleInputs) { multipleInputWatcher = $scope.$watch("fields", function(n, o, s) { if (n !== o) { var strVal = ""; angular.forEach($scope.fields, function(item) { if (item.value) strVal = item.value; }); emitTyping(strVal); } }, true); } else { multipleInputWatcher(); } setMultipleInputs(); }); function emitTyping(inputValue) { if (!angular.isDefined(inputValue)){ return; } var status = inputValue.length ? "typing" : "viewing"; $scope.$emit("record.typing", {status: status, value: inputValue, field_type: $scope.inputType, table: $scope.table, sys_id: $scope.sys_id}); } function preloadedData() { if (typeof window.NOW.snActivityStreamData === 'object' && window.NOW.snActivityStreamData[$scope.table + '_' + $scope.sysId]) { _firstPoll = false; var data = window.NOW.snActivityStreamData[$scope.table + '_' + $scope.sysId]; stream = nowStream.create($scope.table, $scope.query, $scope.sysId, processor, interval, source, $scope.attachments); stream.callback = onPoll; stream.preRequestCallback = beforePoll; stream.lastTimestamp = data.sys_timestamp; if (data.entries && data.entries.length) { stream.lastEntry = angular.copy(data.entries[0]); } _firstPollTimeout = setTimeout(function() { stream.poll(onPoll, beforePoll); _firstPollTimeout = false; }, 20000); beforePoll(); onPoll(data); return true; } return false; } function scheduleNewPoll(lastTimestamp) { cancelStream(); stream = nowStream.create($scope.table, $scope.query, $scope.sysId, processor, interval, source, $scope.attachments); stream.lastTimestamp = lastTimestamp; stream.poll(onPoll, beforePoll); } function reschedulePoll() { var lastTimestamp = stream ? stream.lastTimestamp : 0; if (cancelStream()) { scheduleNewPoll(lastTimestamp); } } function reset() { removeInlineStream(); $scope.loaded = false; startPolling(); } function emitFilterChange() { $scope.$emit('sn.stream.is_filtered_change', $scope.isFiltered); } function startPolling() { if ($scope.loading && !$scope.loaded) return; if (!$scope.active) return; $scope.entries = []; $scope.allEntries = []; $scope.showAllEntriesButton = false; $scope.loaded = false; $scope.loading = true; if (_firstPoll && preloadedData()) { return; } scheduleNewPoll(); $scope.$emit('sn.stream.entries_change', $scope.entries); } function onPoll(response) { $scope.loading = false; if (response.primary_fields) primaryJournalFieldOrder = response.primary_fields; if (!fieldsInitialized) processFields(response.fields); processEntries(response.entries); if (response.inlineStreamLoaded) { $scope.inlineStreamLoaded = true; addInlineStreamEntryClass(); } if (!$scope.loaded) { $scope.loaded = true; $scope.$emit("sn.stream.loaded", response); } } function beforePoll() { $scope.$emit("sn.stream.requested"); } function processFields(fields) { if(!fields || !fields.length) return; fieldsInitialized = true; $scope.allFields = fields; setShowAllFields(); $scope.fieldsVisible = 0; var i = 0; angular.forEach(fields, function(field) { if (!field.isJournal) return; if (i==0) $scope.firstJournal = field.name; i++; if ($scope.fields[field.name]) { angular.extend($scope.fields[field.name], field); } else { $scope.fields[field.name] = field; } $scope.fields[field.name].visible = !$scope.formJournalFields && $scope.fields[field.name].canWrite; if ($scope.fields[field.name].visible) $scope.fieldsVisible++; var fieldColor = field.color; if (fieldColor) fieldColor = field.color.replace(/background-color: /, ''); if (!fieldColor || fieldColor == 'transparent') fieldColor = null; $scope.fields[field.name].color = fieldColor; }); setFieldVisibility(); setPrimaryJournalField(); setMultipleInputs(); } $scope.$watch('formJournalFields', function() { setFieldVisibility(); setPrimaryJournalField(); setMultipleInputs(); }, true); function setFieldVisibility() { if (!$scope.formJournalFields || !$scope.fields || !$scope.showCommentsAndWorkNotes) return; $scope.fieldsVisible = 0; angular.forEach($scope.formJournalFields, function(formField) { if (!$scope.fields[formField.name]) return; var formValue = angular.element('#' + $scope.table + '\\.' + formField.name).val(); if (formValue && formValue.indexOf($window.NOW.STREAM_VALUE_KEY) !== 0) { $scope.fields[formField.name].value = $scope.reduceMentions(formField.value); } else if (formValue === '') { $scope.fields[formField.name].value = ''; } $scope.fields[formField.name].mandatory = formField.mandatory; $scope.fields[formField.name].label = formField.label; $scope.fields[formField.name].messages = formField.messages; $scope.fields[formField.name].visible = formField.visible && !formField.readonly; if ($scope.fields[formField.name].visible) $scope.fieldsVisible++; }); } $scope.getStubbedFieldModel = function(fieldName) { if ($scope.fields[fieldName]) return $scope.fields[fieldName]; $scope.fields[fieldName] = { name: fieldName }; return $scope.fields[fieldName]; }; function setPrimaryJournalField() { if (!$scope.fields || !$scope.showCommentsAndWorkNotes) return; angular.forEach($scope.fields, function(item) { item.isPrimary = false; item.checked = false; }); var visibleFields = Object.keys($scope.fields).filter(function(item) { return $scope.fields[item].visible; }); if (visibleFields.indexOf($scope.preferredInput) != -1) { var field = $scope.fields[$scope.preferredInput]; field.checked = true; field.isPrimary = true; $scope.inputType = $scope.preferredInput; primaryJournalField = $scope.preferredInput; } else { for (var i = 0; i < primaryJournalFieldOrder.length; i++) { var fieldName = primaryJournalFieldOrder[i]; if (visibleFields.indexOf(fieldName) != -1) { $scope.fields[fieldName].isPrimary = true; primaryJournalField = fieldName; $scope.inputType = fieldName; $scope.inputTypeValue = $scope.fields[fieldName].value; break; } } } if(visibleFields.length === 0) { primaryJournalField = ''; $scope.inputType = primaryJournalField; } else if (!$scope.inputType && visibleFields.length > 0) { primaryJournalField = visibleFields[0]; $scope.inputType = primaryJournalField; $scope.fields[primaryJournalField].isPrimary = true; } if ($scope.fields && visibleFields.indexOf(primaryJournalField) == -1) { var keys = Object.keys($scope.fields); if (keys.length) $scope.fields[keys[0]].isPrimary = true; } } function safeArialiveAssertive(message) { if (window.NOW && window.NOW.accessibility && window.NOW.accessibility.ariaLiveAssertive) { window.NOW.accessibility.ariaLiveAssertive(message); } } function setShowAllFields() { var ariaLiveAllActivities = ''; $scope.checkbox.showAllFields = $scope.showAllFields = $scope.allFields && !$scope.allFields.some(function(item) { return !item.isActive; }); $scope.hideAllFields = !$scope.allFields || !$scope.allFields.some(function(item) { return item.isActive; }); $scope.isFiltered = !$scope.showAllFields || $scope.allFields.some(function(item) { return !item.isActive; }); if ($scope.checkbox.showAllFields) ariaLiveAllActivities = 'All activities are displayed'; else if ($scope.hideAllFields) ariaLiveAllActivities = 'All activities are hidden'; safeArialiveAssertive(ariaLiveAllActivities); } $scope.setPrimary = function(entry) { angular.forEach($scope.fields, function(item) { item.checked = false; }); for (var i = 0; i < primaryJournalFieldOrder.length; i++) { var fieldName = primaryJournalFieldOrder[i]; if (entry.writable_journal_fields.indexOf(fieldName) != -1) { entry.primaryJournalField = fieldName; entry.inputType = fieldName; return; } } if (!entry.inputType) { var primaryField = entry.writable_journal_fields[0]; entry.primaryJournalField = primaryField; entry.inputType = primaryField; } }; $scope.updateFieldVisibilityAll = function() { $scope.showAllFields = !$scope.showAllFields; angular.forEach($scope.allFields, function(item) { item.isActive = $scope.showAllFields; }); $scope.updateFieldVisibility(); }; $scope.updateFieldVisibility = function() { var activeFields = $scope.allFields.map(function(item) { return item.name + ',' + item.isActive; }); setShowAllFields(); emitFilterChange(); userPreferences .setPreference($scope.table + '.activity.filter', activeFields.join(';')) .then(function() { reset(); }); }; $scope.configureAvailableFields = function() { $window.personalizer($scope.table, 'activity', $scope.sysId); }; function handleFieldInputsOnToggle(){ angular.forEach($scope.fields, function(item){ var itemIsInput = ($scope.inputType == item.name) ? true : false; if (!itemIsInput) item.value = ''; else if ($scope.multipleInputs) item.value = $scope.inputTypeValue; else $scope.inputTypeValue = item.value; }); } $scope.isInForm = function() { return typeof g_form !== 'undefined'; } function shouldJournalFieldsToggle(){ var toggle = true; if (!$scope.multipleInputs) return toggle; angular.forEach($scope.fields, function(item){ if(($scope.inputType != item.name) && item.value) toggle = false; }); return toggle; } $scope.toggleMultipleInputs = function(val, evt) { if (evt && evt.type === "keydown" && evt.keyCode !== 13 && evt.keyCode !== 32) return; if (!shouldJournalFieldsToggle()) return; userPreferences.setPreference('glide.ui.activity_stream.multiple_inputs', val ? 'true' : 'false') .then(function() { $scope.useMultipleInputs = val; setMultipleInputs(); if ($scope.multipleInputs === val) handleFieldInputsOnToggle(); }); }; $scope.changeEntryInputType = function(fieldName, entry) { var checked = $scope.fields[fieldName].checked; entry.inputType = checked ? fieldName : entry.primaryJournalField; }; function processEntries(entries) { if (!entries || !entries.length) return; entries = entries.reverse(); var newEntries = []; angular.forEach(entries, function (entry) { var entriesToAdd = [entry]; if (entry.attachment) { entry.type = getAttachmentType(entry.attachment); entry.attachment.extension = getAttachmentExt(entry.attachment); } else if (entry.is_email === true){ entry.email = {}; var allFields = entry.entries.custom; for(var i = 0; i < allFields.length; i++){ entry.email[allFields[i].field_name] = { label: allFields[i]['field_label'], displayValue: allFields[i]['new_value'] }; entry.email['is_translation_enabled'] = allFields[i]['is_translation_enabled']; } entry['entries'].custom = []; } else if ($scope.sysId) { entriesToAdd = extractJournalEntries(entry); } else { entriesToAdd = handleJournalEntriesWithoutExtraction(entry); } putGlobalMember(entry['user_id'], entry['sys_created_by'], entry['initials'], entry['user_image']); if (entriesToAdd instanceof Array) { entriesToAdd.forEach(function (e) { $scope.entries.unshift(e); newEntries.unshift(e); }); } else { $scope.entries.unshift(entriesToAdd); newEntries.unshift(entriesToAdd) } if (source != FROM_FORM) $scope.entries = $scope.entries.slice(0, 49); if ($scope.maxEntries != undefined) { var maxNumEntries = parseInt($scope.maxEntries, 10); $scope.entries = $scope.entries.slice(0, maxNumEntries); } }); if ($scope.inlineStreamLoaded) { if ($scope.entries.length > 0) { removeInlineStreamEntryClass(); } } if ($scope.loaded) { $scope.$emit("sn.stream.new_entries", newEntries); triggerResize(); } else if ($scope.pageSize && $scope.entries.length > $scope.pageSize) { setUpPaging(); } $timeout(function() { $scope.$emit('sn.stream.entries_change', $scope.entries); }); } function removeInlineStream() { angular.element(document).find('#sn_form_inline_stream_container').hide().remove(); } function removeInlineStreamEntryClass() { angular.element(document).find('#sn_form_inline_stream_entries').removeClass('sn-form-inline-stream-entries-only'); } function addInlineStreamEntryClass() { angular.element(document).find('#sn_form_inline_stream_entries').addClass('sn-form-inline-stream-entries-only'); } function setUpPaging() { $scope.showAllEntriesButton = true; $scope.allEntries = $scope.entries; $scope.entries = []; loadEntries(0, $scope.pageSize); } $scope.loadMore = function() { if ($scope.entries.length + $scope.pageSize > $scope.allEntries.length) { $scope.loadAll(); return; } loadEntries($scope.loadedEntries, $scope.loadedEntries + $scope.pageSize); }; $scope.loadAll = function() { $scope.showAllEntriesButton = false; loadEntries($scope.loadedEntries, $scope.allEntries.length); }; $scope.translateStreamEntryClick = function(entry, isRetry) { getTranslationDetails(entry, isRetry); }; $scope.translateStreamEntryKeypress = function(event, entry, isRetry) { var key = event.keyCode || event.which; if (key === 32) { event.preventDefault(); getTranslationDetails(entry, isRetry); } }; function getTranslationDetails(entry, isRetry) { if ($injector.has('translateStream')) { var handler = $injector.get('translateStream'); handler.getTranslatedContent(entry, isRetry); } }; $scope.translationToggleClick = function(entry) { toggleTranslationLink(entry); }; $scope.translationToggleKeypress = function(event, entry) { var key = event.keyCode || event.which; if (key === 32) { event.preventDefault(); toggleTranslationLink(entry); } }; function toggleTranslationLink(entry) { if ($injector.has('translateStream')) { var handler = $injector.get('translateStream'); handler.toggleTranslation(entry); } }; $scope.$on('sn.stream.translation_successful', function(event, data) { data.entry.translatedText = $scope.parseSpecial(data.translatedText); }); function loadEntries(start, end) { $scope.entries = $scope.entries.concat($scope.allEntries.slice(start, end)); $scope.loadedEntries = $scope.entries.length; $scope.$emit('sn.stream.entries_change', $scope.entries); } function getAttachmentType(attachment) { if (attachment.content_type.startsWith('image/') && attachment.content_type.indexOf("tiff") < 0 && attachment.size_bytes < 5 * 1024 * 1024 && attachment.path.indexOf(attachment.sys_id) == 0) return 'attachment-image'; return 'attachment'; } function getAttachmentExt(attachment) { var filename = attachment.file_name; return filename.substring(filename.lastIndexOf('.') + 1); } function handleJournalEntriesWithoutExtraction(oneLargeEntry) { if (oneLargeEntry.entries.journal.length === 0) return oneLargeEntry; for (var i = 0; i < oneLargeEntry.entries.journal.length; i++) { newLinesToBR(oneLargeEntry.entries.journal); } return oneLargeEntry; } function extractJournalEntries(oneLargeEntry) { var smallerEntries = []; if (oneLargeEntry.entries.journal.length === 0) return oneLargeEntry; for (var i = 0; i < oneLargeEntry.entries.journal.length; i++) { var journalEntry = angular.copy(oneLargeEntry); journalEntry.entries.journal = journalEntry.entries.journal.slice(i, i + 1); newLinesToBR(journalEntry.entries.journal); journalEntry.entries.changes = []; journalEntry.type = 'journal'; smallerEntries.unshift(journalEntry); } oneLargeEntry.entries.journal = []; oneLargeEntry.type = 'changes'; if (oneLargeEntry.entries.changes.length > 0) smallerEntries.unshift(oneLargeEntry); return smallerEntries; } function newLinesToBR(entries) { angular.forEach(entries, function(item) { if (item.new_value) { item.new_value = item.new_value.replace(/\n/g, '<br/>'); } if (item.sanitized_new_value) { item.sanitized_new_value = item.sanitized_new_value.replace(/\n/g, '<br/>'); } }); } function cancelStream() { if (_firstPollTimeout) { clearTimeout(_firstPollTimeout); _firstPollTimeout = false; } if (!stream) return false; stream.cancel(); stream = null; return true; } function setMultipleInputs() { $scope.multipleInputs = $scope.useMultipleInputs; if ($scope.useMultipleInputs === true || !$scope.formJournalFields) { return; } var numAffectedFields = 0; angular.forEach($scope.formJournalFields, function(item) { if (item.mandatory || item.value) numAffectedFields++; }); if (numAffectedFields > 0) $scope.multipleInputs = true; } function triggerResize() { if (window._frameChanged) setTimeout(_frameChanged, 0); } var filterPopoverButton = angular.element("#activity_field_filter_button"); var filterPopoverContents = angular.element("#activity_field_filter_popover"); var filterFocusTrap; var scrollingContainer; var screenSize; $scope.filterOpen = false; filterPopoverButton.on("shown.bs.popover", function() { $scope.$apply(function () { $scope.filterOpen = true; filterPopoverContents.parent().parent().attr("role", "presentation"); markListBoxAsFocused('activity_filter_all', false); }); filterFocusTrap = $window.focusTrap(filterPopoverContents[0], { clickOutsideDeactivates:true, initialFocus: '#activity_filter_all' }); filterFocusTrap.activate(); }); filterPopoverButton.on("hidden.bs.popover", function() { $scope.$apply(function () { $scope.filterOpen = false; }); filterFocusTrap.deactivate(); }); filterPopoverButton.on('keydown', function(evt) { if (!$scope.filterOpen && evt.keyCode === 13) { filterPopoverButton.popover('show'); } }); filterPopoverContents.on('keydown', function(evt) { if (evt.keyCode === 38 || (evt.shiftKey && evt.keyCode === 9)) { evt.preventDefault(); var focusedElement = getFocusedElement(); if (!focusedElement) return; var previousElementParent = (focusedElement.tagName === 'INPUT') ? focusedElement.parentElement.previousElementSibling : focusedElement.previousElementSibling; if (!previousElementParent) return; focusedElement.removeAttribute('focused'); var previousElementId = (previousElementParent.tagName === 'SPAN') ? previousElementParent.firstElementChild.id : previousElementParent.id; markListBoxAsFocused(previousElementId, true); } else if (evt.keyCode === 40 || evt.keyCode === 9) { evt.preventDefault(); var focusedElement = getFocusedElement(); if (!focusedElement) return; var nextElementParent = (focusedElement.tagName === 'INPUT') ? focusedElement.parentElement.nextElementSibling : focusedElement.nextElementSibling; if (!nextElementParent) return; focusedElement.removeAttribute('focused'); var nextElementId = (nextElementParent.tagName === 'SPAN') ? nextElementParent.firstElementChild.id : nextElementParent.id; markListBoxAsFocused(nextElementId, true); } if (evt.keyCode !== 27) { return; } filterPopoverButton.popover('hide'); }); filterPopoverContents.on("click", "input[type=checkbox]", function() { var focusedElement = getFocusedElement(); if (focusedElement) focusedElement.removeAttribute("focused"); markListBoxAsFocused(this.id, false); }); filterPopoverContents.on("focus", "input[type=checkbox]", function() { if (!scrollingContainer) { scrollingContainer = filterPopoverContents.parent(".popover-content")[0]; screenSize = scrollingContainer.offsetHeight; } var scrollTopPos = scrollingContainer.scrollTop; var itemSize = this.parentElement.offsetHeight; var offsetTop = this.parentElement.offsetTop; var offsetBot = offsetTop + itemSize; if (this.id == "activity_filter_all") { scrollingContainer.scrollTop = 0; } else if (scrollTopPos > offsetTop) { scrollingContainer.scrollTop = offsetTop; } else if (offsetBot > screenSize + scrollTopPos) { scrollingContainer.scrollTop = offsetBot - screenSize; } }); function getFocusedElement() { return document.querySelector("#activity_field_filter_listbox [focused]"); } function markListBoxAsFocused(id, setFocus) { var filterListBox = document.getElementById('activity_field_filter_listbox'); if (!filterListBox) return; filterListBox.setAttribute('aria-activedescendant', id); var focusedElement = document.getElementById(id); if (!focusedElement) return; focusedElement.setAttribute('focused', ''); if (setFocus) focusedElement.focus(); } snCustomEvent.fire("sn.stream.loaded"); }).filter('visibleFields', function() { return function(fields) { var obj = {}; angular.forEach(fields, function(field) { if (field.visible) { obj[field.name] = field; } }); return obj; } }); ; /*! RESOURCE: /scripts/sn/common/stream/directive.snStream.js */ angular.module("sn.common.stream").directive("snStream", function(getTemplateUrl, $http, $sce, $sanitize) { "use strict"; return { restrict: "E", replace: true, scope: { table: "=", query: "=?", sysId: "=?", active: "=", controls: "=?", showCommentsAndWorkNotes: "=?", previousActivity: "=?", sessions: "=", attachments: "=", board: "=", formJournalFields: "=", useMultipleInputs: "=?", preferredInput: "=", labels: "=", subStream: "=", expandEntries: "=", scaleAnimatedGifs: "=", scaleImages :"=", pageSize: "=", maxEntries: "@" }, templateUrl: getTemplateUrl("ng_activity_stream.xml"), controller: "snStream", link: function (scope, element) { element.on("click", ".at-mention", function(evt) { var userID = angular.element(evt.target).attr('class').substring("at-mention at-mention-user-".length); $http({ url: '/api/now/form/mention/user/' + userID, method: "GET" }).then(function(response) { scope.showPopover = true; scope.mentionPopoverProfile = response.data.result; scope.clickEvent = evt; }, function () { $http({ url: '/api/now/live/profiles/' + userID, method: "GET" }).then(function(response) { scope.showPopover = true; var tempProfile = response.data.result; tempProfile.userID = tempProfile.sys_id = response.data.result.document; scope.mentionPopoverProfile = tempProfile; scope.mentionPopoverProfile.sysID = response.data.result["userID"]; scope.clickEvent = evt; }) }); }); scope.toggleEmailIframe = function(email, event){ email.expanded = !email.expanded; event.preventDefault(); }; } }; }); ; /*! RESOURCE: /scripts/sn/common/stream/directive.formStreamEntry.js */ angular.module('sn.common.stream').directive('formStreamEntry', function(getTemplateUrl) { return { restrict: 'A', templateUrl: getTemplateUrl('record_stream_entry.xml') } }); ; /*! RESOURCE: /scripts/sn/common/stream/directive.snExpandedEmail.js */ angular.module("sn.common.stream").directive("snExpandedEmail", function() { "use strict"; return { restrict: "E", replace: true, scope: { email: "=" }, template: "<iframe style='width: 100%;' class='card' src='{{::emailBodySrc}}'></iframe>", controller: function($scope){ $scope.emailBodySrc = "email_display.do?email_id=" + $scope.email.sys_id.displayValue; }, link: function(scope, element) { element.load(function(){ var bodyHeight = $j(this).get(0).contentWindow.document.body.scrollHeight + "px"; $j(this).height(bodyHeight); }); } }; }); ; /*! RESOURCE: /scripts/app.form_presence/controller.formStream.js */ (function() { var journalModel = {}; window.journalModel = journalModel; CustomEvent.observe('sn.form.journal_field.add', function(name, mandatory, readonly, visible, value, label) { journalModel[name] = { name: name, mandatory: mandatory, readonly: readonly, visible: visible, value: value, label: label, messages: [] }; }); CustomEvent.observe('sn.form.journal_field.readonly', function(name, readonly) { modifyJournalAttribute(name, "readonly", readonly); }); CustomEvent.observe('sn.form.journal_field.value', function(name, value) { modifyJournalAttribute(name, "value", value); }); CustomEvent.observe('sn.form.journal_field.mandatory', function(name, mandatory) { modifyJournalAttribute(name, "mandatory", mandatory); }); CustomEvent.observe('sn.form.journal_field.visible', function(name, visible) { modifyJournalAttribute(name, "visible", visible); }); CustomEvent.observe('sn.form.journal_field.label', function(name, visible) { modifyJournalAttribute(name, "label", visible); }); CustomEvent.observe('sn.form.journal_field.show_msg', function(name, message, type) { var messages = journalModel[name]['messages'].concat([{ type: type, message: message }]); modifyJournalAttribute(name, 'messages', messages); }); CustomEvent.observe('sn.form.journal_field.hide_msg', function(name, clearAll) { if (journalModel[name]['messages'].length == 0) return; var desiredValue = []; if (!clearAll) desiredValue = journalModel[name]['messages'].slice(1); modifyJournalAttribute(name, 'messages', desiredValue); }); CustomEvent.observe('sn.form.hide_all_field_msg', function(type) { var fields = Object.keys(journalModel); for (var i = 0; i < fields.length; i++) { var f = fields[i]; if (journalModel[f].messages.length == 0) continue; var messages = []; if (type) { var oldMessages = angular.copy(journalModel[f].messages); for (var j = 0; j < oldMessages.length; j++) { if (oldMessages[j].type != type) messages.push(oldMessages[j]); } } modifyJournalAttribute(f, 'messages', messages); } }); CustomEvent.observe('sn.stream.insert', function(field, text) { if (typeof window.g_form !== "undefined") g_form.getControl(field).value = NOW.STREAM_VALUE_KEY + text; }); CustomEvent.observe('sn.stream.clear', function(field) { if (window.g_form) journalModel[field].value = g_form.getControl(field).value = ""; }); function modifyJournalAttribute(field, prop, value) { if (journalModel[field][prop] === value) return; journalModel[field][prop] = value; CustomEvent.fire('sn.form.journal_field.changed'); } angular.module('sn.common.stream').controller('formStream', function($scope, snCustomEvent, i18n) { var isFiltered = !angular.element('.activity-stream-label-filtered').hasClass('hide'); var _inlineTemplateCache; function renderLabel(count) { var processedLabel = _getLabel(count); angular.element('.activity-stream-label-counter').html(processedLabel); angular.element('.activity-stream-label-filtered').toggleClass('hide', !isFiltered); } function _getLabel(count) { var label = 'Activities: {0}'; return i18n.getMessage(label).withValues([count]); } function _getInlineEntries() { if (_inlineTemplateCache === 0) { return 0; } _inlineTemplateCache = document.querySelectorAll('#sn_form_inline_stream_container ul.activities-form li.h-card_comments').length; return _inlineTemplateCache; } $scope.$on('sn.stream.entries_change', function(evt, entries) { var inlineTemplateCount = _getInlineEntries(); var count = inlineTemplateCount + entries.length; renderLabel(count); }); $scope.$on('sn.stream.is_filtered_change', function(evt, filtered) { isFiltered = filtered; }); $scope.formJournalFields = journalModel; $scope.formJournalFieldsVisible = false; setUp(); snCustomEvent.observe('sn.form.journal_field.changed', function() { setUp(); if (!$scope.$$phase) $scope.$apply(); }); function setUp() { setInputValue(); } function setInputValue() { angular.forEach($scope.formJournalFields, function(item) { if (typeof window.g_form === "undefined") return; item.value = g_form.getValue(item.name); if (!item.readonly && item.visible && item.value) { $scope.$broadcast('sn.stream.input_value', item.name, item.value); } }); } }) })(); ; /*! RESOURCE: /scripts/app.form_presence/directive.scroll_form.js */ angular.module('sn.common.stream').directive('scrollFrom', function() { "use strict"; var SCROLL_TOP_PAD = 10; return { restrict: 'A', link: function($scope, $element, $attrs) { var target = $attrs.scrollFrom; $j(target).click(function(evt) { if (window.g_form) { var tab = g_form._getTabNameForElement($element); if (tab) g_form.activateTab(tab); } $element.find('textarea').filter(':visible:first').focus(); var $scrollRoot = $element.closest('.form-group'); if ($scrollRoot.length === 0) $scrollRoot = $element; var $scrollParent = $scrollRoot.scrollParent(); var offset = $element.offset().top - $scrollParent.offset().top - SCROLL_TOP_PAD + $scrollParent.scrollTop(); $scrollParent.animate({ scrollTop: offset }, '500', 'swing'); evt.stopPropagation(); }) } } }); ; ; /*! RESOURCE: /scripts/sn/common/dynamicTranslation/js_includes_dynamicTranslation.js */ /*! RESOURCE: /scripts/sn/common/dynamicTranslation/_module.js */ angular.module('sn.common.dynamicTranslation', ['sn.common.i18n']); ; /*! RESOURCE: /scripts/sn/common/dynamicTranslation/service.dynamicTranslation.js */ angular.module('sn.common.dynamicTranslation').provider('dynamicTranslation', function () { function getDynamicTranslationRequestConfig() { return { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }; } function setSourceInParms(parms) { parms = parms || {}; parms.event = parms.event || {}; parms.event.source = 'portalAPI'; return parms; } function isNotValidInputText(msg) { return (typeof msg !== 'string'); } function isNotValidString(str) { return ((str == null) || (typeof str !== 'string')) ? true : (str.trim().length === 0); } function isNotValidTranslator(translator) { return ((translator != null) && (typeof translator !== 'string')); } function isNotValidTargetLanguages(targetLanguages) { if (!Array.isArray(targetLanguages) || (targetLanguages.length === 0)) { return true; } for (var index = 0; index < targetLanguages.length; index++) { if (isNotValidString(targetLanguages[index])) { return true; } } return false; } function isNotValidAdditionalParameters(additionalParameters) { if (!Array.isArray(additionalParameters) || (additionalParameters.length === 0)) { return true; } else { for (var index = 0; index < additionalParameters.length; index++) { var additionalParameter = additionalParameters[index]; if (!additionalParameter || (additionalParameter.constructor !== {}.constructor) || (Object.keys(additionalParameter).length !== 2)) { return true; } for (eachkey in additionalParameter) { if (!(eachkey === 'parameterName' || eachkey === 'parameterValue') || isNotValidString(additionalParameter[eachkey])) { return true; } } } } return false; } function isNotValidTexts(texts) { if (!Array.isArray(texts) || (texts.length === 0)) { return true; } for (var index = 0; index < texts.length; index++) { if (isNotValidInputText(texts[index])) { return true; } } return false; } var errorHandler = { rejectErrorMessage: function (response) { if (this.hasMultipleTexts) { this.defer.reject({ 'code': this.code, 'message': response, 'status': 'Error' }); } else { this.defer.reject({ 'code': this.code, 'message': response }); } } }; function validateOptionalParameters(parms, defer, i18n, isTranslation, hasMultipleTexts) { errorHandler['hasMultipleTexts'] = hasMultipleTexts; errorHandler['defer'] = defer; if (parms.constructor !== {}.constructor) { errorHandler['code'] = '40006'; i18n.getMessage("Additional parameters are invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); return false; } if (isNotValidTranslator(parms.translator)) { errorHandler['code'] = '40003'; i18n.getMessage("Translator (\"translator\" field) is invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); return false; } if (isTranslation) { if ((parms.sourceLanguage != null) && isNotValidString(parms.sourceLanguage)) { errorHandler['code'] = '40008'; i18n.getMessage("Source language (\"sourceLanguage\" field) is invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); return false; } if (parms.targetLanguages && isNotValidTargetLanguages(parms.targetLanguages)) { errorHandler['code'] = '40007'; i18n.getMessage("Target languages (\"targetLanguages\" field) are invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); return false; } if (parms.additionalParameters && isNotValidAdditionalParameters(parms.additionalParameters)) { errorHandler['code'] = '40006'; i18n.getMessage("Additional parameters are invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); return false; } } return true; } function handleErrorResponse(response, defer, i18n, hasMultipleTexts) { errorHandler['hasMultipleTexts'] = hasMultipleTexts; errorHandler['defer'] = defer; if (response === 400) { errorHandler['code'] = '40001'; i18n.getMessage("Dynamic Translation plugin is not installed", errorHandler.rejectErrorMessage.bind(errorHandler)); } else { errorHandler['code'] = '40051'; i18n.getMessage("Unknown error occurred", errorHandler.rejectErrorMessage.bind(errorHandler)); } } this.$get = function ($http, $q, i18n) { return { getTranslation: function (textToTranslate, parms) { var GET_DYNAMIC_TRANSLATION = "/api/sn_dt/v1/dynamic_translation/get_dynamic_translation"; function getOnSuccessResponse(data) { var successResponse = { 'translations': data.result.translations, 'translator': data.result.translator }; if (data.result.detectedLanguage) { successResponse['detectedLanguage'] = data.result.detectedLanguage; } return successResponse; } function getOnErrorResponse(data) { return JSON.parse(data.result.errorMessage); } var defer = $q.defer(); if (isNotValidInputText(textToTranslate)) { errorHandler['defer'] = defer; errorHandler['code'] = '40000'; i18n.getMessage("Text is missing or invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); } else if (!parms || validateOptionalParameters(parms, defer, i18n, true, false)) { var requestBody = { 'textToTranslate': textToTranslate, 'parms': setSourceInParms(parms) }; var config = getDynamicTranslationRequestConfig(); $http.post(GET_DYNAMIC_TRANSLATION, requestBody, config).success(function (data) { if (!data.result.isError) defer.resolve(getOnSuccessResponse(data)); else defer.reject(getOnErrorResponse(data)); }).error(function (error, status) { handleErrorResponse(status, defer, i18n, false); }); } return defer.promise; }, getTranslations: function (textsToTranslate, parms) { var GET_DYNAMIC_TRANSLATIONS = "/api/sn_dt/v1/dynamic_translation/get_dynamic_translations"; function getOnSuccessResponse(response) { var successResponse = { 'status': response.result.status, 'translations': response.result.translations, 'translator': response.result.translator }; return successResponse; } function getOnErrorResponse(response) { var errorDetails = JSON.parse(response.result.errorMessage); var errorResponse = { 'status': errorDetails.status, 'code': errorDetails.code, 'message': errorDetails.message }; if (errorDetails['translations']) { errorResponse['translations'] = errorDetails['translations']; } return errorDetails; } var defer = $q.defer(); if ((!textsToTranslate) || isNotValidTexts(textsToTranslate)) { errorHandler['defer'] = defer; errorHandler['code'] = '40000'; errorHandler['hasMultipleTexts'] = true; i18n.getMessage("Text is missing or invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); } else if (!parms || validateOptionalParameters(parms, defer, i18n, true, true)) { var requestBody = { 'textsToTranslate': textsToTranslate, 'parms': setSourceInParms(parms) }; var config = getDynamicTranslationRequestConfig(); $http.post(GET_DYNAMIC_TRANSLATIONS, requestBody, config).success(function (data) { if (!data.result.isError) defer.resolve(getOnSuccessResponse(data)); else defer.reject(getOnErrorResponse(data)); }).error(function (error, status) { handleErrorResponse(status, defer, i18n, true); }); } return defer.promise; }, isTranslationEnabled: function (translator) { var defer = $q.defer(); if ((translator) && (typeof translator !== 'string')) { i18n.getMessage("Translator (\"translator\" field) is invalid", function (response) { defer.reject({ 'code': '40003', 'message': response }); }); } else { var params = { event: { eventName: 'isTranslationEnabled' }, translator: translator }; this.isEnabled(params).then( function (data) { defer.resolve(data.translation); }, function (data) { defer.reject(false); } ); } return defer.promise; }, getDetectedLanguage: function (text, parms) { var GET_DETECTED_LANGUAGE = '/api/sn_dt/v1/dynamic_translation/get_detected_language'; function getOnSuccessResponse(data) { return { 'detectedLanguage': data.result.detectedLanguage, 'alternatives': data.result.alternatives, 'translator': data.result.translator }; } function getOnErrorResponse(data) { return JSON.parse(data.result.errorMessage); } var defer = $q.defer(); if (isNotValidInputText(text)) { errorHandler['defer'] = defer; errorHandler['code'] = '40000'; i18n.getMessage("Text is missing or invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); } else if (!parms || validateOptionalParameters(parms, defer, i18n, false, false)) { var requestBody = { 'text': text, 'parms': setSourceInParms(parms) }; var config = getDynamicTranslationRequestConfig(); $http.post(GET_DETECTED_LANGUAGE, requestBody, config).success(function (data) { if (!data.result.isError) defer.resolve(getOnSuccessResponse(data)); else defer.reject(getOnErrorResponse(data)); }).error(function (response, status) { handleErrorResponse(status, defer, i18n, false); }); } return defer.promise; }, getDetectedLanguages: function (texts, parms) { var GET_DETECTED_LANGUAGES = '/api/sn_dt/v1/dynamic_translation/get_detected_languages'; function getOnSuccessResponse(response) { var successResponse = { 'status': response.result.status, 'detections': response.result.detections, 'translator': response.result.translator }; return successResponse; } function getOnErrorResponse(response) { var errorDetails = JSON.parse(response.result.errorMessage); var errorResponse = { 'status': errorDetails.status, 'code': errorDetails.code, 'message': errorDetails.message }; if (errorDetails['detections']) { errorResponse['detections'] = errorDetails['detections']; } return errorDetails; } var defer = $q.defer(); if ((!texts) || isNotValidTexts(texts)) { errorHandler['defer'] = defer; errorHandler['code'] = '40000'; errorHandler['hasMultipleTexts'] = true; i18n.getMessage("Text is missing or invalid", errorHandler.rejectErrorMessage.bind(errorHandler)); } else if (!parms || validateOptionalParameters(parms, defer, i18n, false, true)) { var requestBody = { 'texts': texts, 'parms': setSourceInParms(parms) }; var config = getDynamicTranslationRequestConfig(); $http.post(GET_DETECTED_LANGUAGES, requestBody, config).success(function (data) { if (!data.result.isError) defer.resolve(getOnSuccessResponse(data)); else defer.reject(getOnErrorResponse(data)); }).error(function (response, status) { handleErrorResponse(status, defer, i18n, true); }); } return defer.promise; }, isEnabled: function (parms) { var IS_ENABLED = "/api/sn_dt/v1/dynamic_translation/is_enabled"; function isValidTranslator(translator) { return (translator && (typeof translator !== 'string')) ? false : true; } var defer = $q.defer(); var translator = (parms && (parms.constructor === {}.constructor)) ? parms.translator : parms; if (isValidTranslator(translator)) { parms = (typeof parms === 'string') ? { 'translator': translator } : parms; var requestBody = { 'parms': setSourceInParms(parms) }; var config = getDynamicTranslationRequestConfig(); $http.post(IS_ENABLED, requestBody, config).success(function (data) { defer.resolve(data.result); }).error(function (response, status) { defer.resolve({ 'translation': false, 'detection': false, 'batchTranslation': false, 'batchDetection': false }); }); } else { i18n.getMessage("Translator (\"translator\" field) is invalid", function (response) { defer.reject({ 'code': '40003', 'message': response }); }); } return defer.promise; } }; }; }); ; ; /*! RESOURCE: /scripts/doctype/GlideWebAnalytics.js */ var GlideWebAnalytics = (function() { function subscribe() { window.snWebaConfig = window.snWebaConfig || {}; if (window.snWebaConfig.subscribed && window.snWebaConfig.subscribed == true) return; var ambClient = getAMB(); if (ambClient == undefined || ambClient == "") return; var webaChannelId = "/weba/config"; var webaCh = ambClient.getChannel(webaChannelId); webaCh.subscribe(function(response) { if (window.snWebaConfig == undefined || window.snWebaConfig == null) window.snWebaConfig = {}; var oldConfig = { siteId : (window.snWebaConfig.siteId)? window.snWebaConfig.siteId: "0" , trackerURL : (window.snWebaConfig.trackerURL)? window.snWebaConfig.trackerURL: "" }; window.snWebaConfig.siteId = response.data.weba_site_id; window.snWebaConfig.trackerURL = response.data.weba_rx_url; window.snWebaConfig.webaScriptPath = response.data.weba_script_path; handleConfigUpdate(oldConfig, window.snWebaConfig); }); ambClient.connect(); window.snWebaConfig.subscribed = true; } function getAMB(){ var ambClient = window.snWebaConfig.ambClient; if (ambClient) return ambClient; window.snWebaConfig.ambClient = (window.g_ambClient) ? window.g_ambClient : ((window.amb)? window.amb.getClient(): ""); return window.snWebaConfig.ambClient; } function handleConfigUpdate(oldConfig, newConfig) { if (shouldRemoveTracker(oldConfig, newConfig)) removeTracker(); else if (shouldUpdateTracker(oldConfig, newConfig)) updateTracker(oldConfig, newConfig); else if (shouldInsertTracker(oldConfig, newConfig)) insertTracker(newConfig); } function shouldRemoveTracker(oldConfig, newConfig){ if (newConfig.siteId == "0" || newConfig.trackerURL == "") return true; return false; } function shouldUpdateTracker(oldConfig, newConfig){ if (oldConfig.siteId && oldConfig.siteId != "0" && oldConfig.siteId != newConfig.siteId) return true; if (oldConfig.trackerURL && oldConfig.trackerURL != newConfig.trackerURL) return true; return false; } function shouldInsertTracker(oldConfig, newConfig){ if (oldConfig.siteId == undefined || oldConfig.siteId == "0") return true; if (oldConfig.trackerURL == undefined || oldConfig.trackerURL == "") return true; return false; } function removeTracker() { if (!trackerExists()) return; removeWebaTracker(); removeWebaScript(); removeWebaElements(); } function removeWebaTracker() { var document = window.parent.document; var trackerScriptId = "webaTracker"; var trackEle = document.getElementById(trackerScriptId); trackEle.parentNode.removeChild(trackEle); } function removeWebaScript() { var document = window.parent.document; var asyncTrackEle = document.getElementById('webaScript'); if (asyncTrackEle == undefined) return; var src = asyncTrackEle.src; if (src != undefined && src.indexOf("piwik") > 0) asyncTrackEle.parentNode.removeChild(asyncTrackEle); } function removeWebaElements() { var document = window.parent.document; var webaEle = document.getElementsByClassName("weba"); var webaSize = webaEle.length - 1; while (webaSize >= 0){ webaEle[webaSize].parentNode.removeChild(webaEle[webaSize]); webaSize--; } } function updateTracker(oldConfig, newConfig) { if (!trackerExists()) return; var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; var updateScript = "_paq.push(['setSiteId', " + newConfig.siteId + "]);" + "_paq.push(['setTrackerUrl', " + "'" + newConfig.trackerURL + "'" + "]);"; var uEle = window.document.createElement("script"); uEle.text = updateScript; uEle.className = "weba"; head.appendChild(uEle); } function insertTracker(newConfig, additionalData) { var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; if (trackerExists()) return; if (!isConfigValid(newConfig)) return; var trackerScript = generateTrackerScript(newConfig, additionalData); var trackerElement = getOrCreateTracker(); trackerElement.text = trackerScript; head.appendChild(trackerElement); } function applyTracker(additionalData) { insertTracker(window.snWebaConfig, additionalData); subscribe(); } function applyTrackEvent(category, key, value, additionalValue) { insertEventTracker(category, key, value, additionalValue); subscribe(); } function insertEventTracker(category, key, value, additionalValue) { if (!isConfigValid(window.snWebaConfig)) return; if (!trackerExists()) insertTracker(window.snWebaConfig); if (typeof category != "string" || typeof key != "string" || typeof value != "string") return; if (additionalValue) additionalValue = (typeof additionalValue == "number")? additionalValue: 0; var eventItems = [ "trackEvent", category, key, value, additionalValue ]; var eventScript = "_paq.push(" + JSON.stringify(eventItems) + ");"; var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; var scriptEle = window.document.createElement("script"); scriptEle.className = "weba"; scriptEle.text = eventScript; head.appendChild(scriptEle); } function trackerExists() { var document = window.parent.document; var trackEle = document.getElementById("webaTracker"); if (trackEle) return true; return false; } function isConfigValid(newConfig) { var zero = "0"; var webaSiteId = (newConfig && newConfig.siteId) ? newConfig.siteId : zero; var trackerURL = (newConfig && newConfig.trackerURL) ? newConfig.trackerURL : ""; if (webaSiteId == null || webaSiteId == "") return false; if (webaSiteId == zero ) return false; if (trackerURL == null || trackerURL == "") return false; return true; } function getOrCreateTracker() { var trackerScriptId = "webaTracker"; var document = window.parent.document; var trackEle = document.getElementById(trackerScriptId); if (trackEle) return trackEle; trackEle = document.createElement("script"); trackEle.id = trackerScriptId; trackEle.type = "text/javascript"; return trackEle; } function getUserId(additionalData) { if (window.NOW && window.NOW.user_id && window.NOW.user_id != "") return window.NOW.user_id; else if (additionalData && additionalData.userId){ return additionalData.userId; } else if (window.NOW && window.NOW.session_id) return window.NOW.session_id; else { var userObj = (window.NOW)? window.NOW.user: null; if (userObj && userObj.userID) return userObj.userID; } return ""; } function generateTrackerScript(webaConfig, additionalData) { var trackerURL = webaConfig.trackerURL; if (trackerURL.endsWith("/")) trackerURL = webaConfig.trackerURL.substring(0, trackerURL.length - 1); var userId = getUserId(additionalData); var script = "var _paq = _paq || [];"; if (userId && userId != ""){ script += "_paq.push(['setUserId', '" + userId + "']);"; } script += "_paq.push(['trackPageView']); _paq.push(['enableLinkTracking']);"; script += "(function() {_paq.push(['setTrackerUrl','" + trackerURL + "']);" + "_paq.push(['setSiteId', " + webaConfig.siteId + "]);" + "var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; " + "g.defer=true; g.src='" + webaConfig.webaScriptPath + "'; " + "g.id='webaScript';s.parentNode.insertBefore(g,s); })();"; return script; } var api = { trackPage: function(additionalData) { if (window.document.readyState == "complete") applyTracker(additionalData); else window.addEventListener("load", function() { applyTracker(additionalData); }, false); }, trackEvent: function(category, key, value, additionalValue, delayInMs) { if (delayInMs == undefined) delayInMs = 3000; window.setTimeout(function() { applyTrackEvent(category, key, value, additionalValue); }, delayInMs); } } return api; })(); ; ; /*! RESOURCE: /scripts/js_includes_ng_amb.js */ /*! RESOURCE: /scripts/js_includes_amb.js */ amb.getClient(); ; /*! RESOURCE: /scripts/app.ng.amb/app.ng.amb.js */ angular.module("ng.amb", ['sn.common.presence', 'sn.common.util']) .value("ambLogLevel", 'info') .value("ambServletURI", '/amb') .value("cometd", angular.element.cometd) .value("ambLoginWindow", 'true'); ; /*! RESOURCE: /scripts/app.ng.amb/service.AMB.js */ angular.module("ng.amb").service("amb", function (AMBOverlay, $window, $q, $log, $rootScope, $timeout) { "use strict"; var ambClient = null; var _window = $window.self; var loginWindow = null; var sameScope = false; ambClient = amb.getClient(); if (_window.g_ambClient) { sameScope = true; } if (sameScope) { var serverConnection = ambClient.getServerConnection(); serverConnection.loginShow = function() { if (!serverConnection.isLoginWindowEnabled()) return; if (loginWindow && loginWindow.isVisible()) return; if (serverConnection.isLoginWindowOverride()) return; var modalConfig = { onBeforeShow: addOverrideStyles }; loginWindow = new AMBOverlay(modalConfig); loginWindow.render(); loginWindow.show(); }; serverConnection.loginHide = function() { if (!loginWindow) return; loginWindow.hide(); loginWindow.destroy(); loginWindow = null; } } function addOverrideStyles(el) { var parent = angular.element(el.target).parent(); var backdrop = parent.find('.modal-backdrop').get(0); if (backdrop !== undefined) backdrop.style.cssText = [backdrop.style.cssText, serverConnection.getLoginWindowOverlayStyle()].join('; '); } var AUTO_CONNECT_TIMEOUT = 20 * 1000; var connected = $q.defer(); var connectionInterrupted = false; var monitorAMB = false; $timeout(startMonitoringAMB, AUTO_CONNECT_TIMEOUT); connected.promise.then(startMonitoringAMB); function startMonitoringAMB() { monitorAMB = true; } function ambInterrupted() { var state = ambClient.getState(); return monitorAMB && state !== "opened" && state !== "initialized" } var interruptionTimeout; var extendedInterruption = false; function setInterrupted(eventName) { connectionInterrupted = true; $rootScope.$broadcast(eventName); if (!interruptionTimeout) { interruptionTimeout = $timeout(function () { extendedInterruption = true; }, 30 * 1000) } connected = $q.defer(); } var connectOpenedEventId = ambClient.subscribeToEvent("connection.opened", function () { $rootScope.$broadcast("amb.connection.opened"); if (interruptionTimeout) { $timeout.cancel(interruptionTimeout); interruptionTimeout = null; } extendedInterruption = false; if(connectionInterrupted) { connectionInterrupted = false; $rootScope.$broadcast("amb.connection.recovered"); } connected.resolve(); }); var connectClosedEventId = ambClient.subscribeToEvent("connection.closed", function () { setInterrupted("amb.connection.closed"); }); var connectBrokenEventId = ambClient.subscribeToEvent("connection.broken", function () { setInterrupted("amb.connection.broken"); }); var connectSessionLoggedin = ambClient.subscribeToEvent("session.logged.in", function () { $rootScope.$broadcast("amb.session.logged.in"); }); var connectSessionReestablished = ambClient.subscribeToEvent("session.reestablished", function () { $rootScope.$broadcast("amb.session.reestablished"); }); var onUnloadWindow = function() { ambClient.unsubscribeFromEvent(connectOpenedEventId); ambClient.unsubscribeFromEvent(connectClosedEventId); ambClient.unsubscribeFromEvent(connectBrokenEventId); angular.element($window).off('unload', onUnloadWindow); }; angular.element($window).on('unload', onUnloadWindow); var defaultAmbConnectionTimeout = 10000; var shouldDeferAmbConnection = _window.NOW && _window.NOW.hasOwnProperty('deferAmbConnection') ? _window.NOW.deferAmbConnection : false; var deferredAmbConnectionTimeout = _window.NOW && _window.NOW.hasOwnProperty('deferredAmbConnectionTimeout') && isValidAmbConnectionTimeout(_window.NOW.deferredAmbConnectionTimeout) ? _window.NOW.deferredAmbConnectionTimeout : defaultAmbConnectionTimeout; if (shouldDeferAmbConnection) { $timeout(autoConnect, deferredAmbConnectionTimeout); } else { var documentReadyState = _window.document ? _window.document.readyState : null; if (documentReadyState === 'complete') autoConnect(); else _window.addEventListener('load', autoConnect); $timeout(autoConnect, defaultAmbConnectionTimeout); } function isInteger(num) { return parseInt(num, 10) === num; } function isValidAmbConnectionTimeout(timeout) { return isInteger(timeout) && timeout > 0; } var initiatedConnection = false; function autoConnect() { if (!initiatedConnection) { initiatedConnection = true; ambClient.connect(); } } return { getServerConnection: function() { return ambClient.getServerConnection(); }, connect: function() { if (initiatedConnection) { ambClient.connect(); } return connected.promise; }, get interrupted() { return ambInterrupted(); }, get extendedInterruption() { return extendedInterruption; }, get connected() { return connected.promise; }, abort: function() { ambClient.abort(); }, disconnect: function() { ambClient.disconnect(); }, getConnectionState: function () { return ambClient.getConnectionState(); }, getClientId: function () { return ambClient.getClientId(); }, getChannel: function(channelName) { return ambClient.getChannel(channelName); }, registerExtension: function(extensionName, extension) { ambClient.registerExtension(extensionName, extension); }, unregisterExtension: function(extensionName) { ambClient.unregisterExtension(extensionName); }, batch: function(batch) { ambClient.batch(batch); }, getState: function() { return ambClient.getState(); }, getFilterString: function(filter) { filter = filter. replace(/\^EQ/g, ''). replace(/\^ORDERBY(?:DESC)?[^^]*/g, ''). replace(/^GOTO/, ''); return btoa(unescape(encodeURIComponent(filter))).replace(/=/g, '-'); }, getChannelRW: function(table, filter) { var t = '/rw/default/' + table + '/' + this.getFilterString(filter); return this.getChannel(t); }, isLoggedIn: function() { return ambClient.isLoggedIn(); }, subscribeToEvent: function(event, callback) { return ambClient.subscribeToEvent(event, callback); }, getConnectionEvents: function() { return ambClient.getConnectionEvents(); }, getEvents: function() { return ambClient.getConnectionEvents(); }, loginComplete: function() { ambClient.loginComplete(); } }; }); ; /*! RESOURCE: /scripts/app.ng.amb/controller.AMBRecordWatcher.js */ angular.module("ng.amb").controller("AMBRecordWatcher", function($scope, $timeout, $window) { "use strict"; var amb = $window.top.g_ambClient; $scope.messages = []; var lastFilter; var watcherChannel; var watcher; function onMessage(message) { $scope.messages.push(message.data); } $scope.getState = function() { return amb.getState(); }; $scope.initWatcher = function() { angular.element(":focus").blur(); if(!$scope.filter || $scope.filter === lastFilter) return; lastFilter = $scope.filter; console.log("initiating watcher on " + $scope.filter); $scope.messages = []; if(watcher) { watcher.unsubscribe(); } var base64EncodeQuery = btoa($scope.filter).replace(/=/g, '-'); var channelId = '/rw/' + base64EncodeQuery; watcherChannel = amb.getChannel(channelId) watcher = watcherChannel.subscribe(onMessage); }; amb.connect(); }) ; /*! RESOURCE: /scripts/app.ng.amb/factory.snRecordWatcher.js */ angular.module("ng.amb").factory('snRecordWatcher', function($rootScope, amb, $timeout, snPresence, $log, urlTools) { "use strict"; var diagnosticLog = true; function initWatcher(table, sys_id, query) { if (!table) return; if (sys_id) var filter = "sys_id=" + sys_id; else filter = query; if (!filter) return; return initChannel(table, filter); } function initList(table, query) { if (!table) return; query = query || "sys_idISNOTEMPTY"; return initChannel(table, query); } function initTaskList(list, prevChannel) { if (prevChannel) prevChannel.unsubscribe(); var sys_ids = list.toString(); var filter = "sys_idIN" + sys_ids; return initChannel("task", filter); } function initChannel(table, filter, callbackFn) { if (isBlockedTable(table)) { $log.log("Blocked from watching", table); return null; } if (diagnosticLog) log(">>> init " + table + "?" + filter); var watcherChannel = amb.getChannelRW(table, filter); watcherChannel.subscribe(callbackFn || onMessage); amb.connect(); return watcherChannel; } function onMessage(message) { var r = message.data; var c = message.channel; if (diagnosticLog) log(">>> record " + r.operation + ": " + r.table_name + "." + r.sys_id + " " + r.display_value); $rootScope.$broadcast('record.updated', r); $rootScope.$broadcast('list.updated', r, c); } function log(message) { $log.log(message); } function isBlockedTable(table) { return table == 'sys_amb_message' || table.startsWith('sys_rw'); } return { initTaskList: initTaskList, initChannel: initChannel, init: function () { var location = urlTools.parseQueryString(window.location.search); var table = location['table'] || location['sysparm_table']; var sys_id = location['sys_id'] || location['sysparm_sys_id']; var query = location['sysparm_query']; initWatcher(table, sys_id, query); snPresence.init(table, sys_id, query); }, initList: initList, initRecord: function(table, sysId) { initWatcher(table, sysId, null); snPresence.initPresence(table, sysId); }, _initWatcher: initWatcher } }); ; /*! RESOURCE: /scripts/app.ng.amb/factory.AMBOverlay.js */ angular.module("ng.amb").factory("AMBOverlay", function($templateCache, $compile, $rootScope) { "use strict"; var showCallbacks = [], beforeShowCallbacks = [], hideCallbacks = [], isRendered = false, modal, modalScope, modalOptions; var defaults = { backdrop: 'static', keyboard: false, show: true }; function AMBOverlay(config) { config = config || {}; if(angular.isFunction(config.onBeforeShow)) beforeShowCallbacks.push(config.onBeforeShow); if(angular.isFunction(config.onShow)) showCallbacks.push(config.onShow); if(angular.isFunction(config.onHide)) hideCallbacks.push(config.onHide); function lazyRender() { if(!angular.element('html')['modal']) { var bootstrapInclude = "/scripts/bootstrap3/bootstrap.js"; ScriptLoader.getScripts([bootstrapInclude], renderModal); } else renderModal(); } function renderModal() { if(isRendered) return; modalScope = angular.extend($rootScope.$new(), config); modal = $compile($templateCache.get("amb_disconnect_modal.xml"))(modalScope); angular.element("body").append(modal); modal.on("show.bs.modal", function (e) { for(var i = 0, len = beforeShowCallbacks.length; i < len; i++) beforeShowCallbacks[i](e); }); modal.on("shown.bs.modal", function(e) { for(var i = 0, len = showCallbacks.length; i < len; i++) showCallbacks[i](e); }); modal.on("hidden.bs.modal", function(e) { for(var i = 0, len = hideCallbacks.length; i < len; i++) hideCallbacks[i](e); }); modalOptions = angular.extend({}, defaults, config); modal.modal(modalOptions); isRendered = true; } function showModal() { if(isRendered) modal.modal('show'); } function hideModal() { if(isRendered) modal.modal('hide'); } function destroyModal() { if(!isRendered) return; modal.modal('hide'); modal.remove(); modalScope.$destroy(); modalScope = void(0); isRendered = false; var pos = showCallbacks.indexOf(config.onShow); if(pos >= 0) showCallbacks.splice(pos, 1); pos = hideCallbacks.indexOf(config.onShow); if(pos >= 0) hideCallbacks.splice(pos, 1); } return { render: lazyRender, destroy: destroyModal, show: showModal, hide: hideModal, isVisible: function() { if(!isRendered) return false; return modal.visible(); } } } $templateCache.put('amb_disconnect_modal.xml', '<div id="amb_disconnect_modal" tabindex="-1" aria-hidden="true" class="modal" role="dialog">' + ' <div class="modal-dialog small-modal" style="width:450px">' + ' <div class="modal-content">' + ' <header class="modal-header">' + ' <h4 id="small_modal1_title" class="modal-title">{{title || "Login"}}</h4>' + ' </header>' + ' <div class="modal-body">' + ' <iframe class="concourse_modal" ng-src=\'{{iframe || "/amb_login.do"}}\' frameborder="0" scrolling="no" height="400px" width="405px"></iframe>' + ' </div>' + ' </div>' + ' </div>' + '</div>' ); return AMBOverlay; }); ; ; /*! RESOURCE: /scripts/angularjs-1.4/thirdparty/angular-ui-bootstrap/ui-bootstrap-tpls-0.12.1.js */ angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.transition","ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]); angular.module("ui.bootstrap.tpls", ["template/accordion/accordion-group.html","template/accordion/accordion.html","template/alert/alert.html","template/carousel/carousel.html","template/carousel/slide.html","template/datepicker/datepicker.html","template/datepicker/day.html","template/datepicker/month.html","template/datepicker/popup.html","template/datepicker/year.html","template/modal/backdrop.html","template/modal/window.html","template/pagination/pager.html","template/pagination/pagination.html","template/tooltip/tooltip-html-unsafe-popup.html","template/tooltip/tooltip-popup.html","template/popover/popover.html","template/progressbar/bar.html","template/progressbar/progress.html","template/progressbar/progressbar.html","template/rating/rating.html","template/tabs/tab.html","template/tabs/tabset.html","template/timepicker/timepicker.html","template/typeahead/typeahead-match.html","template/typeahead/typeahead-popup.html"]); angular.module('ui.bootstrap.transition', []) .factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) { var $transition = function(element, trigger, options) { options = options || {}; var deferred = $q.defer(); var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName']; var transitionEndHandler = function(event) { $rootScope.$apply(function() { element.unbind(endEventName, transitionEndHandler); deferred.resolve(element); }); }; if (endEventName) { element.bind(endEventName, transitionEndHandler); } $timeout(function() { if ( angular.isString(trigger) ) { element.addClass(trigger); } else if ( angular.isFunction(trigger) ) { trigger(element); } else if ( angular.isObject(trigger) ) { element.css(trigger); } if ( !endEventName ) { deferred.resolve(element); } }); deferred.promise.cancel = function() { if ( endEventName ) { element.unbind(endEventName, transitionEndHandler); } deferred.reject('Transition cancelled'); }; return deferred.promise; }; var transElement = document.createElement('trans'); var transitionEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'transition': 'transitionend' }; var animationEndEventNames = { 'WebkitTransition': 'webkitAnimationEnd', 'MozTransition': 'animationend', 'OTransition': 'oAnimationEnd', 'transition': 'animationend' }; function findEndEventName(endEventNames) { for (var name in endEventNames){ if (transElement.style[name] !== undefined) { return endEventNames[name]; } } } $transition.transitionEndEventName = findEndEventName(transitionEndEventNames); $transition.animationEndEventName = findEndEventName(animationEndEventNames); return $transition; }]); angular.module('ui.bootstrap.collapse', ['ui.bootstrap.transition']) .directive('collapse', ['$transition', function ($transition) { return { link: function (scope, element, attrs) { var initialAnimSkip = true; var currentTransition; function doTransition(change) { var newTransition = $transition(element, change); if (currentTransition) { currentTransition.cancel(); } currentTransition = newTransition; newTransition.then(newTransitionDone, newTransitionDone); return newTransition; function newTransitionDone() { if (currentTransition === newTransition) { currentTransition = undefined; } } } function expand() { if (initialAnimSkip) { initialAnimSkip = false; expandDone(); } else { element.removeClass('collapse').addClass('collapsing'); doTransition({ height: element[0].scrollHeight + 'px' }).then(expandDone); } } function expandDone() { element.removeClass('collapsing'); element.addClass('collapse in'); element.css({height: 'auto'}); } function collapse() { if (initialAnimSkip) { initialAnimSkip = false; collapseDone(); element.css({height: 0}); } else { element.css({ height: element[0].scrollHeight + 'px' }); var x = element[0].offsetWidth; element.removeClass('collapse in').addClass('collapsing'); doTransition({ height: 0 }).then(collapseDone); } } function collapseDone() { element.removeClass('collapsing'); element.addClass('collapse'); } scope.$watch(attrs.collapse, function (shouldCollapse) { if (shouldCollapse) { collapse(); } else { expand(); } }); } }; }]); angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse']) .constant('accordionConfig', { closeOthers: true }) .controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) { this.groups = []; this.closeOthers = function(openGroup) { var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers; if ( closeOthers ) { angular.forEach(this.groups, function (group) { if ( group !== openGroup ) { group.isOpen = false; } }); } }; this.addGroup = function(groupScope) { var that = this; this.groups.push(groupScope); groupScope.$on('$destroy', function (event) { that.removeGroup(groupScope); }); }; this.removeGroup = function(group) { var index = this.groups.indexOf(group); if ( index !== -1 ) { this.groups.splice(index, 1); } }; }]) .directive('accordion', function () { return { restrict:'EA', controller:'AccordionController', transclude: true, replace: false, templateUrl: 'template/accordion/accordion.html' }; }) .directive('accordionGroup', function() { return { require:'^accordion', restrict:'EA', transclude:true, replace: true, templateUrl:'template/accordion/accordion-group.html', scope: { heading: '@', isOpen: '=?', isDisabled: '=?' }, controller: function() { this.setHeading = function(element) { this.heading = element; }; }, link: function(scope, element, attrs, accordionCtrl) { accordionCtrl.addGroup(scope); scope.$watch('isOpen', function(value) { if ( value ) { accordionCtrl.closeOthers(scope); } }); scope.toggleOpen = function() { if ( !scope.isDisabled ) { scope.isOpen = !scope.isOpen; } }; } }; }) .directive('accordionHeading', function() { return { restrict: 'EA', transclude: true, template: '', replace: true, require: '^accordionGroup', link: function(scope, element, attr, accordionGroupCtrl, transclude) { accordionGroupCtrl.setHeading(transclude(scope, function() {})); } }; }) .directive('accordionTransclude', function() { return { require: '^accordionGroup', link: function(scope, element, attr, controller) { scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) { if ( heading ) { element.html(''); element.append(heading); } }); } }; }); angular.module('ui.bootstrap.alert', []) .controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) { $scope.closeable = 'close' in $attrs; this.close = $scope.close; }]) .directive('alert', function () { return { restrict:'EA', controller:'AlertController', templateUrl:'template/alert/alert.html', transclude:true, replace:true, scope: { type: '@', close: '&' } }; }) .directive('dismissOnTimeout', ['$timeout', function($timeout) { return { require: 'alert', link: function(scope, element, attrs, alertCtrl) { $timeout(function(){ alertCtrl.close(); }, parseInt(attrs.dismissOnTimeout, 10)); } }; }]); angular.module('ui.bootstrap.bindHtml', []) .directive('bindHtmlUnsafe', function () { return function (scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe); scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) { element.html(value || ''); }); }; }); angular.module('ui.bootstrap.buttons', []) .constant('buttonConfig', { activeClass: 'active', toggleEvent: 'click' }) .controller('ButtonsController', ['buttonConfig', function(buttonConfig) { this.activeClass = buttonConfig.activeClass || 'active'; this.toggleEvent = buttonConfig.toggleEvent || 'click'; }]) .directive('btnRadio', function () { return { require: ['btnRadio', 'ngModel'], controller: 'ButtonsController', link: function (scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio))); }; element.bind(buttonsCtrl.toggleEvent, function () { var isActive = element.hasClass(buttonsCtrl.activeClass); if (!isActive || angular.isDefined(attrs.uncheckable)) { scope.$apply(function () { ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio)); ngModelCtrl.$render(); }); } }); } }; }) .directive('btnCheckbox', function () { return { require: ['btnCheckbox', 'ngModel'], controller: 'ButtonsController', link: function (scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; function getTrueValue() { return getCheckboxValue(attrs.btnCheckboxTrue, true); } function getFalseValue() { return getCheckboxValue(attrs.btnCheckboxFalse, false); } function getCheckboxValue(attributeValue, defaultValue) { var val = scope.$eval(attributeValue); return angular.isDefined(val) ? val : defaultValue; } ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); }; element.bind(buttonsCtrl.toggleEvent, function () { scope.$apply(function () { ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); ngModelCtrl.$render(); }); }); } }; }); angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition']) .controller('CarouselController', ['$scope', '$timeout', '$interval', '$transition', function ($scope, $timeout, $interval, $transition) { var self = this, slides = self.slides = $scope.slides = [], currentIndex = -1, currentInterval, isPlaying; self.currentSlide = null; var destroyed = false; self.select = $scope.select = function(nextSlide, direction) { var nextIndex = slides.indexOf(nextSlide); if (direction === undefined) { direction = nextIndex > currentIndex ? 'next' : 'prev'; } if (nextSlide && nextSlide !== self.currentSlide) { if ($scope.$currentTransition) { $scope.$currentTransition.cancel(); $timeout(goNext); } else { goNext(); } } function goNext() { if (destroyed) { return; } if (self.currentSlide && angular.isString(direction) && !$scope.noTransition && nextSlide.$element) { nextSlide.$element.addClass(direction); var reflow = nextSlide.$element[0].offsetWidth; angular.forEach(slides, function(slide) { angular.extend(slide, {direction: '', entering: false, leaving: false, active: false}); }); angular.extend(nextSlide, {direction: direction, active: true, entering: true}); angular.extend(self.currentSlide||{}, {direction: direction, leaving: true}); $scope.$currentTransition = $transition(nextSlide.$element, {}); (function(next,current) { $scope.$currentTransition.then( function(){ transitionDone(next, current); }, function(){ transitionDone(next, current); } ); }(nextSlide, self.currentSlide)); } else { transitionDone(nextSlide, self.currentSlide); } self.currentSlide = nextSlide; currentIndex = nextIndex; restartTimer(); } function transitionDone(next, current) { angular.extend(next, {direction: '', active: true, leaving: false, entering: false}); angular.extend(current||{}, {direction: '', active: false, leaving: false, entering: false}); $scope.$currentTransition = null; } }; $scope.$on('$destroy', function () { destroyed = true; }); self.indexOfSlide = function(slide) { return slides.indexOf(slide); }; $scope.next = function() { var newIndex = (currentIndex + 1) % slides.length; if (!$scope.$currentTransition) { return self.select(slides[newIndex], 'next'); } }; $scope.prev = function() { var newIndex = currentIndex - 1 < 0 ? slides.length - 1 : currentIndex - 1; if (!$scope.$currentTransition) { return self.select(slides[newIndex], 'prev'); } }; $scope.isActive = function(slide) { return self.currentSlide === slide; }; $scope.$watch('interval', restartTimer); $scope.$on('$destroy', resetTimer); function restartTimer() { resetTimer(); var interval = +$scope.interval; if (!isNaN(interval) && interval > 0) { currentInterval = $interval(timerFn, interval); } } function resetTimer() { if (currentInterval) { $interval.cancel(currentInterval); currentInterval = null; } } function timerFn() { var interval = +$scope.interval; if (isPlaying && !isNaN(interval) && interval > 0) { $scope.next(); } else { $scope.pause(); } } $scope.play = function() { if (!isPlaying) { isPlaying = true; restartTimer(); } }; $scope.pause = function() { if (!$scope.noPause) { isPlaying = false; resetTimer(); } }; self.addSlide = function(slide, element) { slide.$element = element; slides.push(slide); if(slides.length === 1 || slide.active) { self.select(slides[slides.length-1]); if (slides.length == 1) { $scope.play(); } } else { slide.active = false; } }; self.removeSlide = function(slide) { var index = slides.indexOf(slide); slides.splice(index, 1); if (slides.length > 0 && slide.active) { if (index >= slides.length) { self.select(slides[index-1]); } else { self.select(slides[index]); } } else if (currentIndex > index) { currentIndex--; } }; }]) .directive('carousel', [function() { return { restrict: 'EA', transclude: true, replace: true, controller: 'CarouselController', require: 'carousel', templateUrl: 'template/carousel/carousel.html', scope: { interval: '=', noTransition: '=', noPause: '=' } }; }]) .directive('slide', function() { return { require: '^carousel', restrict: 'EA', transclude: true, replace: true, templateUrl: 'template/carousel/slide.html', scope: { active: '=?' }, link: function (scope, element, attrs, carouselCtrl) { carouselCtrl.addSlide(scope, element); scope.$on('$destroy', function() { carouselCtrl.removeSlide(scope); }); scope.$watch('active', function(active) { if (active) { carouselCtrl.select(scope); } }); } }; }); angular.module('ui.bootstrap.dateparser', []) .service('dateParser', ['$locale', 'orderByFilter', function($locale, orderByFilter) { this.parsers = {}; var formatCodeToRegex = { 'yyyy': { regex: '\\d{4}', apply: function(value) { this.year = +value; } }, 'yy': { regex: '\\d{2}', apply: function(value) { this.year = +value + 2000; } }, 'y': { regex: '\\d{1,4}', apply: function(value) { this.year = +value; } }, 'MMMM': { regex: $locale.DATETIME_FORMATS.MONTH.join('|'), apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); } }, 'MMM': { regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'), apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); } }, 'MM': { regex: '0[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; } }, 'M': { regex: '[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; } }, 'dd': { regex: '[0-2][0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; } }, 'd': { regex: '[1-2]?[0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; } }, 'EEEE': { regex: $locale.DATETIME_FORMATS.DAY.join('|') }, 'EEE': { regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|') } }; function createParser(format) { var map = [], regex = format.split(''); angular.forEach(formatCodeToRegex, function(data, code) { var index = format.indexOf(code); if (index > -1) { format = format.split(''); regex[index] = '(' + data.regex + ')'; format[index] = '$'; for (var i = index + 1, n = index + code.length; i < n; i++) { regex[i] = ''; format[i] = '$'; } format = format.join(''); map.push({ index: index, apply: data.apply }); } }); return { regex: new RegExp('^' + regex.join('') + '$'), map: orderByFilter(map, 'index') }; } this.parse = function(input, format) { if ( !angular.isString(input) || !format ) { return input; } format = $locale.DATETIME_FORMATS[format] || format; if ( !this.parsers[format] ) { this.parsers[format] = createParser(format); } var parser = this.parsers[format], regex = parser.regex, map = parser.map, results = input.match(regex); if ( results && results.length ) { var fields = { year: 1900, month: 0, date: 1, hours: 0 }, dt; for( var i = 1, n = results.length; i < n; i++ ) { var mapper = map[i-1]; if ( mapper.apply ) { mapper.apply.call(fields, results[i]); } } if ( isValid(fields.year, fields.month, fields.date) ) { dt = new Date( fields.year, fields.month, fields.date, fields.hours); } return dt; } }; function isValid(year, month, date) { if ( month === 1 && date > 28) { return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); } if ( month === 3 || month === 5 || month === 8 || month === 10) { return date < 31; } return true; } }]); angular.module('ui.bootstrap.position', []) .factory('$position', ['$document', '$window', function ($document, $window) { function getStyle(el, cssprop) { if (el.currentStyle) { return el.currentStyle[cssprop]; } else if ($window.getComputedStyle) { return $window.getComputedStyle(el)[cssprop]; } return el.style[cssprop]; } function isStaticPositioned(element) { return (getStyle(element, 'position') || 'static' ) === 'static'; } var parentOffsetEl = function (element) { var docDomEl = $document[0]; var offsetParent = element.offsetParent || docDomEl; while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docDomEl; }; return { position: function (element) { var elBCR = this.offset(element); var offsetParentBCR = { top: 0, left: 0 }; var offsetParentEl = parentOffsetEl(element[0]); if (offsetParentEl != $document[0]) { offsetParentBCR = this.offset(angular.element(offsetParentEl)); offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop; offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft; } var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: elBCR.top - offsetParentBCR.top, left: elBCR.left - offsetParentBCR.left }; }, offset: function (element) { var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop), left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft) }; }, positionElements: function (hostEl, targetEl, positionStr, appendToBody) { var positionStrParts = positionStr.split('-'); var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center'; var hostElPos, targetElWidth, targetElHeight, targetElPos; hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl); targetElWidth = targetEl.prop('offsetWidth'); targetElHeight = targetEl.prop('offsetHeight'); var shiftWidth = { center: function () { return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2; }, left: function () { return hostElPos.left; }, right: function () { return hostElPos.left + hostElPos.width; } }; var shiftHeight = { center: function () { return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2; }, top: function () { return hostElPos.top; }, bottom: function () { return hostElPos.top + hostElPos.height; } }; switch (pos0) { case 'right': targetElPos = { top: shiftHeight[pos1](), left: shiftWidth[pos0]() }; break; case 'left': targetElPos = { top: shiftHeight[pos1](), left: hostElPos.left - targetElWidth }; break; case 'bottom': targetElPos = { top: shiftHeight[pos0](), left: shiftWidth[pos1]() }; break; default: targetElPos = { top: hostElPos.top - targetElHeight, left: shiftWidth[pos1]() }; break; } return targetElPos; } }; }]); angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position']) .constant('datepickerConfig', { formatDay: 'dd', formatMonth: 'MMMM', formatYear: 'yyyy', formatDayHeader: 'EEE', formatDayTitle: 'MMMM yyyy', formatMonthTitle: 'yyyy', datepickerMode: 'day', minMode: 'day', maxMode: 'year', showWeeks: true, startingDay: 0, yearRange: 20, minDate: null, maxDate: null }) .controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$timeout', '$log', 'dateFilter', 'datepickerConfig', function($scope, $attrs, $parse, $interpolate, $timeout, $log, dateFilter, datepickerConfig) { var self = this, ngModelCtrl = { $setViewValue: angular.noop }; this.modes = ['day', 'month', 'year']; angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle', 'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRange'], function( key, index ) { self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key]; }); angular.forEach(['minDate', 'maxDate'], function( key ) { if ( $attrs[key] ) { $scope.$parent.$watch($parse($attrs[key]), function(value) { self[key] = value ? new Date(value) : null; self.refreshView(); }); } else { self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null; } }); $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode; $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000); this.activeDate = angular.isDefined($attrs.initDate) ? $scope.$parent.$eval($attrs.initDate) : new Date(); $scope.isActive = function(dateObject) { if (self.compare(dateObject.date, self.activeDate) === 0) { $scope.activeDateId = dateObject.uid; return true; } return false; }; this.init = function( ngModelCtrl_ ) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = function() { self.render(); }; }; this.render = function() { if ( ngModelCtrl.$modelValue ) { var date = new Date( ngModelCtrl.$modelValue ), isValid = !isNaN(date); if ( isValid ) { this.activeDate = date; } else { $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); } ngModelCtrl.$setValidity('date', isValid); } this.refreshView(); }; this.refreshView = function() { if ( this.element ) { this._refreshView(); var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null; ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date))); } }; this.createDateObject = function(date, format) { var model = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null; return { date: date, label: dateFilter(date, format), selected: model && this.compare(date, model) === 0, disabled: this.isDisabled(date), current: this.compare(date, new Date()) === 0 }; }; this.isDisabled = function( date ) { return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode}))); }; this.split = function(arr, size) { var arrays = []; while (arr.length > 0) { arrays.push(arr.splice(0, size)); } return arrays; }; $scope.select = function( date ) { if ( $scope.datepickerMode === self.minMode ) { var dt = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : new Date(0, 0, 0, 0, 0, 0, 0); dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() ); ngModelCtrl.$setViewValue( dt ); ngModelCtrl.$render(); } else { self.activeDate = date; $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) - 1 ]; } }; $scope.move = function( direction ) { var year = self.activeDate.getFullYear() + direction * (self.step.years || 0), month = self.activeDate.getMonth() + direction * (self.step.months || 0); self.activeDate.setFullYear(year, month, 1); self.refreshView(); }; $scope.toggleMode = function( direction ) { direction = direction || 1; if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) { return; } $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) + direction ]; }; $scope.keys = { 13:'enter', 32:'space', 33:'pageup', 34:'pagedown', 35:'end', 36:'home', 37:'left', 38:'up', 39:'right', 40:'down' }; var focusElement = function() { $timeout(function() { self.element[0].focus(); }, 0 , false); }; $scope.$on('datepicker.focus', focusElement); $scope.keydown = function( evt ) { var key = $scope.keys[evt.which]; if ( !key || evt.shiftKey || evt.altKey ) { return; } evt.preventDefault(); evt.stopPropagation(); if (key === 'enter' || key === 'space') { if ( self.isDisabled(self.activeDate)) { return; } $scope.select(self.activeDate); focusElement(); } else if (evt.ctrlKey && (key === 'up' || key === 'down')) { $scope.toggleMode(key === 'up' ? 1 : -1); focusElement(); } else { self.handleKeyDown(key, evt); self.refreshView(); } }; }]) .directive( 'datepicker', function () { return { restrict: 'EA', replace: true, templateUrl: 'template/datepicker/datepicker.html', scope: { datepickerMode: '=?', dateDisabled: '&' }, require: ['datepicker', '?^ngModel'], controller: 'DatepickerController', link: function(scope, element, attrs, ctrls) { var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if ( ngModelCtrl ) { datepickerCtrl.init( ngModelCtrl ); } } }; }) .directive('daypicker', ['dateFilter', function (dateFilter) { return { restrict: 'EA', replace: true, templateUrl: 'template/datepicker/day.html', require: '^datepicker', link: function(scope, element, attrs, ctrl) { scope.showWeeks = ctrl.showWeeks; ctrl.step = { months: 1 }; ctrl.element = element; var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function getDaysInMonth( year, month ) { return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month]; } function getDates(startDate, n) { var dates = new Array(n), current = new Date(startDate), i = 0; current.setHours(12); while ( i < n ) { dates[i++] = new Date(current); current.setDate( current.getDate() + 1 ); } return dates; } ctrl._refreshView = function() { var year = ctrl.activeDate.getFullYear(), month = ctrl.activeDate.getMonth(), firstDayOfMonth = new Date(year, month, 1), difference = ctrl.startingDay - firstDayOfMonth.getDay(), numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference, firstDate = new Date(firstDayOfMonth); if ( numDisplayedFromPreviousMonth > 0 ) { firstDate.setDate( - numDisplayedFromPreviousMonth + 1 ); } var days = getDates(firstDate, 42); for (var i = 0; i < 42; i ++) { days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), { secondary: days[i].getMonth() !== month, uid: scope.uniqueId + '-' + i }); } scope.labels = new Array(7); for (var j = 0; j < 7; j++) { scope.labels[j] = { abbr: dateFilter(days[j].date, ctrl.formatDayHeader), full: dateFilter(days[j].date, 'EEEE') }; } scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle); scope.rows = ctrl.split(days, 7); if ( scope.showWeeks ) { scope.weekNumbers = []; var weekNumber = getISO8601WeekNumber( scope.rows[0][0].date ), numWeeks = scope.rows.length; while( scope.weekNumbers.push(weekNumber++) < numWeeks ) {} } }; ctrl.compare = function(date1, date2) { return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) ); }; function getISO8601WeekNumber(date) { var checkDate = new Date(date); checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; } ctrl.handleKeyDown = function( key, evt ) { var date = ctrl.activeDate.getDate(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - 7; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + 7; } else if (key === 'pageup' || key === 'pagedown') { var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1); ctrl.activeDate.setMonth(month, 1); date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date); } else if (key === 'home') { date = 1; } else if (key === 'end') { date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()); } ctrl.activeDate.setDate(date); }; ctrl.refreshView(); } }; }]) .directive('monthpicker', ['dateFilter', function (dateFilter) { return { restrict: 'EA', replace: true, templateUrl: 'template/datepicker/month.html', require: '^datepicker', link: function(scope, element, attrs, ctrl) { ctrl.step = { years: 1 }; ctrl.element = element; ctrl._refreshView = function() { var months = new Array(12), year = ctrl.activeDate.getFullYear(); for ( var i = 0; i < 12; i++ ) { months[i] = angular.extend(ctrl.createDateObject(new Date(year, i, 1), ctrl.formatMonth), { uid: scope.uniqueId + '-' + i }); } scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle); scope.rows = ctrl.split(months, 3); }; ctrl.compare = function(date1, date2) { return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() ); }; ctrl.handleKeyDown = function( key, evt ) { var date = ctrl.activeDate.getMonth(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - 3; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + 3; } else if (key === 'pageup' || key === 'pagedown') { var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1); ctrl.activeDate.setFullYear(year); } else if (key === 'home') { date = 0; } else if (key === 'end') { date = 11; } ctrl.activeDate.setMonth(date); }; ctrl.refreshView(); } }; }]) .directive('yearpicker', ['dateFilter', function (dateFilter) { return { restrict: 'EA', replace: true, templateUrl: 'template/datepicker/year.html', require: '^datepicker', link: function(scope, element, attrs, ctrl) { var range = ctrl.yearRange; ctrl.step = { years: range }; ctrl.element = element; function getStartingYear( year ) { return parseInt((year - 1) / range, 10) * range + 1; } ctrl._refreshView = function() { var years = new Array(range); for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) { years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), { uid: scope.uniqueId + '-' + i }); } scope.title = [years[0].label, years[range - 1].label].join(' - '); scope.rows = ctrl.split(years, 5); }; ctrl.compare = function(date1, date2) { return date1.getFullYear() - date2.getFullYear(); }; ctrl.handleKeyDown = function( key, evt ) { var date = ctrl.activeDate.getFullYear(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - 5; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + 5; } else if (key === 'pageup' || key === 'pagedown') { date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years; } else if (key === 'home') { date = getStartingYear( ctrl.activeDate.getFullYear() ); } else if (key === 'end') { date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1; } ctrl.activeDate.setFullYear(date); }; ctrl.refreshView(); } }; }]) .constant('datepickerPopupConfig', { datepickerPopup: 'yyyy-MM-dd', currentText: 'Today', clearText: 'Clear', closeText: 'Done', closeOnDateSelection: true, appendToBody: false, showButtonBar: true }) .directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig', function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) { return { restrict: 'EA', require: 'ngModel', scope: { isOpen: '=?', currentText: '@', clearText: '@', closeText: '@', dateDisabled: '&' }, link: function(scope, element, attrs, ngModel) { var dateFormat, closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection, appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody; scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar; scope.getText = function( key ) { return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text']; }; attrs.$observe('datepickerPopup', function(value) { dateFormat = value || datepickerPopupConfig.datepickerPopup; ngModel.$render(); }); var popupEl = angular.element('<div datepicker-popup-wrap><div datepicker></div></div>'); popupEl.attr({ 'ng-model': 'date', 'ng-change': 'dateSelection()' }); function cameltoDash( string ){ return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); }); } var datepickerEl = angular.element(popupEl.children()[0]); if ( attrs.datepickerOptions ) { angular.forEach(scope.$parent.$eval(attrs.datepickerOptions), function( value, option ) { datepickerEl.attr( cameltoDash(option), value ); }); } scope.watchData = {}; angular.forEach(['minDate', 'maxDate', 'datepickerMode'], function( key ) { if ( attrs[key] ) { var getAttribute = $parse(attrs[key]); scope.$parent.$watch(getAttribute, function(value){ scope.watchData[key] = value; }); datepickerEl.attr(cameltoDash(key), 'watchData.' + key); if ( key === 'datepickerMode' ) { var setAttribute = getAttribute.assign; scope.$watch('watchData.' + key, function(value, oldvalue) { if ( value !== oldvalue ) { setAttribute(scope.$parent, value); } }); } } }); if (attrs.dateDisabled) { datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })'); } function parseDate(viewValue) { if (!viewValue) { ngModel.$setValidity('date', true); return null; } else if (angular.isDate(viewValue) && !isNaN(viewValue)) { ngModel.$setValidity('date', true); return viewValue; } else if (angular.isString(viewValue)) { var date = dateParser.parse(viewValue, dateFormat) || new Date(viewValue); if (isNaN(date)) { ngModel.$setValidity('date', false); return undefined; } else { ngModel.$setValidity('date', true); return date; } } else { ngModel.$setValidity('date', false); return undefined; } } ngModel.$parsers.unshift(parseDate); scope.dateSelection = function(dt) { if (angular.isDefined(dt)) { scope.date = dt; } ngModel.$setViewValue(scope.date); ngModel.$render(); if ( closeOnDateSelection ) { scope.isOpen = false; element[0].focus(); } }; element.bind('input change keyup', function() { scope.$apply(function() { scope.date = ngModel.$modelValue; }); }); ngModel.$render = function() { var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : ''; element.val(date); scope.date = parseDate( ngModel.$modelValue ); }; var documentClickBind = function(event) { if (scope.isOpen && event.target !== element[0]) { scope.$apply(function() { scope.isOpen = false; }); } }; var keydown = function(evt, noApply) { scope.keydown(evt); }; element.bind('keydown', keydown); scope.keydown = function(evt) { if (evt.which === 27) { evt.preventDefault(); evt.stopPropagation(); scope.close(); } else if (evt.which === 40 && !scope.isOpen) { scope.isOpen = true; } }; scope.$watch('isOpen', function(value) { if (value) { scope.$broadcast('datepicker.focus'); scope.position = appendToBody ? $position.offset(element) : $position.position(element); scope.position.top = scope.position.top + element.prop('offsetHeight'); $document.bind('click', documentClickBind); } else { $document.unbind('click', documentClickBind); } }); scope.select = function( date ) { if (date === 'today') { var today = new Date(); if (angular.isDate(ngModel.$modelValue)) { date = new Date(ngModel.$modelValue); date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate()); } else { date = new Date(today.setHours(0, 0, 0, 0)); } } scope.dateSelection( date ); }; scope.close = function() { scope.isOpen = false; element[0].focus(); }; var $popup = $compile(popupEl)(scope); popupEl.remove(); if ( appendToBody ) { $document.find('body').append($popup); } else { element.after($popup); } scope.$on('$destroy', function() { $popup.remove(); element.unbind('keydown', keydown); $document.unbind('click', documentClickBind); }); } }; }]) .directive('datepickerPopupWrap', function() { return { restrict:'EA', replace: true, transclude: true, templateUrl: 'template/datepicker/popup.html', link:function (scope, element, attrs) { element.bind('click', function(event) { event.preventDefault(); event.stopPropagation(); }); } }; }); angular.module('ui.bootstrap.dropdown', []) .constant('dropdownConfig', { openClass: 'open' }) .service('dropdownService', ['$document', function($document) { var openScope = null; this.open = function( dropdownScope ) { if ( !openScope ) { $document.bind('click', closeDropdown); $document.bind('keydown', escapeKeyBind); } if ( openScope && openScope !== dropdownScope ) { openScope.isOpen = false; } openScope = dropdownScope; }; this.close = function( dropdownScope ) { if ( openScope === dropdownScope ) { openScope = null; $document.unbind('click', closeDropdown); $document.unbind('keydown', escapeKeyBind); } }; var closeDropdown = function( evt ) { if (!openScope) { return; } var toggleElement = openScope.getToggleElement(); if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) { return; } openScope.$apply(function() { openScope.isOpen = false; }); }; var escapeKeyBind = function( evt ) { if ( evt.which === 27 ) { openScope.focusToggleElement(); closeDropdown(); } }; }]) .controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) { var self = this, scope = $scope.$new(), openClass = dropdownConfig.openClass, getIsOpen, setIsOpen = angular.noop, toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop; this.init = function( element ) { self.$element = element; if ( $attrs.isOpen ) { getIsOpen = $parse($attrs.isOpen); setIsOpen = getIsOpen.assign; $scope.$watch(getIsOpen, function(value) { scope.isOpen = !!value; }); } }; this.toggle = function( open ) { return scope.isOpen = arguments.length ? !!open : !scope.isOpen; }; this.isOpen = function() { return scope.isOpen; }; scope.getToggleElement = function() { return self.toggleElement; }; scope.focusToggleElement = function() { if ( self.toggleElement ) { self.toggleElement[0].focus(); } }; scope.$watch('isOpen', function( isOpen, wasOpen ) { $animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass); if ( isOpen ) { scope.focusToggleElement(); dropdownService.open( scope ); } else { dropdownService.close( scope ); } setIsOpen($scope, isOpen); if (angular.isDefined(isOpen) && isOpen !== wasOpen) { toggleInvoker($scope, { open: !!isOpen }); } }); $scope.$on('$locationChangeSuccess', function() { scope.isOpen = false; }); $scope.$on('$destroy', function() { scope.$destroy(); }); }]) .directive('dropdown', function() { return { controller: 'DropdownController', link: function(scope, element, attrs, dropdownCtrl) { dropdownCtrl.init( element ); } }; }) .directive('dropdownToggle', function() { return { require: '?^dropdown', link: function(scope, element, attrs, dropdownCtrl) { if ( !dropdownCtrl ) { return; } dropdownCtrl.toggleElement = element; var toggleDropdown = function(event) { event.preventDefault(); if ( !element.hasClass('disabled') && !attrs.disabled ) { scope.$apply(function() { dropdownCtrl.toggle(); }); } }; element.bind('click', toggleDropdown); element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); scope.$watch(dropdownCtrl.isOpen, function( isOpen ) { element.attr('aria-expanded', !!isOpen); }); scope.$on('$destroy', function() { element.unbind('click', toggleDropdown); }); } }; }); angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition']) .factory('$$stackedMap', function () { return { createNew: function () { var stack = []; return { add: function (key, value) { stack.push({ key: key, value: value }); }, get: function (key) { for (var i = 0; i < stack.length; i++) { if (key == stack[i].key) { return stack[i]; } } }, keys: function() { var keys = []; for (var i = 0; i < stack.length; i++) { keys.push(stack[i].key); } return keys; }, top: function () { return stack[stack.length - 1]; }, remove: function (key) { var idx = -1; for (var i = 0; i < stack.length; i++) { if (key == stack[i].key) { idx = i; break; } } return stack.splice(idx, 1)[0]; }, removeTop: function () { return stack.splice(stack.length - 1, 1)[0]; }, length: function () { return stack.length; } }; } }; }) .directive('modalBackdrop', ['$timeout', function ($timeout) { return { restrict: 'EA', replace: true, templateUrl: 'template/modal/backdrop.html', link: function (scope, element, attrs) { scope.backdropClass = attrs.backdropClass || ''; scope.animate = false; $timeout(function () { scope.animate = true; }); } }; }]) .directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) { return { restrict: 'EA', scope: { index: '@', animate: '=' }, replace: true, transclude: true, templateUrl: function(tElement, tAttrs) { return tAttrs.templateUrl || 'template/modal/window.html'; }, link: function (scope, element, attrs) { element.addClass(attrs.windowClass || ''); scope.size = attrs.size; $timeout(function () { scope.animate = true; if (!element[0].querySelectorAll('[autofocus]').length) { element[0].focus(); } }); scope.close = function (evt) { var modal = $modalStack.getTop(); if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) { evt.preventDefault(); evt.stopPropagation(); $modalStack.dismiss(modal.key, 'backdrop click'); } }; } }; }]) .directive('modalTransclude', function () { return { link: function($scope, $element, $attrs, controller, $transclude) { $transclude($scope.$parent, function(clone) { $element.empty(); $element.append(clone); }); } }; }) .factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap', function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) { var OPENED_MODAL_CLASS = 'modal-open'; var backdropDomEl, backdropScope; var openedWindows = $$stackedMap.createNew(); var $modalStack = {}; function backdropIndex() { var topBackdropIndex = -1; var opened = openedWindows.keys(); for (var i = 0; i < opened.length; i++) { if (openedWindows.get(opened[i]).value.backdrop) { topBackdropIndex = i; } } return topBackdropIndex; } $rootScope.$watch(backdropIndex, function(newBackdropIndex){ if (backdropScope) { backdropScope.index = newBackdropIndex; } }); function removeModalWindow(modalInstance) { var body = $document.find('body').eq(0); var modalWindow = openedWindows.get(modalInstance).value; openedWindows.remove(modalInstance); removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, function() { modalWindow.modalScope.$destroy(); body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0); checkRemoveBackdrop(); }); } function checkRemoveBackdrop() { if (backdropDomEl && backdropIndex() == -1) { var backdropScopeRef = backdropScope; removeAfterAnimate(backdropDomEl, backdropScope, 150, function () { backdropScopeRef.$destroy(); backdropScopeRef = null; }); backdropDomEl = undefined; backdropScope = undefined; } } function removeAfterAnimate(domEl, scope, emulateTime, done) { scope.animate = false; var transitionEndEventName = $transition.transitionEndEventName; if (transitionEndEventName) { var timeout = $timeout(afterAnimating, emulateTime); domEl.bind(transitionEndEventName, function () { $timeout.cancel(timeout); afterAnimating(); scope.$apply(); }); } else { $timeout(afterAnimating); } function afterAnimating() { if (afterAnimating.done) { return; } afterAnimating.done = true; domEl.remove(); if (done) { done(); } } } $document.bind('keydown', function (evt) { var modal; if (evt.which === 27) { modal = openedWindows.top(); if (modal && modal.value.keyboard) { evt.preventDefault(); $rootScope.$apply(function () { $modalStack.dismiss(modal.key, 'escape key press'); }); } } }); $modalStack.open = function (modalInstance, modal) { openedWindows.add(modalInstance, { deferred: modal.deferred, modalScope: modal.scope, backdrop: modal.backdrop, keyboard: modal.keyboard }); var body = $document.find('body').eq(0), currBackdropIndex = backdropIndex(); if (currBackdropIndex >= 0 && !backdropDomEl) { backdropScope = $rootScope.$new(true); backdropScope.index = currBackdropIndex; var angularBackgroundDomEl = angular.element('<div modal-backdrop></div>'); angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass); backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope); body.append(backdropDomEl); } var angularDomEl = angular.element('<div modal-window></div>'); angularDomEl.attr({ 'template-url': modal.windowTemplateUrl, 'window-class': modal.windowClass, 'size': modal.size, 'index': openedWindows.length() - 1, 'animate': 'animate' }).html(modal.content); var modalDomEl = $compile(angularDomEl)(modal.scope); openedWindows.top().value.modalDomEl = modalDomEl; body.append(modalDomEl); body.addClass(OPENED_MODAL_CLASS); }; $modalStack.close = function (modalInstance, result) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow) { modalWindow.value.deferred.resolve(result); removeModalWindow(modalInstance); } }; $modalStack.dismiss = function (modalInstance, reason) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow) { modalWindow.value.deferred.reject(reason); removeModalWindow(modalInstance); } }; $modalStack.dismissAll = function (reason) { var topModal = this.getTop(); while (topModal) { this.dismiss(topModal.key, reason); topModal = this.getTop(); } }; $modalStack.getTop = function () { return openedWindows.top(); }; return $modalStack; }]) .provider('$modal', function () { var $modalProvider = { options: { backdrop: true, keyboard: true }, $get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack', function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) { var $modal = {}; function getTemplatePromise(options) { return options.template ? $q.when(options.template) : $http.get(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl, {cache: $templateCache}).then(function (result) { return result.data; }); } function getResolvePromises(resolves) { var promisesArr = []; angular.forEach(resolves, function (value) { if (angular.isFunction(value) || angular.isArray(value)) { promisesArr.push($q.when($injector.invoke(value))); } }); return promisesArr; } $modal.open = function (modalOptions) { var modalResultDeferred = $q.defer(); var modalOpenedDeferred = $q.defer(); var modalInstance = { result: modalResultDeferred.promise, opened: modalOpenedDeferred.promise, close: function (result) { $modalStack.close(modalInstance, result); }, dismiss: function (reason) { $modalStack.dismiss(modalInstance, reason); } }; modalOptions = angular.extend({}, $modalProvider.options, modalOptions); modalOptions.resolve = modalOptions.resolve || {}; if (!modalOptions.template && !modalOptions.templateUrl) { throw new Error('One of template or templateUrl options is required.'); } var templateAndResolvePromise = $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); templateAndResolvePromise.then(function resolveSuccess(tplAndVars) { var modalScope = (modalOptions.scope || $rootScope).$new(); modalScope.$close = modalInstance.close; modalScope.$dismiss = modalInstance.dismiss; var ctrlInstance, ctrlLocals = {}; var resolveIter = 1; if (modalOptions.controller) { ctrlLocals.$scope = modalScope; ctrlLocals.$modalInstance = modalInstance; angular.forEach(modalOptions.resolve, function (value, key) { ctrlLocals[key] = tplAndVars[resolveIter++]; }); ctrlInstance = $controller(modalOptions.controller, ctrlLocals); if (modalOptions.controllerAs) { modalScope[modalOptions.controllerAs] = ctrlInstance; } } $modalStack.open(modalInstance, { scope: modalScope, deferred: modalResultDeferred, content: tplAndVars[0], backdrop: modalOptions.backdrop, keyboard: modalOptions.keyboard, backdropClass: modalOptions.backdropClass, windowClass: modalOptions.windowClass, windowTemplateUrl: modalOptions.windowTemplateUrl, size: modalOptions.size }); }, function resolveError(reason) { modalResultDeferred.reject(reason); }); templateAndResolvePromise.then(function () { modalOpenedDeferred.resolve(true); }, function () { modalOpenedDeferred.reject(false); }); return modalInstance; }; return $modal; }] }; return $modalProvider; }); angular.module('ui.bootstrap.pagination', []) .controller('PaginationController', ['$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) { var self = this, ngModelCtrl = { $setViewValue: angular.noop }, setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; this.init = function(ngModelCtrl_, config) { ngModelCtrl = ngModelCtrl_; this.config = config; ngModelCtrl.$render = function() { self.render(); }; if ($attrs.itemsPerPage) { $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) { self.itemsPerPage = parseInt(value, 10); $scope.totalPages = self.calculateTotalPages(); }); } else { this.itemsPerPage = config.itemsPerPage; } }; this.calculateTotalPages = function() { var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage); return Math.max(totalPages || 0, 1); }; this.render = function() { $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1; }; $scope.selectPage = function(page) { if ( $scope.page !== page && page > 0 && page <= $scope.totalPages) { ngModelCtrl.$setViewValue(page); ngModelCtrl.$render(); } }; $scope.getText = function( key ) { return $scope[key + 'Text'] || self.config[key + 'Text']; }; $scope.noPrevious = function() { return $scope.page === 1; }; $scope.noNext = function() { return $scope.page === $scope.totalPages; }; $scope.$watch('totalItems', function() { $scope.totalPages = self.calculateTotalPages(); }); $scope.$watch('totalPages', function(value) { setNumPages($scope.$parent, value); if ( $scope.page > value ) { $scope.selectPage(value); } else { ngModelCtrl.$render(); } }); }]) .constant('paginationConfig', { itemsPerPage: 10, boundaryLinks: false, directionLinks: true, firstText: 'First', previousText: 'Previous', nextText: 'Next', lastText: 'Last', rotate: true }) .directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) { return { restrict: 'EA', scope: { totalItems: '=', firstText: '@', previousText: '@', nextText: '@', lastText: '@' }, require: ['pagination', '?ngModel'], controller: 'PaginationController', templateUrl: 'template/pagination/pagination.html', replace: true, link: function(scope, element, attrs, ctrls) { var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (!ngModelCtrl) { return; } var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize, rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate; scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks; scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks; paginationCtrl.init(ngModelCtrl, paginationConfig); if (attrs.maxSize) { scope.$parent.$watch($parse(attrs.maxSize), function(value) { maxSize = parseInt(value, 10); paginationCtrl.render(); }); } function makePage(number, text, isActive) { return { number: number, text: text, active: isActive }; } function getPages(currentPage, totalPages) { var pages = []; var startPage = 1, endPage = totalPages; var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages ); if ( isMaxSized ) { if ( rotate ) { startPage = Math.max(currentPage - Math.floor(maxSize/2), 1); endPage = startPage + maxSize - 1; if (endPage > totalPages) { endPage = totalPages; startPage = endPage - maxSize + 1; } } else { startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1; endPage = Math.min(startPage + maxSize - 1, totalPages); } } for (var number = startPage; number <= endPage; number++) { var page = makePage(number, number, number === currentPage); pages.push(page); } if ( isMaxSized && ! rotate ) { if ( startPage > 1 ) { var previousPageSet = makePage(startPage - 1, '...', false); pages.unshift(previousPageSet); } if ( endPage < totalPages ) { var nextPageSet = makePage(endPage + 1, '...', false); pages.push(nextPageSet); } } return pages; } var originalRender = paginationCtrl.render; paginationCtrl.render = function() { originalRender(); if (scope.page > 0 && scope.page <= scope.totalPages) { scope.pages = getPages(scope.page, scope.totalPages); } }; } }; }]) .constant('pagerConfig', { itemsPerPage: 10, previousText: '« Previous', nextText: 'Next »', align: true }) .directive('pager', ['pagerConfig', function(pagerConfig) { return { restrict: 'EA', scope: { totalItems: '=', previousText: '@', nextText: '@' }, require: ['pager', '?ngModel'], controller: 'PaginationController', templateUrl: 'template/pagination/pager.html', replace: true, link: function(scope, element, attrs, ctrls) { var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (!ngModelCtrl) { return; } scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align; paginationCtrl.init(ngModelCtrl, pagerConfig); } }; }]); angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] ) .provider( '$tooltip', function () { var defaultOptions = { placement: 'top', animation: true, popupDelay: 0 }; var triggerMap = { 'mouseenter': 'mouseleave', 'click': 'click', 'focus': 'blur' }; var globalOptions = {}; this.options = function( value ) { angular.extend( globalOptions, value ); }; this.setTriggers = function setTriggers ( triggers ) { angular.extend( triggerMap, triggers ); }; function snake_case(name){ var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $document, $position, $interpolate ) { return function $tooltip ( type, prefix, defaultTriggerShow ) { var options = angular.extend( {}, defaultOptions, globalOptions ); function getTriggers ( trigger ) { var show = trigger || options.trigger || defaultTriggerShow; var hide = triggerMap[show] || show; return { show: show, hide: hide }; } var directiveName = snake_case( type ); var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var template = '<div '+ directiveName +'-popup '+ 'title="'+startSym+'title'+endSym+'" '+ 'content="'+startSym+'content'+endSym+'" '+ 'placement="'+startSym+'placement'+endSym+'" '+ 'animation="animation" '+ 'is-open="isOpen"'+ '>'+ '</div>'; return { restrict: 'EA', compile: function (tElem, tAttrs) { var tooltipLinker = $compile( template ); return function link ( scope, element, attrs ) { var tooltip; var tooltipLinkedScope; var transitionTimeout; var popupTimeout; var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false; var triggers = getTriggers( undefined ); var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']); var ttScope = scope.$new(true); var positionTooltip = function () { var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody); ttPosition.top += 'px'; ttPosition.left += 'px'; tooltip.css( ttPosition ); }; ttScope.isOpen = false; function toggleTooltipBind () { if ( ! ttScope.isOpen ) { showTooltipBind(); } else { hideTooltipBind(); } } function showTooltipBind() { if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) { return; } prepareTooltip(); if ( ttScope.popupDelay ) { if (!popupTimeout) { popupTimeout = $timeout( show, ttScope.popupDelay, false ); popupTimeout.then(function(reposition){reposition();}); } } else { show()(); } } function hideTooltipBind () { scope.$apply(function () { hide(); }); } function show() { popupTimeout = null; if ( transitionTimeout ) { $timeout.cancel( transitionTimeout ); transitionTimeout = null; } if ( ! ttScope.content ) { return angular.noop; } createTooltip(); tooltip.css({ top: 0, left: 0, display: 'block' }); ttScope.$digest(); positionTooltip(); ttScope.isOpen = true; ttScope.$digest(); return positionTooltip; } function hide() { ttScope.isOpen = false; $timeout.cancel( popupTimeout ); popupTimeout = null; if ( ttScope.animation ) { if (!transitionTimeout) { transitionTimeout = $timeout(removeTooltip, 500); } } else { removeTooltip(); } } function createTooltip() { if (tooltip) { removeTooltip(); } tooltipLinkedScope = ttScope.$new(); tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) { if ( appendToBody ) { $document.find( 'body' ).append( tooltip ); } else { element.after( tooltip ); } }); } function removeTooltip() { transitionTimeout = null; if (tooltip) { tooltip.remove(); tooltip = null; } if (tooltipLinkedScope) { tooltipLinkedScope.$destroy(); tooltipLinkedScope = null; } } function prepareTooltip() { prepPlacement(); prepPopupDelay(); } attrs.$observe( type, function ( val ) { ttScope.content = val; if (!val && ttScope.isOpen ) { hide(); } }); attrs.$observe( prefix+'Title', function ( val ) { ttScope.title = val; }); function prepPlacement() { var val = attrs[ prefix + 'Placement' ]; ttScope.placement = angular.isDefined( val ) ? val : options.placement; } function prepPopupDelay() { var val = attrs[ prefix + 'PopupDelay' ]; var delay = parseInt( val, 10 ); ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay; } var unregisterTriggers = function () { element.unbind(triggers.show, showTooltipBind); element.unbind(triggers.hide, hideTooltipBind); }; function prepTriggers() { var val = attrs[ prefix + 'Trigger' ]; unregisterTriggers(); triggers = getTriggers( val ); if ( triggers.show === triggers.hide ) { element.bind( triggers.show, toggleTooltipBind ); } else { element.bind( triggers.show, showTooltipBind ); element.bind( triggers.hide, hideTooltipBind ); } } prepTriggers(); var animation = scope.$eval(attrs[prefix + 'Animation']); ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation; var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']); appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody; if ( appendToBody ) { scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () { if ( ttScope.isOpen ) { hide(); } }); } scope.$on('$destroy', function onDestroyTooltip() { $timeout.cancel( transitionTimeout ); $timeout.cancel( popupTimeout ); unregisterTriggers(); removeTooltip(); ttScope = null; }); }; } }; }; }]; }) .directive( 'tooltipPopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-popup.html' }; }) .directive( 'tooltip', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'tooltip', 'tooltip', 'mouseenter' ); }]) .directive( 'tooltipHtmlUnsafePopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html' }; }) .directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' ); }]); angular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] ) .directive( 'popoverPopup', function () { return { restrict: 'EA', replace: true, scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/popover/popover.html' }; }) .directive( 'popover', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'popover', 'popover', 'click' ); }]); angular.module('ui.bootstrap.progressbar', []) .constant('progressConfig', { animate: true, max: 100 }) .controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) { var self = this, animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; this.bars = []; $scope.max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max; this.addBar = function(bar, element) { if ( !animate ) { element.css({'transition': 'none'}); } this.bars.push(bar); bar.$watch('value', function( value ) { bar.percent = +(100 * value / $scope.max).toFixed(2); }); bar.$on('$destroy', function() { element = null; self.removeBar(bar); }); }; this.removeBar = function(bar) { this.bars.splice(this.bars.indexOf(bar), 1); }; }]) .directive('progress', function() { return { restrict: 'EA', replace: true, transclude: true, controller: 'ProgressController', require: 'progress', scope: {}, templateUrl: 'template/progressbar/progress.html' }; }) .directive('bar', function() { return { restrict: 'EA', replace: true, transclude: true, require: '^progress', scope: { value: '=', type: '@' }, templateUrl: 'template/progressbar/bar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, element); } }; }) .directive('progressbar', function() { return { restrict: 'EA', replace: true, transclude: true, controller: 'ProgressController', scope: { value: '=', type: '@' }, templateUrl: 'template/progressbar/progressbar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, angular.element(element.children()[0])); } }; }); angular.module('ui.bootstrap.rating', []) .constant('ratingConfig', { max: 5, stateOn: null, stateOff: null }) .controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) { var ngModelCtrl = { $setViewValue: angular.noop }; this.init = function(ngModelCtrl_) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = this.render; this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn; this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff; var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) : new Array( angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max ); $scope.range = this.buildTemplateObjects(ratingStates); }; this.buildTemplateObjects = function(states) { for (var i = 0, n = states.length; i < n; i++) { states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff }, states[i]); } return states; }; $scope.rate = function(value) { if ( !$scope.readonly && value >= 0 && value <= $scope.range.length ) { ngModelCtrl.$setViewValue(value); ngModelCtrl.$render(); } }; $scope.enter = function(value) { if ( !$scope.readonly ) { $scope.value = value; } $scope.onHover({value: value}); }; $scope.reset = function() { $scope.value = ngModelCtrl.$viewValue; $scope.onLeave(); }; $scope.onKeydown = function(evt) { if (/(37|38|39|40)/.test(evt.which)) { evt.preventDefault(); evt.stopPropagation(); $scope.rate( $scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1) ); } }; this.render = function() { $scope.value = ngModelCtrl.$viewValue; }; }]) .directive('rating', function() { return { restrict: 'EA', require: ['rating', 'ngModel'], scope: { readonly: '=?', onHover: '&', onLeave: '&' }, controller: 'RatingController', templateUrl: 'template/rating/rating.html', replace: true, link: function(scope, element, attrs, ctrls) { var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if ( ngModelCtrl ) { ratingCtrl.init( ngModelCtrl ); } } }; }); angular.module('ui.bootstrap.tabs', []) .controller('TabsetController', ['$scope', function TabsetCtrl($scope) { var ctrl = this, tabs = ctrl.tabs = $scope.tabs = []; ctrl.select = function(selectedTab) { angular.forEach(tabs, function(tab) { if (tab.active && tab !== selectedTab) { tab.active = false; tab.onDeselect(); } }); selectedTab.active = true; selectedTab.onSelect(); }; ctrl.addTab = function addTab(tab) { tabs.push(tab); if (tabs.length === 1) { tab.active = true; } else if (tab.active) { ctrl.select(tab); } }; ctrl.removeTab = function removeTab(tab) { var index = tabs.indexOf(tab); if (tab.active && tabs.length > 1 && !destroyed) { var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1; ctrl.select(tabs[newActiveIndex]); } tabs.splice(index, 1); }; var destroyed; $scope.$on('$destroy', function() { destroyed = true; }); }]) .directive('tabset', function() { return { restrict: 'EA', transclude: true, replace: true, scope: { type: '@' }, controller: 'TabsetController', templateUrl: 'template/tabs/tabset.html', link: function(scope, element, attrs) { scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; } }; }) .directive('tab', ['$parse', function($parse) { return { require: '^tabset', restrict: 'EA', replace: true, templateUrl: 'template/tabs/tab.html', transclude: true, scope: { active: '=?', heading: '@', onSelect: '&select', onDeselect: '&deselect' }, controller: function() { }, compile: function(elm, attrs, transclude) { return function postLink(scope, elm, attrs, tabsetCtrl) { scope.$watch('active', function(active) { if (active) { tabsetCtrl.select(scope); } }); scope.disabled = false; if ( attrs.disabled ) { scope.$parent.$watch($parse(attrs.disabled), function(value) { scope.disabled = !! value; }); } scope.select = function() { if ( !scope.disabled ) { scope.active = true; } }; tabsetCtrl.addTab(scope); scope.$on('$destroy', function() { tabsetCtrl.removeTab(scope); }); scope.$transcludeFn = transclude; }; } }; }]) .directive('tabHeadingTransclude', [function() { return { restrict: 'A', require: '^tab', link: function(scope, elm, attrs, tabCtrl) { scope.$watch('headingElement', function updateHeadingElement(heading) { if (heading) { elm.html(''); elm.append(heading); } }); } }; }]) .directive('tabContentTransclude', function() { return { restrict: 'A', require: '^tabset', link: function(scope, elm, attrs) { var tab = scope.$eval(attrs.tabContentTransclude); tab.$transcludeFn(tab.$parent, function(contents) { angular.forEach(contents, function(node) { if (isTabHeading(node)) { tab.headingElement = node; } else { elm.append(node); } }); }); } }; function isTabHeading(node) { return node.tagName && ( node.hasAttribute('tab-heading') || node.hasAttribute('data-tab-heading') || node.tagName.toLowerCase() === 'tab-heading' || node.tagName.toLowerCase() === 'data-tab-heading' ); } }) ; angular.module('ui.bootstrap.timepicker', []) .constant('timepickerConfig', { hourStep: 1, minuteStep: 1, showMeridian: true, meridians: null, readonlyInput: false, mousewheel: true }) .controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) { var selected = new Date(), ngModelCtrl = { $setViewValue: angular.noop }, meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS; this.init = function( ngModelCtrl_, inputs ) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = this.render; var hoursInputEl = inputs.eq(0), minutesInputEl = inputs.eq(1); var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel; if ( mousewheel ) { this.setupMousewheelEvents( hoursInputEl, minutesInputEl ); } $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput; this.setupInputEvents( hoursInputEl, minutesInputEl ); }; var hourStep = timepickerConfig.hourStep; if ($attrs.hourStep) { $scope.$parent.$watch($parse($attrs.hourStep), function(value) { hourStep = parseInt(value, 10); }); } var minuteStep = timepickerConfig.minuteStep; if ($attrs.minuteStep) { $scope.$parent.$watch($parse($attrs.minuteStep), function(value) { minuteStep = parseInt(value, 10); }); } $scope.showMeridian = timepickerConfig.showMeridian; if ($attrs.showMeridian) { $scope.$parent.$watch($parse($attrs.showMeridian), function(value) { $scope.showMeridian = !!value; if ( ngModelCtrl.$error.time ) { var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate(); if (angular.isDefined( hours ) && angular.isDefined( minutes )) { selected.setHours( hours ); refresh(); } } else { updateTemplate(); } }); } function getHoursFromTemplate ( ) { var hours = parseInt( $scope.hours, 10 ); var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24); if ( !valid ) { return undefined; } if ( $scope.showMeridian ) { if ( hours === 12 ) { hours = 0; } if ( $scope.meridian === meridians[1] ) { hours = hours + 12; } } return hours; } function getMinutesFromTemplate() { var minutes = parseInt($scope.minutes, 10); return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined; } function pad( value ) { return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value; } this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) { var isScrollingUp = function(e) { if (e.originalEvent) { e = e.originalEvent; } var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY; return (e.detail || delta > 0); }; hoursInputEl.bind('mousewheel wheel', function(e) { $scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() ); e.preventDefault(); }); minutesInputEl.bind('mousewheel wheel', function(e) { $scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() ); e.preventDefault(); }); }; this.setupInputEvents = function( hoursInputEl, minutesInputEl ) { if ( $scope.readonlyInput ) { $scope.updateHours = angular.noop; $scope.updateMinutes = angular.noop; return; } var invalidate = function(invalidHours, invalidMinutes) { ngModelCtrl.$setViewValue( null ); ngModelCtrl.$setValidity('time', false); if (angular.isDefined(invalidHours)) { $scope.invalidHours = invalidHours; } if (angular.isDefined(invalidMinutes)) { $scope.invalidMinutes = invalidMinutes; } }; $scope.updateHours = function() { var hours = getHoursFromTemplate(); if ( angular.isDefined(hours) ) { selected.setHours( hours ); refresh( 'h' ); } else { invalidate(true); } }; hoursInputEl.bind('blur', function(e) { if ( !$scope.invalidHours && $scope.hours < 10) { $scope.$apply( function() { $scope.hours = pad( $scope.hours ); }); } }); $scope.updateMinutes = function() { var minutes = getMinutesFromTemplate(); if ( angular.isDefined(minutes) ) { selected.setMinutes( minutes ); refresh( 'm' ); } else { invalidate(undefined, true); } }; minutesInputEl.bind('blur', function(e) { if ( !$scope.invalidMinutes && $scope.minutes < 10 ) { $scope.$apply( function() { $scope.minutes = pad( $scope.minutes ); }); } }); }; this.render = function() { var date = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : null; if ( isNaN(date) ) { ngModelCtrl.$setValidity('time', false); $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); } else { if ( date ) { selected = date; } makeValid(); updateTemplate(); } }; function refresh( keyboardChange ) { makeValid(); ngModelCtrl.$setViewValue( new Date(selected) ); updateTemplate( keyboardChange ); } function makeValid() { ngModelCtrl.$setValidity('time', true); $scope.invalidHours = false; $scope.invalidMinutes = false; } function updateTemplate( keyboardChange ) { var hours = selected.getHours(), minutes = selected.getMinutes(); if ( $scope.showMeridian ) { hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; } $scope.hours = keyboardChange === 'h' ? hours : pad(hours); $scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes); $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1]; } function addMinutes( minutes ) { var dt = new Date( selected.getTime() + minutes * 60000 ); selected.setHours( dt.getHours(), dt.getMinutes() ); refresh(); } $scope.incrementHours = function() { addMinutes( hourStep * 60 ); }; $scope.decrementHours = function() { addMinutes( - hourStep * 60 ); }; $scope.incrementMinutes = function() { addMinutes( minuteStep ); }; $scope.decrementMinutes = function() { addMinutes( - minuteStep ); }; $scope.toggleMeridian = function() { addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) ); }; }]) .directive('timepicker', function () { return { restrict: 'EA', require: ['timepicker', '?^ngModel'], controller:'TimepickerController', replace: true, scope: {}, templateUrl: 'template/timepicker/timepicker.html', link: function(scope, element, attrs, ctrls) { var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if ( ngModelCtrl ) { timepickerCtrl.init( ngModelCtrl, element.find('input') ); } } }; }); angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position']) .factory('typeaheadParser', ['$parse', function ($parse) { var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/; return { parse:function (input) { var match = input.match(TYPEAHEAD_REGEXP); if (!match) { throw new Error( 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' + ' but got "' + input + '".'); } return { itemName:match[3], source:$parse(match[4]), viewMapper:$parse(match[2] || match[1]), modelMapper:$parse(match[1]) }; } }; }]) .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser', function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) { var HOT_KEYS = [9, 13, 27, 38, 40]; return { require:'ngModel', link:function (originalScope, element, attrs, modelCtrl) { var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1; var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; var onSelectCallback = $parse(attrs.typeaheadOnSelect); var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false; var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false; var $setModelValue = $parse(attrs.ngModel).assign; var parserResult = typeaheadParser.parse(attrs.typeahead); var hasFocus; var scope = originalScope.$new(); originalScope.$on('$destroy', function(){ scope.$destroy(); }); var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000); element.attr({ 'aria-autocomplete': 'list', 'aria-expanded': false, 'aria-owns': popupId }); var popUpEl = angular.element('<div typeahead-popup></div>'); popUpEl.attr({ id: popupId, matches: 'matches', active: 'activeIdx', select: 'select(activeIdx)', query: 'query', position: 'position' }); if (angular.isDefined(attrs.typeaheadTemplateUrl)) { popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); } var resetMatches = function() { scope.matches = []; scope.activeIdx = -1; element.attr('aria-expanded', false); }; var getMatchId = function(index) { return popupId + '-option-' + index; }; scope.$watch('activeIdx', function(index) { if (index < 0) { element.removeAttr('aria-activedescendant'); } else { element.attr('aria-activedescendant', getMatchId(index)); } }); var getMatchesAsync = function(inputValue) { var locals = {$viewValue: inputValue}; isLoadingSetter(originalScope, true); $q.when(parserResult.source(originalScope, locals)).then(function(matches) { var onCurrentRequest = (inputValue === modelCtrl.$viewValue); if (onCurrentRequest && hasFocus) { if (matches.length > 0) { scope.activeIdx = focusFirst ? 0 : -1; scope.matches.length = 0; for(var i=0; i<matches.length; i++) { locals[parserResult.itemName] = matches[i]; scope.matches.push({ id: getMatchId(i), label: parserResult.viewMapper(scope, locals), model: matches[i] }); } scope.query = inputValue; scope.position = appendToBody ? $position.offset(element) : $position.position(element); scope.position.top = scope.position.top + element.prop('offsetHeight'); element.attr('aria-expanded', true); } else { resetMatches(); } } if (onCurrentRequest) { isLoadingSetter(originalScope, false); } }, function(){ resetMatches(); isLoadingSetter(originalScope, false); }); }; resetMatches(); scope.query = undefined; var timeoutPromise; var scheduleSearchWithTimeout = function(inputValue) { timeoutPromise = $timeout(function () { getMatchesAsync(inputValue); }, waitTime); }; var cancelPreviousTimeout = function() { if (timeoutPromise) { $timeout.cancel(timeoutPromise); } }; modelCtrl.$parsers.unshift(function (inputValue) { hasFocus = true; if (inputValue && inputValue.length >= minSearch) { if (waitTime > 0) { cancelPreviousTimeout(); scheduleSearchWithTimeout(inputValue); } else { getMatchesAsync(inputValue); } } else { isLoadingSetter(originalScope, false); cancelPreviousTimeout(); resetMatches(); } if (isEditable) { return inputValue; } else { if (!inputValue) { modelCtrl.$setValidity('editable', true); return inputValue; } else { modelCtrl.$setValidity('editable', false); return undefined; } } }); modelCtrl.$formatters.push(function (modelValue) { var candidateViewValue, emptyViewValue; var locals = {}; if (inputFormatter) { locals.$model = modelValue; return inputFormatter(originalScope, locals); } else { locals[parserResult.itemName] = modelValue; candidateViewValue = parserResult.viewMapper(originalScope, locals); locals[parserResult.itemName] = undefined; emptyViewValue = parserResult.viewMapper(originalScope, locals); return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue; } }); scope.select = function (activeIdx) { var locals = {}; var model, item; locals[parserResult.itemName] = item = scope.matches[activeIdx].model; model = parserResult.modelMapper(originalScope, locals); $setModelValue(originalScope, model); modelCtrl.$setValidity('editable', true); onSelectCallback(originalScope, { $item: item, $model: model, $label: parserResult.viewMapper(originalScope, locals) }); resetMatches(); $timeout(function() { element[0].focus(); }, 0, false); }; element.bind('keydown', function (evt) { if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { return; } if (scope.activeIdx == -1 && (evt.which === 13 || evt.which === 9)) { return; } evt.preventDefault(); if (evt.which === 40) { scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; scope.$digest(); } else if (evt.which === 38) { scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1; scope.$digest(); } else if (evt.which === 13 || evt.which === 9) { scope.$apply(function () { scope.select(scope.activeIdx); }); } else if (evt.which === 27) { evt.stopPropagation(); resetMatches(); scope.$digest(); } }); element.bind('blur', function (evt) { hasFocus = false; }); var dismissClickHandler = function (evt) { if (element[0] !== evt.target) { resetMatches(); scope.$digest(); } }; $document.bind('click', dismissClickHandler); originalScope.$on('$destroy', function(){ $document.unbind('click', dismissClickHandler); if (appendToBody) { $popup.remove(); } }); var $popup = $compile(popUpEl)(scope); if (appendToBody) { $document.find('body').append($popup); } else { element.after($popup); } } }; }]) .directive('typeaheadPopup', function () { return { restrict:'EA', scope:{ matches:'=', query:'=', active:'=', position:'=', select:'&' }, replace:true, templateUrl:'template/typeahead/typeahead-popup.html', link:function (scope, element, attrs) { scope.templateUrl = attrs.templateUrl; scope.isOpen = function () { return scope.matches.length > 0; }; scope.isActive = function (matchIdx) { return scope.active == matchIdx; }; scope.selectActive = function (matchIdx) { scope.active = matchIdx; }; scope.selectMatch = function (activeIdx) { scope.select({activeIdx:activeIdx}); }; } }; }) .directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) { return { restrict:'EA', scope:{ index:'=', match:'=', query:'=' }, link:function (scope, element, attrs) { var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html'; $http.get(tplUrl, {cache: $templateCache}).success(function(tplContent){ element.replaceWith($compile(tplContent.trim())(scope)); }); } }; }]) .filter('typeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) { var isSanitizePresent; isSanitizePresent = $injector.has('$sanitize'); function escapeRegexp(queryToEscape) { return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } function containsHtml(matchItem) { return /<.*>/g.test(matchItem); } return function(matchItem, query) { if (!isSanitizePresent && containsHtml(matchItem)) { $log.warn('Unsafe use of typeahead please use ngSanitize'); } matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; if (!isSanitizePresent) { matchItem = $sce.trustAsHtml(matchItem); } return matchItem; }; }]); angular.module("template/accordion/accordion-group.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/accordion/accordion-group.html", "<div class=\"panel panel-default\">\n" + " <div class=\"panel-heading\">\n" + " <h4 class=\"panel-title\">\n" + " <a href class=\"accordion-toggle\" ng-click=\"toggleOpen()\" accordion-transclude=\"heading\"><span ng-class=\"{'text-muted': isDisabled}\">{{heading}}</span></a>\n" + " </h4>\n" + " </div>\n" + " <div class=\"panel-collapse\" collapse=\"!isOpen\">\n" + " <div class=\"panel-body\" ng-transclude></div>\n" + " </div>\n" + "</div>\n" + ""); }]); angular.module("template/accordion/accordion.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/accordion/accordion.html", "<div class=\"panel-group\" ng-transclude></div>"); }]); angular.module("template/alert/alert.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/alert/alert.html", "<div class=\"alert\" ng-class=\"['alert-' + (type || 'warning'), closeable ? 'alert-dismissable' : null]\" role=\"alert\">\n" + " <button ng-show=\"closeable\" type=\"button\" class=\"close\" ng-click=\"close()\">\n" + " <span aria-hidden=\"true\">×</span>\n" + " <span class=\"sr-only\">Close</span>\n" + " </button>\n" + " <div ng-transclude></div>\n" + "</div>\n" + ""); }]); angular.module("template/carousel/carousel.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/carousel/carousel.html", "<div ng-mouseenter=\"pause()\" ng-mouseleave=\"play()\" class=\"carousel\" ng-swipe-right=\"prev()\" ng-swipe-left=\"next()\">\n" + " <ol class=\"carousel-indicators\" ng-show=\"slides.length > 1\">\n" + " <li ng-repeat=\"slide in slides track by $index\" ng-class=\"{active: isActive(slide)}\" ng-click=\"select(slide)\"></li>\n" + " </ol>\n" + " <div class=\"carousel-inner\" ng-transclude></div>\n" + " <a class=\"left carousel-control\" ng-click=\"prev()\" ng-show=\"slides.length > 1\"><span class=\"glyphicon glyphicon-chevron-left\"></span></a>\n" + " <a class=\"right carousel-control\" ng-click=\"next()\" ng-show=\"slides.length > 1\"><span class=\"glyphicon glyphicon-chevron-right\"></span></a>\n" + "</div>\n" + ""); }]); angular.module("template/carousel/slide.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/carousel/slide.html", "<div ng-class=\"{\n" + " 'active': leaving || (active && !entering),\n" + " 'prev': (next || active) && direction=='prev',\n" + " 'next': (next || active) && direction=='next',\n" + " 'right': direction=='prev',\n" + " 'left': direction=='next'\n" + " }\" class=\"item text-center\" ng-transclude></div>\n" + ""); }]); angular.module("template/datepicker/datepicker.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/datepicker/datepicker.html", "<div ng-switch=\"datepickerMode\" role=\"application\" ng-keydown=\"keydown($event)\">\n" + " <daypicker ng-switch-when=\"day\" tabindex=\"0\"></daypicker>\n" + " <monthpicker ng-switch-when=\"month\" tabindex=\"0\"></monthpicker>\n" + " <yearpicker ng-switch-when=\"year\" tabindex=\"0\"></yearpicker>\n" + "</div>"); }]); angular.module("template/datepicker/day.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/datepicker/day.html", "<table role=\"grid\" aria-labelledby=\"{{uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" + " <thead>\n" + " <tr>\n" + " <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" + " <th colspan=\"{{5 + showWeeks}}\"><button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" + " <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" + " </tr>\n" + " <tr>\n" + " <th ng-show=\"showWeeks\" class=\"text-center\"></th>\n" + " <th ng-repeat=\"label in labels track by $index\" class=\"text-center\"><small aria-label=\"{{label.full}}\">{{label.abbr}}</small></th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr ng-repeat=\"row in rows track by $index\">\n" + " <td ng-show=\"showWeeks\" class=\"text-center h6\"><em>{{ weekNumbers[$index] }}</em></td>\n" + " <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{dt.uid}}\" aria-disabled=\"{{!!dt.disabled}}\">\n" + " <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default btn-sm\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"{'text-muted': dt.secondary, 'text-info': dt.current}\">{{dt.label}}</span></button>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + ""); }]); angular.module("template/datepicker/month.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/datepicker/month.html", "<table role=\"grid\" aria-labelledby=\"{{uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" + " <thead>\n" + " <tr>\n" + " <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" + " <th><button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" + " <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr ng-repeat=\"row in rows track by $index\">\n" + " <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{dt.uid}}\" aria-disabled=\"{{!!dt.disabled}}\">\n" + " <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"{'text-info': dt.current}\">{{dt.label}}</span></button>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + ""); }]); angular.module("template/datepicker/popup.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/datepicker/popup.html", "<ul class=\"dropdown-menu\" ng-style=\"{display: (isOpen && 'block') || 'none', top: position.top+'px', left: position.left+'px'}\" ng-keydown=\"keydown($event)\">\n" + " <li ng-transclude></li>\n" + " <li ng-if=\"showButtonBar\" style=\"padding:10px 9px 2px\">\n" + " <span class=\"btn-group pull-left\">\n" + " <button type=\"button\" class=\"btn btn-sm btn-info\" ng-click=\"select('today')\">{{ getText('current') }}</button>\n" + " <button type=\"button\" class=\"btn btn-sm btn-danger\" ng-click=\"select(null)\">{{ getText('clear') }}</button>\n" + " </span>\n" + " <button type=\"button\" class=\"btn btn-sm btn-success pull-right\" ng-click=\"close()\">{{ getText('close') }}</button>\n" + " </li>\n" + "</ul>\n" + ""); }]); angular.module("template/datepicker/year.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/datepicker/year.html", "<table role=\"grid\" aria-labelledby=\"{{uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" + " <thead>\n" + " <tr>\n" + " <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" + " <th colspan=\"3\"><button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" + " <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr ng-repeat=\"row in rows track by $index\">\n" + " <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{dt.uid}}\" aria-disabled=\"{{!!dt.disabled}}\">\n" + " <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"{'text-info': dt.current}\">{{dt.label}}</span></button>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + ""); }]); angular.module("template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/modal/backdrop.html", "<div class=\"modal-backdrop fade {{ backdropClass }}\"\n" + " ng-class=\"{in: animate}\"\n" + " ng-style=\"{'z-index': 1040 + (index && 1 || 0) + index*10}\"\n" + "></div>\n" + ""); }]); angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/modal/window.html", "<div tabindex=\"-1\" role=\"dialog\" class=\"modal fade\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\" ng-click=\"close($event)\">\n" + " <div class=\"modal-dialog\" ng-class=\"{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}\"><div class=\"modal-content\" modal-transclude></div></div>\n" + "</div>"); }]); angular.module("template/pagination/pager.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/pagination/pager.html", "<ul class=\"pager\">\n" + " <li ng-class=\"{disabled: noPrevious(), previous: align}\"><a href ng-click=\"selectPage(page - 1)\">{{getText('previous')}}</a></li>\n" + " <li ng-class=\"{disabled: noNext(), next: align}\"><a href ng-click=\"selectPage(page + 1)\">{{getText('next')}}</a></li>\n" + "</ul>"); }]); angular.module("template/pagination/pagination.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/pagination/pagination.html", "<ul class=\"pagination\">\n" + " <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noPrevious()}\"><a href ng-click=\"selectPage(1)\">{{getText('first')}}</a></li>\n" + " <li ng-if=\"directionLinks\" ng-class=\"{disabled: noPrevious()}\"><a href ng-click=\"selectPage(page - 1)\">{{getText('previous')}}</a></li>\n" + " <li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active}\"><a href ng-click=\"selectPage(page.number)\">{{page.text}}</a></li>\n" + " <li ng-if=\"directionLinks\" ng-class=\"{disabled: noNext()}\"><a href ng-click=\"selectPage(page + 1)\">{{getText('next')}}</a></li>\n" + " <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noNext()}\"><a href ng-click=\"selectPage(totalPages)\">{{getText('last')}}</a></li>\n" + "</ul>"); }]); angular.module("template/tooltip/tooltip-html-unsafe-popup.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/tooltip/tooltip-html-unsafe-popup.html", "<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" + " <div class=\"tooltip-arrow\"></div>\n" + " <div class=\"tooltip-inner\" bind-html-unsafe=\"content\"></div>\n" + "</div>\n" + ""); }]); angular.module("template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/tooltip/tooltip-popup.html", "<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" + " <div class=\"tooltip-arrow\"></div>\n" + " <div class=\"tooltip-inner\" ng-bind=\"content\"></div>\n" + "</div>\n" + ""); }]); angular.module("template/popover/popover.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/popover/popover.html", "<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" + " <div class=\"arrow\"></div>\n" + "\n" + " <div class=\"popover-inner\">\n" + " <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" + " <div class=\"popover-content\" ng-bind=\"content\"></div>\n" + " </div>\n" + "</div>\n" + ""); }]); angular.module("template/progressbar/bar.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/progressbar/bar.html", "<div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: percent + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" ng-transclude></div>"); }]); angular.module("template/progressbar/progress.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/progressbar/progress.html", "<div class=\"progress\" ng-transclude></div>"); }]); angular.module("template/progressbar/progressbar.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/progressbar/progressbar.html", "<div class=\"progress\">\n" + " <div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: percent + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" ng-transclude></div>\n" + "</div>"); }]); angular.module("template/rating/rating.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/rating/rating.html", "<span ng-mouseleave=\"reset()\" ng-keydown=\"onKeydown($event)\" tabindex=\"0\" role=\"slider\" aria-valuemin=\"0\" aria-valuemax=\"{{range.length}}\" aria-valuenow=\"{{value}}\">\n" + " <i ng-repeat=\"r in range track by $index\" ng-mouseenter=\"enter($index + 1)\" ng-click=\"rate($index + 1)\" class=\"glyphicon\" ng-class=\"$index < value && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')\">\n" + " <span class=\"sr-only\">({{ $index < value ? '*' : ' ' }})</span>\n" + " </i>\n" + "</span>"); }]); angular.module("template/tabs/tab.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/tabs/tab.html", "<li ng-class=\"{active: active, disabled: disabled}\">\n" + " <a href ng-click=\"select()\" tab-heading-transclude>{{heading}}</a>\n" + "</li>\n" + ""); }]); angular.module("template/tabs/tabset.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/tabs/tabset.html", "<div>\n" + " <ul class=\"nav nav-{{type || 'tabs'}}\" ng-class=\"{'nav-stacked': vertical, 'nav-justified': justified}\" ng-transclude></ul>\n" + " <div class=\"tab-content\">\n" + " <div class=\"tab-pane\" \n" + " ng-repeat=\"tab in tabs\" \n" + " ng-class=\"{active: tab.active}\"\n" + " tab-content-transclude=\"tab\">\n" + " </div>\n" + " </div>\n" + "</div>\n" + ""); }]); angular.module("template/timepicker/timepicker.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/timepicker/timepicker.html", "<table>\n" + " <tbody>\n" + " <tr class=\"text-center\">\n" + " <td><a ng-click=\"incrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" + " <td> </td>\n" + " <td><a ng-click=\"incrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" + " <td ng-show=\"showMeridian\"></td>\n" + " </tr>\n" + " <tr>\n" + " <td style=\"width:50px;\" class=\"form-group\" ng-class=\"{'has-error': invalidHours}\">\n" + " <input type=\"text\" ng-model=\"hours\" ng-change=\"updateHours()\" class=\"form-control text-center\" ng-mousewheel=\"incrementHours()\" ng-readonly=\"readonlyInput\" maxlength=\"2\">\n" + " </td>\n" + " <td>:</td>\n" + " <td style=\"width:50px;\" class=\"form-group\" ng-class=\"{'has-error': invalidMinutes}\">\n" + " <input type=\"text\" ng-model=\"minutes\" ng-change=\"updateMinutes()\" class=\"form-control text-center\" ng-readonly=\"readonlyInput\" maxlength=\"2\">\n" + " </td>\n" + " <td ng-show=\"showMeridian\"><button type=\"button\" class=\"btn btn-default text-center\" ng-click=\"toggleMeridian()\">{{meridian}}</button></td>\n" + " </tr>\n" + " <tr class=\"text-center\">\n" + " <td><a ng-click=\"decrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" + " <td> </td>\n" + " <td><a ng-click=\"decrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" + " <td ng-show=\"showMeridian\"></td>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + ""); }]); angular.module("template/typeahead/typeahead-match.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/typeahead/typeahead-match.html", "<a href tabindex=\"-1\" ng-bind-html=\"match.label | typeaheadHighlight:query\"></a>\n" + ""); }]); angular.module("template/typeahead/typeahead-popup.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/typeahead/typeahead-popup.html", "<ul class=\"dropdown-menu\" ng-show=\"isOpen()\" ng-style=\"{top: position.top+'px', left: position.left+'px'}\" style=\"display: block;\" role=\"listbox\" aria-hidden=\"{{!isOpen()}}\">\n" + " <li ng-repeat=\"match in matches track by $index\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index)\" role=\"option\" id=\"{{match.id}}\">\n" + " <div typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" + " </li>\n" + "</ul>\n" + ""); }]); ; /*! RESOURCE: /scripts/thirdparty/modernizr/modernizr.custom.min.js */ /* Modernizr 2.8.3 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-localstorage-postmessage-websockets-webworkers-touch-cssclasses-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load */ ;window.Modernizr=function(a,b,c){function A(a){j.cssText=a}function B(a,b){return A(m.join(a+";")+(b||""))}function C(a,b){return typeof a===b}function D(a,b){return!!~(""+a).indexOf(b)}function E(a,b){for(var d in a){var e=a[d];if(!D(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function F(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:C(f,"function")?f.bind(d||b):f}return!1}function G(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+o.join(d+" ")+d).split(" ");return C(b,"string")||C(b,"undefined")?E(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),F(e,b,c))}var d="2.8.3",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["­",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},x=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=C(e[d],"function"),C(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),y={}.hasOwnProperty,z;!C(y,"undefined")&&!C(y.call,"undefined")?z=function(a,b){return y.call(a,b)}:z=function(a,b){return b in a&&C(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e}),q.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},q.canvastext=function(){return!!e.canvas&&!!C(b.createElement("canvas").getContext("2d").fillText,"function")},q.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:w(["@media (",m.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},q.postmessage=function(){return!!a.postMessage},q.indexedDB=function(){return!!G("indexedDB",a)},q.hashchange=function(){return x("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},q.history=function(){return!!a.history&&!!history.pushState},q.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},q.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},q.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},q.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},q.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},q.webworkers=function(){return!!a.Worker},q.applicationcache=function(){return!!a.applicationCache};for(var H in q)z(q,H)&&(v=H.toLowerCase(),e[v]=q[H](),t.push((e[v]?"":"no-")+v));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)z(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},A(""),i=k=null,e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.hasEvent=x,e.testProp=function(a){return E([a])},e.testAllProps=G,e.testStyles=w,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))}; /*! RESOURCE: /scripts/thirdparty/velocity/velocity.min.js */ /*! VelocityJS.org (1.2.2). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */ /*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */ !function (e) { function t(e) { var t = e.length, r = $.type(e); return "function" === r || $.isWindow(e) ? !1 : 1 === e.nodeType && t ? !0 : "array" === r || 0 === t || "number" == typeof t && t > 0 && t - 1 in e } if (!e.jQuery) { var $ = function (e, t) { return new $.fn.init(e, t) }; $.isWindow = function (e) { return null != e && e == e.window }, $.type = function (e) { return null == e ? e + "" : "object" == typeof e || "function" == typeof e ? a[o.call(e)] || "object" : typeof e }, $.isArray = Array.isArray || function (e) { return "array" === $.type(e) }, $.isPlainObject = function (e) { var t; if (!e || "object" !== $.type(e) || e.nodeType || $.isWindow(e))return !1; try { if (e.constructor && !n.call(e, "constructor") && !n.call(e.constructor.prototype, "isPrototypeOf"))return !1 } catch (r) { return !1 } for (t in e); return void 0 === t || n.call(e, t) }, $.each = function (e, r, a) { var n, o = 0, i = e.length, s = t(e); if (a) { if (s)for (; i > o && (n = r.apply(e[o], a), n !== !1); o++); else for (o in e)if (n = r.apply(e[o], a), n === !1)break } else if (s)for (; i > o && (n = r.call(e[o], o, e[o]), n !== !1); o++); else for (o in e)if (n = r.call(e[o], o, e[o]), n === !1)break; return e }, $.data = function (e, t, a) { if (void 0 === a) { var n = e[$.expando], o = n && r[n]; if (void 0 === t)return o; if (o && t in o)return o[t] } else if (void 0 !== t) { var n = e[$.expando] || (e[$.expando] = ++$.uuid); return r[n] = r[n] || {}, r[n][t] = a, a } }, $.removeData = function (e, t) { var a = e[$.expando], n = a && r[a]; n && $.each(t, function (e, t) { delete n[t] }) }, $.extend = function () { var e, t, r, a, n, o, i = arguments[0] || {}, s = 1, l = arguments.length, u = !1; for ("boolean" == typeof i && (u = i, i = arguments[s] || {}, s++), "object" != typeof i && "function" !== $.type(i) && (i = {}), s === l && (i = this, s--); l > s; s++)if (null != (n = arguments[s]))for (a in n)e = i[a], r = n[a], i !== r && (u && r && ($.isPlainObject(r) || (t = $.isArray(r))) ? (t ? (t = !1, o = e && $.isArray(e) ? e : []) : o = e && $.isPlainObject(e) ? e : {}, i[a] = $.extend(u, o, r)) : void 0 !== r && (i[a] = r)); return i }, $.queue = function (e, r, a) { function n(e, r) { var a = r || []; return null != e && (t(Object(e)) ? !function (e, t) { for (var r = +t.length, a = 0, n = e.length; r > a;)e[n++] = t[a++]; if (r !== r)for (; void 0 !== t[a];)e[n++] = t[a++]; return e.length = n, e }(a, "string" == typeof e ? [e] : e) : [].push.call(a, e)), a } if (e) { r = (r || "fx") + "queue"; var o = $.data(e, r); return a ? (!o || $.isArray(a) ? o = $.data(e, r, n(a)) : o.push(a), o) : o || [] } }, $.dequeue = function (e, t) { $.each(e.nodeType ? [e] : e, function (e, r) { t = t || "fx"; var a = $.queue(r, t), n = a.shift(); "inprogress" === n && (n = a.shift()), n && ("fx" === t && a.unshift("inprogress"), n.call(r, function () { $.dequeue(r, t) })) }) }, $.fn = $.prototype = { init: function (e) { if (e.nodeType)return this[0] = e, this; throw new Error("Not a DOM node.") }, offset: function () { var t = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : {top: 0, left: 0}; return { top: t.top + (e.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0), left: t.left + (e.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0) } }, position: function () { function e() { for (var e = this.offsetParent || document; e && "html" === !e.nodeType.toLowerCase && "static" === e.style.position;)e = e.offsetParent; return e || document } var t = this[0], e = e.apply(t), r = this.offset(), a = /^(?:body|html)$/i.test(e.nodeName) ? { top: 0, left: 0 } : $(e).offset(); return r.top -= parseFloat(t.style.marginTop) || 0, r.left -= parseFloat(t.style.marginLeft) || 0, e.style && (a.top += parseFloat(e.style.borderTopWidth) || 0, a.left += parseFloat(e.style.borderLeftWidth) || 0), { top: r.top - a.top, left: r.left - a.left } } }; var r = {}; $.expando = "velocity" + (new Date).getTime(), $.uuid = 0; for (var a = {}, n = a.hasOwnProperty, o = a.toString, i = "Boolean Number String Function Array Date RegExp Object Error".split(" "), s = 0; s < i.length; s++)a["[object " + i[s] + "]"] = i[s].toLowerCase(); $.fn.init.prototype = $.fn, e.Velocity = {Utilities: $} } }(window), function (e) { "object" == typeof module && "object" == typeof module.exports ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : e() }(function () { return function (e, t, r, a) { function n(e) { for (var t = -1, r = e ? e.length : 0, a = []; ++t < r;) { var n = e[t]; n && a.push(n) } return a } function o(e) { return g.isWrapped(e) ? e = [].slice.call(e) : g.isNode(e) && (e = [e]), e } function i(e) { var t = $.data(e, "velocity"); return null === t ? a : t } function s(e) { return function (t) { return Math.round(t * e) * (1 / e) } } function l(e, r, a, n) { function o(e, t) { return 1 - 3 * t + 3 * e } function i(e, t) { return 3 * t - 6 * e } function s(e) { return 3 * e } function l(e, t, r) { return ((o(t, r) * e + i(t, r)) * e + s(t)) * e } function u(e, t, r) { return 3 * o(t, r) * e * e + 2 * i(t, r) * e + s(t) } function c(t, r) { for (var n = 0; m > n; ++n) { var o = u(r, e, a); if (0 === o)return r; var i = l(r, e, a) - t; r -= i / o } return r } function p() { for (var t = 0; b > t; ++t)w[t] = l(t * x, e, a) } function f(t, r, n) { var o, i, s = 0; do i = r + (n - r) / 2, o = l(i, e, a) - t, o > 0 ? n = i : r = i; while (Math.abs(o) > h && ++s < v); return i } function d(t) { for (var r = 0, n = 1, o = b - 1; n != o && w[n] <= t; ++n)r += x; --n; var i = (t - w[n]) / (w[n + 1] - w[n]), s = r + i * x, l = u(s, e, a); return l >= y ? c(t, s) : 0 == l ? s : f(t, r, r + x) } function g() { V = !0, (e != r || a != n) && p() } var m = 4, y = .001, h = 1e-7, v = 10, b = 11, x = 1 / (b - 1), S = "Float32Array"in t; if (4 !== arguments.length)return !1; for (var P = 0; 4 > P; ++P)if ("number" != typeof arguments[P] || isNaN(arguments[P]) || !isFinite(arguments[P]))return !1; e = Math.min(e, 1), a = Math.min(a, 1), e = Math.max(e, 0), a = Math.max(a, 0); var w = S ? new Float32Array(b) : new Array(b), V = !1, C = function (t) { return V || g(), e === r && a === n ? t : 0 === t ? 0 : 1 === t ? 1 : l(d(t), r, n) }; C.getControlPoints = function () { return [{x: e, y: r}, {x: a, y: n}] }; var T = "generateBezier(" + [e, r, a, n] + ")"; return C.toString = function () { return T }, C } function u(e, t) { var r = e; return g.isString(e) ? v.Easings[e] || (r = !1) : r = g.isArray(e) && 1 === e.length ? s.apply(null, e) : g.isArray(e) && 2 === e.length ? b.apply(null, e.concat([t])) : g.isArray(e) && 4 === e.length ? l.apply(null, e) : !1, r === !1 && (r = v.Easings[v.defaults.easing] ? v.defaults.easing : h), r } function c(e) { if (e) { var t = (new Date).getTime(), r = v.State.calls.length; r > 1e4 && (v.State.calls = n(v.State.calls)); for (var o = 0; r > o; o++)if (v.State.calls[o]) { var s = v.State.calls[o], l = s[0], u = s[2], f = s[3], d = !!f, m = null; f || (f = v.State.calls[o][3] = t - 16); for (var y = Math.min((t - f) / u.duration, 1), h = 0, b = l.length; b > h; h++) { var S = l[h], w = S.element; if (i(w)) { var V = !1; if (u.display !== a && null !== u.display && "none" !== u.display) { if ("flex" === u.display) { var C = ["-webkit-box", "-moz-box", "-ms-flexbox", "-webkit-flex"]; $.each(C, function (e, t) { x.setPropertyValue(w, "display", t) }) } x.setPropertyValue(w, "display", u.display) } u.visibility !== a && "hidden" !== u.visibility && x.setPropertyValue(w, "visibility", u.visibility); for (var T in S)if ("element" !== T) { var k = S[T], A, F = g.isString(k.easing) ? v.Easings[k.easing] : k.easing; if (1 === y)A = k.endValue; else { var E = k.endValue - k.startValue; if (A = k.startValue + E * F(y, u, E), !d && A === k.currentValue)continue } if (k.currentValue = A, "tween" === T)m = A; else { if (x.Hooks.registered[T]) { var j = x.Hooks.getRoot(T), H = i(w).rootPropertyValueCache[j]; H && (k.rootPropertyValue = H) } var N = x.setPropertyValue(w, T, k.currentValue + (0 === parseFloat(A) ? "" : k.unitType), k.rootPropertyValue, k.scrollData); x.Hooks.registered[T] && (i(w).rootPropertyValueCache[j] = x.Normalizations.registered[j] ? x.Normalizations.registered[j]("extract", null, N[1]) : N[1]), "transform" === N[0] && (V = !0) } } u.mobileHA && i(w).transformCache.translate3d === a && (i(w).transformCache.translate3d = "(0px, 0px, 0px)", V = !0), V && x.flushTransformCache(w) } } u.display !== a && "none" !== u.display && (v.State.calls[o][2].display = !1), u.visibility !== a && "hidden" !== u.visibility && (v.State.calls[o][2].visibility = !1), u.progress && u.progress.call(s[1], s[1], y, Math.max(0, f + u.duration - t), f, m), 1 === y && p(o) } } v.State.isTicking && P(c) } function p(e, t) { if (!v.State.calls[e])return !1; for (var r = v.State.calls[e][0], n = v.State.calls[e][1], o = v.State.calls[e][2], s = v.State.calls[e][4], l = !1, u = 0, c = r.length; c > u; u++) { var p = r[u].element; if (t || o.loop || ("none" === o.display && x.setPropertyValue(p, "display", o.display), "hidden" === o.visibility && x.setPropertyValue(p, "visibility", o.visibility)), o.loop !== !0 && ($.queue(p)[1] === a || !/\.velocityQueueEntryFlag/i.test($.queue(p)[1])) && i(p)) { i(p).isAnimating = !1, i(p).rootPropertyValueCache = {}; var f = !1; $.each(x.Lists.transforms3D, function (e, t) { var r = /^scale/.test(t) ? 1 : 0, n = i(p).transformCache[t]; i(p).transformCache[t] !== a && new RegExp("^\\(" + r + "[^.]").test(n) && (f = !0, delete i(p).transformCache[t]) }), o.mobileHA && (f = !0, delete i(p).transformCache.translate3d), f && x.flushTransformCache(p), x.Values.removeClass(p, "velocity-animating") } if (!t && o.complete && !o.loop && u === c - 1)try { o.complete.call(n, n) } catch (d) { setTimeout(function () { throw d }, 1) } s && o.loop !== !0 && s(n), i(p) && o.loop === !0 && !t && ($.each(i(p).tweensContainer, function (e, t) { /^rotate/.test(e) && 360 === parseFloat(t.endValue) && (t.endValue = 0, t.startValue = 360), /^backgroundPosition/.test(e) && 100 === parseFloat(t.endValue) && "%" === t.unitType && (t.endValue = 0, t.startValue = 100) }), v(p, "reverse", {loop: !0, delay: o.delay})), o.queue !== !1 && $.dequeue(p, o.queue) } v.State.calls[e] = !1; for (var g = 0, m = v.State.calls.length; m > g; g++)if (v.State.calls[g] !== !1) { l = !0; break } l === !1 && (v.State.isTicking = !1, delete v.State.calls, v.State.calls = []) } var f = function () { if (r.documentMode)return r.documentMode; for (var e = 7; e > 4; e--) { var t = r.createElement("div"); if (t.innerHTML = "<!--[if IE " + e + "]><span></span><![endif]-->", t.getElementsByTagName("span").length)return t = null, e } return a }(), d = function () { var e = 0; return t.webkitRequestAnimationFrame || t.mozRequestAnimationFrame || function (t) { var r = (new Date).getTime(), a; return a = Math.max(0, 16 - (r - e)), e = r + a, setTimeout(function () { t(r + a) }, a) } }(), g = { isString: function (e) { return "string" == typeof e }, isArray: Array.isArray || function (e) { return "[object Array]" === Object.prototype.toString.call(e) }, isFunction: function (e) { return "[object Function]" === Object.prototype.toString.call(e) }, isNode: function (e) { return e && e.nodeType }, isNodeList: function (e) { return "object" == typeof e && /^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(e)) && e.length !== a && (0 === e.length || "object" == typeof e[0] && e[0].nodeType > 0) }, isWrapped: function (e) { return e && (e.jquery || t.Zepto && t.Zepto.zepto.isZ(e)) }, isSVG: function (e) { return t.SVGElement && e instanceof t.SVGElement }, isEmptyObject: function (e) { for (var t in e)return !1; return !0 } }, $, m = !1; if (e.fn && e.fn.jquery ? ($ = e, m = !0) : $ = t.Velocity.Utilities, 8 >= f && !m)throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity."); if (7 >= f)return void(jQuery.fn.velocity = jQuery.fn.animate); var y = 400, h = "swing", v = { State: { isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent), isAndroid: /Android/i.test(navigator.userAgent), isGingerbread: /Android 2\.3\.[3-7]/i.test(navigator.userAgent), isChrome: t.chrome, isFirefox: /Firefox/i.test(navigator.userAgent), prefixElement: r.createElement("div"), prefixMatches: {}, scrollAnchor: null, scrollPropertyLeft: null, scrollPropertyTop: null, isTicking: !1, calls: [] }, CSS: {}, Utilities: $, Redirects: {}, Easings: {}, Promise: t.Promise, defaults: { queue: "", duration: y, easing: h, begin: a, complete: a, progress: a, display: a, visibility: a, loop: !1, delay: !1, mobileHA: !0, _cacheValues: !0 }, init: function (e) { $.data(e, "velocity", { isSVG: g.isSVG(e), isAnimating: !1, computedStyle: null, tweensContainer: null, rootPropertyValueCache: {}, transformCache: {} }) }, hook: null, mock: !1, version: {major: 1, minor: 2, patch: 2}, debug: !1 }; t.pageYOffset !== a ? (v.State.scrollAnchor = t, v.State.scrollPropertyLeft = "pageXOffset", v.State.scrollPropertyTop = "pageYOffset") : (v.State.scrollAnchor = r.documentElement || r.body.parentNode || r.body, v.State.scrollPropertyLeft = "scrollLeft", v.State.scrollPropertyTop = "scrollTop"); var b = function () { function e(e) { return -e.tension * e.x - e.friction * e.v } function t(t, r, a) { var n = {x: t.x + a.dx * r, v: t.v + a.dv * r, tension: t.tension, friction: t.friction}; return {dx: n.v, dv: e(n)} } function r(r, a) { var n = { dx: r.v, dv: e(r) }, o = t(r, .5 * a, n), i = t(r, .5 * a, o), s = t(r, a, i), l = 1 / 6 * (n.dx + 2 * (o.dx + i.dx) + s.dx), u = 1 / 6 * (n.dv + 2 * (o.dv + i.dv) + s.dv); return r.x = r.x + l * a, r.v = r.v + u * a, r } return function a(e, t, n) { var o = {x: -1, v: 0, tension: null, friction: null}, i = [0], s = 0, l = 1e-4, u = .016, c, p, f; for (e = parseFloat(e) || 500, t = parseFloat(t) || 20, n = n || null, o.tension = e, o.friction = t, c = null !== n, c ? (s = a(e, t), p = s / n * u) : p = u; ;)if (f = r(f || o, p), i.push(1 + f.x), s += 16, !(Math.abs(f.x) > l && Math.abs(f.v) > l))break; return c ? function (e) { return i[e * (i.length - 1) | 0] } : s } }(); v.Easings = { linear: function (e) { return e }, swing: function (e) { return .5 - Math.cos(e * Math.PI) / 2 }, spring: function (e) { return 1 - Math.cos(4.5 * e * Math.PI) * Math.exp(6 * -e) } }, $.each([["ease", [.25, .1, .25, 1]], ["ease-in", [.42, 0, 1, 1]], ["ease-out", [0, 0, .58, 1]], ["ease-in-out", [.42, 0, .58, 1]], ["easeInSine", [.47, 0, .745, .715]], ["easeOutSine", [.39, .575, .565, 1]], ["easeInOutSine", [.445, .05, .55, .95]], ["easeInQuad", [.55, .085, .68, .53]], ["easeOutQuad", [.25, .46, .45, .94]], ["easeInOutQuad", [.455, .03, .515, .955]], ["easeInCubic", [.55, .055, .675, .19]], ["easeOutCubic", [.215, .61, .355, 1]], ["easeInOutCubic", [.645, .045, .355, 1]], ["easeInQuart", [.895, .03, .685, .22]], ["easeOutQuart", [.165, .84, .44, 1]], ["easeInOutQuart", [.77, 0, .175, 1]], ["easeInQuint", [.755, .05, .855, .06]], ["easeOutQuint", [.23, 1, .32, 1]], ["easeInOutQuint", [.86, 0, .07, 1]], ["easeInExpo", [.95, .05, .795, .035]], ["easeOutExpo", [.19, 1, .22, 1]], ["easeInOutExpo", [1, 0, 0, 1]], ["easeInCirc", [.6, .04, .98, .335]], ["easeOutCirc", [.075, .82, .165, 1]], ["easeInOutCirc", [.785, .135, .15, .86]]], function (e, t) { v.Easings[t[0]] = l.apply(null, t[1]) }); var x = v.CSS = { RegEx: { isHex: /^#([A-f\d]{3}){1,2}$/i, valueUnwrap: /^[A-z]+\((.*)\)$/i, wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/, valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi }, Lists: { colors: ["fill", "stroke", "stopColor", "color", "backgroundColor", "borderColor", "borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor", "outlineColor"], transformsBase: ["translateX", "translateY", "scale", "scaleX", "scaleY", "skewX", "skewY", "rotateZ"], transforms3D: ["transformPerspective", "translateZ", "scaleZ", "rotateX", "rotateY"] }, Hooks: { templates: { textShadow: ["Color X Y Blur", "black 0px 0px 0px"], boxShadow: ["Color X Y Blur Spread", "black 0px 0px 0px 0px"], clip: ["Top Right Bottom Left", "0px 0px 0px 0px"], backgroundPosition: ["X Y", "0% 0%"], transformOrigin: ["X Y Z", "50% 50% 0px"], perspectiveOrigin: ["X Y", "50% 50%"] }, registered: {}, register: function () { for (var e = 0; e < x.Lists.colors.length; e++) { var t = "color" === x.Lists.colors[e] ? "0 0 0 1" : "255 255 255 1"; x.Hooks.templates[x.Lists.colors[e]] = ["Red Green Blue Alpha", t] } var r, a, n; if (f)for (r in x.Hooks.templates) { a = x.Hooks.templates[r], n = a[0].split(" "); var o = a[1].match(x.RegEx.valueSplit); "Color" === n[0] && (n.push(n.shift()), o.push(o.shift()), x.Hooks.templates[r] = [n.join(" "), o.join(" ")]) } for (r in x.Hooks.templates) { a = x.Hooks.templates[r], n = a[0].split(" "); for (var e in n) { var i = r + n[e], s = e; x.Hooks.registered[i] = [r, s] } } }, getRoot: function (e) { var t = x.Hooks.registered[e]; return t ? t[0] : e }, cleanRootPropertyValue: function (e, t) { return x.RegEx.valueUnwrap.test(t) && (t = t.match(x.RegEx.valueUnwrap)[1]), x.Values.isCSSNullValue(t) && (t = x.Hooks.templates[e][1]), t }, extractValue: function (e, t) { var r = x.Hooks.registered[e]; if (r) { var a = r[0], n = r[1]; return t = x.Hooks.cleanRootPropertyValue(a, t), t.toString().match(x.RegEx.valueSplit)[n] } return t }, injectValue: function (e, t, r) { var a = x.Hooks.registered[e]; if (a) { var n = a[0], o = a[1], i, s; return r = x.Hooks.cleanRootPropertyValue(n, r), i = r.toString().match(x.RegEx.valueSplit), i[o] = t, s = i.join(" ") } return r } }, Normalizations: { registered: { clip: function (e, t, r) { switch (e) { case"name": return "clip"; case"extract": var a; return x.RegEx.wrappedValueAlreadyExtracted.test(r) ? a = r : (a = r.toString().match(x.RegEx.valueUnwrap), a = a ? a[1].replace(/,(\s+)?/g, " ") : r), a; case"inject": return "rect(" + r + ")" } }, blur: function (e, t, r) { switch (e) { case"name": return v.State.isFirefox ? "filter" : "-webkit-filter"; case"extract": var a = parseFloat(r); if (!a && 0 !== a) { var n = r.toString().match(/blur\(([0-9]+[A-z]+)\)/i); a = n ? n[1] : 0 } return a; case"inject": return parseFloat(r) ? "blur(" + r + ")" : "none" } }, opacity: function (e, t, r) { if (8 >= f)switch (e) { case"name": return "filter"; case"extract": var a = r.toString().match(/alpha\(opacity=(.*)\)/i); return r = a ? a[1] / 100 : 1; case"inject": return t.style.zoom = 1, parseFloat(r) >= 1 ? "" : "alpha(opacity=" + parseInt(100 * parseFloat(r), 10) + ")" } else switch (e) { case"name": return "opacity"; case"extract": return r; case"inject": return r } } }, register: function () { 9 >= f || v.State.isGingerbread || (x.Lists.transformsBase = x.Lists.transformsBase.concat(x.Lists.transforms3D)); for (var e = 0; e < x.Lists.transformsBase.length; e++)!function () { var t = x.Lists.transformsBase[e]; x.Normalizations.registered[t] = function (e, r, n) { switch (e) { case"name": return "transform"; case"extract": return i(r) === a || i(r).transformCache[t] === a ? /^scale/i.test(t) ? 1 : 0 : i(r).transformCache[t].replace(/[()]/g, ""); case"inject": var o = !1; switch (t.substr(0, t.length - 1)) { case"translate": o = !/(%|px|em|rem|vw|vh|\d)$/i.test(n); break; case"scal": case"scale": v.State.isAndroid && i(r).transformCache[t] === a && 1 > n && (n = 1), o = !/(\d)$/i.test(n); break; case"skew": o = !/(deg|\d)$/i.test(n); break; case"rotate": o = !/(deg|\d)$/i.test(n) } return o || (i(r).transformCache[t] = "(" + n + ")"), i(r).transformCache[t] } } }(); for (var e = 0; e < x.Lists.colors.length; e++)!function () { var t = x.Lists.colors[e]; x.Normalizations.registered[t] = function (e, r, n) { switch (e) { case"name": return t; case"extract": var o; if (x.RegEx.wrappedValueAlreadyExtracted.test(n))o = n; else { var i, s = { black: "rgb(0, 0, 0)", blue: "rgb(0, 0, 255)", gray: "rgb(128, 128, 128)", green: "rgb(0, 128, 0)", red: "rgb(255, 0, 0)", white: "rgb(255, 255, 255)" }; /^[A-z]+$/i.test(n) ? i = s[n] !== a ? s[n] : s.black : x.RegEx.isHex.test(n) ? i = "rgb(" + x.Values.hexToRgb(n).join(" ") + ")" : /^rgba?\(/i.test(n) || (i = s.black), o = (i || n).toString().match(x.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g, " ") } return 8 >= f || 3 !== o.split(" ").length || (o += " 1"), o; case"inject": return 8 >= f ? 4 === n.split(" ").length && (n = n.split(/\s+/).slice(0, 3).join(" ")) : 3 === n.split(" ").length && (n += " 1"), (8 >= f ? "rgb" : "rgba") + "(" + n.replace(/\s+/g, ",").replace(/\.(\d)+(?=,)/g, "") + ")" } } }() } }, Names: { camelCase: function (e) { return e.replace(/-(\w)/g, function (e, t) { return t.toUpperCase() }) }, SVGAttribute: function (e) { var t = "width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2"; return (f || v.State.isAndroid && !v.State.isChrome) && (t += "|transform"), new RegExp("^(" + t + ")$", "i").test(e) }, prefixCheck: function (e) { if (v.State.prefixMatches[e])return [v.State.prefixMatches[e], !0]; for (var t = ["", "Webkit", "Moz", "ms", "O"], r = 0, a = t.length; a > r; r++) { var n; if (n = 0 === r ? e : t[r] + e.replace(/^\w/, function (e) { return e.toUpperCase() }), g.isString(v.State.prefixElement.style[n]))return v.State.prefixMatches[e] = n, [n, !0] } return [e, !1] } }, Values: { hexToRgb: function (e) { var t = /^#?([a-f\d])([a-f\d])([a-f\d])$/i, r = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i, a; return e = e.replace(t, function (e, t, r, a) { return t + t + r + r + a + a }), a = r.exec(e), a ? [parseInt(a[1], 16), parseInt(a[2], 16), parseInt(a[3], 16)] : [0, 0, 0] }, isCSSNullValue: function (e) { return 0 == e || /^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(e) }, getUnitType: function (e) { return /^(rotate|skew)/i.test(e) ? "deg" : /(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(e) ? "" : "px" }, getDisplayType: function (e) { var t = e && e.tagName.toString().toLowerCase(); return /^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(t) ? "inline" : /^(li)$/i.test(t) ? "list-item" : /^(tr)$/i.test(t) ? "table-row" : /^(table)$/i.test(t) ? "table" : /^(tbody)$/i.test(t) ? "table-row-group" : "block" }, addClass: function (e, t) { e.classList ? e.classList.add(t) : e.className += (e.className.length ? " " : "") + t }, removeClass: function (e, t) { e.classList ? e.classList.remove(t) : e.className = e.className.toString().replace(new RegExp("(^|\\s)" + t.split(" ").join("|") + "(\\s|$)", "gi"), " ") } }, getPropertyValue: function (e, r, n, o) { function s(e, r) { function n() { u && x.setPropertyValue(e, "display", "none") } var l = 0; if (8 >= f)l = $.css(e, r); else { var u = !1; if (/^(width|height)$/.test(r) && 0 === x.getPropertyValue(e, "display") && (u = !0, x.setPropertyValue(e, "display", x.Values.getDisplayType(e))), !o) { if ("height" === r && "border-box" !== x.getPropertyValue(e, "boxSizing").toString().toLowerCase()) { var c = e.offsetHeight - (parseFloat(x.getPropertyValue(e, "borderTopWidth")) || 0) - (parseFloat(x.getPropertyValue(e, "borderBottomWidth")) || 0) - (parseFloat(x.getPropertyValue(e, "paddingTop")) || 0) - (parseFloat(x.getPropertyValue(e, "paddingBottom")) || 0); return n(), c } if ("width" === r && "border-box" !== x.getPropertyValue(e, "boxSizing").toString().toLowerCase()) { var p = e.offsetWidth - (parseFloat(x.getPropertyValue(e, "borderLeftWidth")) || 0) - (parseFloat(x.getPropertyValue(e, "borderRightWidth")) || 0) - (parseFloat(x.getPropertyValue(e, "paddingLeft")) || 0) - (parseFloat(x.getPropertyValue(e, "paddingRight")) || 0); return n(), p } } var d; d = i(e) === a ? t.getComputedStyle(e, null) : i(e).computedStyle ? i(e).computedStyle : i(e).computedStyle = t.getComputedStyle(e, null), "borderColor" === r && (r = "borderTopColor"), l = 9 === f && "filter" === r ? d.getPropertyValue(r) : d[r], ("" === l || null === l) && (l = e.style[r]), n() } if ("auto" === l && /^(top|right|bottom|left)$/i.test(r)) { var g = s(e, "position"); ("fixed" === g || "absolute" === g && /top|left/i.test(r)) && (l = $(e).position()[r] + "px") } return l } var l; if (x.Hooks.registered[r]) { var u = r, c = x.Hooks.getRoot(u); n === a && (n = x.getPropertyValue(e, x.Names.prefixCheck(c)[0])), x.Normalizations.registered[c] && (n = x.Normalizations.registered[c]("extract", e, n)), l = x.Hooks.extractValue(u, n) } else if (x.Normalizations.registered[r]) { var p, d; p = x.Normalizations.registered[r]("name", e), "transform" !== p && (d = s(e, x.Names.prefixCheck(p)[0]), x.Values.isCSSNullValue(d) && x.Hooks.templates[r] && (d = x.Hooks.templates[r][1])), l = x.Normalizations.registered[r]("extract", e, d) } if (!/^[\d-]/.test(l))if (i(e) && i(e).isSVG && x.Names.SVGAttribute(r))if (/^(height|width)$/i.test(r))try { l = e.getBBox()[r] } catch (g) { l = 0 } else l = e.getAttribute(r); else l = s(e, x.Names.prefixCheck(r)[0]); return x.Values.isCSSNullValue(l) && (l = 0), v.debug >= 2 && console.log("Get " + r + ": " + l), l }, setPropertyValue: function (e, r, a, n, o) { var s = r; if ("scroll" === r)o.container ? o.container["scroll" + o.direction] = a : "Left" === o.direction ? t.scrollTo(a, o.alternateValue) : t.scrollTo(o.alternateValue, a); else if (x.Normalizations.registered[r] && "transform" === x.Normalizations.registered[r]("name", e))x.Normalizations.registered[r]("inject", e, a), s = "transform", a = i(e).transformCache[r]; else { if (x.Hooks.registered[r]) { var l = r, u = x.Hooks.getRoot(r); n = n || x.getPropertyValue(e, u), a = x.Hooks.injectValue(l, a, n), r = u } if (x.Normalizations.registered[r] && (a = x.Normalizations.registered[r]("inject", e, a), r = x.Normalizations.registered[r]("name", e)), s = x.Names.prefixCheck(r)[0], 8 >= f)try { e.style[s] = a } catch (c) { v.debug && console.log("Browser does not support [" + a + "] for [" + s + "]") } else i(e) && i(e).isSVG && x.Names.SVGAttribute(r) ? e.setAttribute(r, a) : e.style[s] = a; v.debug >= 2 && console.log("Set " + r + " (" + s + "): " + a) } return [s, a] }, flushTransformCache: function (e) { function t(t) { return parseFloat(x.getPropertyValue(e, t)) } var r = ""; if ((f || v.State.isAndroid && !v.State.isChrome) && i(e).isSVG) { var a = { translate: [t("translateX"), t("translateY")], skewX: [t("skewX")], skewY: [t("skewY")], scale: 1 !== t("scale") ? [t("scale"), t("scale")] : [t("scaleX"), t("scaleY")], rotate: [t("rotateZ"), 0, 0] }; $.each(i(e).transformCache, function (e) { /^translate/i.test(e) ? e = "translate" : /^scale/i.test(e) ? e = "scale" : /^rotate/i.test(e) && (e = "rotate"), a[e] && (r += e + "(" + a[e].join(" ") + ") ", delete a[e]) }) } else { var n, o; $.each(i(e).transformCache, function (t) { return n = i(e).transformCache[t], "transformPerspective" === t ? (o = n, !0) : (9 === f && "rotateZ" === t && (t = "rotate"), void(r += t + n + " ")) }), o && (r = "perspective" + o + " " + r) } x.setPropertyValue(e, "transform", r) } }; x.Hooks.register(), x.Normalizations.register(), v.hook = function (e, t, r) { var n = a; return e = o(e), $.each(e, function (e, o) { if (i(o) === a && v.init(o), r === a)n === a && (n = v.CSS.getPropertyValue(o, t)); else { var s = v.CSS.setPropertyValue(o, t, r); "transform" === s[0] && v.CSS.flushTransformCache(o), n = s } }), n }; var S = function () { function e() { return l ? T.promise || null : f } function n() { function e(e) { function p(e, t) { var r = a, i = a, s = a; return g.isArray(e) ? (r = e[0], !g.isArray(e[1]) && /^[\d-]/.test(e[1]) || g.isFunction(e[1]) || x.RegEx.isHex.test(e[1]) ? s = e[1] : (g.isString(e[1]) && !x.RegEx.isHex.test(e[1]) || g.isArray(e[1])) && (i = t ? e[1] : u(e[1], o.duration), e[2] !== a && (s = e[2]))) : r = e, t || (i = i || o.easing), g.isFunction(r) && (r = r.call(n, w, P)), g.isFunction(s) && (s = s.call(n, w, P)), [r || 0, i, s] } function f(e, t) { var r, a; return a = (t || "0").toString().toLowerCase().replace(/[%A-z]+$/, function (e) { return r = e, "" }), r || (r = x.Values.getUnitType(e)), [a, r] } function d() { var e = { myParent: n.parentNode || r.body, position: x.getPropertyValue(n, "position"), fontSize: x.getPropertyValue(n, "fontSize") }, a = e.position === N.lastPosition && e.myParent === N.lastParent, o = e.fontSize === N.lastFontSize; N.lastParent = e.myParent, N.lastPosition = e.position, N.lastFontSize = e.fontSize; var s = 100, l = {}; if (o && a)l.emToPx = N.lastEmToPx, l.percentToPxWidth = N.lastPercentToPxWidth, l.percentToPxHeight = N.lastPercentToPxHeight; else { var u = i(n).isSVG ? r.createElementNS("http://www.w3.org/2000/svg", "rect") : r.createElement("div"); v.init(u), e.myParent.appendChild(u), $.each(["overflow", "overflowX", "overflowY"], function (e, t) { v.CSS.setPropertyValue(u, t, "hidden") }), v.CSS.setPropertyValue(u, "position", e.position), v.CSS.setPropertyValue(u, "fontSize", e.fontSize), v.CSS.setPropertyValue(u, "boxSizing", "content-box"), $.each(["minWidth", "maxWidth", "width", "minHeight", "maxHeight", "height"], function (e, t) { v.CSS.setPropertyValue(u, t, s + "%") }), v.CSS.setPropertyValue(u, "paddingLeft", s + "em"), l.percentToPxWidth = N.lastPercentToPxWidth = (parseFloat(x.getPropertyValue(u, "width", null, !0)) || 1) / s, l.percentToPxHeight = N.lastPercentToPxHeight = (parseFloat(x.getPropertyValue(u, "height", null, !0)) || 1) / s, l.emToPx = N.lastEmToPx = (parseFloat(x.getPropertyValue(u, "paddingLeft")) || 1) / s, e.myParent.removeChild(u) } return null === N.remToPx && (N.remToPx = parseFloat(x.getPropertyValue(r.body, "fontSize")) || 16), null === N.vwToPx && (N.vwToPx = parseFloat(t.innerWidth) / 100, N.vhToPx = parseFloat(t.innerHeight) / 100), l.remToPx = N.remToPx, l.vwToPx = N.vwToPx, l.vhToPx = N.vhToPx, v.debug >= 1 && console.log("Unit ratios: " + JSON.stringify(l), n), l } if (o.begin && 0 === w)try { o.begin.call(m, m) } catch (y) { setTimeout(function () { throw y }, 1) } if ("scroll" === k) { var S = /^x$/i.test(o.axis) ? "Left" : "Top", V = parseFloat(o.offset) || 0, C, A, F; o.container ? g.isWrapped(o.container) || g.isNode(o.container) ? (o.container = o.container[0] || o.container, C = o.container["scroll" + S], F = C + $(n).position()[S.toLowerCase()] + V) : o.container = null : (C = v.State.scrollAnchor[v.State["scrollProperty" + S]], A = v.State.scrollAnchor[v.State["scrollProperty" + ("Left" === S ? "Top" : "Left")]], F = $(n).offset()[S.toLowerCase()] + V), s = { scroll: { rootPropertyValue: !1, startValue: C, currentValue: C, endValue: F, unitType: "", easing: o.easing, scrollData: {container: o.container, direction: S, alternateValue: A} }, element: n }, v.debug && console.log("tweensContainer (scroll): ", s.scroll, n) } else if ("reverse" === k) { if (!i(n).tweensContainer)return void $.dequeue(n, o.queue); "none" === i(n).opts.display && (i(n).opts.display = "auto"), "hidden" === i(n).opts.visibility && (i(n).opts.visibility = "visible"), i(n).opts.loop = !1, i(n).opts.begin = null, i(n).opts.complete = null, b.easing || delete o.easing, b.duration || delete o.duration, o = $.extend({}, i(n).opts, o); var E = $.extend(!0, {}, i(n).tweensContainer); for (var j in E)if ("element" !== j) { var H = E[j].startValue; E[j].startValue = E[j].currentValue = E[j].endValue, E[j].endValue = H, g.isEmptyObject(b) || (E[j].easing = o.easing), v.debug && console.log("reverse tweensContainer (" + j + "): " + JSON.stringify(E[j]), n) } s = E } else if ("start" === k) { var E; i(n).tweensContainer && i(n).isAnimating === !0 && (E = i(n).tweensContainer), $.each(h, function (e, t) { if (RegExp("^" + x.Lists.colors.join("$|^") + "$").test(e)) { var r = p(t, !0), n = r[0], o = r[1], i = r[2]; if (x.RegEx.isHex.test(n)) { for (var s = ["Red", "Green", "Blue"], l = x.Values.hexToRgb(n), u = i ? x.Values.hexToRgb(i) : a, c = 0; c < s.length; c++) { var f = [l[c]]; o && f.push(o), u !== a && f.push(u[c]), h[e + s[c]] = f } delete h[e] } } }); for (var R in h) { var O = p(h[R]), z = O[0], q = O[1], M = O[2]; R = x.Names.camelCase(R); var I = x.Hooks.getRoot(R), B = !1; if (i(n).isSVG || "tween" === I || x.Names.prefixCheck(I)[1] !== !1 || x.Normalizations.registered[I] !== a) { (o.display !== a && null !== o.display && "none" !== o.display || o.visibility !== a && "hidden" !== o.visibility) && /opacity|filter/.test(R) && !M && 0 !== z && (M = 0), o._cacheValues && E && E[R] ? (M === a && (M = E[R].endValue + E[R].unitType), B = i(n).rootPropertyValueCache[I]) : x.Hooks.registered[R] ? M === a ? (B = x.getPropertyValue(n, I), M = x.getPropertyValue(n, R, B)) : B = x.Hooks.templates[I][1] : M === a && (M = x.getPropertyValue(n, R)); var W, G, D, X = !1; if (W = f(R, M), M = W[0], D = W[1], W = f(R, z), z = W[0].replace(/^([+-\/*])=/, function (e, t) { return X = t, "" }), G = W[1], M = parseFloat(M) || 0, z = parseFloat(z) || 0, "%" === G && (/^(fontSize|lineHeight)$/.test(R) ? (z /= 100, G = "em") : /^scale/.test(R) ? (z /= 100, G = "") : /(Red|Green|Blue)$/i.test(R) && (z = z / 100 * 255, G = "")), /[\/*]/.test(X))G = D; else if (D !== G && 0 !== M)if (0 === z)G = D; else { l = l || d(); var Y = /margin|padding|left|right|width|text|word|letter/i.test(R) || /X$/.test(R) || "x" === R ? "x" : "y"; switch (D) { case"%": M *= "x" === Y ? l.percentToPxWidth : l.percentToPxHeight; break; case"px": break; default: M *= l[D + "ToPx"] } switch (G) { case"%": M *= 1 / ("x" === Y ? l.percentToPxWidth : l.percentToPxHeight); break; case"px": break; default: M *= 1 / l[G + "ToPx"] } } switch (X) { case"+": z = M + z; break; case"-": z = M - z; break; case"*": z = M * z; break; case"/": z = M / z } s[R] = { rootPropertyValue: B, startValue: M, currentValue: M, endValue: z, unitType: G, easing: q }, v.debug && console.log("tweensContainer (" + R + "): " + JSON.stringify(s[R]), n) } else v.debug && console.log("Skipping [" + I + "] due to a lack of browser support.") } s.element = n } s.element && (x.Values.addClass(n, "velocity-animating"), L.push(s), "" === o.queue && (i(n).tweensContainer = s, i(n).opts = o), i(n).isAnimating = !0, w === P - 1 ? (v.State.calls.push([L, m, o, null, T.resolver]), v.State.isTicking === !1 && (v.State.isTicking = !0, c())) : w++) } var n = this, o = $.extend({}, v.defaults, b), s = {}, l; switch (i(n) === a && v.init(n), parseFloat(o.delay) && o.queue !== !1 && $.queue(n, o.queue, function (e) { v.velocityQueueEntryFlag = !0, i(n).delayTimer = { setTimeout: setTimeout(e, parseFloat(o.delay)), next: e } }), o.duration.toString().toLowerCase()) { case"fast": o.duration = 200; break; case"normal": o.duration = y; break; case"slow": o.duration = 600; break; default: o.duration = parseFloat(o.duration) || 1 } v.mock !== !1 && (v.mock === !0 ? o.duration = o.delay = 1 : (o.duration *= parseFloat(v.mock) || 1, o.delay *= parseFloat(v.mock) || 1)), o.easing = u(o.easing, o.duration), o.begin && !g.isFunction(o.begin) && (o.begin = null), o.progress && !g.isFunction(o.progress) && (o.progress = null), o.complete && !g.isFunction(o.complete) && (o.complete = null), o.display !== a && null !== o.display && (o.display = o.display.toString().toLowerCase(), "auto" === o.display && (o.display = v.CSS.Values.getDisplayType(n))), o.visibility !== a && null !== o.visibility && (o.visibility = o.visibility.toString().toLowerCase()), o.mobileHA = o.mobileHA && v.State.isMobile && !v.State.isGingerbread, o.queue === !1 ? o.delay ? setTimeout(e, o.delay) : e() : $.queue(n, o.queue, function (t, r) { return r === !0 ? (T.promise && T.resolver(m), !0) : (v.velocityQueueEntryFlag = !0, void e(t)) }), "" !== o.queue && "fx" !== o.queue || "inprogress" === $.queue(n)[0] || $.dequeue(n) } var s = arguments[0] && (arguments[0].p || $.isPlainObject(arguments[0].properties) && !arguments[0].properties.names || g.isString(arguments[0].properties)), l, f, d, m, h, b; if (g.isWrapped(this) ? (l = !1, d = 0, m = this, f = this) : (l = !0, d = 1, m = s ? arguments[0].elements || arguments[0].e : arguments[0]), m = o(m)) { s ? (h = arguments[0].properties || arguments[0].p, b = arguments[0].options || arguments[0].o) : (h = arguments[d], b = arguments[d + 1]); var P = m.length, w = 0; if (!/^(stop|finish)$/i.test(h) && !$.isPlainObject(b)) { var V = d + 1; b = {}; for (var C = V; C < arguments.length; C++)g.isArray(arguments[C]) || !/^(fast|normal|slow)$/i.test(arguments[C]) && !/^\d/.test(arguments[C]) ? g.isString(arguments[C]) || g.isArray(arguments[C]) ? b.easing = arguments[C] : g.isFunction(arguments[C]) && (b.complete = arguments[C]) : b.duration = arguments[C] } var T = {promise: null, resolver: null, rejecter: null}; l && v.Promise && (T.promise = new v.Promise(function (e, t) { T.resolver = e, T.rejecter = t })); var k; switch (h) { case"scroll": k = "scroll"; break; case"reverse": k = "reverse"; break; case"finish": case"stop": $.each(m, function (e, t) { i(t) && i(t).delayTimer && (clearTimeout(i(t).delayTimer.setTimeout), i(t).delayTimer.next && i(t).delayTimer.next(), delete i(t).delayTimer) }); var A = []; return $.each(v.State.calls, function (e, t) { t && $.each(t[1], function (r, n) { var o = b === a ? "" : b; return o === !0 || t[2].queue === o || b === a && t[2].queue === !1 ? void $.each(m, function (r, a) { a === n && ((b === !0 || g.isString(b)) && ($.each($.queue(a, g.isString(b) ? b : ""), function (e, t) { g.isFunction(t) && t(null, !0) }), $.queue(a, g.isString(b) ? b : "", [])), "stop" === h ? (i(a) && i(a).tweensContainer && o !== !1 && $.each(i(a).tweensContainer, function (e, t) { t.endValue = t.currentValue }), A.push(e)) : "finish" === h && (t[2].duration = 1)) }) : !0 }) }), "stop" === h && ($.each(A, function (e, t) { p(t, !0) }), T.promise && T.resolver(m)), e(); default: if (!$.isPlainObject(h) || g.isEmptyObject(h)) { if (g.isString(h) && v.Redirects[h]) { var F = $.extend({}, b), E = F.duration, j = F.delay || 0; return F.backwards === !0 && (m = $.extend(!0, [], m).reverse()), $.each(m, function (e, t) { parseFloat(F.stagger) ? F.delay = j + parseFloat(F.stagger) * e : g.isFunction(F.stagger) && (F.delay = j + F.stagger.call(t, e, P)), F.drag && (F.duration = parseFloat(E) || (/^(callout|transition)/.test(h) ? 1e3 : y), F.duration = Math.max(F.duration * (F.backwards ? 1 - e / P : (e + 1) / P), .75 * F.duration, 200)), v.Redirects[h].call(t, t, F || {}, e, P, m, T.promise ? T : a) }), e() } var H = "Velocity: First argument (" + h + ") was not a property map, a known action, or a registered redirect. Aborting."; return T.promise ? T.rejecter(new Error(H)) : console.log(H), e() } k = "start" } var N = { lastParent: null, lastPosition: null, lastFontSize: null, lastPercentToPxWidth: null, lastPercentToPxHeight: null, lastEmToPx: null, remToPx: null, vwToPx: null, vhToPx: null }, L = []; $.each(m, function (e, t) { g.isNode(t) && n.call(t) }); var F = $.extend({}, v.defaults, b), R; if (F.loop = parseInt(F.loop), R = 2 * F.loop - 1, F.loop)for (var O = 0; R > O; O++) { var z = {delay: F.delay, progress: F.progress}; O === R - 1 && (z.display = F.display, z.visibility = F.visibility, z.complete = F.complete), S(m, "reverse", z) } return e() } }; v = $.extend(S, v), v.animate = S; var P = t.requestAnimationFrame || d; return v.State.isMobile || r.hidden === a || r.addEventListener("visibilitychange", function () { r.hidden ? (P = function (e) { return setTimeout(function () { e(!0) }, 16) }, c()) : P = t.requestAnimationFrame || d }), e.Velocity = v, e !== t && (e.fn.velocity = S, e.fn.velocity.defaults = v.defaults), $.each(["Down", "Up"], function (e, t) { v.Redirects["slide" + t] = function (e, r, n, o, i, s) { var l = $.extend({}, r), u = l.begin, c = l.complete, p = { height: "", marginTop: "", marginBottom: "", paddingTop: "", paddingBottom: "" }, f = {}; l.display === a && (l.display = "Down" === t ? "inline" === v.CSS.Values.getDisplayType(e) ? "inline-block" : "block" : "none"), l.begin = function () { u && u.call(i, i); for (var r in p) { f[r] = e.style[r]; var a = v.CSS.getPropertyValue(e, r); p[r] = "Down" === t ? [a, 0] : [0, a] } f.overflow = e.style.overflow, e.style.overflow = "hidden" }, l.complete = function () { for (var t in f)e.style[t] = f[t]; c && c.call(i, i), s && s.resolver(i) }, v(e, p, l) } }), $.each(["In", "Out"], function (e, t) { v.Redirects["fade" + t] = function (e, r, n, o, i, s) { var l = $.extend({}, r), u = {opacity: "In" === t ? 1 : 0}, c = l.complete; l.complete = n !== o - 1 ? l.begin = null : function () { c && c.call(i, i), s && s.resolver(i) }, l.display === a && (l.display = "In" === t ? "auto" : "none"), v(this, u, l) } }), v }(window.jQuery || window.Zepto || window, window, document) }); /*! RESOURCE: /scripts/thirdparty/velocity/velocity.ui.js */ ; (function (factory) { if (typeof require === "function" && typeof exports === "object") { module.exports = factory(); } else if (typeof define === "function" && define.amd) { define(["velocity"], factory); } else { factory(); } }(function () { return function (global, window, document, undefined) { if (!global.Velocity || !global.Velocity.Utilities) { window.console && console.log("Velocity UI Pack: Velocity must be loaded first. Aborting."); return; } else { var Velocity = global.Velocity, $ = Velocity.Utilities; } var velocityVersion = Velocity.version, requiredVersion = {major: 1, minor: 1, patch: 0}; function greaterSemver(primary, secondary) { var versionInts = []; if (!primary || !secondary) { return false; } $.each([primary, secondary], function (i, versionObject) { var versionIntsComponents = []; $.each(versionObject, function (component, value) { while (value.toString().length < 5) { value = "0" + value; } versionIntsComponents.push(value); }); versionInts.push(versionIntsComponents.join("")) }); return (parseFloat(versionInts[0]) > parseFloat(versionInts[1])); } if (greaterSemver(requiredVersion, velocityVersion)) { var abortError = "Velocity UI Pack: You need to update Velocity (jquery.velocity.js) to a newer version. Visit http://github.com/julianshapiro/velocity."; alert(abortError); throw new Error(abortError); } Velocity.RegisterEffect = Velocity.RegisterUI = function (effectName, properties) { function animateParentHeight(elements, direction, totalDuration, stagger) { var totalHeightDelta = 0, parentNode; $.each(elements.nodeType ? [elements] : elements, function (i, element) { if (stagger) { totalDuration += i * stagger; } parentNode = element.parentNode; $.each(["height", "paddingTop", "paddingBottom", "marginTop", "marginBottom"], function (i, property) { totalHeightDelta += parseFloat(Velocity.CSS.getPropertyValue(element, property)); }); }); Velocity.animate( parentNode, {height: (direction === "In" ? "+" : "-") + "=" + totalHeightDelta}, {queue: false, easing: "ease-in-out", duration: totalDuration * (direction === "In" ? 0.6 : 1)} ); } Velocity.Redirects[effectName] = function (element, redirectOptions, elementsIndex, elementsSize, elements, promiseData) { var finalElement = (elementsIndex === elementsSize - 1); if (typeof properties.defaultDuration === "function") { properties.defaultDuration = properties.defaultDuration.call(elements, elements); } else { properties.defaultDuration = parseFloat(properties.defaultDuration); } for (var callIndex = 0; callIndex < properties.calls.length; callIndex++) { var call = properties.calls[callIndex], propertyMap = call[0], redirectDuration = (redirectOptions.duration || properties.defaultDuration || 1000), durationPercentage = call[1], callOptions = call[2] || {}, opts = {}; opts.duration = redirectDuration * (durationPercentage || 1); opts.queue = redirectOptions.queue || ""; opts.easing = callOptions.easing || "ease"; opts.delay = parseFloat(callOptions.delay) || 0; opts._cacheValues = callOptions._cacheValues || true; if (callIndex === 0) { opts.delay += (parseFloat(redirectOptions.delay) || 0); if (elementsIndex === 0) { opts.begin = function () { redirectOptions.begin && redirectOptions.begin.call(elements, elements); var direction = effectName.match(/(In|Out)$/); if ((direction && direction[0] === "In") && propertyMap.opacity !== undefined) { $.each(elements.nodeType ? [elements] : elements, function (i, element) { Velocity.CSS.setPropertyValue(element, "opacity", 0); }); } if (redirectOptions.animateParentHeight && direction) { animateParentHeight(elements, direction[0], redirectDuration + opts.delay, redirectOptions.stagger); } } } if (redirectOptions.display !== null) { if (redirectOptions.display !== undefined && redirectOptions.display !== "none") { opts.display = redirectOptions.display; } else if (/In$/.test(effectName)) { var defaultDisplay = Velocity.CSS.Values.getDisplayType(element); opts.display = (defaultDisplay === "inline") ? "inline-block" : defaultDisplay; } } if (redirectOptions.visibility && redirectOptions.visibility !== "hidden") { opts.visibility = redirectOptions.visibility; } } if (callIndex === properties.calls.length - 1) { function injectFinalCallbacks() { if ((redirectOptions.display === undefined || redirectOptions.display === "none") && /Out$/.test(effectName)) { $.each(elements.nodeType ? [elements] : elements, function (i, element) { Velocity.CSS.setPropertyValue(element, "display", "none"); }); } redirectOptions.complete && redirectOptions.complete.call(elements, elements); if (promiseData) { promiseData.resolver(elements || element); } } opts.complete = function () { if (properties.reset) { for (var resetProperty in properties.reset) { var resetValue = properties.reset[resetProperty]; if (Velocity.CSS.Hooks.registered[resetProperty] === undefined && (typeof resetValue === "string" || typeof resetValue === "number")) { properties.reset[resetProperty] = [properties.reset[resetProperty], properties.reset[resetProperty]]; } } var resetOptions = {duration: 0, queue: false}; if (finalElement) { resetOptions.complete = injectFinalCallbacks; } Velocity.animate(element, properties.reset, resetOptions); } else if (finalElement) { injectFinalCallbacks(); } }; if (redirectOptions.visibility === "hidden") { opts.visibility = redirectOptions.visibility; } } Velocity.animate(element, propertyMap, opts); } }; return Velocity; }; Velocity.RegisterEffect.packagedEffects = { "callout.bounce": { defaultDuration: 550, calls: [ [{translateY: -30}, 0.25], [{translateY: 0}, 0.125], [{translateY: -15}, 0.125], [{translateY: 0}, 0.25] ] }, "callout.shake": { defaultDuration: 800, calls: [ [{translateX: -11}, 0.125], [{translateX: 11}, 0.125], [{translateX: -11}, 0.125], [{translateX: 11}, 0.125], [{translateX: -11}, 0.125], [{translateX: 11}, 0.125], [{translateX: -11}, 0.125], [{translateX: 0}, 0.125] ] }, "callout.flash": { defaultDuration: 1100, calls: [ [{opacity: [0, "easeInOutQuad", 1]}, 0.25], [{opacity: [1, "easeInOutQuad"]}, 0.25], [{opacity: [0, "easeInOutQuad"]}, 0.25], [{opacity: [1, "easeInOutQuad"]}, 0.25] ] }, "callout.pulse": { defaultDuration: 825, calls: [ [{scaleX: 1.1, scaleY: 1.1}, 0.50, {easing: "easeInExpo"}], [{scaleX: 1, scaleY: 1}, 0.50] ] }, "callout.swing": { defaultDuration: 950, calls: [ [{rotateZ: 15}, 0.20], [{rotateZ: -10}, 0.20], [{rotateZ: 5}, 0.20], [{rotateZ: -5}, 0.20], [{rotateZ: 0}, 0.20] ] }, "callout.tada": { defaultDuration: 1000, calls: [ [{scaleX: 0.9, scaleY: 0.9, rotateZ: -3}, 0.10], [{scaleX: 1.1, scaleY: 1.1, rotateZ: 3}, 0.10], [{scaleX: 1.1, scaleY: 1.1, rotateZ: -3}, 0.10], ["reverse", 0.125], ["reverse", 0.125], ["reverse", 0.125], ["reverse", 0.125], ["reverse", 0.125], [{scaleX: 1, scaleY: 1, rotateZ: 0}, 0.20] ] }, "transition.fadeIn": { defaultDuration: 500, calls: [ [{opacity: [1, 0]}] ] }, "transition.fadeOut": { defaultDuration: 500, calls: [ [{opacity: [0, 1]}] ] }, "transition.flipXIn": { defaultDuration: 700, calls: [ [{opacity: [1, 0], transformPerspective: [800, 800], rotateY: [0, -55]}] ], reset: {transformPerspective: 0} }, "transition.flipXOut": { defaultDuration: 700, calls: [ [{opacity: [0, 1], transformPerspective: [800, 800], rotateY: 55}] ], reset: {transformPerspective: 0, rotateY: 0} }, "transition.flipYIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0], transformPerspective: [800, 800], rotateX: [0, -45]}] ], reset: {transformPerspective: 0} }, "transition.flipYOut": { defaultDuration: 800, calls: [ [{opacity: [0, 1], transformPerspective: [800, 800], rotateX: 25}] ], reset: {transformPerspective: 0, rotateX: 0} }, "transition.flipBounceXIn": { defaultDuration: 900, calls: [ [{opacity: [0.725, 0], transformPerspective: [400, 400], rotateY: [-10, 90]}, 0.50], [{opacity: 0.80, rotateY: 10}, 0.25], [{opacity: 1, rotateY: 0}, 0.25] ], reset: {transformPerspective: 0} }, "transition.flipBounceXOut": { defaultDuration: 800, calls: [ [{opacity: [0.9, 1], transformPerspective: [400, 400], rotateY: -10}, 0.50], [{opacity: 0, rotateY: 90}, 0.50] ], reset: {transformPerspective: 0, rotateY: 0} }, "transition.flipBounceYIn": { defaultDuration: 850, calls: [ [{opacity: [0.725, 0], transformPerspective: [400, 400], rotateX: [-10, 90]}, 0.50], [{opacity: 0.80, rotateX: 10}, 0.25], [{opacity: 1, rotateX: 0}, 0.25] ], reset: {transformPerspective: 0} }, "transition.flipBounceYOut": { defaultDuration: 800, calls: [ [{opacity: [0.9, 1], transformPerspective: [400, 400], rotateX: -15}, 0.50], [{opacity: 0, rotateX: 90}, 0.50] ], reset: {transformPerspective: 0, rotateX: 0} }, "transition.swoopIn": { defaultDuration: 850, calls: [ [{ opacity: [1, 0], transformOriginX: ["100%", "50%"], transformOriginY: ["100%", "100%"], scaleX: [1, 0], scaleY: [1, 0], translateX: [0, -700], translateZ: 0 }] ], reset: {transformOriginX: "50%", transformOriginY: "50%"} }, "transition.swoopOut": { defaultDuration: 850, calls: [ [{ opacity: [0, 1], transformOriginX: ["50%", "100%"], transformOriginY: ["100%", "100%"], scaleX: 0, scaleY: 0, translateX: -700, translateZ: 0 }] ], reset: {transformOriginX: "50%", transformOriginY: "50%", scaleX: 1, scaleY: 1, translateX: 0} }, "transition.whirlIn": { defaultDuration: 850, calls: [ [{ opacity: [1, 0], transformOriginX: ["50%", "50%"], transformOriginY: ["50%", "50%"], scaleX: [1, 0], scaleY: [1, 0], rotateY: [0, 160] }, 1, {easing: "easeInOutSine"}] ] }, "transition.whirlOut": { defaultDuration: 750, calls: [ [{ opacity: [0, "easeInOutQuint", 1], transformOriginX: ["50%", "50%"], transformOriginY: ["50%", "50%"], scaleX: 0, scaleY: 0, rotateY: 160 }, 1, {easing: "swing"}] ], reset: {scaleX: 1, scaleY: 1, rotateY: 0} }, "transition.shrinkIn": { defaultDuration: 750, calls: [ [{ opacity: [1, 0], transformOriginX: ["50%", "50%"], transformOriginY: ["50%", "50%"], scaleX: [1, 1.5], scaleY: [1, 1.5], translateZ: 0 }] ] }, "transition.shrinkOut": { defaultDuration: 600, calls: [ [{ opacity: [0, 1], transformOriginX: ["50%", "50%"], transformOriginY: ["50%", "50%"], scaleX: 1.3, scaleY: 1.3, translateZ: 0 }] ], reset: {scaleX: 1, scaleY: 1} }, "transition.expandIn": { defaultDuration: 700, calls: [ [{ opacity: [1, 0], transformOriginX: ["50%", "50%"], transformOriginY: ["50%", "50%"], scaleX: [1, 0.625], scaleY: [1, 0.625], translateZ: 0 }] ] }, "transition.expandOut": { defaultDuration: 700, calls: [ [{ opacity: [0, 1], transformOriginX: ["50%", "50%"], transformOriginY: ["50%", "50%"], scaleX: 0.5, scaleY: 0.5, translateZ: 0 }] ], reset: {scaleX: 1, scaleY: 1} }, "transition.bounceIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0], scaleX: [1.05, 0.3], scaleY: [1.05, 0.3]}, 0.40], [{scaleX: 0.9, scaleY: 0.9, translateZ: 0}, 0.20], [{scaleX: 1, scaleY: 1}, 0.50] ] }, "transition.bounceOut": { defaultDuration: 800, calls: [ [{scaleX: 0.95, scaleY: 0.95}, 0.35], [{scaleX: 1.1, scaleY: 1.1, translateZ: 0}, 0.35], [{opacity: [0, 1], scaleX: 0.3, scaleY: 0.3}, 0.30] ], reset: {scaleX: 1, scaleY: 1} }, "transition.bounceUpIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0], translateY: [-30, 1000]}, 0.60, {easing: "easeOutCirc"}], [{translateY: 10}, 0.20], [{translateY: 0}, 0.20] ] }, "transition.bounceUpOut": { defaultDuration: 1000, calls: [ [{translateY: 20}, 0.20], [{opacity: [0, "easeInCirc", 1], translateY: -1000}, 0.80] ], reset: {translateY: 0} }, "transition.bounceDownIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0], translateY: [30, -1000]}, 0.60, {easing: "easeOutCirc"}], [{translateY: -10}, 0.20], [{translateY: 0}, 0.20] ] }, "transition.bounceDownOut": { defaultDuration: 1000, calls: [ [{translateY: -20}, 0.20], [{opacity: [0, "easeInCirc", 1], translateY: 1000}, 0.80] ], reset: {translateY: 0} }, "transition.bounceLeftIn": { defaultDuration: 750, calls: [ [{opacity: [1, 0], translateX: [30, -1250]}, 0.60, {easing: "easeOutCirc"}], [{translateX: -10}, 0.20], [{translateX: 0}, 0.20] ] }, "transition.bounceLeftOut": { defaultDuration: 750, calls: [ [{translateX: 30}, 0.20], [{opacity: [0, "easeInCirc", 1], translateX: -1250}, 0.80] ], reset: {translateX: 0} }, "transition.bounceRightIn": { defaultDuration: 750, calls: [ [{opacity: [1, 0], translateX: [-30, 1250]}, 0.60, {easing: "easeOutCirc"}], [{translateX: 10}, 0.20], [{translateX: 0}, 0.20] ] }, "transition.bounceRightOut": { defaultDuration: 750, calls: [ [{translateX: -30}, 0.20], [{opacity: [0, "easeInCirc", 1], translateX: 1250}, 0.80] ], reset: {translateX: 0} }, "transition.slideUpIn": { defaultDuration: 900, calls: [ [{opacity: [1, 0], translateY: [0, 20], translateZ: 0}] ] }, "transition.slideUpOut": { defaultDuration: 900, calls: [ [{opacity: [0, 1], translateY: -20, translateZ: 0}] ], reset: {translateY: 0} }, "transition.slideDownIn": { defaultDuration: 900, calls: [ [{opacity: [1, 0], translateY: [0, -20], translateZ: 0}] ] }, "transition.slideDownOut": { defaultDuration: 900, calls: [ [{opacity: [0, 1], translateY: 20, translateZ: 0}] ], reset: {translateY: 0} }, "transition.slideLeftIn": { defaultDuration: 1000, calls: [ [{opacity: [1, 0], translateX: [0, -20], translateZ: 0}] ] }, "transition.slideLeftOut": { defaultDuration: 1050, calls: [ [{opacity: [0, 1], translateX: -20, translateZ: 0}] ], reset: {translateX: 0} }, "transition.slideRightIn": { defaultDuration: 1000, calls: [ [{opacity: [1, 0], translateX: [0, 20], translateZ: 0}] ] }, "transition.slideRightOut": { defaultDuration: 1050, calls: [ [{opacity: [0, 1], translateX: 20, translateZ: 0}] ], reset: {translateX: 0} }, "transition.slideUpBigIn": { defaultDuration: 850, calls: [ [{opacity: [1, 0], translateY: [0, 75], translateZ: 0}] ] }, "transition.slideUpBigOut": { defaultDuration: 800, calls: [ [{opacity: [0, 1], translateY: -75, translateZ: 0}] ], reset: {translateY: 0} }, "transition.slideDownBigIn": { defaultDuration: 850, calls: [ [{opacity: [1, 0], translateY: [0, -75], translateZ: 0}] ] }, "transition.slideDownBigOut": { defaultDuration: 800, calls: [ [{opacity: [0, 1], translateY: 75, translateZ: 0}] ], reset: {translateY: 0} }, "transition.slideLeftBigIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0], translateX: [0, -75], translateZ: 0}] ] }, "transition.slideLeftBigOut": { defaultDuration: 750, calls: [ [{opacity: [0, 1], translateX: -75, translateZ: 0}] ], reset: {translateX: 0} }, "transition.slideRightBigIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0], translateX: [0, 75], translateZ: 0}] ] }, "transition.slideRightBigOut": { defaultDuration: 750, calls: [ [{opacity: [0, 1], translateX: 75, translateZ: 0}] ], reset: {translateX: 0} }, "transition.perspectiveUpIn": { defaultDuration: 800, calls: [ [{ opacity: [1, 0], transformPerspective: [800, 800], transformOriginX: [0, 0], transformOriginY: ["100%", "100%"], rotateX: [0, -180] }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%"} }, "transition.perspectiveUpOut": { defaultDuration: 850, calls: [ [{ opacity: [0, 1], transformPerspective: [800, 800], transformOriginX: [0, 0], transformOriginY: ["100%", "100%"], rotateX: -180 }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateX: 0} }, "transition.perspectiveDownIn": { defaultDuration: 800, calls: [ [{ opacity: [1, 0], transformPerspective: [800, 800], transformOriginX: [0, 0], transformOriginY: [0, 0], rotateX: [0, 180] }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%"} }, "transition.perspectiveDownOut": { defaultDuration: 850, calls: [ [{ opacity: [0, 1], transformPerspective: [800, 800], transformOriginX: [0, 0], transformOriginY: [0, 0], rotateX: 180 }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateX: 0} }, "transition.perspectiveLeftIn": { defaultDuration: 950, calls: [ [{ opacity: [1, 0], transformPerspective: [2000, 2000], transformOriginX: [0, 0], transformOriginY: [0, 0], rotateY: [0, -180] }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%"} }, "transition.perspectiveLeftOut": { defaultDuration: 950, calls: [ [{ opacity: [0, 1], transformPerspective: [2000, 2000], transformOriginX: [0, 0], transformOriginY: [0, 0], rotateY: -180 }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateY: 0} }, "transition.perspectiveRightIn": { defaultDuration: 950, calls: [ [{ opacity: [1, 0], transformPerspective: [2000, 2000], transformOriginX: ["100%", "100%"], transformOriginY: [0, 0], rotateY: [0, 180] }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%"} }, "transition.perspectiveRightOut": { defaultDuration: 950, calls: [ [{ opacity: [0, 1], transformPerspective: [2000, 2000], transformOriginX: ["100%", "100%"], transformOriginY: [0, 0], rotateY: 180 }] ], reset: {transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateY: 0} }, "snTransition.listStreamSlideIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0.5], translateY: [0, -225]}, 1.0, {easing: "easeOutQuart"}], ] }, "snTransition.recordStreamSlideIn": { defaultDuration: 800, calls: [ [{opacity: [1, 0.5], translateY: [0, -82]}, 1.0, {easing: "easeOutQuart"}], ] }, "snTransition.slideOut": { defaultDuration: 600, calls: [ [{opacity: [1, 0.5], translateX: [-400, 0]}, 1.0, {easing: "easeOutQuart"}], ] }, "snTransition.slideIn": { defaultDuration: 600, calls: [ [{opacity: [1, 1], translateX: [0, -400]}, 1.0, {easing: "easeOutQuart"}], ] }, "snTransition.streamSlideLeft": { defaultDuration: 600, calls: [ [{opacity: [1, 0.5], translateX: [0, 400]}, 1.0, {easing: "easeOutQuart"}], ] }, "snTransition.streamSlideRight": { defaultDuration: 600, calls: [ [{opacity: [1, 0.5], translateX: [400, 0]}, 1.0, {easing: "easeOutQuart"}], ] } }; for (var effectName in Velocity.RegisterEffect.packagedEffects) { Velocity.RegisterEffect(effectName, Velocity.RegisterEffect.packagedEffects[effectName]); } Velocity.RunSequence = function (originalSequence) { var sequence = $.extend(true, [], originalSequence); if (sequence.length > 1) { $.each(sequence.reverse(), function (i, currentCall) { var nextCall = sequence[i + 1]; if (nextCall) { var currentCallOptions = currentCall.o || currentCall.options, nextCallOptions = nextCall.o || nextCall.options; var timing = (currentCallOptions && currentCallOptions.sequenceQueue === false) ? "begin" : "complete", callbackOriginal = nextCallOptions && nextCallOptions[timing], options = {}; options[timing] = function () { var nextCallElements = nextCall.e || nextCall.elements; var elements = nextCallElements.nodeType ? [nextCallElements] : nextCallElements; callbackOriginal && callbackOriginal.call(elements, elements); Velocity(currentCall); } if (nextCall.o) { nextCall.o = $.extend({}, nextCallOptions, options); } else { nextCall.options = $.extend({}, nextCallOptions, options); } } }); sequence.reverse(); } Velocity(sequence[0]); }; }((window.jQuery || window.Zepto || window), window, document); })); ; /*! RESOURCE: /scripts/thirdparty/radio/radioGroup.js */ var RadioGroup = function (domNode) { this.domNode = domNode; this.radioButtons = []; this.firstRadioButton = null; this.lastRadioButton = null; }; RadioGroup.prototype.init = function () { if (!this.domNode.getAttribute('role')) { this.domNode.setAttribute('role', 'radiogroup'); } var rbs = this.domNode.querySelectorAll('[role=radio]'); for (var i = 0; i < rbs.length; i++) { var rb = new RadioButton(rbs[i], this); rb.init(); this.radioButtons.push(rb); if (!this.firstRadioButton) { this.firstRadioButton = rb; } this.lastRadioButton = rb; } this.firstRadioButton.domNode.tabIndex = 0; }; RadioGroup.prototype.setChecked = function (currentItem) { for (var i = 0; i < this.radioButtons.length; i++) { var rb = this.radioButtons[i]; rb.domNode.setAttribute('aria-checked', 'false'); rb.domNode.tabIndex = -1; } currentItem.domNode.setAttribute('aria-checked', 'true'); currentItem.domNode.click(); currentItem.domNode.tabIndex = 0; currentItem.domNode.focus(); }; RadioGroup.prototype.setCheckedToPreviousItem = function (currentItem) { var index; if (currentItem === this.firstRadioButton) { this.setChecked(this.lastRadioButton); } else { index = this.radioButtons.indexOf(currentItem); this.setChecked(this.radioButtons[index - 1]); } }; RadioGroup.prototype.setCheckedToNextItem = function (currentItem) { var index; if (currentItem === this.lastRadioButton) { this.setChecked(this.firstRadioButton); } else { index = this.radioButtons.indexOf(currentItem); this.setChecked(this.radioButtons[index + 1]); } }; ; /*! RESOURCE: /scripts/thirdparty/radio/radioButton.js */ var RadioButton = function (domNode, groupObj) { this.domNode = domNode; this.radioGroup = groupObj; this.keyCode = Object.freeze({ 'RETURN': 13, 'SPACE': 32, 'END': 35, 'HOME': 36, 'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'DOWN': 40 }); }; RadioButton.prototype.init = function () { this.domNode.tabIndex = -1; this.domNode.setAttribute('aria-checked', 'false'); this.domNode.addEventListener('keydown', this.handleKeydown.bind(this)); this.domNode.addEventListener('click', this.handleClick.bind(this)); this.domNode.addEventListener('focus', this.handleFocus.bind(this)); this.domNode.addEventListener('blur', this.handleBlur.bind(this)); }; RadioButton.prototype.handleKeydown = function (event) { var tgt = event.currentTarget, flag = false, clickEvent; switch (event.keyCode) { case this.keyCode.SPACE: case this.keyCode.RETURN: this.radioGroup.setChecked(this); flag = true; break; case this.keyCode.UP: this.radioGroup.setCheckedToPreviousItem(this); flag = true; break; case this.keyCode.DOWN: this.radioGroup.setCheckedToNextItem(this); flag = true; break; case this.keyCode.LEFT: this.radioGroup.setCheckedToPreviousItem(this); flag = true; break; case this.keyCode.RIGHT: this.radioGroup.setCheckedToNextItem(this); flag = true; break; default: break; } if (flag) { event.stopPropagation(); event.preventDefault(); } }; RadioButton.prototype.handleClick = function (event) { this.radioGroup.setChecked(this); }; RadioButton.prototype.handleFocus = function (event) { this.domNode.classList.add('focus'); }; RadioButton.prototype.handleBlur = function (event) { this.domNode.classList.remove('focus'); }; ; ; /*! RESOURCE: /scripts/js_includes_navpage15.js */ /*! RESOURCE: /scripts/concourse_gjsv.js */ var GJSV = 2.0; ; /*! RESOURCE: /scripts/concourse_framebuster.js */ $j(function() { if (window.self != window.top && window.name.indexOf('sn_frame') == -1) { var path = window.location.pathname; if (path.indexOf('/navpage.do') != 0 && path != '/') { top.location.href = window.location.href; return; } var src = $j('iframe#gsft_main').attr('src'); top.location.href = "/nav_to.do?uri=" + encodeURIComponent(src); } }); ; /*! RESOURCE: /scripts/consts/GlideEvent.js */ var GlideEvent = { WINDOW_CLICKED: 'glide:window_clicked', WINDOW_BLURRED: 'glide:window_blurred', WINDOW_FOCUSED: 'glide:window_focused', IMAGE_PICKED: 'glide:image_picked', NAV_MANAGER_LOADED: 'glide:nav_manager_loaded', NAV_FORM_DIRTY_CANCEL_STAY: 'glide:nav_form_dirty_cancel_stay', NAV_SYNC_LIST_WITH_FORM: 'glide:nav_sync_list_with_form', NAV_LOAD_FORM_FROM_LIST: 'glide:nav_load_form_from_list', NAV_SAVE_PREFERENCES: 'glide:nav_save_preferences', NAV_UPDATE_EDGE_BUTTON_STATES: 'glide:nav_update_edge_button_states', NAV_OPEN_URL: 'glide:nav_open_url', NAV_ADD_BOOKMARK: 'glide:nav_add_bookmark', NAV_REMOVE_BOOKMARK: 'glide:nav_remove_bookmark', NAV_UPDATE_BOOKMARK: 'glide:nav_update_bookmark', NAV_DRAGGING_BOOKMARK_START: 'glide:nav_dragging_bookmark_start', NAV_DRAGGING_BOOKMARK_STOP: 'glide:nav_dragging_bookmark_stop', NAV_HIDE_ALL_TOOLTIPS: 'glide:nav_hide_all_tooltips', NAV_QUEUE_BOOKMARK_OPEN_FLYOUT: 'glide:nav_queue_bookmark_open_flyout', NAV_OPEN_BOOKMARK: 'glide:nav_open_bookmark', NAV_BOOKMARK_ADDED: 'glide:nav_bookmark_added', NAV_BOOKMARK_REMOVED: 'glide:nav_bookmark_removed', NAV_EAST_PANE_RESIZED: 'glide:nav_east_pane_resized', NAV_ADD_FLYOUT: 'glide:nav_add_flyout', NAV_REMOVE_FLYOUT: 'glide:nav_remove_flyout', NAV_TOGGLE_FLYOUT: 'glide:nav_toggle_flyout', NAV_HIDE_FLYOUTS: 'glide:nav_hide_flyouts', NAV_PANE_CLICKED: 'glide:nav_window_clicked' }; ; /*! RESOURCE: /scripts/libs/keyboardJS/keyboard.0.2.2.min.js */ (function(e,t){if(typeof define==="function"&&define.amd){define(t)}else{var n=e.parent!=null?e.parent:e;n.k=n.KeyboardJS=t}})(this,function(e,t,n){function r(e,t,n){if(e.addEventListener){e.addEventListener(t,n,false)}else{e.attachEvent("on"+t,function(t){return n.call(e,t)})}}function f(){var e=[];for(var t=a.length;t>-1;t-=1){if(a[t]){var n=a[t];for(var r=0;r<n.length;r+=1){var i=n[r],s=true;for(var u=0;u<i.keys.length;u+=1){var f=i.keys[u];if(o.indexOf(f)<0){s=false}}if(s){e.push(i)}}}}return e}function l(e){if(o<1){return true}var t=f(),n=[],r;for(var i=0;i<t.length;i+=1){var s=t[i],a=false;for(var l=0;l<s.keys.length;l+=1){var c=s.keys[l];if(n.indexOf(c)>-1){break}}if(!a){if(typeof s.callback==="function"){if(!s.callback(e,s.keys,s.keyCombo)){r=false}}if(!u[s.keyCombo]){u[s.keyCombo]=[s]}else{u[s.keyCombo].push(s)}for(var l=0;l<s.keys.length;l+=1){var c=s.keys[l];if(n.indexOf(c)<0){n.push(c)}}}}return r}function c(e){var t=f();var n;for(var r in u){if(u.hasOwnProperty(r)){var i=u[r],s=false;for(var o=0;o<t.length;o+=1){var a=t[o].keyCombo;if(a===r){s=true;break}}if(!s){var l=i!=null?i.length:0;for(var c=0;c<l;c++){if(typeof i[c].endCallback==="function"){if(!i[c].endCallback(e,i[c].keys,i[c].keyCombo)){n=false}}}delete u[r]}}}return n}function h(e,t,n){function r(){if(o&&o.length){var e=a[o.length];if(e.indexOf(u)>-1){var t=a[o.length].indexOf(u);a[o.length].splice(t,1)}}return a}var i=e.toLowerCase().replace(/\s/g,"").split(",");for(var s=0;s<i.length;s+=1){var o=i[s].split("+");if(o.length){if(!a[o.length]){a[o.length]=[]}var u={callback:t,endCallback:n,keyCombo:i[s],keys:o};a[o.length].push(u)}}return{clear:r}}function p(e,t,n,r,i){function s(){if(typeof u==="function"){u()}if(typeof a==="function"){a()}if(typeof f==="function"){f()}if(typeof l==="function"){l()}if(typeof c==="function"){clearInterval(c)}}var o=[0,0];if(typeof i!=="function"){return false}var u=h(e,function(){if(o[0]===0){o[0]=-1}},function(){o[0]=0}).clear;var a=h(t,function(){if(o[0]===0){o[0]=1}},function(){o[0]=0}).clear;var f=h(n,function(){if(o[1]===0){o[1]=-1}},function(){o[1]=0}).clear;var l=h(r,function(){if(o[1]===0){o[1]=1}},function(){o[1]=0}).clear;var c=setInterval(function(){if(o[0]===0&&o[1]===0){return}i(o)},1);return{clear:s}}function d(e){if(e==="all"){a=[];return}e=e.replace(/\s/g,"").split(",");for(var t=a.length;t>-1;t-=1){if(a[t]){var n=a[t];for(var r=0;r<n.length;r+=1){var i=n[r],s=false;for(var o=0;o<i.keys.length;o+=1){var u=i.keys[o];for(var f=0;f<e.length;f+=1){var l=e[f];if(l===u){s=true;break}}if(s){break}}if(s){a[t].splice(r,1);r-=1;if(a[t].length<1){delete a[t]}}}}}}function v(){return o}function m(e,t){i[e]=t}function g(e){if(i[e]){s=i[e]}}[].indexOf||(Array.prototype.indexOf=function(e,t,n){for(n=this.length,t=(n+~~t)%n;t<n&&(!(t in this)||this[t]!==e);t++);return t^n?t:-1});var i={us:{backspace:8,tab:9,enter:13,shift:16,ctrl:17,alt:18,pause:19,"break":19,capslock:20,escape:27,esc:27,space:32,spacebar:32,pageup:33,pagedown:34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,"delete":46,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,meta:91,command:91,windows:91,win:91,_91:92,select:93,num0:96,num1:97,num2:98,num3:99,num4:100,num5:101,num6:102,num7:103,num8:104,num9:105,multiply:106,add:107,subtract:109,decimal:110,divide:111,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,numlock:144,num:144,scrolllock:145,scroll:145,semicolon:186,equal:187,equalsign:187,comma:188,dash:189,period:190,slash:191,forwardslash:191,graveaccent:192,openbracket:219,backslash:220,closebracket:221,singlequote:222}};var s=i["us"],o=[],u={};var a=n!=null?n.keyBindingGroups:[];$j(e.document).bind("keydown.keyJS",function(e){for(var t in s){if(s.hasOwnProperty(t)&&e.keyCode===s[t]){if(o.indexOf(t)<0){o.push(t)}}}return l(e)});$j(e.document).bind("keyup.keyJS",function(e){for(var t in s){if(s.hasOwnProperty(t)&&e.keyCode===s[t]){var n=o.indexOf(t);if(n>-1){o.splice(n,1)}}}return c(e)});r(e,"blur",function(e){o=[];return c(e)});return{bind:{key:h,axis:p},activeKeys:v,keyBindingGroups:a,unbind:{key:d},locale:{add:m,set:g},context:e,frame:t}}) /*! RESOURCE: /scripts/keyboard/KeyboardRegistry.js */ window.top.validKeys = { "backspace": 8, "tab": 9, "enter": 13, "shift": 16, "ctrl": 17, "alt": 18, "pause": 19, "break": 19, "capslock": 20, "escape": 27, "esc": 27, "space": 32, "spacebar": 32, "pageup": 33, "pagedown": 34, "end": 35, "home": 36, "left": 37, "up": 38, "right": 39, "down": 40, "insert": 45, "delete": 46, "0": 48, "1": 49, "2": 50, "3": 51, "4": 52, "5": 53, "6": 54, "7": 55, "8": 56, "9": 57, "a": 65, "b": 66, "c": 67, "d": 68, "e": 69, "f": 70, "g": 71, "h": 72, "i": 73, "j": 74, "k": 75, "l": 76, "m": 77, "n": 78, "o": 79, "p": 80, "q": 81, "r": 82, "s": 83, "t": 84, "u": 85, "v": 86, "w": 87, "x": 88, "y": 89, "z": 90, "meta": 91, "command": 91, "windows": 91, "win": 91, "_91": 92, "select": 93, "num0": 96, "num1": 97, "num2": 98, "num3": 99, "num4": 100, "num5": 101, "num6": 102, "num7": 103, "num8": 104, "num9": 105, "multiply": 106, "add": 107, "subtract": 109, "decimal": 110, "divide": 111, "f1": 112, "f2": 113, "f3": 114, "f4": 115, "f5": 116, "f6": 117, "f7": 118, "f8": 119, "f9": 120, "f10": 121, "f11": 122, "f12": 123, "numlock": 144, "num": 144, "scrolllock": 145, "scroll": 145, "semicolon": 186, "equal": 187, "equalsign": 187, "comma": 188, "dash": 189, "period": 190, "slash": 191, "forwardslash": 191, "graveaccent": 192, "openbracket": 219, "backslash": 220, "closebracket": 221, "singlequote": 222 }; (function patchKeyboardJs(window) { var parentKeyboardJS = window.KeyboardJS; window.KeyboardJS = function() { var patchedKeyboardJS = parentKeyboardJS.apply(this, arguments); patchedKeyboardJS.locale.add("snow:us", window.top.validKeys); patchedKeyboardJS.locale.set("snow:us"); return patchedKeyboardJS; }; })(window); var KeyboardRegistry = function(context) { this.initialize(context); } KeyboardRegistry.prototype = { mainFrame: "gsft_main", formFrame: "gsft_main_form", initialize: function(context) { var primary = window.KeyboardJS(window); var children = new Object(); if($j(window.document).find('iframe').length > 0) { var frames = $j(window.document).find('iframe'); for(var i = 0; i < frames.length; i++) { var frameElem = frames.get(i); var index = $j(frameElem).attr('name'); var fWindow = frameElem.contentWindow; children[index] = window.KeyboardJS(fWindow,frameElem); } } this.primary = primary; this.children = children; }, bind: function(keyCombo, onDownCallback, onUpCallbackOrData, data) { var obj = { registry: this, global: function(exclude) { return this._selector(null, null, null, exclude); }, formFrame: function() { return this.frame(this.registry.formFrame); }, form: function(id, name, action, method) { var elementName = 'form'; var attrMap1 = new Object(); var attrMap2 = new Object(); attrMap1['id'] = attrMap2['id'] = id; attrMap1['name'] = attrMap2['name'] = name; attrMap1['action'] = attrMap2['action'] = action; attrMap1['method'] = method != null ? method.toLowerCase() : null; attrMap2['method'] = method != null ? method.toUpperCase() : null; return this._selector(this._buildSelector(elementName, attrMap1, attrMap2)); }, frame: function(name, selector, exact) { return this._selector(selector, name, exact); }, selector: function(selector,exact) { return this._selector(selector, null, exact); }, _selector: function(selector, frameName, exact, exclude) { var onDownCallback = this.onDownCallback; var getEventTarget = this._getEventTarget; var onUpCallback = this.onUpCallback; var data = typeof onUpCallback === 'function' || onUpCallback == null ? this.data : onUpCallback; var callback = function(event, keys, combo, callback) { if(callback == null || typeof callback !== 'function') return true; var target = getEventTarget(event) var isMatch = selector == null || $j(target).is(selector); if(!isMatch && exact) return true; if(!isMatch) { $j(target).parents().each(function() { isMatch = $j(this).is(selector); if(isMatch) return false; }); if(!isMatch) return true; } var e = !event ? window.event : event; e.data = data != null ? data : {}; e.data._target = target; var output = callback(e,keys,combo); return output === false ? false : true; }; var onDown = function(event, keys, combo) { return callback(event, keys, combo, onDownCallback); }; var onUp = function(event, keys, combo) { return callback(event, keys, combo, onUpCallback); }; frameName = this.registry.primary != null ? frameName : (frameName == null || frameName == this.registry.mainFrame ? this.registry.formFrame : 'dummy'); exclude = frameName == null ? exclude : null; var response = new Object(); if ((frameName == null || frameName == 'top' || $j.isEmptyObject(this.registry.children)) && (exclude == null || exclude != 'top')) { response['top'] = this.registry.primary.bind.key(this.keyCombo, onDown, onUp); } var c = typeof window.console == "undefined" ? {log:function(str){}} : window.console; for ( var key in this.registry.children) { if((frameName == null || frameName == key) && (exclude == null || exclude != key)) { response[key] = this.registry.children[key].bind.key(this.keyCombo, onDown, onUp); } } if (frameName == null || frameName != 'dummy') { var fName = frameName != null && this.registry.children[key] != null ? frameName : null; var logging = false; if (logging && (fName != null || frameName == null || $j.isEmptyObject(this.registry.children)) && (exclude == null || fName != exclude)) { c.log("KeyboardRegistry: The '" + this.keyCombo + "' key has been bound to the " + (selector != null ? "selector '" + selector + "' " : "document ") + (exact ? "as an exact match ": "as a parent match ") + (fName != null ? ("to frame '" + fName + "'") : "to all frames") + "."); } } return { "clear" : function() { for(var key in response) { var keyBindingGroups = response[key].clear(); } } } }, _buildSelector: function(selector, attrMap1, attrMap2) { var sel1 = this._buildSelector0(selector, attrMap1); if(attrMap2 != null) { var sel2 = this._buildSelector0(selector, attrMap2); return sel1 + "," + sel2; } else { return sel1; } }, _buildSelector0: function(selector, attrMap) { for(var key in attrMap) { if(attrMap[key] != null) { selector += '['+ key +'="'+ attrMap[key] +'"]'; } } return selector; }, _getEventTarget: function(e) { if (!e) var e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) targ = targ.parentNode; return targ; } }; obj.keyCombo = keyCombo.toLowerCase(); obj.onDownCallback = onDownCallback; obj.onUpCallback = onUpCallbackOrData; obj.data = data; return obj; }, toString: function() { return "KeyboardRegistry"; } }; ; /*! RESOURCE: /scripts/concourse/SingletonKeyboardRegistry.js */ var SingletonKeyboardRegistry = (function($) { var instance; var windowNames = []; var createInstance = function() { instance = new ChildKeyboardRegistry(); return instance; }; var ChildKeyboardRegistry = function() { this.initialize(window); }; ChildKeyboardRegistry.prototype = Object.create(KeyboardRegistry.prototype); ChildKeyboardRegistry.prototype.addFrame = function(frameWindow) { var bindings, binding, index, frame; if (frameWindow.name) { index = frameWindow.name; frame = $(frameWindow.parent.document).find('iframe[name=' + index + ']'); if (frame.length) { $(frameWindow).bind('unload.keyJS', {context:window, index:index, children:this.children, registry:this}, function(e) { $(this.document).unbind('.keyJS'); $(this).unbind('.keyJS'); }); $(frame).bind('load.keyJS', {children:this.children, index:index, win:window, registry:this}, function(e) { if (!this.contentWindow) return; e.data.children[e.data.index] = e.data.win.KeyboardJS(this.contentWindow, this, e.data.children[e.data.index]); $(this.contentWindow).bind('unload.keyJS', {index:e.data.index, children:e.data.children, registry:e.data.registry}, function(e) { $(frame).unbind('.keyJS'); }); }); } } }; if (window.self != window.top) return null; CustomEvent.on('navigation.complete', function(frame) { if (instance) { instance.addFrame(frame); } }); return { getInstance : function() { if (!instance) { return createInstance(); } else { return instance; } } } })(jQuery); ; /*! RESOURCE: /scripts/concourse/keyboardShortcuts.js */ function getShortcutCombination(action) { if (window.g_keyboard_shortcuts && window.g_keyboard_shortcuts[action] && window.g_keyboard_shortcuts[action].key_combination) return window.g_keyboard_shortcuts[action].key_combination; return ''; } function getShortcutEnabledState(action) { if (window.g_keyboard_shortcuts && window.g_keyboard_shortcuts[action] && typeof window.g_keyboard_shortcuts[action].enabled === 'boolean') return window.g_keyboard_shortcuts[action].enabled; return true; } var MagellanNavigatorKeyboardUtils = (function($){ var textInputs = /textarea|input|select/i; function isTargetEditable (event) { var targetElement = event.target; if (targetElement) { if (textInputs.test(targetElement.nodeName)) { return true; } if ($(targetElement).attr('contenteditable')) { return true; } } return false; } function shouldAllowInInputs() { if (typeof window.g_keyboard_shortcuts === 'undefined' || typeof window.g_keyboard_shortcuts.allow_in_input_fields === 'undefined') return false; return window.g_keyboard_shortcuts.allow_in_input_fields; } function areShortcutsEnabled() { if (typeof window.g_keyboard_shortcuts === 'undefined' || typeof window.g_keyboard_shortcuts.enabled === 'undefined') return true; return window.g_keyboard_shortcuts.enabled; } return { isEventValidFactory: function(_shortcutsEnabled, _allowInInputs) { var shortcutsEnabled = _shortcutsEnabled === undefined ? areShortcutsEnabled() : _shortcutsEnabled; var allowInInputs = _allowInInputs === undefined ? shouldAllowInInputs() : _allowInInputs; if (shortcutsEnabled && !allowInInputs) { return function negate(event) { return !isTargetEditable.call(null, event); }; } else if (shortcutsEnabled && allowInInputs) { return function () { return true; }; } else { return function () { return false; }; } }, isShortcutValidFactory: function(keyboardRegistry) { var validKeys = window.top.validKeys; return function(keyCombo, action) { var defaultKeyCombo = { 'globalSearch': 'ctrl+alt+g', 'mainFrame': 'ctrl+alt+p', 'navToggle': 'ctrl+alt+c', 'navFilter': 'ctrl+alt+f', 'impersonator': 'ctrl+alt+i' }; var keys = keyCombo.toLowerCase().replace(/\s/g, '').split('+'); var bindings = keyboardRegistry.primary.keyBindingGroups[keys.length]; for (var i = 0; i < keys.length; i++) { if (!validKeys.hasOwnProperty(keys[i])) { console.log('%cKeyboard shortcut (' + keyCombo + ') defined for ' + action + ' is invalid. Reverting to default (' + defaultKeyCombo[action] + ').', 'color:red;'); keyCombo = defaultKeyCombo[action]; break; } } if (bindings) { for (var i = 0; i < bindings.length; i++) { if (keyCombo.toLowerCase().replace(/\s/g, '') === bindings[i].keyCombo) { console.log('%cKeyboard shortcut (' + keyCombo + ') defined for ' + action + ' is already in use. No action taken.', 'color:red;'); return false; } } } return keyCombo; } } } })(jQuery); (function($) { if (window.top != window.self) return; $('document').ready(function() { var keyboardRegistry = SingletonKeyboardRegistry.getInstance(); var isEventValid = MagellanNavigatorKeyboardUtils.isEventValidFactory(); var validShortcut = MagellanNavigatorKeyboardUtils.isShortcutValidFactory(keyboardRegistry); var impersonateButtonScope; CustomEvent.observe('application_navigator_keyboard_shortcuts_updated', function (keyboardShortcutsEnabled) { isEventValid = MagellanNavigatorKeyboardUtils.isEventValidFactory(keyboardShortcutsEnabled); }); function bindShortcut(shortcut, action, shortcutEnabled, callback) { var validKeyCombo = validShortcut(shortcut, action); if (validKeyCombo) { keyboardRegistry.bind(validKeyCombo, function(evt) { if (shortcutEnabled && isEventValid(evt)) callback(evt); }).selector(null, true); } } function globalSearchCallback(evt) { $('#sysparm_search').focus(); evt.preventDefault(); } function mainFrameCallback(evt) { window.top.moveFocusToMainContent(); evt.preventDefault(); } function navigatorToggleCallback(evt) { CustomEvent.fireAll('magellan_collapse.toggle'); evt.preventDefault(); } function navigatorFilterCallback(evt) { window.top.moveFocusToNavigationFilter(); evt.preventDefault(); } function impersonatorCallback(evt) { if (!impersonateButtonScope && angular) { var impersonateButton = angular.element($('#glide_ui_impersonator')); if (impersonateButton) { impersonateButtonScope = impersonateButton.scope(); } } if (impersonateButtonScope) { impersonateButtonScope.$broadcast('dialog.impersonate.show'); evt.preventDefault(); } } bindShortcut(getShortcutCombination('global_search'), 'globalSearch', getShortcutEnabledState('global_search'), globalSearchCallback); bindShortcut(getShortcutCombination('main_frame'), 'mainFrame', getShortcutEnabledState('main_frame'), mainFrameCallback); bindShortcut(getShortcutCombination('navigator_toggle'), 'navToggle', getShortcutEnabledState('navigator_toggle'), navigatorToggleCallback); bindShortcut(getShortcutCombination('navigator_filter'), 'navFilter', getShortcutEnabledState('navigator_filter'), navigatorFilterCallback); bindShortcut(getShortcutCombination('impersonator'), 'impersonator', getShortcutEnabledState('impersonator'), impersonatorCallback); }); })(jQuery); ; /*! RESOURCE: /scripts/concourse/focusUtils.js */ function moveFocusToMainContent() { var main = top.gsft_main; var focusableElement = jQuery(main.document).find(':focusable').first(); if (focusableElement.length) focusableElement.focus(); else main.focus(); } function moveFocusToNavigationFilter() { (function($) { if ($('.navpage-layout').hasClass('navpage-nav-collapsed')) { CustomEvent.fireAll('magellan_collapse.toggle'); $(document).one("nav.expanded", function() { $('#filter').focus(); }); } else { if (!$('.navpage-layout').hasClass('magellan-edit-mode')) { $('#filter').focus(); } } })(jQuery); } ; /*! RESOURCE: /scripts/sn/common/messaging/js_includes_messaging.js */ /*! RESOURCE: /scripts/doctype/CustomEventManager.js */ var NOW = NOW || {}; var CustomEventManager = (function (existingCustomEvent) { "use strict"; var events = (existingCustomEvent && existingCustomEvent.events) || {}; var isFiringFlag = false; var trace = false; var suppressEvents = false; var NOW_MSG = 'NOW.PostMessage'; function observe(eventName, fn){ if (trace) jslog("$CustomEventManager observing: " + eventName); on(eventName, fn); } function on(name, func) { if (!func || typeof func !== 'function') return; if (typeof name === 'undefined') return; if (!events[name]) events[name] = []; events[name].push(func); } function un(name, func) { if (!events[name]) return; var idx = -1; for (var i = 0; i < events[name].length; i++) { if (events[name][i] === func) { idx = i; break; } } if (idx >= 0) events[name].splice(idx, 1) } function unAll(name) { if (events[name]) delete events[name]; } function fire(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); return fireEvent.apply(null, arguments); } function fireUp(eventName, args){ var win = window; while (win){ try { if (win.CustomEvent.fireEvent.apply(null, arguments) === false) return; win = win.parent === win ? null : win.parent; }catch(e){ return; } } } function fireEvent() { if (suppressEvents) return true; var args = Array.prototype.slice.apply(arguments); var name = args.shift(); var eventList = events[name]; if (!eventList) return true; var event = eventList.slice(); isFiringFlag = true; for (var i = 0, l = event.length; i < l; i++) { var ev = event[i]; if (!ev) continue; if (ev.apply(null, args) === false) { isFiringFlag = false; return false; } } isFiringFlag = false; return true; } function isFiring() { return isFiringFlag; } function forward(name, element, func) { on(name, func); element.addEventListener(name, function(e) { fireEvent(e.type, this, e); }.bind(api)); } function isOriginInWhiteList(origin, whitelistStr) { if (!whitelistStr) { return false; } var delimiterRegex = /[\n, ]/; var whitelist = whitelistStr.split(delimiterRegex) .filter(function(whiteListedOrigin) { return whiteListedOrigin; }) .map(function(whiteListedOrigin) { return whiteListedOrigin.toLowerCase(); }); if (~whitelist.indexOf(origin.toLowerCase())) { return true; } return false; } function shouldProcessMessage(sourceOrigin) { if (!window.g_concourse_onmessage_enforce_same_origin || sourceOrigin === window.location.origin) { return true; } return isOriginInWhiteList(sourceOrigin, window.g_concourse_onmessage_enforce_same_origin_whitelist); } function registerPostMessageEvent() { if (NOW.registeredPostMessageEvent) { return; } if (!window.postMessage) { return; } window.addEventListener('message', function (event) { if (!shouldProcessMessage(event.origin)) { console.warn('Incoming message ignored due to origin mismatch.'); return; } var nowMessageJSON = event.data; var nowMessage; try { nowMessage = JSON.parse(nowMessageJSON.toString()); } catch (e) { return; } if (!nowMessage.type == NOW_MSG) { return; } fire(nowMessage.eventName, nowMessage.args); }, false); NOW.registeredPostMessageEvent = true; } function doPostMessage(win, event, msg, targetOrigin) { var nowMessage = {type: NOW_MSG, eventName: event, args: msg}; var nowMessageJSON; if (!win || !win.postMessage) { return } nowMessageJSON = JSON.stringify(nowMessage); win.postMessage(nowMessageJSON, targetOrigin); } function fireTop(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); fireEvent.apply(null, arguments); var t = getTopWindow(); if (t !== null && window !== t) t.CustomEvent.fire(eventName, args); } function fireAll(eventName, args) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); var topWindow = getTopWindow(); if (topWindow !== window.self) CustomEvent.fireEvent(eventName, args); notifyAllFrom(topWindow); function notifyAllFrom(rootFrame) { var childFrame; rootFrame.CustomEvent.fireEvent(eventName, args); for (var i = 0; i < rootFrame.frames.length; i++) { try { childFrame = rootFrame.frames[i]; if (!childFrame) continue; if (childFrame.CustomEvent && typeof childFrame.CustomEvent.fireEvent === "function") { notifyAllFrom(childFrame); } } catch(e) { } } } } function fireToWindow(targetWindow, eventName, args, usePostMessage, targetOrigin) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + args.length); if (usePostMessage) { doPostMessage(targetWindow, eventName, args, targetOrigin); } else { targetWindow.CustomEvent.fireEvent(eventName, args); } } function getTopWindow() { var topWindow = window.self; try { while (topWindow.CustomEvent.fireEvent && topWindow !== topWindow.parent && topWindow.parent.CustomEvent.fireEvent) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } function isTopWindow() { return getTopWindow() == window.self; } function jslog(msg, src, dateTime) { try { if (!src) { var path = window.self.location.pathname; src = path.substring(path.lastIndexOf('/') + 1); } if (window.self.opener && window != window.self.opener) { if (window.self.opener.jslog) { window.self.opener.jslog(msg, src, dateTime); } } else if (parent && parent.jslog && jslog != parent.jslog) { parent.jslog(msg, src, dateTime); } else { if (window.console && window.console.log) console.log(msg); } } catch (e) { } } var api = { set trace(value) { trace = !!value; }, get trace() { return trace; }, set suppressEvents(value) { suppressEvents = !!value; }, get suppressEvents() { return suppressEvents; }, get events() { return events; }, set events(value) { events = value; }, on: on, un: un, unAll: unAll, forward: forward, isFiring: isFiring, fireEvent: fireEvent, observe: observe, fire: fire, fireTop: fireTop, fireAll: fireAll, fireToWindow: fireToWindow, isTopWindow: isTopWindow, fireUp: fireUp, toString: function() { return 'CustomEventManager'; } }; registerPostMessageEvent(); return api; })(NOW.CustomEvent); NOW.CustomEvent = CustomEventManager; if (typeof CustomEvent !== "undefined") { CustomEvent.observe = NOW.CustomEvent.observe.bind(NOW.CustomEvent); CustomEvent.fire = NOW.CustomEvent.fire.bind(NOW.CustomEvent); CustomEvent.fireUp = NOW.CustomEvent.fireUp.bind(NOW.CustomEvent); CustomEvent.fireTop = NOW.CustomEvent.fireTop.bind(NOW.CustomEvent); CustomEvent.fireAll = NOW.CustomEvent.fireAll.bind(NOW.CustomEvent); CustomEvent.fireToWindow = NOW.CustomEvent.fireToWindow.bind(NOW.CustomEvent); CustomEvent.on = NOW.CustomEvent.on.bind(NOW.CustomEvent); CustomEvent.un = NOW.CustomEvent.un.bind(NOW.CustomEvent); CustomEvent.unAll = NOW.CustomEvent.unAll.bind(NOW.CustomEvent); CustomEvent.forward = NOW.CustomEvent.forward.bind(NOW.CustomEvent); CustomEvent.isFiring = NOW.CustomEvent.isFiring.bind(NOW.CustomEvent); CustomEvent.fireEvent = NOW.CustomEvent.fireEvent.bind(NOW.CustomEvent); CustomEvent.events = NOW.CustomEvent.events; CustomEvent.isTopWindow = NOW.CustomEvent.isTopWindow.bind(NOW.CustomEvent); } else { window.CustomEvent = NOW.CustomEvent; } ; /*! RESOURCE: /scripts/sn/common/messaging/_module.js */ angular.module('sn.common.messaging', []); angular.module('sn.messaging', ['sn.common.messaging']); ; /*! RESOURCE: /scripts/sn/common/messaging/service.snCustomEvent.js */ angular.module('sn.common.messaging').factory('snCustomEvent', function() { "use strict"; if (typeof NOW.CustomEvent === 'undefined') throw "CustomEvent not found in NOW global"; return NOW.CustomEvent; }); ; ; /*! RESOURCE: /scripts/concourse/_module.js */ angular.module('sn.concourse', [ 'ng.common', 'sn.messaging', 'sn.common.session_notification', 'sn.common.bindWatch', 'ngSanitize', 'ngAnimate', 'sn.concourse_pane_extension', 'sn.concourse_view_stack' ]); ; /*! RESOURCE: /scripts/concourse/factory.keyboardRegistry.js */ angular.module('ng.common').factory('keyboardRegistry', [function() { if (window.top.SingletonKeyboardRegistry) { var keyboardRegistry = window.top.SingletonKeyboardRegistry.getInstance(); return keyboardRegistry; } }]); ; /*! RESOURCE: /scripts/concourse/directive.preferenceChanger.js */ angular.module('sn.concourse').directive('preferenceChanger', function(getTemplateUrl, snCustomEvent, userPreferences) { "use strict"; return { restrict: 'E', scope: { label: '@', moreinfo: '@', type: '@', fireEvent: '@', preference: '@', reload: '@', confirm: '@', disabledmsg: '@', defaultValue: '@', options: '=' }, replace: true, templateUrl: getTemplateUrl('cc_preference_changer.xml'), controller: function($scope, $window, $timeout) { $scope.id = (Math.random() * 1000) + $scope.preference.replace(/\./g, '_'); userPreferences.getPreference($scope.preference).then(function(val) { if ($scope.type === 'boolean') { if (val) { try { $scope.prefValue = JSON.parse(val); } catch (e) { $scope.prefValue = val; } } else if (val === undefined && $scope.defaultValue === "true"){ $scope.prefValue = true; } } else $scope.prefValue = val; if (val == "null" && $scope.options){ $scope.prefValue = $scope.options[0].value; } $scope.origValue = $scope.prefValue; if ($scope.fireEvent) { snCustomEvent.on($scope.fireEvent, function(newVal){ if ($scope.prefValue === newVal) return; $timeout(function() { $scope.prefValue = newVal || newVal === "true"; }); }); } $scope.$watch('prefValue', function(newValue, oldValue) { if (newValue != oldValue) { if ($scope.confirm) { if (newValue == $scope.origValue) return; if (!confirm($scope.confirm)) { $timeout(function() { $scope.prefValue = $scope.origValue; }); return; } } userPreferences.setPreference($scope.preference, newValue).then(function() { if ($scope.reload) $window.location.reload(); if ($scope.fireEvent) snCustomEvent.fireAll($scope.fireEvent, newValue); }); } }); }); }, link: function($scope, $element) { $element.on('change', 'input[type=checkbox]', function() { $scope.prefValue = angular.element(this).prop('checked'); $scope.$apply(); }); $element.on('change', 'input[type=radio]', function() { $scope.prefValue = this.getAttribute('value'); $scope.$apply(); }) } } }); ; /*! RESOURCE: /scripts/concourse/directive.themePicker.js */ angular.module('sn.concourse').directive('themePicker', function(getTemplateUrl, userPreferences, $timeout, snCustomEvent) { "use strict"; return{ restrict: 'E', templateUrl: getTemplateUrl('concourse_theme_picker.xml'), controller: function($scope, $http) { $scope.executionCount = 0; var lazyLoaded = false; function getData(){ $http.get("/api/now/ui/theme").then(function(response){ if (response && response.data && response.data.result && response.data.result.themes){ $scope.themes = response.data.result.themes; if (response.data.result.defaultTheme) $scope.defaultTheme = response.data.result.defaultTheme; var initialPress = true; document.getElementById("nav-settings-button").addEventListener("click", function() { if (initialPress) { initialPress = false; processLazyLoad(); } }); } }); } getData(); function processLazyLoad() { if (lazyLoaded) return; var cb = function() { lazyLoad($scope.themes, document); if (document.getElementById("gsft_main")) lazyLoad($scope.themes, document.getElementById("gsft_main").contentDocument); }; (function() { var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); var raf = requestAnimationFrame; if (raf) raf(cb); else document.getElementById("gsft_main").contentWindow.addEventListener('load', cb); lazyLoaded = true; } function lazyLoad(themes, frameContext){ var links = frameContext.getElementsByTagName("link"); var styles = []; for (var i = 0; links.length > i; i++) { if (links[i].getAttribute("type") == "text/css") { styles.push(links[i]); } } var styleFrame; if (!document.getElementById("styleFrame")) { styleFrame = frameContext.createElement("iframe"); document.head.appendChild(styleFrame); styleFrame.id = "styleFrame0"; lazyLoadStyles(themes, frameContext, styleFrame, styles); } else { var highestStyle = 0; var currentStyle = 0; var allFrames = document.getElementsByTagName("iframe"); for (i = 0; i < allFrames.length; i++) { if (allFrames[i].id.indexOf("styleFrame") > -1) { currentStyle = allFrames[i].id.split("styleFrame")[0]; if (currentStyle.parseInt() > highestStyle) highestStyle = currentStyle; } } styleFrame = document.getElementById("styleFrame" + highestStyle); styleFrame.setAttribute("style", "display:none"); lazyLoadStyles(themes, frameContext, styleFrame, styles); } } function lazyLoadStyles(themes, frameContext, styleFrame, styles) { var styleCount = 0; var frameCount = 1; var firstRun = true; for (var i = 0; styles.length > i; i++) { var styleLink = styles[i].getAttribute("href"); styleLink = styleLink.split("&theme="); for (var n = 0; themes.length > n; n++) { if (!styleLink[1] || styleLink[1] != $scope.themes[n].id) { if (firstRun && !styleFrame.contentDocument.body) { var frameForm = styleFrame.contentDocument.createElement('html'); styleFrame.contentDocument.appendChild(frameForm); var frameHead = styleFrame.contentDocument.createElement('body'); styleFrame.contentDocument.getElementsByTagName("html")[0].appendChild(frameHead); firstRun = false; } insertStyles(styleFrame, styleLink, n); styleCount++; if (styleCount >= (31 * frameCount) && !document.getElementById("styleFrame" + frameCount)) { styleFrame = frameContext.createElement("iframe"); document.head.appendChild(styleFrame); styleFrame.id = "styleFrame" + frameCount; styleFrame.setAttribute("style", "display:none"); frameCount++; firstRun = true; } } } } } function insertStyles(styleFrame, styleLink, count){ var linkElement = styleFrame.contentDocument.createElement('link'); linkElement.rel = 'stylesheet'; linkElement.type = "text/css"; linkElement.href = styleLink[0] + "&theme=" + $scope.themes[count].id; styleFrame.contentDocument.body.appendChild(linkElement); } snCustomEvent.observe('sn:set_theme', function(themeId) { processLazyLoad(); setTimeout(function() { $scope.updateTheme({ id: themeId }); }, 500); }); $scope.updateTheme = function(theme){ userPreferences.setPreference('glide.css.theme.ui16', theme.id); $http.put("/api/now/ui/theme/preference", theme); if(theme.name) document.getElementById(theme.name).children[2].checked = true; $scope.executionCount ++; if ($scope.executionCount < 2) { callStylePanes(theme); } else { setTimeout(function (){callStylePanes(theme);}, 1000); } $scope.defaultTheme = theme.id; function callStylePanes(theme){ setStyles(theme, "nav"); setStyles(theme, "content"); setStyles(theme, "collab"); setStyles(theme, "jsdebug"); } function setStyles(theme, pane) { var styles = []; var frameContext = ""; var headTag = ""; if(pane == "nav") { headTag = document.getElementsByTagName("head")[0]; if (!headTag) return; styles = headTag.getElementsByTagName("link"); frameContext = document; } else if(pane == "content"){ if (!document.getElementById("gsft_main")) return; headTag = document.getElementById("gsft_main").contentDocument.getElementsByTagName("head")[0]; styles = headTag.getElementsByTagName("link"); frameContext = document.getElementById("gsft_main").contentDocument; } else if(pane == "collab"){ if (document.getElementById("edge_east")) { headTag = document.getElementById("edge_east").parentElement; if (!headTag) return; styles = headTag.getElementsByTagName("link"); if (!styles) return; frameContext = document; } else return; } else if(pane == "jsdebug") { if (document.getElementById("javascript_debugger")) { headTag = document.getElementById("javascript_debugger").contentDocument.getElementsByTagName("body")[0]; if (!headTag) return; styles = headTag.getElementsByTagName("link"); if (!styles) return; frameContext = document.getElementById("javascript_debugger").contentDocument; } else return; } applyStyles(styles, theme, frameContext); } function applyStyles(styles, theme, frameContext){ var styleObject = []; var styleList = []; if (styles.length > 20) removeOldStyles(frameContext); for (var i = 0; styles.length > i; i++) { var styleLink = styles[i].getAttribute("href"); var link = styles[i].getAttribute("href"); if (styles[i].getAttribute("type") == "text/css" && styles[i].getAttribute("class") != "old-template" && link != "/styles/spectrum.css" && link != "/styles/third-party/jquery_notification.css" && link.indexOf("tinymce") === -1) { styleObject.push(styles[i]); styleLink = styleLink.split("&theme="); styleLink = styleLink[0]; styleLink += "&theme=" + theme.id; var newStyle = frameContext.createElement("link"); newStyle.setAttribute("type", "text/css"); newStyle.setAttribute("rel", "stylesheet"); newStyle.setAttribute("href", styleLink); styleList.push(newStyle); styles[i].setAttribute("class","old-template"); } } for (i = 0; styleList.length > i; i++){ styleObject[i].parentNode.appendChild(styleList[i]); } setTimeout(function(){removeOldStyles(frameContext)}, 2000); $scope.executionCount--; } function removeOldStyles(frameContext){ var oldTemplates = frameContext.getElementsByClassName("old-template"); var otLength = oldTemplates.length; for (var i = 0; otLength > i; i++) { oldTemplates[0].parentNode.removeChild(oldTemplates[0]); } } } }, link : function(scope, element) { scope.addTooltip = function (first) { if (first) { $timeout(function () { jQuery(element).find('a').tooltip({ placement: 'auto', container: 'body' }) }); } }; } } }); ; /*! RESOURCE: /scripts/concourse/directive.requestManager.js */ angular.module("sn.concourse").directive("requestManager",["$http", "snCustomEvent", "getTemplateUrl", "$timeout", "MessagesStack", "$interval", "i18n", function($http, snCustomEvent, getTemplateUrl, $timeout, MessagesStack, $interval, i18n){ return { restrict: 'E', scope: { timerDelay: '@' }, templateUrl: getTemplateUrl('concourse_request_manager.xml'), controller: function($scope, $http){ var interval = 0; var timeOut; var loadingStartTime = 0; var startTime = 0; var finalMsgTimeOut = 0; var checkingWithServer = false; var serverCheckTime = 0; var loadCancelValidation = false; var transactionCheckDelay = 2000; $scope.cancelling = false; $scope.showAlert = false; $scope.hideButton = false; $scope.statusMessage = ''; $scope.timer = 0; if (!$scope.timerDelay){ $scope.timerDelay = 15; } var delayTime = $scope.timerDelay * 1000; snCustomEvent.observe("request_start", function(){ if(timeOut) return; startTime = new Date(); if (finalMsgTimeOut) $timeout.cancel(finalMsgTimeOut); finalMsgTimeOut = 0; timeOut = $timeout(checkTransaction, delayTime); }); snCustomEvent.observe("load_page_request_start", function(){ loadCancelValidation = true; if(loadingStartTime) return; startTime = new Date(); if (finalMsgTimeOut) $timeout.cancel(finalMsgTimeOut); finalMsgTimeOut = 0; timeOut = $timeout(checkTransaction, delayTime); }); snCustomEvent.observe("request_complete", handleRequestComplete); snCustomEvent.observe("load_page_request_complete",function(){ loadCancelValidation = false; handleRequestComplete(); }); snCustomEvent.observe("request_cancel", $scope.handleRequestCancel); snCustomEvent.observe("clear_message", clearMessage); function checkTransaction(){ if (checkingWithServer) return; checkingWithServer = true; serverCheckTime = new Date(); $http.get("/cancel_my_transaction.do?status=true&sysparm_output=json").then(function(response){ checkTransactionResponse(response); }); } function checkTransactionResponse(response){ if (response && response.data && response.data.status){ checkingWithServer = false; var message = response.data.status; if ("No session, nothing to cancel" == message) clearMessage(); else if ("complete" == message) handleRequestComplete(); else startIntervalTimer(); } else clearMessage(); } function clearMessage(){ $scope.showAlertBar(false); } function handleRequestComplete() { if(loadCancelValidation == false) { $scope.timer = getTime(); if ($scope.cancelling) setStatus(i18n.getMessage("Transaction cancelled") + ":"); else setStatus(i18n.getMessage("Transaction completed") + ":"); $scope.hideAlertButton(true); $scope.cancelling = false; clearTimers(); if (startTime == 0) { clearMessage(); return; } setTimerMessage(); finalMsgTimeOut = $timeout(clearMessage, 2500); startTime = 0; serverCheckTime = 0; } } function startIntervalTimer(){ if (interval) return; $scope.showAlertBar(true); $scope.hideAlertButton(false); handleInterval(); interval = setInterval(handleInterval, transactionCheckDelay); } function clearTimers() { if (interval) clearInterval(interval); if (timeOut) $timeout.cancel(timeOut); interval = 0; timeOut = 0; } function handleInterval(){ var timer = new Date() - serverCheckTime; if (timer >= transactionCheckDelay) checkTransaction(); $scope.timer = getTime(); if ($scope.cancelling) setStatus(i18n.getMessage("Transaction cancelling") + ":"); else setStatus(i18n.getMessage("Running Transaction") + ":"); setTimerMessage(); if($scope.timer == 0){ handleRequestComplete(); } } function getTime(){ if (startTime == 0) return 0; var timer = new Date() - startTime; return Math.round(timer / 100)/10; } function setStatus(message) { if ($scope.statusMessage === message || $scope.timer < $scope.timerDelay) return; $scope.statusMessage = message; angular.element('#request_status_message').text(message); } function setTimerMessage() { if ($scope.timer < $scope.timerDelay) return; var timerMessage = i18n.format(i18n.getMessage('{0} seconds'), $scope.timer); angular.element('#request_timer').text(timerMessage); } $scope.handleRequestCancel = function(){ if($scope.cancelling) return; $scope.cancelling = true; $scope.hideAlertButton(true); setStatus(i18n.getMessage("Transaction cancelling") + ":"); $http.get("cancel_my_transaction.do?sysparm_output=xml").then(checkTransactionResponse); }; $scope.hideAlertButton = function(disabled){ $scope.hideButton = disabled; }; $scope.showAlertBar = function(enabled){ if ($scope.showAlert === enabled) return; if (enabled) MessagesStack.push("request-manager"); $scope.showAlert = enabled; if (!enabled) setTimeout(function() { MessagesStack.pop("request-manager"); }, 1300 ); }; } } }]); ; /*! RESOURCE: /scripts/concourse/directive.elevateRoleIndicator.js */ angular.module('sn.concourse').directive('elevateRoleIndicator', ['snCustomEvent', function(snCustomEvent) { "use strict" return { restrict : 'E', replace : true, template : '<span ng-show="hasActiveRole" class="icon icon-unlocked elevated-role-indicator"></span>', controller : function($scope) { $scope.hasActiveRole = false; snCustomEvent.on('user.elevatedRoles.updated', function(activeRoles) { if (activeRoles.length) { $scope.hasActiveRole = true; } else { $scope.hasActiveRole = false; } }); } } }]); ; /*! RESOURCE: /scripts/concourse/directive.printerFriendly.js */ angular.module("sn.concourse").directive('printerFriendly', function(getTemplateUrl) { return{ restrict: 'E', templateUrl: getTemplateUrl('concourse_print_friendly.xml'), controller: function($scope){ $scope.printList = function(maxRows){ verifyEventHandlers(); var veryLargeNumber = "999999999"; var print = true; var features = "resizable=yes,scrollbars=yes,status=yes,toolbar=no,menubar=yes,location=no"; if (navigator.appVersion.indexOf("Mac OS X") != -1 && navigator.appVersion.indexOf("Chrome") != -1) features = ""; var href = ""; if (top.gsft_main) var frame = top.gsft_main.gsft_list_form_modal; if (!frame) { frame = top.gsft_main; if (!frame) frame = top; } if (frame.document.getElementById("printURL") != null) { href = frame.document.getElementById("printURL").value; href = printListURLDecode(href); } if (!href) { if (frame.document.getElementById("sysparm_total_rows") != null) { validateMaxRows(maxRows); } var formTest; var f = 0; var form = frame.document.forms['sys_personalize']; if (form && form.sysparm_referring_url) { href = form.sysparm_referring_url.value; if (href.indexOf("?sys_id=-1") != -1 && !href.startsWith('sys_report_template')) { alert(getMessage("Please save the current form before printing.")); return false; } if (navigator.appVersion.indexOf("MSIE") != -1) { var isFormPage = frame.document.getElementById("isFormPage"); if (isFormPage != null && isFormPage.value == "true") href = href.replace(/javascript%3A/gi, "_javascript_%3A"); } href = printListURLDecode(href); } else href = document.getElementById("gsft_main").contentWindow.location.href; } if( href.indexOf("?") <0 ) href += "?"; else href += "&"; href = href.replace("partial_page=", "syshint_unimportant="); href = href.replace("sysparm_media=", "syshint_unimportant="); href += "sysparm_stack=no&sysparm_force_row_count=" + veryLargeNumber + "&sysparm_media=print"; if (print) { if (href != null && href != "") { win = window.open(href, "Printer_friendly_format", features); win.focus(); } else { alert("Nothing to print"); } } }; function verifyEventHandlers(maxRows){ var mainWin = getMainWindow(); if (mainWin && mainWin.CustomEvent && mainWin.CustomEvent.fire && mainWin.CustomEvent.fire("print", maxRows) === false) return false; } function validateMaxRows(maxRows){ var mRows = parseInt(maxRows); if (mRows < 1) mRows = 5000; var totalrows = frame.document.getElementById("sysparm_total_rows").value; if (parseInt(totalrows) > parseInt(mRows)) print = confirm(getMessage("Printing large lists may affect system performance. Continue?")); } function printListURLDecode(href) { href = href.replace(/@99@/g, "&"); href = href.replace(/@88@/g, "@99@"); href = href.replace(/@77@/g, "@88@"); href = href.replace(/@66@/g, "@77@"); return href; } function getMainWindow() { var topWindow = getTopWindow(); return topWindow['gsft_main']; } function getTopWindow() { var topWindow = window.self; try { while (topWindow.GJSV && topWindow != topWindow.parent && topWindow.parent.GJSV) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } } } }); ; /*! RESOURCE: /scripts/concourse/directive.applicationPicker.js */ angular.module('sn.concourse').directive('applicationPicker', [ 'snCustomEvent', 'getTemplateUrl', '$rootScope', 'userPreferences', 'applicationService', function(snCustomEvent, getTemplateUrl, $rootScope, userPreferences, applicationService) { "use strict" return { restrict : 'E', replace : false, templateUrl : getTemplateUrl('concourse_application_picker.xml'), scope : { current : '=', inHeader : '=', showInHeader : '=' }, controller : function($scope) { $scope.closeModal = function(){ angular.element('#settings_modal').modal('hide'); }; $scope.app = applicationService.applicationData; if ($scope.current) { applicationService.initialize($scope.current, $scope.showInHeader); } $scope.refreshApplicationPicker = function() { applicationService.getApplicationList(); }; $scope.updateCurrent = function() { applicationService.updateCurrent(); }; snCustomEvent.observe('glide:ui_notification.application_change', function() { applicationService.getApplicationList(); }); snCustomEvent.observe('sn:refresh_application_picker', function() { applicationService.getApplicationList(); }); snCustomEvent.observe('sn:change_application', function(appId) { applicationService.getApplicationList().then(function() { applicationService.applicationData.currentId = appId; $scope.updateCurrent(); }); }); }, link : function(scope, element) { element.tooltip({ selector: '[data-toggle="tooltip"]', title: function() { var $this = angular.element(this); return $this.attr('title') || $this.text(); } }); element.on('mouseover', function() { if (!applicationService.hasFetchedData()) { applicationService.getApplicationList(); } }); element.on('change', 'input[type=checkbox]', function() { var showInHeader = angular.element(this).prop('checked'); applicationService.applicationData.showInHeader = showInHeader; scope.showInHeader = showInHeader; if (showInHeader) { userPreferences.setPreference('glide.ui.application_picker.in_header', 'true'); } else { userPreferences.setPreference('glide.ui.application_picker.in_header', ''); } }); $rootScope.$on('concourse.application.refresh', function() { var iframe = jQuery('iframe#gsft_main'); if (iframe.length) { iframe[0].contentWindow.location.reload(); } }); } } }]).factory('applicationService', ['$http', 'snCustomEvent', '$rootScope', function($http, snCustomEvent, $rootScope) { var fetchedInitialData = false; var initialized = false; var applicationData = { list : [], current : {}, currentId : '', showInHeader : false }; var hasFetchedData = function() { return fetchedInitialData; }; var initialize = function(current, showInHeader) { if (initialized) return; initialized = true; applicationData.list = [current]; applicationData.current = current; applicationData.currentId = current.sysId; applicationData.showInHeader = showInHeader; }; var getApplicationList = function() { fetchedInitialData = true; return $http.get('/api/now/ui/concoursepicker/application?cache=' + new Date().getTime()).then(function(response) { if (response && response.data && response.data.result) { applicationData.list = response.data.result.list; if (response.data.result.current && response.data.result.current != applicationData.currentId) { var apps = response.data.result.list; var curr = response.data.result.current; for (var i = 0; i < apps.length; i++) { if (curr == apps[i].sysId) { applicationData.current = apps[i] applicationData.currentId = apps[i].sysId; break; } } triggerChangeEvent(); } } }); }; var updateCurrent = function() { var apps = applicationData.list; var curr = applicationData.currentId; for (var i = 0; i < apps.length; i++) { if (curr == apps[i].sysId) { applicationData.current = apps[i]; break; } } $http.put('/api/now/ui/concoursepicker/application', { app_id : applicationData.currentId }).then(function(response) { if (response && response.data && response.data.result && response.data.result.app_id) { triggerRefreshFrameEvent(); triggerChangeEvent(); } }); }; function triggerChangeEvent() { $rootScope.$broadcast('concourse.application.changed', applicationData.current); } function triggerRefreshFrameEvent() { $rootScope.$broadcast('concourse.application.refresh', {}); } $rootScope.$on('concourse.application.changed', function(evt, current) { applicationData.current = current; applicationData.currentId = current.sysId; }); return { hasFetchedData : hasFetchedData, getApplicationList : getApplicationList, updateCurrent : updateCurrent, applicationData : applicationData, initialize : initialize } }]); ; /*! RESOURCE: /scripts/concourse/directive.updateSetPicker.js */ angular.module('sn.concourse').directive('updateSetPicker', [ 'snCustomEvent', 'getTemplateUrl', '$rootScope', 'userPreferences', 'updateSetService', function(snCustomEvent, getTemplateUrl, $rootScope, userPreferences, updateSetService) { "use strict" return { restrict : 'E', replace : false, templateUrl : getTemplateUrl('concourse_update_set_picker.xml'), scope : { current : '=', inHeader : '=', showInHeader : '=' }, controller : function($scope) { $scope.closeModal = function(){ angular.element('#settings_modal').modal('hide'); }; if ($scope.current) { updateSetService.initialize($scope.current, $scope.showInHeader); } $scope.updateSets = updateSetService.updateSetData; $scope.getUpdateSetList = function() { return updateSetService.getUpdateSetList(); }; $scope.refreshUpdateSetList = $scope.getUpdateSetList; $scope.updateCurrent = function() { updateSetService.updateCurrent(); }; $rootScope.$on('concourse.update_set.in_header.change', function(evt, showInHeader) { $scope.showInHeader = showInHeader; }); snCustomEvent.observe('sn:change_update_set', function(updateSetId) { $scope.getUpdateSetList().then(function() { updateSetService.updateSetData.currentId = updateSetId; $scope.updateCurrent(); }); }); }, link : function(scope, element) { element.tooltip({ selector: '[data-toggle="tooltip"]', title: function() { var $this = angular.element(this); return $this.attr('title') || $this.text(); } }); element.on('mouseover', function() { if (!updateSetService.hasFetchedData()) { updateSetService.getUpdateSetList(); } }); element.on('change', 'input[type=checkbox]', function() { var showInHeader = angular.element(this).prop('checked'); updateSetService.updateSetData.showInHeader = showInHeader; scope.showInHeader = showInHeader; if (showInHeader) { userPreferences.setPreference('glide.ui.update_set_picker.in_header', 'true'); } else { userPreferences.setPreference('glide.ui.update_set_picker.in_header', ''); } }); } } }]).factory('updateSetService', ['$http', 'snCustomEvent', '$rootScope', function($http, snCustomEvent, $rootScope) { var fetchedInitialData = false; var initialized = false; var updateSetData = { list : [], current : {}, currentId : '', showInHeader : false }; var hasFetchedData = function() { return fetchedInitialData; }; var initialize = function(current, showInHeader) { if (initialized) return; initialized = true; updateSetData.list = [current]; updateSetData.current = current; updateSetData.currentId = current.sysId; updateSetData.showInHeader = showInHeader; }; var updateCurrent = function() { var updateSets = updateSetData.list; var curr = updateSetData.currentId; for (var i = 0; i < updateSets.length; i++) { if (curr == updateSets[i].sysId) { updateSetData.current = updateSets[i]; } } $http.put('/api/now/ui/concoursepicker/updateset', updateSetData.current); }; var getUpdateSetList = function() { fetchedInitialData = true; return $http.get('/api/now/ui/concoursepicker/updateset?cache=' + new Date().getTime()).then(function(response) { if (response && response.data && response.data.result) { if (response.data.result.updateSet) { updateSetData.list = response.data.result.updateSet; if (response.data.result.current) { var updateSets = response.data.result.updateSet; var curr = response.data.result.current; for (var i = 0; i < updateSets.length; i++) { if (curr.sysId == updateSets[i].sysId) { updateSetData.current = updateSets[i]; updateSetData.currentId = updateSets[i].sysId; break; } } } } } }); }; snCustomEvent.observe('sn:refresh_update_set', function() { getUpdateSetList(); }); $rootScope.$on('concourse.application.changed', function() { getUpdateSetList(); }); return { hasFetchedData : hasFetchedData, updateSetData : updateSetData, initialize : initialize, updateCurrent : updateCurrent, getUpdateSetList : getUpdateSetList } }]); ; /*! RESOURCE: /scripts/concourse/directive.preferencePicker.js */ angular.module('sn.concourse').directive('preferencePicker', ['$http', 'getTemplateUrl', function($http, getTemplateUrl) { "use strict"; return { templateUrl: getTemplateUrl('concourse_preference_picker.xml'), restrict: 'E', scope: { current: '=', list: '=', endpoint: '@', reload: '@', labelTitle: '@', refreshTitle: '@' }, controller: function($scope) { $scope.getList = function() { $http.get('/api/now/ui/concoursepicker/' + $scope.endpoint).then(function(response) { if (response && response.data && response.data.result && response.data.result.list) { $scope.list = response.data.result.list; if (response.data.result.current) { $scope.current = response.data.result.current; } } }); }; $scope.refreshPicker = function() { $scope.getList(); }; $scope.updateCurrent = function() { $http.put('/api/now/ui/concoursepicker/' + $scope.endpoint, {current: $scope.current}).then(function(response) { if (response && response.data && response.data.result && response.data.result.success) { if ($scope.reload) { $scope.reloadPage(); } } }) }; $scope.reloadPage = function() { window.top.location.reload(true); }; } } }]); ; /*! RESOURCE: /scripts/concourse/directive.domainPicker.js */ angular.module('sn.concourse').directive('domainPicker', [ 'getTemplateUrl', 'domainService', '$rootScope', 'userPreferences', 'snCustomEvent', function(getTemplateUrl, domainService, $rootScope, userPreferences, snCustomEvent) { "use strict"; return { templateUrl: getTemplateUrl('concourse_domain_picker.xml'), restrict: 'E', replace: false, scope: { current: '=', inHeader: '=', showInHeader: '=' }, controller: function($scope) { $scope.domains = domainService.domainData; if ($scope.current) domainService.initialize($scope.current, $scope.showInHeader); $scope.domainList = $scope.domains.list; $scope.getDomains = function() { domainService.getDomainList(); }; $scope.updateDomain = function() { domainService.setDomain(); }; $rootScope.$on('concourse.domain.refresh', function() { $scope.refreshMainFrame(); }); }, link: function(scope, element) { element.on('mouseover', function() { if (!domainService.hasFetchedData()) { domainService.getDomainList(); } }); scope.refreshMainFrame = function() { var iframe = jQuery('iframe#gsft_main'); if (iframe.length) { iframe[0].contentWindow.location.reload(); } snCustomEvent.fireTop('navigator.refresh'); }; element.on('change', 'input[type=checkbox]', function() { var showInHeader = angular.element(this).prop('checked'); domainService.domainData.showInHeader = showInHeader; scope.showInHeader = showInHeader; if (showInHeader) { userPreferences.setPreference('glide.ui.domain_picker.in_header', 'true'); } else { userPreferences.setPreference('glide.ui.domain_picker.in_header', ''); } }); } } }]).factory('domainService', ['$http', 'snCustomEvent', '$rootScope', '$timeout', function($http, snCustomEvent, $rootScope, $timeout) { var fetchedInitialData = false; var initialized = false; var domainData = { list: [], current: {}, currentValue: "", showInHeader: false }; var hasFetchedData = function() { return fetchedInitialData; }; var initialize = function(current, showInHeader) { if (initialized) return; initialized = true; domainData.list = [current]; domainData.current = current; domainData.currentValue = current.value; domainData.showInHeader = showInHeader; }; var getDomainList = function() { fetchedInitialData = true; return $http.get('/api/now/ui/concoursepicker/domain?cache=' + new Date().getTime()).then(function(response) { if (response && response.data && response.data.result) { if (response.data.result.list) { domainData.list = response.data.result.list; if (response.data.result.current) { var list = domainData.list; var curr = response.data.result.current.value; for (var i = 0; i < list.length; i++) { if (curr == list[i].value) { domainData.current = list[i]; domainData.currentValue = list[i].value; } } } } } }); }; var setDomain = function() { setCurrent(domainData.currentValue); $http.put('/api/now/ui/concoursepicker/domain', domainData.current).then(function(response) { if (response && response.data && response.data.result && response.data.result.current) { triggerMainFrameRefresh(); } }); }; function triggerMainFrameRefresh() { $rootScope.$broadcast('concourse.domain.refresh', {}); snCustomEvent.fireTop('navigator.refresh'); } function setCurrent(value) { var list = domainData.list; for (var i = 0; i < list.length; i++) { if (value == list[i].value) { domainData.current = list[i]; return; } } } function setDomainFromName(domainName) { if (!fetchedInitialData) { getDomainList().then(function() { $timeout(setDomainFromName(domainName)); }); } for (var i = 0; i < domainData.list.length; i++) { if (domainData.list[i].label == domainName) { domainData.current = domainData.list[i]; domainData.currentValue = domainData.list[i].value; } } } snCustomEvent.observe('glide:ui_notification.session_change', function(data) { if (typeof data.xml.dataset !== 'undefined' && data.xml.dataset.attrSession_domain !== 'undefined' && domainData.currentValue !== data.xml.dataset.attrSession_domain) { setDomainFromName(data.xml.dataset.attrSession_domain); } }); snCustomEvent.observe('record.domain', function(data) { if (data && typeof data.domain === 'string' && data.domain.length && domainData.currentValue !== data.domain) { setDomainFromName(data.domain); } }); return { initialize: initialize, setDomain: setDomain, getDomainList: getDomainList, hasFetchedData: hasFetchedData, domainData: domainData } }]); ; /*! RESOURCE: /scripts/concourse/directive.encryptionPicker.js */ angular.module('sn.concourse').directive('encryptionPicker', [ 'snCustomEvent', 'getTemplateUrl', 'encryptionService', '$rootScope', 'userPreferences', function(snCustomEvent, getTemplateUrl, encryptionService, $rootScope, userPreferences) { "use strict" return { templateUrl : getTemplateUrl('concourse_encryption_picker.xml'), restrict : 'E', replace : false, scope : { current : '=', inHeader : '=', showInHeader : '=' }, controller : function($scope) { $scope.encryptions = encryptionService.encryptionData; if ($scope.current) encryptionService.initialize($scope.current, $scope.showInHeader); $scope.getEncryptions = function() { encryptionService.getEncryptionList(); }; $scope.updateEncryption = function() { encryptionService.setEncryption(); }; }, link : function(scope, element) { element.on('mouseover', function() { if (!encryptionService.hasFetchedData()) { encryptionService.getEncryptionList(); } }); element.on('change', 'input[type=checkbox]', function() { var showInHeader = angular.element(this).prop('checked'); encryptionService.encryptionData.showInHeader = showInHeader; scope.showInHeader = showInHeader; if (showInHeader) { userPreferences.setPreference('glide.ui.encryption_picker.in_header', 'true'); } else { userPreferences.setPreference('glide.ui.encryption_picker.in_header', ''); } }); } } }]).factory('encryptionService', ['$http', 'snCustomEvent', '$rootScope', function($http, snCustomEvent, $rootScope) { var fetchedInitialData = false; var initialized = false; var encryptionData = { list : [], current : {}, currentValue : "", showInHeader : false }; var hasFetchedData = function() { return fetchedInitialData; }; var initialize = function(current, showInHeader) { if (initialized) return; initialized = true; encryptionData.list = [current]; encryptionData.current = current; encryptionData.currentValue = current.value; encryptionData.showInHeader = showInHeader; }; var getEncryptionList = function() { fetchedInitialData = true; $http.get('/api/now/ui/concoursepicker/encryption?cache=' + new Date().getTime()).then(function(response) { if (response && response.data && response.data.result) { if (response.data.result.list) { encryptionData.list = response.data.result.list; if (response.data.result.current) { var list = encryptionData.list; var curr = response.data.result.current.value; for (var i = 0; i < list.length; i++) { if (curr == list[i].value) { encryptionData.current = list[i]; encryptionData.currentValue = list[i].value; } } } } } }); }; var setEncryption = function() { setCurrent(encryptionData.currentValue); $http.put('/api/now/ui/concoursepicker/encryption', {id : encryptionData.current.value}).then(function(response) { }); }; function setCurrent(id) { var list = encryptionData.list; for (var i = 0; i < list.length; i++) { if (id == list[i].value) { encryptionData.current = list[i]; return; } } }; return { initialize : initialize, setEncryption : setEncryption, getEncryptionList : getEncryptionList, hasFetchedData : hasFetchedData, encryptionData : encryptionData } }]); ; /*! RESOURCE: /scripts/concourse/directive.cryptoModulePicker.js */ angular.module('sn.concourse').directive('cryptoModulePicker', [ 'snCustomEvent', 'getTemplateUrl', 'cryptoModuleService', '$rootScope', 'userPreferences', function(snCustomEvent, getTemplateUrl, cryptoModuleService, $rootScope, userPreferences) { "use strict" return { templateUrl : getTemplateUrl('concourse_crypto_module_picker.xml'), restrict : 'E', replace : false, scope : { current : '=', inHeader : '=', showInHeader : '=' }, controller : function($scope) { $scope.cryptoModules = cryptoModuleService.cryptoModuleData; if ($scope.current) cryptoModuleService.initialize($scope.current, $scope.showInHeader); $scope.getCryptoModules = function() { cryptoModuleService.getCryptoModuleList(); }; $scope.updateCryptoModule = function() { cryptoModuleService.setCryptoModule(); }; }, link : function(scope, element) { element.on('mouseover', function() { if (!cryptoModuleService.hasFetchedData()) { cryptoModuleService.getCryptoModuleList(); } }); element.on('change', 'input[type=checkbox]', function() { var showInHeader = angular.element(this).prop('checked'); cryptoModuleService.cryptoModuleData.showInHeader = showInHeader; scope.showInHeader = showInHeader; if (showInHeader) { userPreferences.setPreference('glide.ui.crypto_module_picker.in_header', 'true'); } else { userPreferences.setPreference('glide.ui.crypto_module_picker.in_header', ''); } }); } } }]).factory('cryptoModuleService', ['$http', 'snCustomEvent', '$rootScope', function($http, snCustomEvent, $rootScope) { var fetchedInitialData = false; var initialized = false; var cryptoModuleData = { list : [], current : {}, currentValue : "", showInHeader : false }; var hasFetchedData = function() { return fetchedInitialData; }; var initialize = function(current, showInHeader) { if (initialized) return; initialized = true; cryptoModuleData.list = [current]; cryptoModuleData.current = current; cryptoModuleData.currentValue = current.value; cryptoModuleData.showInHeader = showInHeader; }; var getCryptoModuleList = function() { fetchedInitialData = true; $http.get('/api/now/ui/concoursepicker/cryptoModule?cache=' + new Date().getTime()).then(function(response) { if (response && response.data && response.data.result) { if (response.data.result.list) { cryptoModuleData.list = response.data.result.list; if (response.data.result.current) { var list = cryptoModuleData.list; var curr = response.data.result.current.value; for (var i = 0; i < list.length; i++) { if (curr == list[i].value) { cryptoModuleData.current = list[i]; cryptoModuleData.currentValue = list[i].value; } } } } } }); }; var setCryptoModule = function() { setCurrent(cryptoModuleData.currentValue); $http.put('/api/now/ui/concoursepicker/cryptoModule', {id : cryptoModuleData.current.value}).then(function(response) { }); }; function setCurrent(id) { var list = cryptoModuleData.list; for (var i = 0; i < list.length; i++) { if (id == list[i].value) { cryptoModuleData.current = list[i]; return; } } }; return { initialize : initialize, setCryptoModule : setCryptoModule, getCryptoModuleList : getCryptoModuleList, hasFetchedData : hasFetchedData, cryptoModuleData : cryptoModuleData } }]); ; /*! RESOURCE: /scripts/concourse/directive.javascriptDebugger.js */ angular.module("sn.concourse").directive('javascriptDebugger', function(getTemplateUrl){ return{ restrict: 'E', scope: { label: '@', moreinfo: '@', type: '@' }, templateUrl: getTemplateUrl('concourse_javascript_debugger.xml'), controller:function($scope){ $scope.visible = isDebugPanelVisible(); $scope.showJsDebugger = function(){ var isVisible = isDebugPanelVisible(); if (!isVisible) initDebugIframe(); var jqueryLayout = document.getElementById('edge_south_debug').parentNode; if (jqueryLayout.className.indexOf("navpage-bottom-hidden") == -1) { jqueryLayout.className += " navpage-bottom-hidden"; } else { jqueryLayout.className = jqueryLayout.className.replace(' navpage-bottom-hidden',''); } isVisible = !isVisible; var debuggerFrame = getTopWindow()['javascript_debugger']; var cevt = debuggerFrame.CustomEvent; if(!cevt && debuggerFrame.contentWindow) cevt = debuggerFrame.contentWindow.CustomEvent; if (cevt && cevt.fire) { cevt.fire(isVisible ? 'debuggerTools.visible' : 'debuggerTools.hidden'); } }; function isDebugPanelVisible() { var southDebugEdge = document.getElementById('edge_south_debug'); if (!southDebugEdge) { return false; } var jqueryLayout = southDebugEdge.parentNode; if (jqueryLayout) { return jqueryLayout.className.indexOf("navpage-bottom-hidden") == -1; } else { return false; } } function initDebugIframe() { var footerTrayFrm = document.getElementById('javascript_debugger'); if (!footerTrayFrm.isLoaded) { footerTrayFrm.src = 'concourseJsDebug.do?sysparm_doctype=true&sysparm_stack=no'; footerTrayFrm.isLoaded = true; debugToolSplitterContext.init(); var debugToolsSplitterH = document.getElementById('debugToolsSplitterH'); if (debugToolsSplitterH) debugToolsSplitterH.observe('mousedown', debugToolSplitterContext.mouseDownHandler); } } function getTopWindow() { var topWindow = window.self; try { while (topWindow.GJSV && topWindow != topWindow.parent && topWindow.parent.GJSV) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } var debugToolSplitterContext = function() { var isDragSplitter = false; var footerTray = null; var splitter_h = null; var ghostSplitter = null; var glassPane = null; var minCloseHeight = 15; var minHeight = 38; var me = null; function setGhost() { var dims = footerTray.getDimensions(); var rect = splitter_h.getClientRects(); ghostSplitter.setStyle('width:' + dims.width + 'px;left:' + rect.left + 'px;display:block;'); } function hideGhost() { ghostSplitter.setStyle('display:none;top:-100px;'); glassPane.setStyle('display:none;width:0px;height:0px;'); } function mouseMoveHandler(e) { if (isDragSplitter !== true) return; var mouseY = e.pageY || e.clientY + document.documentElement.scrollTop - 3; var size = glassPane.getDimensions().height - mouseY; if (size >= minCloseHeight) ghostSplitter.setStyle('top:' + mouseY + 'px'); } function mouseDownHandler(e) { if (e.element().id == 'debugToolsSplitterH') { Event.stop(e); footerTray = $('footerTray'); splitter_h = $('debugToolsSplitterH'); ghostSplitter = $('ghostSplitter'); glassPane = $('glassPane'); if (glassPane == null) { var div = document.createElement('div'); div.id = 'glassPane'; div.className = 'glass-pane'; document.body.appendChild(div); glassPane = $('glassPane'); } else { glassPane.setStyle('display:block;height:100%;width:100%;'); } glassPane.observe('mouseup', me.endDragHandler); glassPane.observe('mouseout', me.endDragHandler); glassPane.observe('mousemove', me.mouseMoveHandler); isDragSplitter = true; setGhost(); me.mouseMoveHandler(e); } } function endDragHandler(e) { if (isDragSplitter === true) { isDragSplitter = false; var mouseY = e.pageY || e.clientY + document.documentElement.scrollTop; mouseY = glassPane.getDimensions().height - mouseY; if (mouseY < minCloseHeight) { debuggerTools.toggleJSDebugger(); } else { mouseY = (mouseY < minHeight) ? minHeight : mouseY + 5; footerTray.setStyle('height:' + mouseY + 'px'); footerTray.restoreHeight = mouseY; } hideGhost(); } if (glassPane) { glassPane.stopObserving('mouseup', me.endDragHandler); glassPane.stopObserving('mouseout', me.endDragHandler); glassPane.stopObserving('mousemove', me.mouseMoveHandler); } footerTray = null; splitter_h = null; ghostSplitter = null; glassPane = null; } return { init: function() { me = this; }, mouseDownHandler: mouseDownHandler, endDragHandler: endDragHandler, mouseMoveHandler: mouseMoveHandler }; }(); } } }); ; /*! RESOURCE: /scripts/concourse/directive.atfInspector.js */ angular.module("sn.concourse").directive('atfInspector', ['snCustomEvent', 'userPreferences', function(snCustomEvent, userPreferences){ return{ restrict: 'E', scope: { label: '@', moreinfo: '@', type: '@' }, controller:function($scope, $http, $window){ snCustomEvent.observe('atf_inspector_toggle_event', function (status) { if (status) { enableATFInspector($window); } else { disableATFInspector($window); } }); function enableATFInspector($window) { var absPath = decodeURIComponent($window.location.href); if (absPath.indexOf('atf_page_inspector') == -1) { userPreferences.setPreference('glide.atf_inspector.switch.on', true).then(function() { var encodedURL = encodeURIComponent("&sysparm_url="); var encodedStack = encodeURIComponent('sysparm_stack=no'); window.location.assign(window.location.href.replace('?uri=', '?uri=/$atf_page_inspector.do?' + encodedStack + encodedURL)); }); } } function disableATFInspector() { var absPath = decodeURIComponent($window.location.href); if (absPath.indexOf('atf_page_inspector') != -1) { userPreferences.setPreference('glide.atf_inspector.switch.on', false).then(function() { var curPath = absPath.substr(absPath.indexOf('sysparm_url=') + 12); $window.location.assign('/nav_to.do?uri=' + curPath); }); } } } } }]); ; /*! RESOURCE: /scripts/concourse/debuggerTools.js */ var debuggerTools = function() { var minHeight = 38; function restoreHeight() { if (!isDebugPanelVisible()) return; var panel = document.getElementById('edge_south_debug') || document.getElementById('footerTray'); if (panel.getHeight() <= minHeight) toggleTrayCollapsed(); } function toggleTrayCollapsed() { if (!isDebugPanelVisible()) return; var jqueryLayout = document.getElementById('edge_south_debug'); var minimize = false; if (jqueryLayout) { var myLayout = $j(document.body).layout(); var height = minHeight - 7; minimize = (jqueryLayout.getHeight() > height); myLayout.sizePane("south", minimize ? height : myLayout.restoreHeight); } else { var footerTray = document.getElementById('footerTray'); minimize = (footerTray.getHeight() > minHeight); footerTray.style.height = (minimize ? minHeight : footerTray.restoreHeight) + 'px'; } } function initDebugIframe() { var javascriptDebugger = document.getElementById('javascript_debugger'); if (!javascriptDebugger.isLoaded) { javascriptDebugger.src = 'concourseJsDebug.do?sysparm_doctype=true&sysparm_stack=no'; javascriptDebugger.isLoaded = true; debugToolSplitterContext.init(); var debugToolsSplitterH = document.getElementById('debugToolsSplitterH'); if (debugToolsSplitterH) debugToolsSplitterH.observe('mousedown', debugToolSplitterContext.mouseDownHandler); } } function selectFieldWatcherTab() { var wndw = getJsDebugWindow(); if (!wndw || !wndw.selectFieldWatcherTab) setTimeout(selectFieldWatcherTab, 100); else wndw.selectFieldWatcherTab(); } function isDebugPanelVisible() { var jqueryLayout = document.getElementById('edge_south_debug'); if (jqueryLayout) { return window.getComputedStyle(jqueryLayout,null).height != "0px"; } else { var footerTrayRow = document.getElementById('footerTrayRow'); if (footerTrayRow) return (footerTrayRow.className.indexOf('footer-tray-hidden') == -1); else return false; } } function toggleJSDebugger() { var isVisible = isDebugPanelVisible(); if (!isVisible) initDebugIframe(); var jqueryLayout = document.getElementById('edge_south_debug').parentElement; if (jqueryLayout) { if(jqueryLayout.className.indexOf("navpage-bottom-hidden") == -1) jqueryLayout.className += " navpage-bottom-hidden"; else jqueryLayout.className = jqueryLayout.className.replace(" navpage-bottom-hidden", ""); } else { var footerTrayRow = document.getElementById('footerTrayRow'); if (footerTrayRow) footerTrayRow.toggleClassName('footer-tray-hidden'); } isVisible = !isVisible; var debuggerFrame = getTopWindow()['javascript_debugger']; var cevt = debuggerFrame.CustomEvent; if(!cevt && debuggerFrame.contentWindow) cevt = debuggerFrame.contentWindow.CustomEvent; if (cevt && cevt.fire) { cevt.fire(isVisible ? 'debuggerTools.visible' : 'debuggerTools.hidden'); } } function showFieldWatcher() { toggleJSDebugger(); selectFieldWatcherTab(); } function getJsDebugWindow() { return document.getElementById('javascript_debugger').contentWindow; } function getTopWindow() { var topWindow = window.self; try { while (topWindow.GJSV && topWindow != topWindow.parent && topWindow.parent.GJSV) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } return { restoreHeight: restoreHeight, toggleTrayCollapsed: toggleTrayCollapsed, isDebugPanelVisible: isDebugPanelVisible, toggleJSDebugger: toggleJSDebugger, showJSDebugger: toggleJSDebugger, showFieldWatcher: showFieldWatcher, getJsDebugWindow: getJsDebugWindow }; }(); function jslog(msg, src, dateTime) { if (window.console && window.console.log) console.log(msg); if (debuggerTools.isDebugPanelVisible()) { if (!src) src = "navpage.do"; if(typeof getFormattedTime == "function") { msg = '<div class="debug_line"><span class="log-time CLIENT">' + getFormattedTime(dateTime) + '</span><span class="log-category">' + src + '</span><span class="log-message">' + msg + "</span></div>"; } else{ msg = '<div class="debug_line"><span class="log-time CLIENT">' + getTimeFormatted(dateTime) + '</span><span class="log-category">' + src + '</span><span class="log-message">' + msg + "</span></div>"; } var wndw = debuggerTools.getJsDebugWindow(); if (typeof wndw != undefined && wndw.addJsLogMessage) wndw.addJsLogMessage(msg); } } function getTimeFormatted(dateTime){ var d = new Date(); var hour = d.getHours(); var minute = d.getMinutes(); var second = d.getSeconds(); var millisecond = d.getMilliseconds(); if (10 > hour) hour = "0" + hour; if (10 > minute) minute = "0" + minute; if (10 > second) second = "0" + second; if (100 > millisecond){ if (10 > millisecond) millisecond = "0" + millisecond; millisecond = "0" + millisecond; } var formattedTime = hour + ":" + minute + ":" + second + " (" + millisecond + ")"; return formattedTime; } var debugToolSplitterContext = function() { var isDragSplitter = false; var footerTray = null; var splitter_h = null; var ghostSplitter = null; var glassPane = null; var minCloseHeight = 15; var minHeight = 38; var me = null; function setGhost() { var dims = footerTray.getDimensions(); var rect = splitter_h.getClientRects(); ghostSplitter.setAttribute('style', 'width:' + dims.width + 'px;left:' + rect.left + 'px;display:block;'); } function hideGhost() { ghostSplitter.setAttribute('style', 'display:none;top:-100px;'); glassPane.setAttribute('style', 'display:none;width:0px;height:0px;'); } function mouseMoveHandler(e) { if (isDragSplitter !== true) return; var mouseY = e.pageY || e.clientY + document.documentElement.scrollTop - 3; var size = glassPane.getDimensions().height - mouseY; if (size >= minCloseHeight) ghostSplitter.setAttribute('style', 'top:' + mouseY + 'px'); } function mouseDownHandler(e) { if (e.element().id == 'debugToolsSplitterH') { Event.stop(e); footerTray = document.getElementById('footerTray'); splitter_h = document.getElementById('debugToolsSplitterH'); ghostSplitter = document.getElementById('ghostSplitter'); glassPane = document.getElementById('glassPane'); if (glassPane == null) { var div = document.createElement('div'); div.id = 'glassPane'; div.className = 'glass-pane'; document.body.appendChild(div); glassPane = document.getElementById('glassPane'); } else { glassPane.setAttribute('style', 'display:block;height:100%;width:100%;'); } glassPane.observe('mouseup', me.endDragHandler); glassPane.observe('mouseout', me.endDragHandler); glassPane.observe('mousemove', me.mouseMoveHandler); isDragSplitter = true; setGhost(); me.mouseMoveHandler(e); } } function endDragHandler(e) { if (isDragSplitter === true) { isDragSplitter = false; var mouseY = e.pageY || e.clientY + document.documentElement.scrollTop; mouseY = glassPane.getDimensions().height - mouseY; if (mouseY < minCloseHeight) { debuggerTools.toggleJSDebugger(); } else { mouseY = (mouseY < minHeight) ? minHeight : mouseY + 5; footerTray.setAttribute('style', 'height:' + mouseY + 'px'); footerTray.restoreHeight = mouseY; } hideGhost(); } if (glassPane) { glassPane.stopObserving('mouseup', me.endDragHandler); glassPane.stopObserving('mouseout', me.endDragHandler); glassPane.stopObserving('mousemove', me.mouseMoveHandler); } footerTray = null; splitter_h = null; ghostSplitter = null; glassPane = null; } return { init: function() { me = this; }, mouseDownHandler: mouseDownHandler, endDragHandler: endDragHandler, mouseMoveHandler: mouseMoveHandler }; }(); ; /*! RESOURCE: /scripts/concourse/directive.navBannerLogo.js */ angular.module('sn.concourse').directive('navBannerLogo', function(snCustomEvent, $sanitize) { "use strict"; return { restrict: 'A', link: function($scope, $element) { $scope.setNavigatingState = function(state) { top.NOW.magellan && top.NOW.magellan.setNavigatingState && top.NOW.magellan.setNavigatingState(state); }; snCustomEvent.observe('glide.product.image.light', function(value) { if (value) $element.find('[data-sys-properties="glide.product.image.light"]').css('background-image', 'url(' + value + ')'); }); snCustomEvent.observe('glide.product.description', function(value) { if (value) $element.find('[data-sys-properties="glide.product.description"]').html($sanitize(value)); }); snCustomEvent.observe('css.$navpage-header-bg', function(value) { if (value){ var props = { 'background-color': [ '.navpage-header', '.tabs-container ul li', '.panel-tool-icons', '.sn-connect-aside.sn-aside_inverted .sn-aside-group-title', '.nav-body .nav-favorites-show-application .nav-favorites-show-application-title', '.nav-body .nav-favorites-show-application .nav-favorites-show-more-title', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-application-title', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-more-title', '.sn-frameset-header' ], 'border-color': ['.sn-navhub.sn-connect-aside-navhub'] }; for(var prop in props) { jQuery(props[prop].join(',')).css(prop, value); } var bannerImageContainer = jQuery('iFrame').contents().find('.header_color'); if (bannerImageContainer) bannerImageContainer.css('background-color', value); } }); snCustomEvent.observe('css.$navpage-header-color', function(value) { if (value) { var selectors = [ '.sn-frameset-header .sysparm-search-icon:before', '.navpage-pickers .label-icon', '.tabs-container ul li a', '.sn-connect-aside.sn-aside_inverted', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li:active .sn-widget-list-title', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li:active .sn-widget-list-details', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-list-title', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-list-content', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-list-details', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-members-list-btn-close', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-list-title span', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-list-content span', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-list-details span', '.sn-connect-aside.sn-aside_inverted .sn-widget-list li .sn-widget-list-bg_active .sn-widget-members-list-btn-close span', '.nav-body .nav-favorites-show-application .nav-favorites-show-application-title', '.nav-body .nav-favorites-show-application .nav-favorites-show-more-title', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-application-title', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-more-title', '.nav-body ul.nav-application-tree .app-node:hover > .nav-favorite-app', '.nav-body ul.nav-history-list li a:hover span', '.sn-frameset-header .banner-text', '.current-user-dropdown' ]; jQuery(selectors.join(',')).css('color', value); } }); snCustomEvent.observe('css.$navpage-header-divider-color', function(value) { if (value) { var selectors = '.navpage-layout .navbar-divider'; jQuery(selectors).css('background-color', value); } }); snCustomEvent.observe('css.$navpage-nav-bg', function(value) { if (value){ var props = { 'background-color': [ '.navpage-nav', '.navpage-right', '.tabs-container', '.sn-connect-aside.sn-aside_inverted', '.sn-navhub.sn-connect-aside-navhub', '.sn-navhub.sn-connect-aside-navhub .sn-navhub-buttons', '#favorite_preview', '.nav-edit-favorites-icon-grid > a.selected', '.magellan_navigator', '.nav-header input[name=filter]', '.nav-header input[name=filter]:focus', '.nav-body .nav-favorites-show-more', '.nav-body .nav-favorites-show-application .nav-favorites-show-application-inner', '.nav-body .nav-favorites-show-application .nav-favorites-show-more-inner', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-application-inner', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-more-inner', '.nav-body .nav-favorites-show-application .nav-favorites-show-application-inner .nav-favorite-group-title', '.nav-body .nav-favorites-show-application .nav-favorites-show-more-inner .nav-favorite-group-title', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-application-inner .nav-favorite-group-title', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-more-inner .nav-favorite-group-title', '.nav-body ul.nav-favorites-list', '.nav-body ul.nav-favorites-list .nav-favorite-group .nav-favorite-group-title', '.nav-footer', '.navpage-history ul > li', '.sn-pane-footer', '.sn-live-search' ], 'border-color': [ '.create-favorite .nav-edit-favorites-icon-grid > a.selected', '#icon_colors a.color-bg-white:focus, #icon_colors a.color-bg-white:active', '#icon_colors a:focus, #icon_colors a:active', '.favorite-preview', '.nav-edit-favorites-icon-grid > a:focus, .nav-edit-favorites-icon-grid > a:active' ], 'border-right-color': [ '.nav-body .nav-favorites-show-application .arrow', '.nav-body .nav-favorites-show-more-panel .arrow' ] }; for(var prop in props) { jQuery(props[prop].join(',')).css(prop, value); } } }); snCustomEvent.observe('css.$navpage-nav-bg-sub', function(value) { if (value){ var props = { 'background-color': [ '.sn-connect-aside.sn-aside_inverted', '.sn-navhub.sn-connect-aside-navhub', '.favorite-preview', '.nav-edit-favorites-icon-grid > a.selected', '.nav-body .nav-favorites-show-application .nav-favorites-show-application-inner', '.nav-body .nav-favorites-show-application .nav-favorites-show-more-inner', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-application-inner', '.nav-body .nav-favorites-show-more-panel .nav-favorites-show-more-inner', '.nav-body ul.nav-favorites-list', '.navpage-history ul > li', '.sn-aside.sn-aside_themed', '.sn-aside.sn-aside_themed .sn-widget-list_v2 .sn-widget-list-item:not(.module-node)' ], 'border-color': [ '#icon_colors a.color-bg-white:focus, #icon_colors a.color-bg-white:active', '#icon_colors a:focus, #icon_colors a:active', '.nav-edit-favorites-icon-grid > a:focus, .nav-edit-favorites-icon-grid > a:active' ], 'border-right-color': [ '.nav-body .nav-favorites-show-application .arrow', '.nav-body .nav-favorites-show-more-panel .arrow' ] }; for(var prop in props) { jQuery(props[prop].join(',')).css(prop, value); } } }); snCustomEvent.observe('css.$subnav-background-color', function(value) { if (value) jQuery('.nav-body ul li ul').css('background-color', value); }); snCustomEvent.observe('css.$navpage-nav-border', function(value) { if (value){ var props = { 'border-color': [ '.sn-frameset-header #sysparm_search:focus', '.sn-frameset-header .dropdown.open button', '.nav-header input[name=filter]', '.nav-header input[name=filter]:focus', '.sn-live-search .twitter-typeahead input', '.sn-live-search-flex .form-control', '.sn-live-search-flex .form-control:focus' ], 'border-top-color': [ '.nav-body .nav-favorites-show-more', '.nav-footer', '.sn-pane-footer', '.panel-tool-icons' ], 'border-left-color': [ '.panel-tool-icons' ], 'border-bottom-color': [ '.navpage-nav-collapsed .nav-header', '.navpage-nav-collapsed .nav-body ul.nav-favorites-list > li > a' ] }; for(var prop in props) { jQuery(props[prop].join(',')).css(prop, value); } } }); snCustomEvent.observe('css.$navpage-nav-color-sub', function(value) { if (value) { var selectors = [ '.magellan_navigator .sn-aside.sn-aside_themed .sn-widget-list_v2 li .sn-widget-list-action', '.magellan_navigator .sn-aside.sn-aside_themed .sn-widget-list_v2 .sn-widget-list_v2 li .sn-widget-list-action', '.magellan_navigator .sn-application-tree .sn-widget-list_v2 li .sn-widget-list-title', '.magellan_navigator .sn-application-tree .sn-widget-list_v2 li .sn-widget-list-subtitle', '.magellan_navigator .sn-application-tree .sn-widget-list_v2 li .sn-widget-list-action', '.magellan_navigator .sn-widget-list_indentation .sn-widget-list_v2 .sn-aside-group-title' ]; jQuery(selectors.join(',')).css('color', value); } }); snCustomEvent.observe('css.$navpage-nav-unselected-color', function(value) { if (value) { var selectors = [ '.magellan_navigator .sn-navhub.sn-navhub_themed .sn-navhub-btn::before' ]; jQuery(selectors.join(',')).css('color', value); try { document.styleSheets[0].addRule('.magellan_navigator .sn-navhub.sn-navhub_themed .sn-navhub-btn::before', 'color: ' + value + ' !important;'); } catch (e) {} } }); snCustomEvent.observe('css.$navpage-nav-selected-color', function(value) { if (value) { var selectors = [ '.sn-connect-aside.sn-aside_inverted .sn-widget-list li:active', '.sn-navhub.sn-connect-aside-navhub .sn-navhub-buttons .btn:active', '.sn-navhub.sn-connect-aside-navhub .sn-navhub-buttons .btn.state-active', '.sn-navhub.sn-connect-aside-navhub .sn-navhub-buttons .btn:active::before', '.sn-navhub.sn-connect-aside-navhub .sn-navhub-buttons .btn.state-active::before', '.magellan-edit-mode .selected', '.magellan-edit-mode .selected .draggable', '.magellan-edit-mode .selected .nav-favorite-group-title', '.magellan-edit-mode .selected > a > div.nav-favorite-title', '.nav-header .nav-segmented li.active', '.nav-header .nav-segmented li.active a:focus', '.nav-body ul.nav-history-list li a:hover', '.sn-navhub.sn-navhub_themed .sn-navhub-btn.state-active' ]; jQuery(selectors.join(',')).css('color', value); try { document.styleSheets[0].addRule('.sn-navhub.sn-navhub_themed .sn-navhub-btn.state-active::before', 'color: ' + value + ' !important;'); } catch (e) {} } }); snCustomEvent.observe('css.$nav-highlight-main', function(value) { if (value) { var selectors = [ '.nav-body a:hover', '.nav-body a:focus', '.nav-body .nav-expandable:hover', '.nav-body .nav-app:hover, .nav-body .nav-app:focus', '.nav-body .nav-highlight', '.nav-body ul.nav-favorites-list > li > span:hover', '.nav-body ul.nav-favorites-list > li > a:hover', '.nav-body ul.nav-favorites-list .nav-favorite-group .nav-favorite-group-title:hover', '.nav-body ul.nav-history-list li a:hover', '.navpage-nav-collapsed .nav-body ul.nav-favorites-list > li .nav-favorite-group:hover' ]; jQuery(selectors.join(',')).css('background-color', value); } }); snCustomEvent.observe('css.$navpage-nav-selected-bg', function(value) { if (value) { var selectors = [ '.sn-navhub.sn-connect-aside-navhub .sn-navhub-buttons .btn:active', '.sn-navhub.sn-connect-aside-navhub .sn-navhub-buttons .btn.state-active', '.magellan-edit-mode .selected', '.magellan-edit-mode .selected .nav-favorite-group-title', '.nav-header .nav-segmented li.active', '.sn-navhub.sn-navhub_themed .sn-navhub-btn.state-active' ]; jQuery(selectors.join(',')).css('background-color', value); try { document.styleSheets[0].addRule('.sn-navhub.sn-navhub_themed .sn-navhub-btn.state-active::before', 'background-color: ' + value + ' !important;'); } catch (e) {} } }); snCustomEvent.observe('css.$nav-hr-color', function(value) { if (value) jQuery('.sn-aside.sn-aside_themed .sn-widget-list_v2 .sn-widget-list-divider').css('background-color', value); }); } } }); ; /*! RESOURCE: /scripts/concourse/directive.concourseMainPane.js */ angular.module('sn.concourse').directive('concourseMainPane', function(getTemplateUrl, snCustomEvent, concoursePaneExtensionRegistry) { return { restrict: 'A', scope: { initialUrl: '@', test: '@', enableExtensions: '@' }, link: function(scope, element) { init(); function init() { var isIE9 = navigator.userAgent.indexOf('MSIE9') != -1; if (isIE9) { loadForIE9(); return; } loadUrl(scope.initialUrl); } function loadForIE9() { var hash = window.location.hash; if (hash != '' && hash.indexOf('#/nav_to.do?uri=') == 0) { var uri = hash.substr(16); uri = decodeURIComponent(uri); if (uri.length > 1) { loadUrl(url); } } } function loadUrl(url) { getFrame().attr('src', url); } getFrame().bind('load', function() { showFrame(); }); snCustomEvent.observe('sn.spa.intercept', function(srcInfo) { if (scope.enableExtensions !== 'true') return; var type = srcInfo.type; var url = srcInfo.window.location.href; if (!concoursePaneExtensionRegistry.hasHandler(type)) return; hideFrame(); concoursePaneExtensionRegistry.process(type, getPaneExtensionContainer(), url, { startTime: srcInfo.window.g_loadTime }); if ("stop" in srcInfo.window) srcInfo.window.stop(); else srcInfo.document.execCommand("Stop"); srcInfo.document.write('<!--'); }); function getPaneExtensionContainer() { return element.find('.extension-pane-container'); } function getFrame() { return element.find('iframe[name=gsft_main]'); } function hideFrame() { getFrame().hide(); getPaneExtensionContainer().show(); } function showFrame() { getPaneExtensionContainer().hide(); getFrame().show(); } } } }); ; /*! RESOURCE: /scripts/concourse/controller.unImpersonate.js */ angular.module('sn.concourse').controller('unImpersonate', function($scope, $http) { "use strict"; $scope.impersonate = function(id) { $http.post('/api/now/ui/impersonate/' + id, {}).success(function() { window.location = "/"; }); }; }); ; /*! RESOURCE: /scripts/AtfConcourse/directive.atfSessionMessage.js */ angular.module("sn.concourse").directive("atfSessionMessage", ["getTemplateUrl", "$timeout", "$interval", "MessagesStack", function(getTemplateUrl, $timeout, $interval, MessagesStack) { return { restrict: 'E', templateUrl: getTemplateUrl('concourse_atf_session_message.xml'), controller: function($scope) { var ATF_SESSION_COOKIE = "atf_context"; $scope.showAlert = false; function renderLink() { var messageSpan = document.getElementById('atf_session_message_message_span_id'); if (null === messageSpan) return; var messageHTML = messageSpan.innerHTML; messageHTML = messageHTML.replace(/</g, "<"); messageHTML = messageHTML.replace(/>/g, ">"); messageSpan.innerHTML = messageHTML; } renderLink(); $interval(checkAtfCookies, 1500); function checkAtfCookies() { var doesCookieExist = !!getCookie(ATF_SESSION_COOKIE); if ($scope.showAlert === doesCookieExist) return; if (doesCookieExist) MessagesStack.push("atf-session-message"); $scope.showAlert = doesCookieExist; if (!doesCookieExist) { setTimeout( function() { MessagesStack.pop("atf-session-message"); }, 1300 ); } } function getCookie(name) { var nameEQ = name + "="; var theCookie = document.cookie.split(';'); for (var i = 0; i < theCookie.length; i++) { var c = theCookie[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length); } return null; } } } }]); ; /*! RESOURCE: /scripts/concourse/messagesStackService.js */ function MessagesStack() { this.push = function push(directiveName) { var markerNode = document.querySelector("div[id=messages_stack_visible] ~ *:not([messages-stack-member])"); if (!markerNode ) { console.error("The position to insert after messages_stack_visible was not found"); return; } var direct = document.getElementsByTagName(directiveName); if (!direct || !direct.length || direct.length !== 1) { console.error("Directive <"+directiveName+"> to insert was not determined (was not found or more than one is present on page"); return; } markerNode.parentNode.insertBefore(direct[0], markerNode); }; this.pop = function pop(directiveName) { var hiddenContainer = document.getElementById("messages_stack_hidden"); if (!hiddenContainer) { console.error("Position to insert after messages_stack_hidden was not found"); return; } var direct = document.getElementsByTagName(directiveName); if (!direct || !direct.length || direct.length !== 1) { console.error("Directive <"+directiveName+"> to insert was not determined (was not found or more than one is present on page"); return; } hiddenContainer.parentNode.appendChild(direct[0]); }; } angular .module('sn.concourse') .service('MessagesStack', MessagesStack); ; /*! RESOURCE: /scripts/concourse_pane_extension/js_includes_concourse_pane_extension.js */ /*! RESOURCE: /scripts/thirdparty/ocLazyLoad/ocLazyLoad.js */ (function (angular, window) { 'use strict'; var regModules = ['ng', 'oc.lazyLoad'], regInvokes = {}, regConfigs = [], modulesToLoad = [], realModules = [], recordDeclarations = [], broadcast = angular.noop, runBlocks = {}, justLoaded = []; var ocLazyLoad = angular.module('oc.lazyLoad', ['ng']); ocLazyLoad.provider('$ocLazyLoad', ["$controllerProvider", "$provide", "$compileProvider", "$filterProvider", "$injector", "$animateProvider", function ($controllerProvider, $provide, $compileProvider, $filterProvider, $injector, $animateProvider) { var modules = {}, providers = { $controllerProvider: $controllerProvider, $compileProvider: $compileProvider, $filterProvider: $filterProvider, $provide: $provide, $injector: $injector, $animateProvider: $animateProvider }, debug = false, events = false, moduleCache = [], modulePromises = {}; moduleCache.push = function (value) { if (this.indexOf(value) === -1) { Array.prototype.push.apply(this, arguments); } }; this.config = function (config) { if (angular.isDefined(config.modules)) { if (angular.isArray(config.modules)) { angular.forEach(config.modules, function (moduleConfig) { modules[moduleConfig.name] = moduleConfig; }); } else { modules[config.modules.name] = config.modules; } } if (angular.isDefined(config.debug)) { debug = config.debug; } if (angular.isDefined(config.events)) { events = config.events; } }; this._init = function _init(element) { if (modulesToLoad.length === 0) { var elements = [element], names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/, append = function append(elm) { return elm && elements.push(elm); }; angular.forEach(names, function (name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (typeof element[0] !== 'undefined' && element[0].querySelectorAll) { angular.forEach(element[0].querySelectorAll('.' + name), append); angular.forEach(element[0].querySelectorAll('.' + name + '\\:'), append); angular.forEach(element[0].querySelectorAll('[' + name + ']'), append); } }); angular.forEach(elements, function (elm) { if (modulesToLoad.length === 0) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { modulesToLoad.push((match[2] || '').replace(/\s+/g, ',')); } else { angular.forEach(elm.attributes, function (attr) { if (modulesToLoad.length === 0 && names[attr.name]) { modulesToLoad.push(attr.value); } }); } } }); } if (modulesToLoad.length === 0 && !((window.jasmine || window.mocha) && angular.isDefined(angular.mock))) { console.error('No module found during bootstrap, unable to init ocLazyLoad. You should always use the ng-app directive or angular.boostrap when you use ocLazyLoad.'); } var addReg = function addReg(moduleName) { if (regModules.indexOf(moduleName) === -1) { regModules.push(moduleName); var mainModule = angular.module(moduleName); _invokeQueue(null, mainModule._invokeQueue, moduleName); _invokeQueue(null, mainModule._configBlocks, moduleName); angular.forEach(mainModule.requires, addReg); } }; angular.forEach(modulesToLoad, function (moduleName) { addReg(moduleName); }); modulesToLoad = []; recordDeclarations.pop(); }; var stringify = function stringify(obj) { try { return JSON.stringify(obj); } catch (e) { var cache = []; return JSON.stringify(obj, function (key, value) { if (angular.isObject(value) && value !== null) { if (cache.indexOf(value) !== -1) { return; } cache.push(value); } return value; }); } }; var hashCode = function hashCode(str) { var hash = 0, i, chr, len; if (str.length == 0) { return hash; } for (i = 0, len = str.length; i < len; i++) { chr = str.charCodeAt(i); hash = (hash << 5) - hash + chr; hash |= 0; } return hash; }; function _register(providers, registerModules, params) { if (registerModules) { var k, moduleName, moduleFn, tempRunBlocks = []; for (k = registerModules.length - 1; k >= 0; k--) { moduleName = registerModules[k]; if (!angular.isString(moduleName)) { moduleName = getModuleName(moduleName); } if (!moduleName || justLoaded.indexOf(moduleName) !== -1 || modules[moduleName] && realModules.indexOf(moduleName) === -1) { continue; } var newModule = regModules.indexOf(moduleName) === -1; moduleFn = ngModuleFct(moduleName); if (newModule) { regModules.push(moduleName); _register(providers, moduleFn.requires, params); } if (moduleFn._runBlocks.length > 0) { runBlocks[moduleName] = []; while (moduleFn._runBlocks.length > 0) { runBlocks[moduleName].push(moduleFn._runBlocks.shift()); } } if (angular.isDefined(runBlocks[moduleName]) && (newModule || params.rerun)) { tempRunBlocks = tempRunBlocks.concat(runBlocks[moduleName]); } _invokeQueue(providers, moduleFn._invokeQueue, moduleName, params.reconfig); _invokeQueue(providers, moduleFn._configBlocks, moduleName, params.reconfig); broadcast(newModule ? 'ocLazyLoad.moduleLoaded' : 'ocLazyLoad.moduleReloaded', moduleName); registerModules.pop(); justLoaded.push(moduleName); } var instanceInjector = providers.getInstanceInjector(); angular.forEach(tempRunBlocks, function (fn) { instanceInjector.invoke(fn); }); } } function _registerInvokeList(args, moduleName) { var invokeList = args[2][0], type = args[1], newInvoke = false; if (angular.isUndefined(regInvokes[moduleName])) { regInvokes[moduleName] = {}; } if (angular.isUndefined(regInvokes[moduleName][type])) { regInvokes[moduleName][type] = {}; } var onInvoke = function onInvoke(invokeName, invoke) { if (!regInvokes[moduleName][type].hasOwnProperty(invokeName)) { regInvokes[moduleName][type][invokeName] = []; } if (checkHashes(invoke, regInvokes[moduleName][type][invokeName])) { newInvoke = true; regInvokes[moduleName][type][invokeName].push(invoke); broadcast('ocLazyLoad.componentLoaded', [moduleName, type, invokeName]); } }; function checkHashes(potentialNew, invokes) { var isNew = true, newHash; if (invokes.length) { newHash = signature(potentialNew); angular.forEach(invokes, function (invoke) { isNew = isNew && signature(invoke) !== newHash; }); } return isNew; } function signature(data) { if (angular.isArray(data)) { return hashCode(data.toString()); } else if (angular.isObject(data)) { return hashCode(stringify(data)); } else { if (angular.isDefined(data) && data !== null) { return hashCode(data.toString()); } else { return data; } } } if (angular.isString(invokeList)) { onInvoke(invokeList, args[2][1]); } else if (angular.isObject(invokeList)) { angular.forEach(invokeList, function (invoke, key) { if (angular.isString(invoke)) { onInvoke(invoke, invokeList[1]); } else { onInvoke(key, invoke); } }); } else { return false; } return newInvoke; } function _invokeQueue(providers, queue, moduleName, reconfig) { if (!queue) { return; } var i, len, args, provider; for (i = 0, len = queue.length; i < len; i++) { args = queue[i]; if (angular.isArray(args)) { if (providers !== null) { if (providers.hasOwnProperty(args[0])) { provider = providers[args[0]]; } else { throw new Error('unsupported provider ' + args[0]); } } var isNew = _registerInvokeList(args, moduleName); if (args[1] !== 'invoke') { if (isNew && angular.isDefined(provider)) { provider[args[1]].apply(provider, args[2]); } } else { var callInvoke = function callInvoke(fct) { var invoked = regConfigs.indexOf(moduleName + '-' + fct); if (invoked === -1 || reconfig) { if (invoked === -1) { regConfigs.push(moduleName + '-' + fct); } if (angular.isDefined(provider)) { provider[args[1]].apply(provider, args[2]); } } }; if (angular.isFunction(args[2][0])) { callInvoke(args[2][0]); } else if (angular.isArray(args[2][0])) { for (var j = 0, jlen = args[2][0].length; j < jlen; j++) { if (angular.isFunction(args[2][0][j])) { callInvoke(args[2][0][j]); } } } } } } } function getModuleName(module) { var moduleName = null; if (angular.isString(module)) { moduleName = module; } else if (angular.isObject(module) && module.hasOwnProperty('name') && angular.isString(module.name)) { moduleName = module.name; } return moduleName; } function moduleExists(moduleName) { if (!angular.isString(moduleName)) { return false; } try { return ngModuleFct(moduleName); } catch (e) { if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) { return false; } } } this.$get = ["$log", "$rootElement", "$rootScope", "$cacheFactory", "$q", function ($log, $rootElement, $rootScope, $cacheFactory, $q) { var instanceInjector, filesCache = $cacheFactory('ocLazyLoad'); if (!debug) { $log = {}; $log['error'] = angular.noop; $log['warn'] = angular.noop; $log['info'] = angular.noop; } providers.getInstanceInjector = function () { return instanceInjector ? instanceInjector : instanceInjector = $rootElement.data('$injector') || angular.injector(); }; broadcast = function broadcast(eventName, params) { if (events) { $rootScope.$broadcast(eventName, params); } if (debug) { $log.info(eventName, params); } }; function reject(e) { var deferred = $q.defer(); $log.error(e.message); deferred.reject(e); return deferred.promise; } return { _broadcast: broadcast, _$log: $log, _getFilesCache: function getFilesCache() { return filesCache; }, toggleWatch: function toggleWatch(watch) { if (watch) { recordDeclarations.push(true); } else { recordDeclarations.pop(); } }, getModuleConfig: function getModuleConfig(moduleName) { if (!angular.isString(moduleName)) { throw new Error('You need to give the name of the module to get'); } if (!modules[moduleName]) { return null; } return angular.copy(modules[moduleName]); }, setModuleConfig: function setModuleConfig(moduleConfig) { if (!angular.isObject(moduleConfig)) { throw new Error('You need to give the module config object to set'); } modules[moduleConfig.name] = moduleConfig; return moduleConfig; }, getModules: function getModules() { return regModules; }, isLoaded: function isLoaded(modulesNames) { var moduleLoaded = function moduleLoaded(module) { var isLoaded = regModules.indexOf(module) > -1; if (!isLoaded) { isLoaded = !!moduleExists(module); } return isLoaded; }; if (angular.isString(modulesNames)) { modulesNames = [modulesNames]; } if (angular.isArray(modulesNames)) { var i, len; for (i = 0, len = modulesNames.length; i < len; i++) { if (!moduleLoaded(modulesNames[i])) { return false; } } return true; } else { throw new Error('You need to define the module(s) name(s)'); } }, _getModuleName: getModuleName, _getModule: function getModule(moduleName) { try { return ngModuleFct(moduleName); } catch (e) { if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) { e.message = 'The module "' + stringify(moduleName) + '" that you are trying to load does not exist. ' + e.message; } throw e; } }, moduleExists: moduleExists, _loadDependencies: function _loadDependencies(moduleName, localParams) { var loadedModule, requires, diff, promisesList = [], self = this; moduleName = self._getModuleName(moduleName); if (moduleName === null) { return $q.when(); } else { try { loadedModule = self._getModule(moduleName); } catch (e) { return reject(e); } requires = self.getRequires(loadedModule); } angular.forEach(requires, function (requireEntry) { if (angular.isString(requireEntry)) { var config = self.getModuleConfig(requireEntry); if (config === null) { moduleCache.push(requireEntry); return; } requireEntry = config; config.name = undefined; } if (self.moduleExists(requireEntry.name)) { diff = requireEntry.files.filter(function (n) { return self.getModuleConfig(requireEntry.name).files.indexOf(n) < 0; }); if (diff.length !== 0) { self._$log.warn('Module "', moduleName, '" attempted to redefine configuration for dependency. "', requireEntry.name, '"\n Additional Files Loaded:', diff); } if (angular.isDefined(self.filesLoader)) { promisesList.push(self.filesLoader(requireEntry, localParams).then(function () { return self._loadDependencies(requireEntry); })); } else { return reject(new Error('Error: New dependencies need to be loaded from external files (' + requireEntry.files + '), but no loader has been defined.')); } return; } else if (angular.isArray(requireEntry)) { var files = []; angular.forEach(requireEntry, function (entry) { var config = self.getModuleConfig(entry); if (config === null) { files.push(entry); } else if (config.files) { files = files.concat(config.files); } }); if (files.length > 0) { requireEntry = { files: files }; } } else if (angular.isObject(requireEntry)) { if (requireEntry.hasOwnProperty('name') && requireEntry['name']) { self.setModuleConfig(requireEntry); moduleCache.push(requireEntry['name']); } } if (angular.isDefined(requireEntry.files) && requireEntry.files.length !== 0) { if (angular.isDefined(self.filesLoader)) { promisesList.push(self.filesLoader(requireEntry, localParams).then(function () { return self._loadDependencies(requireEntry); })); } else { return reject(new Error('Error: the module "' + requireEntry.name + '" is defined in external files (' + requireEntry.files + '), but no loader has been defined.')); } } }); return $q.all(promisesList); }, inject: function inject(moduleName) { var localParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var real = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; var self = this, deferred = $q.defer(); if (angular.isDefined(moduleName) && moduleName !== null) { if (angular.isArray(moduleName)) { var promisesList = []; angular.forEach(moduleName, function (module) { promisesList.push(self.inject(module, localParams, real)); }); return $q.all(promisesList); } else { self._addToLoadList(self._getModuleName(moduleName), true, real); } } if (modulesToLoad.length > 0) { var res = modulesToLoad.slice(); var loadNext = function loadNext(moduleName) { moduleCache.push(moduleName); modulePromises[moduleName] = deferred.promise; self._loadDependencies(moduleName, localParams).then(function success() { try { justLoaded = []; _register(providers, moduleCache, localParams); } catch (e) { self._$log.error(e.message); deferred.reject(e); return; } if (modulesToLoad.length > 0) { loadNext(modulesToLoad.shift()); } else { deferred.resolve(res); } }, function error(err) { deferred.reject(err); }); }; loadNext(modulesToLoad.shift()); } else if (localParams && localParams.name && modulePromises[localParams.name]) { return modulePromises[localParams.name]; } else { deferred.resolve(); } return deferred.promise; }, getRequires: function getRequires(module) { var requires = []; angular.forEach(module.requires, function (requireModule) { if (regModules.indexOf(requireModule) === -1) { requires.push(requireModule); } }); return requires; }, _invokeQueue: _invokeQueue, _registerInvokeList: _registerInvokeList, _register: _register, _addToLoadList: _addToLoadList, _unregister: function _unregister(modules) { if (angular.isDefined(modules)) { if (angular.isArray(modules)) { angular.forEach(modules, function (module) { regInvokes[module] = undefined; }); } } } }; }]; this._init(angular.element(window.document)); }]); var bootstrapFct = angular.bootstrap; angular.bootstrap = function (element, modules, config) { angular.forEach(modules.slice(), function (module) { _addToLoadList(module, true, true); }); return bootstrapFct(element, modules, config); }; var _addToLoadList = function _addToLoadList(name, force, real) { if ((recordDeclarations.length > 0 || force) && angular.isString(name) && modulesToLoad.indexOf(name) === -1) { modulesToLoad.push(name); if (real) { realModules.push(name); } } }; var ngModuleFct = angular.module; angular.module = function (name, requires, configFn) { _addToLoadList(name, false, true); return ngModuleFct(name, requires, configFn); }; if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) { module.exports = 'oc.lazyLoad'; } })(angular, window); (function (angular) { 'use strict'; angular.module('oc.lazyLoad').directive('ocLazyLoad', ["$ocLazyLoad", "$compile", "$animate", "$parse", "$timeout", function ($ocLazyLoad, $compile, $animate, $parse, $timeout) { return { restrict: 'A', terminal: true, priority: 1000, compile: function compile(element, attrs) { var content = element[0].innerHTML; element.html(''); return function ($scope, $element, $attr) { var model = $parse($attr.ocLazyLoad); $scope.$watch(function () { return model($scope) || $attr.ocLazyLoad; }, function (moduleName) { if (angular.isDefined(moduleName)) { $ocLazyLoad.load(moduleName).then(function () { $animate.enter(content, $element); $compile($element.contents())($scope); }); } }, true); }; } }; }]); })(angular); (function (angular) { 'use strict'; angular.module('oc.lazyLoad').config(["$provide", function ($provide) { $provide.decorator('$ocLazyLoad', ["$delegate", "$q", "$window", "$interval", function ($delegate, $q, $window, $interval) { var uaCssChecked = false, useCssLoadPatch = false, anchor = $window.document.getElementsByTagName('head')[0] || $window.document.getElementsByTagName('body')[0]; $delegate.buildElement = function buildElement(type, path, params) { var deferred = $q.defer(), el, loaded, filesCache = $delegate._getFilesCache(), cacheBuster = function cacheBuster(url) { var dc = new Date().getTime(); if (url.indexOf('?') >= 0) { if (url.substring(0, url.length - 1) === '&') { return url + '_dc=' + dc; } return url + '&_dc=' + dc; } else { return url + '?_dc=' + dc; } }; if (angular.isUndefined(filesCache.get(path))) { filesCache.put(path, deferred.promise); } switch (type) { case 'css': el = $window.document.createElement('link'); el.type = 'text/css'; el.rel = 'stylesheet'; el.href = params.cache === false ? cacheBuster(path) : path; break; case 'js': el = $window.document.createElement('script'); el.src = params.cache === false ? cacheBuster(path) : path; break; default: filesCache.remove(path); deferred.reject(new Error('Requested type "' + type + '" is not known. Could not inject "' + path + '"')); break; } el.onload = el['onreadystatechange'] = function (e) { if (el['readyState'] && !/^c|loade/.test(el['readyState']) || loaded) return; el.onload = el['onreadystatechange'] = null; loaded = 1; $delegate._broadcast('ocLazyLoad.fileLoaded', path); deferred.resolve(); }; el.onerror = function () { filesCache.remove(path); deferred.reject(new Error('Unable to load ' + path)); }; el.async = params.serie ? 0 : 1; var insertBeforeElem = anchor.lastChild; if (params.insertBefore) { var element = angular.element(angular.isDefined(window.jQuery) ? params.insertBefore : document.querySelector(params.insertBefore)); if (element && element.length > 0) { insertBeforeElem = element[0]; } } insertBeforeElem.parentNode.insertBefore(el, insertBeforeElem); if (type == 'css') { if (!uaCssChecked) { var ua = $window.navigator.userAgent.toLowerCase(); if (/iP(hone|od|ad)/.test($window.navigator.platform)) { var v = $window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); var iOSVersion = parseFloat([parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)].join('.')); useCssLoadPatch = iOSVersion < 6; } else if (ua.indexOf("android") > -1) { var androidVersion = parseFloat(ua.slice(ua.indexOf("android") + 8)); useCssLoadPatch = androidVersion < 4.4; } else if (ua.indexOf('safari') > -1) { var versionMatch = ua.match(/version\/([\.\d]+)/i); useCssLoadPatch = versionMatch && versionMatch[1] && parseFloat(versionMatch[1]) < 6; } } if (useCssLoadPatch) { var tries = 1000; var interval = $interval(function () { try { el.sheet.cssRules; $interval.cancel(interval); el.onload(); } catch (e) { if (--tries <= 0) { el.onerror(); } } }, 20); } } return deferred.promise; }; return $delegate; }]); }]); })(angular); (function (angular) { 'use strict'; angular.module('oc.lazyLoad').config(["$provide", function ($provide) { $provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) { $delegate.filesLoader = function filesLoader(config) { var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var cssFiles = [], templatesFiles = [], jsFiles = [], promises = [], cachePromise = null, filesCache = $delegate._getFilesCache(); $delegate.toggleWatch(true); angular.extend(params, config); var pushFile = function pushFile(path) { var file_type = null, m; if (angular.isObject(path)) { file_type = path.type; path = path.path; } cachePromise = filesCache.get(path); if (angular.isUndefined(cachePromise) || params.cache === false) { if ((m = /^(css|less|html|htm|js)?(?=!)/.exec(path)) !== null) { file_type = m[1]; path = path.substr(m[1].length + 1, path.length); } if (!file_type) { if ((m = /[.](css|less|html|htm|js)?((\?|#).*)?$/.exec(path)) !== null) { file_type = m[1]; } else if (!$delegate.jsLoader.hasOwnProperty('ocLazyLoadLoader') && $delegate.jsLoader.hasOwnProperty('requirejs')) { file_type = 'js'; } else { $delegate._$log.error('File type could not be determined. ' + path); return; } } if ((file_type === 'css' || file_type === 'less') && cssFiles.indexOf(path) === -1) { cssFiles.push(path); } else if ((file_type === 'html' || file_type === 'htm') && templatesFiles.indexOf(path) === -1) { templatesFiles.push(path); } else if (file_type === 'js' || jsFiles.indexOf(path) === -1) { jsFiles.push(path); } else { $delegate._$log.error('File type is not valid. ' + path); } } else if (cachePromise) { promises.push(cachePromise); } }; if (params.serie) { pushFile(params.files.shift()); } else { angular.forEach(params.files, function (path) { pushFile(path); }); } if (cssFiles.length > 0) { var cssDeferred = $q.defer(); $delegate.cssLoader(cssFiles, function (err) { if (angular.isDefined(err) && $delegate.cssLoader.hasOwnProperty('ocLazyLoadLoader')) { $delegate._$log.error(err); cssDeferred.reject(err); } else { cssDeferred.resolve(); } }, params); promises.push(cssDeferred.promise); } if (templatesFiles.length > 0) { var templatesDeferred = $q.defer(); $delegate.templatesLoader(templatesFiles, function (err) { if (angular.isDefined(err) && $delegate.templatesLoader.hasOwnProperty('ocLazyLoadLoader')) { $delegate._$log.error(err); templatesDeferred.reject(err); } else { templatesDeferred.resolve(); } }, params); promises.push(templatesDeferred.promise); } if (jsFiles.length > 0) { var jsDeferred = $q.defer(); $delegate.jsLoader(jsFiles, function (err) { if (angular.isDefined(err) && ($delegate.jsLoader.hasOwnProperty("ocLazyLoadLoader") || $delegate.jsLoader.hasOwnProperty("requirejs"))) { $delegate._$log.error(err); jsDeferred.reject(err); } else { jsDeferred.resolve(); } }, params); promises.push(jsDeferred.promise); } if (promises.length === 0) { var deferred = $q.defer(), err = "Error: no file to load has been found, if you're trying to load an existing module you should use the 'inject' method instead of 'load'."; $delegate._$log.error(err); deferred.reject(err); return deferred.promise; } else if (params.serie && params.files.length > 0) { return $q.all(promises).then(function () { return $delegate.filesLoader(config, params); }); } else { return $q.all(promises)['finally'](function (res) { $delegate.toggleWatch(false); return res; }); } }; $delegate.load = function (originalModule) { var originalParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var self = this, config = null, deferredList = [], deferred = $q.defer(), errText; var module = angular.copy(originalModule); var params = angular.copy(originalParams); if (angular.isArray(module)) { angular.forEach(module, function (m) { deferredList.push(self.load(m, params)); }); $q.all(deferredList).then(function (res) { deferred.resolve(res); }, function (err) { deferred.reject(err); }); return deferred.promise; } if (angular.isString(module)) { config = self.getModuleConfig(module); if (!config) { config = { files: [module] }; } } else if (angular.isObject(module)) { if (angular.isDefined(module.path) && angular.isDefined(module.type)) { config = { files: [module] }; } else { config = self.setModuleConfig(module); } } if (config === null) { var moduleName = self._getModuleName(module); errText = 'Module "' + (moduleName || 'unknown') + '" is not configured, cannot load.'; $delegate._$log.error(errText); deferred.reject(new Error(errText)); return deferred.promise; } else { if (angular.isDefined(config.template)) { if (angular.isUndefined(config.files)) { config.files = []; } if (angular.isString(config.template)) { config.files.push(config.template); } else if (angular.isArray(config.template)) { config.files.concat(config.template); } } } var localParams = angular.extend({}, params, config); if (angular.isUndefined(config.files) && angular.isDefined(config.name) && $delegate.moduleExists(config.name)) { return $delegate.inject(config.name, localParams, true); } $delegate.filesLoader(config, localParams).then(function () { $delegate.inject(null, localParams).then(function (res) { deferred.resolve(res); }, function (err) { deferred.reject(err); }); }, function (err) { deferred.reject(err); }); return deferred.promise; }; return $delegate; }]); }]); })(angular); (function (angular) { 'use strict'; angular.module('oc.lazyLoad').config(["$provide", function ($provide) { $provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) { $delegate.cssLoader = function (paths, callback, params) { var promises = []; angular.forEach(paths, function (path) { promises.push($delegate.buildElement('css', path, params)); }); $q.all(promises).then(function () { callback(); }, function (err) { callback(err); }); }; $delegate.cssLoader.ocLazyLoadLoader = true; return $delegate; }]); }]); })(angular); (function (angular) { 'use strict'; angular.module('oc.lazyLoad').config(["$provide", function ($provide) { $provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) { $delegate.jsLoader = function (paths, callback, params) { var promises = []; angular.forEach(paths, function (path) { promises.push($delegate.buildElement('js', path, params)); }); $q.all(promises).then(function () { callback(); }, function (err) { callback(err); }); }; $delegate.jsLoader.ocLazyLoadLoader = true; return $delegate; }]); }]); })(angular); (function (angular) { 'use strict'; angular.module('oc.lazyLoad').config(["$provide", function ($provide) { $provide.decorator('$ocLazyLoad', ["$delegate", "$templateCache", "$q", "$http", function ($delegate, $templateCache, $q, $http) { $delegate.templatesLoader = function (paths, callback, params) { var promises = [], filesCache = $delegate._getFilesCache(); angular.forEach(paths, function (url) { var deferred = $q.defer(); promises.push(deferred.promise); $http.get(url, params).success(function (data) { if (angular.isString(data) && data.length > 0) { angular.forEach(angular.element(data), function (node) { if (node.nodeName === 'SCRIPT' && node.type === 'text/ng-template') { $templateCache.put(node.id, node.innerHTML); } }); } if (angular.isUndefined(filesCache.get(url))) { filesCache.put(url, true); } deferred.resolve(); }).error(function (err) { deferred.reject(new Error('Unable to load template file "' + url + '": ' + err)); }); }); return $q.all(promises).then(function () { callback(); }, function (err) { callback(err); }); }; $delegate.templatesLoader.ocLazyLoadLoader = true; return $delegate; }]); }]); })(angular); 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; }; } ; /*! RESOURCE: /scripts/concourse_pane_extension/_module.js */ angular.module('sn.concourse_pane_extension', ['oc.lazyLoad']); ; /*! RESOURCE: /scripts/concourse_pane_extension/service.concoursePaneExtensionRegistry.js */ angular.module('sn.concourse_pane_extension').service('concoursePaneExtensionRegistry', function() { var handlers = {}; return { register: function(type, handler) { handlers[type] = handler; }, hasHandler: function(type) { return handlers.hasOwnProperty(type); }, process: function(type, elementRoot, url, otherStuff) { handlers[type].call(null, elementRoot, url, otherStuff); console.log("Intercept handled", type, url, otherStuff); } } }); ; /*! RESOURCE: /scripts/sn/common/bindWatch/js_includes_bind_watch.js */ /*! RESOURCE: /scripts/sn/common/bindWatch/_module.js */ angular.module('sn.common.bindWatch', []); ; /*! RESOURCE: /scripts/sn/common/bindWatch/config.bindWatch.js */ angular.module('sn.common.bindWatch').config(function($provide) { "use strict"; $parseExpressionator.$inject = ['$delegate']; function $parseExpressionator($delegate) { function wrapParse(parse, exp, interceptor) { var parts; var part; var expression; var rawExpression; var notifiers; if (typeof exp === 'string' && /^:([a-zA-Z0-9][\w-]*):(.+)$/.test(exp)) { parts = exp.split(/:/); notifiers = []; while (parts.length) { part = parts.shift(); if (part) { if (/^\s*[\{\[]/.test(part)) { rawExpression = [part].concat(parts).join(':'); break; } notifiers.push(part); } } if (!rawExpression) rawExpression = notifiers.splice(-1, 1)[0]; expression = parse.call(this, '::' + rawExpression, interceptor); expression.$$watchDelegate = dynamicWatcher(expression, notifiers); return expression; } else { return parse.call(this, exp, interceptor); } } return wrapParse.bind(null, $delegate); } function dynamicWatcher(expression, keys) { if (expression.$$watchDelegate.wrapped) return expression.$$watchDelegate; function setupListeners(scope, callback) { keys.forEach(function(newKey) { scope.$on('$$applyTwoWayBinding::' + newKey, callback); }); } function wrapDelegate(watchDelegate, scope, listener, objectEquality, parsedExpression) { var delegateCall = watchDelegate.bind(this, scope, listener, objectEquality, parsedExpression); setupListeners(scope, delegateCall); delegateCall(); } var delegate = wrapDelegate.bind(this, expression.$$watchDelegate); delegate.wrapped = true; return delegate; } $provide.decorator('$parse', $parseExpressionator); }); ; /*! RESOURCE: /scripts/sn/common/bindWatch/BindWatch.js */ angular.module('sn.common.bindWatch').factory('BindWatch', function() { "use strict"; return function(scope, map) { if (!scope || !map) throw new Error('No scope or map provided'); Object.keys(map).forEach(function (key) { scope.$watch(map[key], function(key, n, o) { if (n !== o) scope.$broadcast('$$applyTwoWayBinding::' + key); }.bind(null, key)); }); } }); ; ; ; /*! RESOURCE: /scripts/concourse_view_stack/js_includes_concourse_view_stack.js */ /*! RESOURCE: /scripts/concourse_view_stack/_module.js */ angular.module('sn.concourse_view_stack', []); ; /*! RESOURCE: /scripts/concourse_view_stack/service.viewStack.js */ angular.module('sn.concourse_view_stack').service('viewStackService', function(i18n, systemProperties) { "use strict"; var defaultViews = [ { tab: 'general', name: 'general', replace: true, template: 'concourse_settings_general.xml', icon: 'cog', title: i18n.getMessage('General') }, { tab: 'theme', name: 'theme', template: 'concourse_settings_theme.xml', replace: true, icon: 'image', title: i18n.getMessage('Theme') }, { tab: 'accessibility', name: 'accessibility', template: 'concourse_settings_accessibility.xml', replace: true, icon: 'accessibility', title: i18n.getMessage('Accessibility') }, { tab: 'list', name: 'list', template: 'concourse_settings_lists.xml', replace: true, icon: 'table', title: i18n.getMessage('Lists') }, { tab: 'form', name: 'form', template: 'concourse_settings_forms.xml', replace: true, icon: 'form', title: i18n.getMessage('Forms') }, { tab: 'notifications', name: 'notifications_category', template: 'notification_preference_category.xml', title: i18n.getMessage('Applications') }, { tab: 'notifications', name: 'notifications_channel', template: 'notification_preference_channel.xml', title: i18n.getMessage('Channels') }, { tab: 'notifications', name: 'notifications_form', template: 'notification_preference_form.xml', title: i18n.getMessage('Apply Conditions') } ]; if (window.NOW.user.allRoles.indexOf('snc_external')==-1) { defaultViews.push({ tab: 'notifications', name: 'notifications_general', template: systemProperties.notifications ? 'notification_preference_general.xml' : 'concourse_settings_notifications_connect.xml', replace: true, icon: 'notification-bell', title: i18n.getMessage('Notification preferences') }) } if (systemProperties.developer) { defaultViews.push({ tab: 'developer', name: 'developer', template: 'concourse_settings_developer.xml', replace: true, icon: 'console', title: i18n.getMessage('Developer') }) } return { get: function get(key, options) { var defaultView = defaultViews.filter(function(item) { return item.name == key; })[0]; if (!defaultView) { throw 'Invalid view key: ' + key; } return angular.extend({}, defaultView, options); }, getTopLevelViews: function getTopLevelViews() { return defaultViews .filter(function(view) { return view.replace; }) .map(function(view) { return angular.extend({}, view); }) } }; }); ; ; /*! RESOURCE: /scripts/concourse/directive.mainPane.js */ angular.module('sn.concourse').directive('mainPane', function(snCustomEvent, $log) { "use strict"; return { restrict: 'A', link: function($scope, $element) { var permalinkBlacklist = new RegExp('login_redirect.do|about:blank|/welcome.do|/blank.do|/login.do'); function isBlacklisted(uri){ return permalinkBlacklist.test(uri); } function setPermalink(win){ if (win && win.location && !isBlacklisted(win.location.href)){ var pageUrl = win.location.href.substr(win.location.href.indexOf(win.location.pathname)); snCustomEvent.fire('magellanNavigator.permalink.set', { title : win.document.title, relativePath: pageUrl } ); overloadTitle(win); } } function overloadTitle(win){ win.document.origTitle = win.document.title; $element[0].title = win.document.title; try { Object.defineProperty(win.document, "title", { set: function(title) { this.origTitle = title; snCustomEvent.fire('magellanNavigator.permalink.set', {title: title}); }, get: function() { if (typeof this.origTitle == 'undefined') return ''; return this.origTitle; }, configurable: true }); }catch(e){ $log.error(e); } } $element.load(function(){ for (var key in window.localStorage) { if (key.startsWith("sn.polaris.")) { window.localStorage.removeItem(key); } } var win = this.contentWindow; setPermalink(win); }); var iframeWindow = $element.get(0).contentWindow; if (iframeWindow) setPermalink(iframeWindow); snCustomEvent.observe('glide:nav_open_url', function(options) { if (options && options.url) { $element.attr('src', options.url); } }); } } }) ; /*! RESOURCE: /scripts/heisenberg/angular/_module.heisenberg.js */ (function() { "use strict"; angular.module('heisenberg', []); })(); ; /*! RESOURCE: /scripts/heisenberg/angular/directive.snPopoverBasic.js */ (function($) { angular.module('heisenberg').directive('snPopoverBasic', function() { "use strict"; return { restrict: 'C', link: function(scope, elem) { elem.each(function () { var $this = $(this); if (!$this.data('bs.popover')) $this.popover(); }); } } }); })(jQuery); ; /*! RESOURCE: /scripts/heisenberg/angular/directive.snTooltipBasic.js */ (function($) { "use strict"; if ('ontouchstart' in document.documentElement) return; angular.module('heisenberg').directive('snTooltipBasic', function() { return { restrict: 'C', link: function(scope, elem) { if (isMobile()) return; var $elem = $(elem); if ($elem.data('bs.tooltip')) return; var bsTooltip = $.fn.tooltip.Constructor; var delayShow = bsTooltip.DEFAULTS.delay.show || 500; $elem.hideFix(); $elem.one('mouseenter', function() { if ($elem.data('bs.tooltip')) return; $elem.tooltip({ container: $elem.attr('data-container') || 'body' }); $elem.data('hover', setTimeout(function() { $elem.tooltip('show'); }, delayShow)); }); $elem.one('mouseleave', function() { var hover = $elem.data('hover'); if (hover) { clearTimeout($elem.data('hover')); $elem.removeData('hover') } }); $elem.click(function() { hideToolTip(); }); scope.$on('$destroy', function() { destroyToolTip(); }); function destroyToolTip() { if ($elem.tooltip) { $elem.tooltip('destroy'); } } function hideToolTip() { if ($elem.tooltip) { $elem.tooltip('hide'); } } function isMobile() { if (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)) { return true; } else { return false; } } } }; }); })(jQuery); ; /*! RESOURCE: /scripts/concourse/controller.impersonate.js */ angular.module('sn.concourse').controller('Impersonate', function($scope, $http, $log, $window, userPreferences, snCustomEvent) { "use strict"; $scope.searchConfig = { field: { value: null, displayValue: null, attributes : 'ref_ac_columns_search=true,ref_ac_columns=name;sys_id;user_name' }, additionalDisplayColumns: 'user_name', disabled: false }; $scope.submitFromReference = function() { var user = $scope.searchConfig.field.value; $scope.impersonate(user); }; $scope.$on('dialog.impersonate.show', function loadRecents() { $scope.show_error = false; $http.get('/api/now/ui/impersonate/recent').then(function(response) { $scope.recent_impersonations = response.data.result; }); }); snCustomEvent.observe('sn:impersonate', function(user_name) { $scope.impersonate(user_name); }); $scope.impersonate = function(user_name) { if (!user_name) return; $http.post('/api/now/ui/impersonate/' + user_name, {}).success(function() { $scope.show_error = false; window.location = "/"; }).error(function(response) { if (response.error) { $scope.show_error = true; $scope.error = response.error; $log.error("Impersonate failed", response.error); } }); }; }); ; /*! RESOURCE: /scripts/concourse/controller.elevateRoles.js */ angular.module('sn.concourse').controller('elevateRoles', ['$http', '$scope', '$rootScope', '$window', 'snCustomEvent', function($http, $scope, $rootScope, $window, snCustomEvent) { "use strict"; $scope.selected = []; $scope.activeRoles = []; $scope.activeElevatedRoles = []; $scope.sessionExpired = false; $http.get('/api/now/ui/impersonate/role').then(function(response) { if (response && response.data && response.data.result && response.data.result.roles && response.data.result.activeRoles) { $scope.roles = response.data.result.roles; $scope.activeRoles = response.data.result.activeRoles; setSelected(response.data.result.roles, response.data.result.activeRoles); } }); snCustomEvent.on('glide:ui_notification.security', function(notification) { expireElevatedRoles(notification); }); $scope.$on('dialog.elevateRoles.closed', function() { $scope.sessionExpired = false; }); function expireElevatedRoles(notification) { if ($scope.activeElevatedRoles && $scope.activeElevatedRoles.length) { $scope.sessionExpired = true; $rootScope.$broadcast('dialog.elevateRoles.show'); } } function setSelected(roles, activeRoles) { $scope.activeElevatedRoles = []; $scope.selected = []; for (var i = 0; i < roles.length; i++) { for (var j = 0; j < activeRoles.length; j++) { if (roles[i].name === activeRoles[j]) { $scope.selected.push(activeRoles[j]); $scope.activeElevatedRoles.push(roles[i]); } } } snCustomEvent.fireAll('user.elevatedRoles.updated', $scope.activeElevatedRoles); } $scope.toggleRole = function(role) { if ($scope.selected.indexOf(role.name) != -1) { $scope.selected.splice($scope.selected.indexOf(role.name), 1); } else { $scope.selected.push(role.name); } }; $scope.isSelected = function(role) { return $scope.selected.indexOf(role.name) != -1; }; snCustomEvent.observe('sn:elevate_roles', function(roles) { if (!angular.isArray(roles)) roles = [ roles ]; $scope.selected = roles; $scope.updateElevatedRoles(); }); $scope.updateElevatedRoles = function() { $http.post('/api/now/ui/impersonate/role', {roles: $scope.selected.join(',')}).then(function(response) { if (response && response.data && response.data.result) { window.location.reload(); } }); }; }]); ; /*! RESOURCE: /scripts/concourse/controller.settings.js */ angular.module('sn.concourse').controller('settings', function($scope, $timeout, glideUrlBuilder, getTemplateUrl, i18n, snCustomEvent, modalPath, shouldModalOpen, viewStackService, concourseSettings) { "use strict"; $scope.settings = angular.extend({}, concourseSettings); $scope.animateViewStackHeaders = false; activate(); function updateAriaRecordMessage(event) { if (!event || !event.action) return; var ariaMsg = ''; if (event.action === 'sysverb_insert') ariaMsg = i18n.getMessage('record inserted'); else if (event.action === 'sysverb_update') ariaMsg = i18n.getMessage('record updated'); else if (event.action === 'sysverb_delete') ariaMsg = i18n.getMessage('record deleted'); clearAriaLiveRegion(); var ariaRecordMsgElem = angular.element('#aria_live_iframe_action'); if (ariaRecordMsgElem.length) { var actionMsgSpan = angular.element("<span id='iframe_action_message'>" + ariaMsg + "</span>"); ariaRecordMsgElem.append(actionMsgSpan); } } function clearAriaLiveRegion() { var ariaRecordMsgElem = angular.element('#iframe_action_message'); if (ariaRecordMsgElem.length) ariaRecordMsgElem.remove(); } snCustomEvent.on('iframe_form.sysverb_insert', updateAriaRecordMessage); snCustomEvent.on('iframe_form.sysverb_delete', updateAriaRecordMessage); snCustomEvent.on('iframe_form.sysverb_update', updateAriaRecordMessage); $scope.previousView = function previousView() { if ($scope.viewStack.length > 1) { return $scope.viewStack[$scope.viewStack.length - 2]; } }; $scope.currentView = function currentView() { return $scope.viewStack[$scope.viewStack.length - 1]; }; $scope.getViewTemplate = function getViewTemplate(view) { return getTemplateUrl(view.template); }; $scope.openView = openView; $scope.back = function($event) { if ($event.type === 'keypress' && $event.keyCode !== 13 && $event.keyCode !== 32) { return; } if ($event.type === 'keypress' && ($event.keyCode === 13 || $event.keyCode === 32)) { $event.preventDefault(); $event.stopPropagation(); } back(); }; $scope.$on('dialog.settingsModal.show', function () { $scope.$broadcast('concourse_settings.view.refresh'); }); $scope.$on('concourse_settings.view.open', function(e, data) { _addViewObject(data) }); $scope.$on('concourse_settings.view.back', function() { back(true); }); $scope.$on('concourse_settings.view.render_complete', function() { initialFocus(); }); $scope.openViewOnKeypress = function ($event) { var firstView = this.views[0].name; var lastView = this.views[this.views.length-1].name; if ($event.keyCode === 40) { if (this.$last) { return openViewWithFocus(firstView); } else if (this.$$nextSibling) { return openViewWithFocus(this.$$nextSibling.view.name) } } else if ($event.keyCode === 38) { if (this.$first) { return openViewWithFocus(lastView); } else if (this.$$prevSibling) { return openViewWithFocus(this.$$prevSibling.view.name) } } return; } function openViewWithFocus (view) { angular.element('[data-tab-name=' + view + ']').focus(); openView(view); } function initialFocus() { var currentView = $scope.currentView(); if (!currentView) return; if (currentView.initialFocusSet) return; if (currentView.initFocus) { currentView.initialFocusSet = true; $timeout(function() { var elem = angular.element(currentView.initFocus); if (elem.length) elem[0].focus(); }); } } function back() { if ($scope.viewStack.length === 1) { return; } var view = $scope.viewStack.pop(); $scope.$broadcast('concourse_settings.view.closed', view); if (view.previouslyFocusedElement) { $timeout(function() { view.previouslyFocusedElement.focus(); }); } else if ($scope.viewStack.length === 1) { angular.element('[data-tab-name=' + $scope.viewStack[0].name + ']').focus(); } } function activate() { $scope.viewStack = [viewStackService.get("general")]; $scope.views = viewStackService.getTopLevelViews(); if (!modalPath) return; var parts = getModalPathParts(); parts.forEach(function(part) { openView(part.view, part.options); }); if (shouldModalOpen) toggleModal(true); } function openView(view, options){ var view = viewStackService.get(view, options); _addViewObject(view); } function _addViewObject(view) { if (view.replace) { $scope.viewStack = []; $scope.animateViewStackHeaders = false; } $scope.viewStack.push(view); if ($scope.viewStack.length > 1) { $scope.animateViewStackHeaders = true; } } function getModalPathParts() { var parts = (modalPath || "").split("."); parts.shift(); var views = []; parts.forEach(function(part) { var url = glideUrlBuilder.newGlideUrl(part); views.push({ view: url.contextPath, options: { params: url.getParams() } }); }) return views; } function toggleModal(bool) { var message = bool ? 'dialog.settingsModal.show' : 'dialog.settingsModal.close'; $scope.$evalAsync(function(){ $scope.$broadcast(message); }); } }); ; /*! RESOURCE: /scripts/concourse/directive.domainReferencePicker.js */ angular.module('sn.concourse').directive('domainReferencePicker', function($http, $rootScope, snCustomEvent, getTemplateUrl, domainReferenceService, userPreferences) { return { templateUrl: getTemplateUrl('concourse_domain_reference_picker.xml'), restrict: 'E', replace: false, scope: { current: '=', inHeader: '=', showInHeader: '=' }, controller: function($scope, $http, $rootScope, snCustomEvent) { $scope.domainConfig = domainReferenceService.domainConfig; $scope.domainOptions = { placeholder: $scope.current ? $scope.current.label : '', width: $scope.inHeader ? '150px' : '89%' }; $scope.$watch('current', function() { $scope.domainOptions.placeholder = $scope.current.label; }); domainReferenceService.showInHeader = $scope.showInHeader; $scope.domains = domainReferenceService; $scope.updateDomainFromReference = function() { $http.put('/api/now/ui/concoursepicker/domain', {value: $scope.domainConfig.field.value}).then(function() { triggerMainFrameRefresh(); }); }; $scope.resetDomain = function() { $http.put('/api/now/ui/concoursepicker/domain', {}).then(function(response) { if (response && response.data && response.data.result && response.data.result.current) { $scope.domainConfig.field.displayValue = response.data.result.current.label; $scope.domainConfig.field.value = response.data.result.current.value; } triggerMainFrameRefresh(); }); }; $scope.$watch("domainReferenceService.domainConfig", function(n, o) { if (n != o) { $scope.updateSelect(n.field.displayValue); } }); function triggerMainFrameRefresh() { var iframe = jQuery('iframe#gsft_main'); if (iframe.length) { iframe[0].contentWindow.location.reload(); } snCustomEvent.fireTop('navigator.refresh'); } }, link: function(scope, element) { scope.updateSelect = function(text) { element.find('.select2-chosen').text(text); }; element.on('change', 'input[type=checkbox]', function() { var showInHeader = angular.element(this).prop('checked'); domainReferenceService.showInHeader = showInHeader; scope.showInHeader = showInHeader; if (showInHeader) { userPreferences.setPreference('glide.ui.domain_picker.in_header', 'true'); } else { userPreferences.setPreference('glide.ui.domain_picker.in_header', ''); } }); } } }).factory('domainReferenceService', ['snCustomEvent', function(snCustomEvent) { var domainConfig = { field: { value: null, displayValue: null } }; var showInHeader = false; function setDomain(domainName, domainId) { domainConfig.field.displayValue = domainName; if (domainId) domainConfig.field.value = domainId; else if (domainName == 'global') domainConfig.field.value = 'global'; } snCustomEvent.observe('record.domain', function(data) { if (data && data.domainName && domainConfig.field.displayValue != data.domainName) { setDomain(data.domainName, data.domainId); } }); return { domainConfig: domainConfig, showInHeader: showInHeader }; }]); ; /*! RESOURCE: /scripts/concourse/dateTimeFormat.js */ (function () { CustomEvent.observe('cc_dateformat_set', function (preferences) { try { preferences = JSON.parse(preferences); } catch(ex) { preferences = {}; } if (preferences.timeAgo === false && preferences.dateBoth === false) CustomEvent.fireAll('timeago_set', false); if (preferences.timeAgo === true && preferences.dateBoth === false) CustomEvent.fireAll('timeago_set', true); if (preferences.dateBoth === true) CustomEvent.fireAll('date_both', true); }); CustomEvent.observe('cc_dateformat_compact_set', function (bool) { CustomEvent.fireAll('shortdates_set', bool); }); })(); ; /*! RESOURCE: /scripts/sn/common/notification/js_includes_notification.js */ /*! RESOURCE: /scripts/sn/common/notification/_module.js */ angular.module('sn.common.notification', ['sn.common.util', 'ngSanitize', 'sn.common.i18n']); ; /*! RESOURCE: /scripts/sn/common/notification/factory.notificationWrapper.js */ angular.module("sn.common.notification").factory("snNotificationWrapper", function($window, $timeout) { "use strict"; function assignHandler(notification, handlerName, options){ if (typeof options[handlerName] === "function") notification[handlerName.toLowerCase()] = options[handlerName]; } return function NotificationWrapper(title, options) { var defaults = { dir: 'auto', lang: 'en_US', decay: true, lifespan: 4000, body: "", tag: "", icon: '/native_notification_icon.png' }; var optionsOnClick = options.onClick; options.onClick = function() { if(angular.isFunction($window.focus)) $window.focus(); if(typeof optionsOnClick === "function") optionsOnClick(); } var result = {}; options = angular.extend(defaults, options); var previousOnClose = options.onClose; options.onClose = function() { if(angular.isFunction(result.onclose)) result.onclose(); if(angular.isFunction(previousOnClose)) previousOnClose(); } var notification = new $window.Notification(title, options); assignHandler(notification, "onShow", options); assignHandler(notification, "onClick", options); assignHandler(notification, "onError", options); assignHandler(notification, "onClose", options); if (options.decay && options.lifespan > 0) $timeout(function() { notification.close(); }, options.lifespan) result.close = function() { notification.close(); } return result; } }) ; /*! RESOURCE: /scripts/sn/common/notification/service.snNotifier.js */ angular.module("sn.common.notification").factory("snNotifier", function ($window, snNotificationWrapper) { "use strict"; return function(settings) { function requestNotificationPermission() { if($window.Notification && $window.Notification.permission === "default") $window.Notification.requestPermission(); } function canUseNativeNotifications() { return ($window.Notification && $window.Notification.permission === "granted"); } var currentNotifications = []; settings = angular.extend({ notifyMethods: ["native", "glide"] }, settings); var methods = { 'native': nativeNotify, 'glide': glideNotify }; function nativeNotify(title, options) { if(canUseNativeNotifications()) { var newNotification = snNotificationWrapper(title, options); newNotification.onclose = function () { stopTrackingNotification(newNotification) }; currentNotifications.push(newNotification); return true; } return false; } function glideNotify(title, options) { return false; } function stopTrackingNotification(newNotification) { var index = currentNotifications.indexOf(newNotification); if(index > -1) currentNotifications.splice(index, 1); } function notify(title, options) { if(typeof options === "string") options = {body: options}; options = options || {}; for(var i = 0, len = settings.notifyMethods.length; i < len; i++) if(typeof settings.notifyMethods[i] == "string") { if(methods[settings.notifyMethods[i]](title, options)) break; } else { if(settings.notifyMethods[i](title, options)) break; } } function clearAllNotifications() { while(currentNotifications.length > 0) currentNotifications.pop().close(); } return { notify: notify, canUseNativeNotifications: canUseNativeNotifications, clearAllNotifications: clearAllNotifications, requestNotificationPermission: requestNotificationPermission } } }); ; /*! RESOURCE: /scripts/sn/common/notification/directive.snNotification.js */ angular.module('sn.common.notification').directive('snNotification', function($timeout, $rootScope) { "use strict"; return { restrict: 'E', replace: true, template: '<div class="notification-container"></div>', link: function(scope, element) { scope.addNotification = function(payload) { if (!payload) payload = {}; if (!payload.text) payload.text = ''; if (!payload.classes) payload.classes = ''; if (!payload.duration) payload.duration = 5000; angular.element('<div/>').qtip({ content: { text: payload.text, title: { button: false } }, position: { target: [0, 0], container: angular.element('.notification-container') }, show: { event: false, ready: true, effect: function () { angular.element(this).stop(0, 1).animate({ height: 'toggle' }, 400, 'swing'); }, delay: 0, persistent: false }, hide: { event: false, effect: function (api) { angular.element(this).stop(0, 1).animate({ height: 'toggle' }, 400, 'swing'); } }, style: { classes: 'jgrowl' + ' ' + payload.classes, tip: false }, events: { render: function (event, api) { if (!api.options.show.persistent) { angular.element(this).bind('mouseover mouseout', function(e) { clearTimeout(api.timer); if (e.type !== 'mouseover') { api.timer = setTimeout(function() { api.hide(e); }, payload.duration); } }) .triggerHandler('mouseout'); } } } }); }, scope.$on('notification.notify', function(event, payload) { scope.addNotification(payload); }); } }; }); ; /*! RESOURCE: /scripts/sn/common/notification/service.snNotification.js */ angular.module('sn.common.notification').factory('snNotification', function($document, $templateCache, $compile, $rootScope, $timeout, $q, getTemplateUrl, $http, i18n) { 'use strict'; var openNotifications = [], timeouts = {}, options = { top: 20, gap: 10, duration: 5000 }, a11yContainer, a11yDuration = 5000; return { show: function(type, message, duration, onClick, container) { return createNotificationElement(type, message).then(function(element) { return displayAndDestroyNotification(element, container, duration); }); }, showScreenReaderOnly: function(type, message, duration, onClick, container) { return createNotificationElement(type, message, true).then(function(element) { return displayAndDestroyNotification(element, container, duration); }); }, hide: hide, setOptions: function(opts) { if (angular.isObject(opts)) angular.extend(options, opts); } }; function displayAndDestroyNotification(element, container, duration) { displayNotification(element, container); checkAndSetDestroyDuration(element, duration); return element; } function getTemplate() { var templateName = 'sn_notification.xml', template = $templateCache.get(templateName), deferred = $q.defer(); if (!template) { var url = getTemplateUrl(templateName); $http.get(url).then(function(result) { $templateCache.put(templateName, result.data); deferred.resolve(result.data); }, function(reason) { return $q.reject(reason); }); } else deferred.resolve(template); return deferred.promise; } function createNotificationElement(type, message, screenReaderOnly) { var thisScope, thisElement; var icon = 'icon-info'; screenReaderOnly = typeof(screenReaderOnly) === 'undefined' ? false : screenReaderOnly; if (type == 'error') { icon = 'icon-cross-circle'; } else if (type == 'warning') { icon = 'icon-alert'; } else if (type == 'success') { icon = 'icon-check-circle'; } return getTemplate().then(function(template) { thisScope = $rootScope.$new(); thisScope.type = type; thisScope.message = message; thisScope.icon = icon; thisScope.screenReaderOnly = screenReaderOnly; thisElement = $compile(template)(thisScope); return angular.element(thisElement[0]); }); } function displayNotification(element, container) { if( !a11yContainer ) { a11yContainer = angular.element('<div class="notification-a11y-container sr-only" aria-live="assertive">'); $document.find('body').append(a11yContainer); } var container = $document.find(container || 'body'), id = 'elm' + Date.now(), pos; container.append(element); pos = options.top + openNotifications.length * getElementHeight(element); positionElement(element, pos); element.addClass('visible'); element.attr('id', id); element.find('button').bind('click', function(e) { hideElement(element); }); openNotifications.push(element); if (options.duration > 0) timeouts[id] = $timeout(function () { hideNext(); }, options.duration); $timeout(function() { var srElement = angular.element('<div>').text(element.text()); a11yContainer.append(srElement); $timeout(function() { srElement.remove(); }, a11yDuration, false); }, 0, false) } function hide(element) { $timeout.cancel(timeouts[element.attr('id')]); element.removeClass('visible'); element.addClass('hidden'); element.find('button').eq(0).unbind(); element.scope().$destroy(); element.remove(); repositionAll(); } function hideElement(element) { var index = openNotifications.indexOf(element); openNotifications.splice(index, 1); hide(element); } function hideNext() { var element = openNotifications.shift(); if (element) hide(element); } function getElementHeight(element) { return element[0].offsetHeight + options.gap; } function positionElement(element, pos) { element[0].style.top = pos + 'px'; } function repositionAll() { var pos = options.top; openNotifications.forEach(function(element) { positionElement(element, pos); pos += getElementHeight(element); }); } function checkAndSetDestroyDuration(element, duration){ if (duration){ timeouts[element.attr('id')] = $timeout(function(){ hideElement(element); }, duration); } } }); ; ; /*! RESOURCE: /scripts/sn/common/session_notification/js_includes_session_notification.js */ /*! RESOURCE: /scripts/sn/common/session_notification/_module.js */ angular.module('sn.common.session_notification', ['sn.common.notification', 'sn.common.i18n']); ; /*! RESOURCE: /scripts/sn/common/session_notification/service.sessionNotificationInterceptor.js */ angular.module('sn.common.session_notification').config(function($httpProvider) { var HEADER_KEY = "X-WantSessionNotificationMessages"; function handleSessionNotificationResponse(response, snCustomEvent) { if (!response.data.result || !response.data.session || !response.data.session.notifications) return response; var deDupedNotifications = _deDupedNotifications(response.data.session.notifications); angular.forEach(deDupedNotifications, function(item) { var method = 'fire'; if (item.type == 'ui_notification') method = 'fireTop'; snCustomEvent[method]("session_notification", item); }); return response; } function handleSessionNotificationRequest(config) { if (config.url.indexOf('xmlhttp.do') === 0 || config.url.indexOf('/api/now/ui/presence') === 0 || typeof g_form != "undefined") return config; if (HEADER_KEY in config.headers) return config; config.headers[HEADER_KEY] = 'true'; return config; } $httpProvider.interceptors.push(function(snCustomEvent) { return { 'request': function(config) { return handleSessionNotificationRequest(config); }, 'response': function (response) { return handleSessionNotificationResponse(response, snCustomEvent); } }; }); function _deDupedNotifications(notifications){ var _deDupedMessages = notifications.map(function(item){ return item.text }); return notifications.filter(function(notification, index){ return _deDupedMessages.indexOf(notification.text) == index; }); } }); angular.module('sn.common.session_notification').run(function(snCustomEvent, snNotification) { snCustomEvent.observe('session_notification', function(item) { var duration = 0; var ephemeralAlertTypes = ['system']; var notUsTypes = ['system_event', 'service', 'action', 'processed']; if (!item.text || notUsTypes.indexOf(item.notification_type) > -1) return; if (item.duration) duration = parseInt(item.duration, 10); else if (ephemeralAlertTypes.indexOf(item.notification_type) > -1){ duration = 5000; } type = 'info'; if (item.type) type = item.type; if (type != 'info' && type != 'error' && type != 'success' && type != 'warning' && type != 'danger') type = 'info'; snNotification.show(type, item.text, duration); item.notification_type = 'processed'; return false; }); }); ; /*! RESOURCE: /scripts/sn/common/session_notification/service.uiNotificationHandler.js */ angular.module('sn.common.session_notification').run(function(snCustomEvent, snNotification, i18n) { snNotification.setOptions({ duration: 0 }); snCustomEvent.observe('session_notification', function(item) { if (!snCustomEvent.isTopWindow()) return; if (item.notification_type == 'system'){ outputMessage(item.text, parseInt(item.duration, 10)); } if (item.notification_type == 'update_set_change'){ var string = 'Your current update set has been changed to {0}'; if (item.notification_attributes && item.notification_attributes.msg){ string += "<br/>" + item.notification_attributes.msg; item.type = 'warning'; } i18n.getMessage(string, function(msg) { var formattedMsg = i18n.format(msg, item.notification_attributes.name); handleMessage(item, formattedMsg, 10000); }); } if (item.notification_type == 'system_event' && item.notification_attributes && item.notification_attributes.event == 'refresh_nav') { snCustomEvent.fireTop('navigator.refresh'); } return; }); function handleMessage(item, message, duration) { var dur = duration || false; triggerPickerRefresh(); if (item.notification_attributes.update_only == 'true') return; outputMessage(message, dur); } function triggerPickerRefresh() { snCustomEvent.fireAll('sn:refresh_update_set'); } function outputMessage(msg, duration) { snNotification.show('info', msg, duration); } }); ; /*! RESOURCE: /scripts/sn/common/session_notification/service.legacySessionNotificationHandler.js */ angular.module('sn.common.session_notification').run(function(snCustomEvent) { window.NOW.ngLegacySessionNotificationSupport = true; snCustomEvent.observe('legacy_session_notification', function(span) { var notification = { notification_attributes: {} }; if (span && span.attributes.length > 0) { for (var i = 0; i < span.attributes.length; i++) { var attr = span.attributes[i]; var name = attr.name; if (name.indexOf('data-') != -1) name = name.substring('data-'.length); if (name.startsWith('attr-')) { name = name.substring('attr-'.length) notification.notification_attributes[name] = attr.value; continue; } notification[name] = attr.value; } } if (notification['class'] == 'ui_notification') { notification.notification_type = notification.type || 'ui_notification'; notification.type = notification.type || 'ui_notification'; snCustomEvent.fireTop('session_notification', notification); return; } snCustomEvent.fire('session_notification', notification); return false; }); snCustomEvent.observe('glide:ui_notification.update_set_change', function(notification) { snCustomEvent.fire('legacy_session_notification', notification.xml); }); snCustomEvent.observe('glide:ui_notification.system', function(notification) { if (typeof notification != 'undefined' && typeof notification.xml != 'undefined') { snCustomEvent.fire('legacy_session_notification', notification.xml); } }); snCustomEvent.observe('glide:ui_notification.system_event', function(notification) { if (typeof notification != 'undefined' && typeof notification.xml != 'undefined') { var type = notification.xml.getAttribute('data-attr-event'); if (typeof type != 'undefined' && type === 'refresh_nav') { snCustomEvent.fireTop('navigator.refresh'); } } }); snCustomEvent.observe('glide:ui_notification.error', function(notificaiton) { snCustomEvent.fire('legacy_session_notification', notificaiton.xml); return false; }); snCustomEvent.observe('glide:ui_notification.info', function(notificaiton) { snCustomEvent.fire('legacy_session_notification', notificaiton.xml); return false; }); }); ; ; /*! RESOURCE: /scripts/js_includes_overviewhelp.js */ /*! RESOURCE: /scripts/doctype/CustomEventManager.js */ var NOW = NOW || {}; var CustomEventManager = (function (existingCustomEvent) { "use strict"; var events = (existingCustomEvent && existingCustomEvent.events) || {}; var isFiringFlag = false; var trace = false; var suppressEvents = false; var NOW_MSG = 'NOW.PostMessage'; function observe(eventName, fn){ if (trace) jslog("$CustomEventManager observing: " + eventName); on(eventName, fn); } function on(name, func) { if (!func || typeof func !== 'function') return; if (typeof name === 'undefined') return; if (!events[name]) events[name] = []; events[name].push(func); } function un(name, func) { if (!events[name]) return; var idx = -1; for (var i = 0; i < events[name].length; i++) { if (events[name][i] === func) { idx = i; break; } } if (idx >= 0) events[name].splice(idx, 1) } function unAll(name) { if (events[name]) delete events[name]; } function fire(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); return fireEvent.apply(null, arguments); } function fireUp(eventName, args){ var win = window; while (win){ try { if (win.CustomEvent.fireEvent.apply(null, arguments) === false) return; win = win.parent === win ? null : win.parent; }catch(e){ return; } } } function fireEvent() { if (suppressEvents) return true; var args = Array.prototype.slice.apply(arguments); var name = args.shift(); var eventList = events[name]; if (!eventList) return true; var event = eventList.slice(); isFiringFlag = true; for (var i = 0, l = event.length; i < l; i++) { var ev = event[i]; if (!ev) continue; if (ev.apply(null, args) === false) { isFiringFlag = false; return false; } } isFiringFlag = false; return true; } function isFiring() { return isFiringFlag; } function forward(name, element, func) { on(name, func); element.addEventListener(name, function(e) { fireEvent(e.type, this, e); }.bind(api)); } function isOriginInWhiteList(origin, whitelistStr) { if (!whitelistStr) { return false; } var delimiterRegex = /[\n, ]/; var whitelist = whitelistStr.split(delimiterRegex) .filter(function(whiteListedOrigin) { return whiteListedOrigin; }) .map(function(whiteListedOrigin) { return whiteListedOrigin.toLowerCase(); }); if (~whitelist.indexOf(origin.toLowerCase())) { return true; } return false; } function shouldProcessMessage(sourceOrigin) { if (!window.g_concourse_onmessage_enforce_same_origin || sourceOrigin === window.location.origin) { return true; } return isOriginInWhiteList(sourceOrigin, window.g_concourse_onmessage_enforce_same_origin_whitelist); } function registerPostMessageEvent() { if (NOW.registeredPostMessageEvent) { return; } if (!window.postMessage) { return; } window.addEventListener('message', function (event) { if (!shouldProcessMessage(event.origin)) { console.warn('Incoming message ignored due to origin mismatch.'); return; } var nowMessageJSON = event.data; var nowMessage; try { nowMessage = JSON.parse(nowMessageJSON.toString()); } catch (e) { return; } if (!nowMessage.type == NOW_MSG) { return; } fire(nowMessage.eventName, nowMessage.args); }, false); NOW.registeredPostMessageEvent = true; } function doPostMessage(win, event, msg, targetOrigin) { var nowMessage = {type: NOW_MSG, eventName: event, args: msg}; var nowMessageJSON; if (!win || !win.postMessage) { return } nowMessageJSON = JSON.stringify(nowMessage); win.postMessage(nowMessageJSON, targetOrigin); } function fireTop(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); fireEvent.apply(null, arguments); var t = getTopWindow(); if (t !== null && window !== t) t.CustomEvent.fire(eventName, args); } function fireAll(eventName, args) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); var topWindow = getTopWindow(); if (topWindow !== window.self) CustomEvent.fireEvent(eventName, args); notifyAllFrom(topWindow); function notifyAllFrom(rootFrame) { var childFrame; rootFrame.CustomEvent.fireEvent(eventName, args); for (var i = 0; i < rootFrame.frames.length; i++) { try { childFrame = rootFrame.frames[i]; if (!childFrame) continue; if (childFrame.CustomEvent && typeof childFrame.CustomEvent.fireEvent === "function") { notifyAllFrom(childFrame); } } catch(e) { } } } } function fireToWindow(targetWindow, eventName, args, usePostMessage, targetOrigin) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + args.length); if (usePostMessage) { doPostMessage(targetWindow, eventName, args, targetOrigin); } else { targetWindow.CustomEvent.fireEvent(eventName, args); } } function getTopWindow() { var topWindow = window.self; try { while (topWindow.CustomEvent.fireEvent && topWindow !== topWindow.parent && topWindow.parent.CustomEvent.fireEvent) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } function isTopWindow() { return getTopWindow() == window.self; } function jslog(msg, src, dateTime) { try { if (!src) { var path = window.self.location.pathname; src = path.substring(path.lastIndexOf('/') + 1); } if (window.self.opener && window != window.self.opener) { if (window.self.opener.jslog) { window.self.opener.jslog(msg, src, dateTime); } } else if (parent && parent.jslog && jslog != parent.jslog) { parent.jslog(msg, src, dateTime); } else { if (window.console && window.console.log) console.log(msg); } } catch (e) { } } var api = { set trace(value) { trace = !!value; }, get trace() { return trace; }, set suppressEvents(value) { suppressEvents = !!value; }, get suppressEvents() { return suppressEvents; }, get events() { return events; }, set events(value) { events = value; }, on: on, un: un, unAll: unAll, forward: forward, isFiring: isFiring, fireEvent: fireEvent, observe: observe, fire: fire, fireTop: fireTop, fireAll: fireAll, fireToWindow: fireToWindow, isTopWindow: isTopWindow, fireUp: fireUp, toString: function() { return 'CustomEventManager'; } }; registerPostMessageEvent(); return api; })(NOW.CustomEvent); NOW.CustomEvent = CustomEventManager; if (typeof CustomEvent !== "undefined") { CustomEvent.observe = NOW.CustomEvent.observe.bind(NOW.CustomEvent); CustomEvent.fire = NOW.CustomEvent.fire.bind(NOW.CustomEvent); CustomEvent.fireUp = NOW.CustomEvent.fireUp.bind(NOW.CustomEvent); CustomEvent.fireTop = NOW.CustomEvent.fireTop.bind(NOW.CustomEvent); CustomEvent.fireAll = NOW.CustomEvent.fireAll.bind(NOW.CustomEvent); CustomEvent.fireToWindow = NOW.CustomEvent.fireToWindow.bind(NOW.CustomEvent); CustomEvent.on = NOW.CustomEvent.on.bind(NOW.CustomEvent); CustomEvent.un = NOW.CustomEvent.un.bind(NOW.CustomEvent); CustomEvent.unAll = NOW.CustomEvent.unAll.bind(NOW.CustomEvent); CustomEvent.forward = NOW.CustomEvent.forward.bind(NOW.CustomEvent); CustomEvent.isFiring = NOW.CustomEvent.isFiring.bind(NOW.CustomEvent); CustomEvent.fireEvent = NOW.CustomEvent.fireEvent.bind(NOW.CustomEvent); CustomEvent.events = NOW.CustomEvent.events; CustomEvent.isTopWindow = NOW.CustomEvent.isTopWindow.bind(NOW.CustomEvent); } else { window.CustomEvent = NOW.CustomEvent; } ; /*! RESOURCE: /scripts/app.overviewhelp/app.overviewhelp.js */ (function() { angular.module('sn.overviewhelp', ['sn.base', 'ng.common']); angular.module('sn.overviewhelp').directive('overviewhelp', function(getTemplateUrl, snCustomEvent, $document, $timeout) { "use strict"; return { restrict: 'E', scope: { pageName: "@", active: "@", embedded: "@" }, templateUrl: getTemplateUrl('ng_overview_help.xml'), link: function($scope, $element, $attrs) { $attrs.$observe('active', function() { $scope.active = $scope.$eval($attrs.active); }); $scope.$on('overviewhelp.active', function() { $timeout(function() { var focusTarget = $element.find('a, button').first(); focusTarget.focus(); var element = $element.get(0); element.addEventListener("focusout", function(e) { if (element.contains(e.relatedTarget)) focusTarget = e.relatedTarget; else $timeout(function() { focusTarget.focus(); }); }); }); }); $element.on('keydown', function(evt) { var $firstItem = $element.find('a, button').first(); var $lastItem = $element.find('a, button').last(); if (evt.keyCode != 9) return; if ($firstItem.is(evt.target) && evt.shiftKey) { $lastItem.focus(); evt.stopPropagation(); evt.preventDefault(); } else if ($lastItem.is(evt.target) && !evt.shiftKey) { $firstItem.focus(); evt.stopPropagation(); evt.preventDefault(); } }); $document.on("keydown", function(evt) { if ($scope.active && evt.keyCode == 27) { $scope.close(); } }); }, controller: function($scope, $http, urlTools, $element, userPreferences) { var $carousel = null; $scope.currentPanel = 0; snCustomEvent.observe('overview_help.activate', function(data) { if (data.pageName && data.pageName == $scope.pageName) activate(); }); $scope.$watch('active', function(newValue) { if (newValue) activate(); }); $scope.$watch('loaded', function(newValue) { if (newValue) { $carousel = $element.carousel({ interval: 10000, wrap: true, pause: 'hover' }); } }) function activate() { var url = urlTools.urlFor('overview_help', { page: $scope.pageName }); $http.get(url).success(function(response) { $scope.panels = response.panels; $scope.icon_buttons = response.icon_buttons; $scope.footer_bg = response.footer_bg; $scope.hasNext = $scope.panels.length > 1; $scope.loaded = true; $scope.active = true; $scope.$broadcast('overviewhelp.active'); if ($carousel) { $carousel.carousel('cycle'); } }); } $scope.next = function() { $carousel.carousel('next'); } $element.on('slide.bs.carousel', function(evt) { $scope.currentPanel = parseInt(evt.relatedTarget.getAttribute('data-panel-number'), 10); $scope.$apply(); }); $scope.$watch('currentPanel + loaded', function() { if (!$scope.panels) { $scope.hasNext = false; $scope.hasPrev = false; return; } $scope.hasNext = $scope.currentPanel + 1 < $scope.panels.length; }); $scope.close = function() { $carousel.carousel('pause'); userPreferences.setPreference('overview_help.visited.' + $scope.pageName, 'true').then(function() { snCustomEvent.fireAll('overview_help.finished', {id: $scope.pageName}); if ($scope.embedded == 'true') $scope.active = false; }); } } } }); })(); ; /*! RESOURCE: /scripts/app.overviewhelp/directive.snTriggerOverviewHelp.js */ angular.module('sn.overviewhelp').directive('snTriggerOverviewHelp', function(snCustomEvent) { return { restrict: 'A', link: function($scope, $element, $attrs) { $element.click(function() { var pageName = $attrs.snTriggerOverviewHelp; snCustomEvent.fire('overview_help.activate', { pageName: pageName }); $element.closest('.popover').popover('hide'); }); } } }); ; ; /*! RESOURCE: /scripts/concourse/deprecated.js */ "use strict"; function alertDeprecated(oldFnName, newName){ if (console && console.warn) { console.warn("WARNING! Deprecated function called. The global function '" + oldFnName + "' has been deprecated, please use '" + newName + "' from your application's context instead."); } } var g_application_picker = { fillApplications : function() { CustomEvent.fireTop('sn:refresh_application_picker'); } }; function popupOpenFocus(url, name, pWidth, pHeight, features, snapToLastMousePosition, closeOnLoseFocus) { alertDeprecated("popupOpenFocus()", "window.g_navigation.openPopup()"); if (url.indexOf("?") != -1) url += "&"; else url += "?"; url += "sysparm_domain_restore=false"; if (url.indexOf("sysparm_nameofstack") == -1) url += "&sysparm_stack=no"; if (snapToLastMousePosition) { if (lastMouseX - pWidth < 0) { lastMouseX = pWidth; } if (lastMouseY + pHeight > screen.height) { lastMouseY -= (lastMouseY + pHeight + 50) - screen.height; } lastMouseX -= pWidth; lastMouseY += 10; features += ",screenX=" + lastMouseX + ",left=" + lastMouseX + ",screenY=" + lastMouseY + ",top=" + lastMouseY; } if (closeOnLoseFocus) { var popupCurrent = window.open(url, name, features, false); if (!popupCurrent) { alert('Please disable your popup blocker to use this feature'); return null; } else { popupCurrent.focus(); popupCurrent.opener = window.self; return popupCurrent; } } else { var win = window.open(url, name, features, false); if (win) { win.focus(); win.opener = window.self; } return win; } } ; /*! RESOURCE: /scripts/concourse/directive.enableAccessibility.js */ angular.module('sn.concourse').directive('enableAccessibility', ['userPreferences', function(userPreferences) { return { template : '<a class="skip-links sr-only sr-only-focusable" href="#">{{::label}}</a>', restrict : 'E', replace : true, scope : { label : '@', confirm : '@' }, link : function(scope, element) { element.on('click', function(evt) { evt.preventDefault(); if (confirm(scope.confirm)) { userPreferences.setPreference('glide.ui.accessibility', true).then(function() { window.location.reload(); }); } }); } } }]); ; /*! RESOURCE: /scripts/concourse/searchFocus.js */ (function($) { $(function() { var search = $('#sysparm_search'); search.on('focus', function() { search.addClass('focus'); }); search.on('blur', function() { if (!search.val()) { search.removeClass('focus'); } }); }); })(jQuery); ; /*! RESOURCE: /scripts/js_includes_weba.js */ /*! RESOURCE: /scripts/doctype/GlideWebAnalytics.js */ var GlideWebAnalytics = (function() { function subscribe() { window.snWebaConfig = window.snWebaConfig || {}; if (window.snWebaConfig.subscribed && window.snWebaConfig.subscribed == true) return; var ambClient = getAMB(); if (ambClient == undefined || ambClient == "") return; var webaChannelId = "/weba/config"; var webaCh = ambClient.getChannel(webaChannelId); webaCh.subscribe(function(response) { if (window.snWebaConfig == undefined || window.snWebaConfig == null) window.snWebaConfig = {}; var oldConfig = { siteId : (window.snWebaConfig.siteId)? window.snWebaConfig.siteId: "0" , trackerURL : (window.snWebaConfig.trackerURL)? window.snWebaConfig.trackerURL: "" }; window.snWebaConfig.siteId = response.data.weba_site_id; window.snWebaConfig.trackerURL = response.data.weba_rx_url; window.snWebaConfig.webaScriptPath = response.data.weba_script_path; handleConfigUpdate(oldConfig, window.snWebaConfig); }); ambClient.connect(); window.snWebaConfig.subscribed = true; } function getAMB(){ var ambClient = window.snWebaConfig.ambClient; if (ambClient) return ambClient; window.snWebaConfig.ambClient = (window.g_ambClient) ? window.g_ambClient : ((window.amb)? window.amb.getClient(): ""); return window.snWebaConfig.ambClient; } function handleConfigUpdate(oldConfig, newConfig) { if (shouldRemoveTracker(oldConfig, newConfig)) removeTracker(); else if (shouldUpdateTracker(oldConfig, newConfig)) updateTracker(oldConfig, newConfig); else if (shouldInsertTracker(oldConfig, newConfig)) insertTracker(newConfig); } function shouldRemoveTracker(oldConfig, newConfig){ if (newConfig.siteId == "0" || newConfig.trackerURL == "") return true; return false; } function shouldUpdateTracker(oldConfig, newConfig){ if (oldConfig.siteId && oldConfig.siteId != "0" && oldConfig.siteId != newConfig.siteId) return true; if (oldConfig.trackerURL && oldConfig.trackerURL != newConfig.trackerURL) return true; return false; } function shouldInsertTracker(oldConfig, newConfig){ if (oldConfig.siteId == undefined || oldConfig.siteId == "0") return true; if (oldConfig.trackerURL == undefined || oldConfig.trackerURL == "") return true; return false; } function removeTracker() { if (!trackerExists()) return; removeWebaTracker(); removeWebaScript(); removeWebaElements(); } function removeWebaTracker() { var document = window.parent.document; var trackerScriptId = "webaTracker"; var trackEle = document.getElementById(trackerScriptId); trackEle.parentNode.removeChild(trackEle); } function removeWebaScript() { var document = window.parent.document; var asyncTrackEle = document.getElementById('webaScript'); if (asyncTrackEle == undefined) return; var src = asyncTrackEle.src; if (src != undefined && src.indexOf("piwik") > 0) asyncTrackEle.parentNode.removeChild(asyncTrackEle); } function removeWebaElements() { var document = window.parent.document; var webaEle = document.getElementsByClassName("weba"); var webaSize = webaEle.length - 1; while (webaSize >= 0){ webaEle[webaSize].parentNode.removeChild(webaEle[webaSize]); webaSize--; } } function updateTracker(oldConfig, newConfig) { if (!trackerExists()) return; var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; var updateScript = "_paq.push(['setSiteId', " + newConfig.siteId + "]);" + "_paq.push(['setTrackerUrl', " + "'" + newConfig.trackerURL + "'" + "]);"; var uEle = window.document.createElement("script"); uEle.text = updateScript; uEle.className = "weba"; head.appendChild(uEle); } function insertTracker(newConfig, additionalData) { var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; if (trackerExists()) return; if (!isConfigValid(newConfig)) return; var trackerScript = generateTrackerScript(newConfig, additionalData); var trackerElement = getOrCreateTracker(); trackerElement.text = trackerScript; head.appendChild(trackerElement); } function applyTracker(additionalData) { insertTracker(window.snWebaConfig, additionalData); subscribe(); } function applyTrackEvent(category, key, value, additionalValue) { insertEventTracker(category, key, value, additionalValue); subscribe(); } function insertEventTracker(category, key, value, additionalValue) { if (!isConfigValid(window.snWebaConfig)) return; if (!trackerExists()) insertTracker(window.snWebaConfig); if (typeof category != "string" || typeof key != "string" || typeof value != "string") return; if (additionalValue) additionalValue = (typeof additionalValue == "number")? additionalValue: 0; var eventItems = [ "trackEvent", category, key, value, additionalValue ]; var eventScript = "_paq.push(" + JSON.stringify(eventItems) + ");"; var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; var scriptEle = window.document.createElement("script"); scriptEle.className = "weba"; scriptEle.text = eventScript; head.appendChild(scriptEle); } function trackerExists() { var document = window.parent.document; var trackEle = document.getElementById("webaTracker"); if (trackEle) return true; return false; } function isConfigValid(newConfig) { var zero = "0"; var webaSiteId = (newConfig && newConfig.siteId) ? newConfig.siteId : zero; var trackerURL = (newConfig && newConfig.trackerURL) ? newConfig.trackerURL : ""; if (webaSiteId == null || webaSiteId == "") return false; if (webaSiteId == zero ) return false; if (trackerURL == null || trackerURL == "") return false; return true; } function getOrCreateTracker() { var trackerScriptId = "webaTracker"; var document = window.parent.document; var trackEle = document.getElementById(trackerScriptId); if (trackEle) return trackEle; trackEle = document.createElement("script"); trackEle.id = trackerScriptId; trackEle.type = "text/javascript"; return trackEle; } function getUserId(additionalData) { if (window.NOW && window.NOW.user_id && window.NOW.user_id != "") return window.NOW.user_id; else if (additionalData && additionalData.userId){ return additionalData.userId; } else if (window.NOW && window.NOW.session_id) return window.NOW.session_id; else { var userObj = (window.NOW)? window.NOW.user: null; if (userObj && userObj.userID) return userObj.userID; } return ""; } function generateTrackerScript(webaConfig, additionalData) { var trackerURL = webaConfig.trackerURL; if (trackerURL.endsWith("/")) trackerURL = webaConfig.trackerURL.substring(0, trackerURL.length - 1); var userId = getUserId(additionalData); var script = "var _paq = _paq || [];"; if (userId && userId != ""){ script += "_paq.push(['setUserId', '" + userId + "']);"; } script += "_paq.push(['trackPageView']); _paq.push(['enableLinkTracking']);"; script += "(function() {_paq.push(['setTrackerUrl','" + trackerURL + "']);" + "_paq.push(['setSiteId', " + webaConfig.siteId + "]);" + "var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; " + "g.defer=true; g.src='" + webaConfig.webaScriptPath + "'; " + "g.id='webaScript';s.parentNode.insertBefore(g,s); })();"; return script; } var api = { trackPage: function(additionalData) { if (window.document.readyState == "complete") applyTracker(additionalData); else window.addEventListener("load", function() { applyTracker(additionalData); }, false); }, trackEvent: function(category, key, value, additionalValue, delayInMs) { if (delayInMs == undefined) delayInMs = 3000; window.setTimeout(function() { applyTrackEvent(category, key, value, additionalValue); }, delayInMs); } } return api; })(); ; ; ; /*! RESOURCE: /scripts/app.magellan/js_includes_magellan.js */ /*! RESOURCE: /scripts/magellan.js */ $j(function($) { "use strict"; var TEXT = 'text'; var MESSAGES = window.top.Magellan.globals.messages; $('#nav_west').tooltip({placement: 'bottom', container: 'body', selector: '.nav-views.sn-navhub-content>div'}); $(document).on('dragover', '#nav_west_center', function(event) { event.preventDefault(); }); $(document).on('drop', '#nav_west_center', function(event) { event.preventDefault(); var t = event.originalEvent.dataTransfer.getData('text'); if (typeof t == 'string' && t.length) { try { t = JSON.parse(t); CustomEvent.fireAll('magellanNavigator:createFavorite', t); } catch (e) {} } }); var $doc, $win; $('#gsft_main').on('load', function() { $doc = $(this.contentWindow.document); $doc.on('drop', function(event) { event.preventDefault(); CustomEvent.fireTop(GlideEvent.NAV_DRAGGING_BOOKMARK_STOP); }); $doc.on('dragstart', 'a, button, img', function(event) { onFavoriteDragStart(event, this); }); $doc.on('dragend', 'a, button, img', function(event) { CustomEvent.fireTop(GlideEvent.NAV_DRAGGING_BOOKMARK_STOP); }); $win = $(this.contentWindow).on('unload', function() { $doc.off(); $doc.unbind(); $doc = null; $win.off(); $win.unbind(); $win = null; }); }); var onFavoriteDragStart = function(event, elem) { var $elem = $(elem); var container; if ($elem.hasClass('sn-breadcrumb-filter')) { container = $elem.parents('.breadcrumb-container'); setBreadcrumb(event, $elem, container, 'sn-breadcrumb-filter'); } else if ($elem.hasClass('breadcrumb_link')) { container = $elem.parents('.breadcrumb_container'); setBreadcrumb(event, $elem, container, 'breadcrumb_link'); } else if ($elem.hasClass('breadcrumb') && $elem.attr('name') == 'breadcrumb') { event.originalEvent.dataTransfer.setData(TEXT, JSON.stringify({ icon: 'book', url: $elem.attr('href'), table: table, title: table + ": " + $elem.text() })); } else if ($elem.hasClass('list-select-record') || $elem.hasClass('linked') || $elem.hasClass('report_link') || $elem.hasClass('kb_link') || $elem.hasClass('service_catalog')) { event.originalEvent.dataTransfer.setData(TEXT, JSON.stringify({ icon: 'form', url: $elem.attr('href').replace(/.*nav_to.do\?uri=/i, ''), title: $elem.text() })); } else { return } CustomEvent.fireTop(GlideEvent.NAV_DRAGGING_BOOKMARK_START); }; function _shouldSkip(evt) { if (!evt) { return; } var keyCode = evt.keyCode || evt.which; if (keyCode === 9) { return true; } var evtWhitelist = [1, 13, 49]; return (keyCode && evtWhitelist.indexOf(keyCode) === -1); } var setBreadcrumb = function(event, $elem, container, linkClass) { var table = container.attr('table'); var fixedQuery = container.attr('fixed_query'); var view = container.attr('view'); var filter = $elem.attr('filter'); event.originalEvent.dataTransfer.setData(TEXT, JSON.stringify({ icon: 'book', url: table + '_list.do?sysparm_query=' + (filter ? encodeURIComponent(filter) : '') + '&sysparm_fixed_query=' + (fixedQuery ? encodeURIComponent(fixedQuery) : '') + (view ? '&sysparm_view=' + view : ''), table : table, title : table + ": " + getBreadcrumbText($elem, container, linkClass) })); } var getBreadcrumbText = function($elem, container, linkClass) { var textArray = []; var links = container.find('button.' + linkClass); if (!links.length && linkClass === 'breadcrumb_link') links = container.find('a.' + linkClass); var index = links.index($elem); links.each(function(idx) { var text = $(this).find('b').text(); if (!text) { text = $(this).find('[aria-hidden=true]').text(); } if (!text) { text = $(this).text(); } textArray.push(text); if (idx == index) return false; }); return textArray.join(' > '); }; $('.magellan_navigator').on('keydown', function(evt) { if (evt.keyCode >= 35 && evt.keyCode <= 40) { var focused = $(document.activeElement); var nav = focused.parents('.magellan_navigator'); if (nav.length) { var isLeft = evt.keyCode == 37; var isRight = evt.keyCode == 39; var isHome = evt.keyCode == 36; var isEnd = evt.keyCode == 35; var isUp = evt.keyCode == 38; var isDown = evt.keyCode == 40; if (focused.is('#filter') && !isDown) return; evt.preventDefault(); var list = $('#filter, #magellan_tablist a:visible, #gsft_nav a:visible, #gsft_nav button:visible'); var highlight = $('#gsft_nav a:focus, #gsft_nav a.state-active'); var index, next; if (highlight && highlight.length) { index = list.index(highlight); highlight.removeClass('state-active'); } if (typeof index == 'undefined' || index == -1) { index = list.index(focused); } if (isDown) { next = getFirstNavigableElement(list, index + 1, false); if (next) next.focus(); else if (highlight && !highlight.is(focused)) highlight.focus(); } else if (isUp) { next = getFirstNavigableElement(list, index - 1, true); if (next && index !== 0) next.focus(); else if (highlight && !highlight.is(focused)) highlight.focus(); } if (!window.g_accessibility) return; if (isHome) { $(list[0]).focus(); return; } else if (isEnd) { next = getLastNavigableElement(list); if (next) next.focus(); return; } var isExpandable = focused.is('.app-node, .nav-expandable, .expandable'); var isExpanded = focused.attr('aria-expanded') == 'true'; if (isExpandable) { if ((!isExpanded && isRight) || (isExpanded && isLeft)) focused.click(); else if (isRight && isExpanded) { next = getFirstNavigableElement(list, index + 1, false); if (next) next.focus(); } else if (isLeft && !isExpanded) { next = getFirstNavigableParent(list, index); if (next) next.focus(); } } else if (isLeft) { next = getFirstNavigableParent(list, index); if (next) next.focus(); } } } }); $('.magellan_navigator').on('dblclick', '.allApps.state-active', function() { var openList = $('#gsft_nav').find('.nav-application-tree > .sn-widget > .collapse.in'); var el = $('#concourse_application_tree')[0]; var scope = angular.element(el).scope(); if (openList.length) { scope.closeAllApplications().then(function() { openList.collapse('hide'); }); } else { scope.renderAllApplications().then(function() { var appsList = $('#gsft_nav').find('.nav-application-tree > .sn-widget > .collapse'); appsList.collapse('show'); }); } }); $('.magellan_navigator').on('click keypress', '.nav-favorite-module', function(evt) { if (_shouldSkip(evt)) { return; } evt.preventDefault(); evt.stopPropagation(); var $this = $(this); var id = $this.data('id'); if (id) { if ($this.hasClass('icon-star-empty')) { setFavorite($this, true); $this.parent().addClass('state-overwrite'); $.ajax({ url : '/api/now/ui/favorite/module', type : 'POST', contentType : 'application/json', headers : { Accept : 'application/json' }, data : JSON.stringify({'id' : id}) }).done(function(response) { if (response && response.result && response.result.favorite) { CustomEvent.fireAll('magellanNavigator:favoriteSaved', response.result.favorite); } }); } else { $this.parent().removeClass('state-overwrite'); $.ajax({ url : '/api/now/ui/favorite/module?id=' + id, type : 'DELETE', contentType : 'application/json', headers : { Accept : 'application/json' } }).done(function() { CustomEvent.fireAll('magellanNavigator:favoriteModuleRemoved', id); setFavorite($('[data-id=' + id + '].nav-favorite-module'), false); }) } } }); $('.magellan_navigator').on('click keypress', '.nav-favorite-app', function(evt) { if (_shouldSkip(evt)) { return; } evt.preventDefault(); evt.stopPropagation(); var $this = $(this); if ($this.hasClass('icon-star-empty')) { var id = $this.data('id'); var title = $this.data('favorite-title'); $this.addClass('state-overwrite'); if (id && title) { setFavorite($this, true); var modules = $this.parents('li').find('.nav-favorite-module'); setFavorite(modules, true); $.ajax({ url : '/api/now/ui/favorite/application', type : 'POST', contentType : 'application/json', headers : { Accept : 'application/json' }, data : JSON.stringify({'application' : id, 'title' : title}) }).done(function(response) { if (response && response.result && response.result.group) { CustomEvent.fireAll('magellanNavigator:favoriteGroupSaved', response.result.group); } }); } } else { var id = $this.data('id'); $this.removeClass('state-overwrite'); if (id) { $.ajax({ url : '/api/now/ui/favorite/application?id=' + id, type : 'DELETE', contentType : 'application/json', headers : { Accept : 'application/json' } }).done(function() { CustomEvent.fireAll('magellanNavigator:favoriteGroupRemoved', id); CustomEvent.fireAll('magellanNavigator:unstarFavoritedGroup', id); }); } } }); $('.magellan_navigator').on('click keypress', '.nav-edit-app', function(evt) { if (_shouldSkip(evt)) { return; } evt.preventDefault(); evt.stopPropagation(); var id = $(this).data('id'); window.open('/sys_app_application.do?sysparm_clear_stack=true&sys_id=' + id, 'gsft_main'); }); $('.magellan_navigator').on('click keypress', '.nav-edit-module', function(evt) { if (_shouldSkip(evt)) { return; } evt.preventDefault(); evt.stopPropagation(); var id = $(this).data('id'); window.open('/sys_app_module.do?sysparm_clear_stack=true&sys_id=' + id, 'gsft_main'); }); CustomEvent.observe('magellanNavigator:unstarFavoritedGroup', function(id) { var app = $('[data-id=' + id + '].nav-favorite-app'); setFavorite(app, false); var modules = app.parents('li').find('.nav-favorite-module'); setFavorite(modules, false); }); CustomEvent.observe('magellanNavigator:favoriteSaved', function(favorite) { if (favorite && favorite.module) { var module = $('[data-id=' + favorite.module + '].nav-favorite-module'); setFavorite(module, true); } }); CustomEvent.observe('magellanNavigator:favoritedModuleRemoved', function(favorite) { if (favorite && favorite.module) { var module = $('[data-id=' + favorite.module + '].nav-favorite-module'); setFavorite(module, false); } }); CustomEvent.observe('magellan_EditMode.change', function(mode) { if (mode) { $('.navpage-layout').addClass('magellan-edit-mode'); setTimeout(function() { var editFavorites = $('#nav_edit_favorites_hidden'); var takeover = $('<div id="nav_edit_favorites_takeover" role="main" aria-labelledby="nav_edit_favorites_title">'); takeover.css({'left' : '-100%'}); takeover.append(editFavorites.children().detach()); $('body').append(takeover); $('main').css('visibility', 'hidden'); $('.navpage-right').css('display', 'none'); takeover.velocity({'left' : '0'}, { easing : 'easeInQuad', complete : function() { $('#favorite-title').focus(); } }); }, 400); } else { $('main').css('visibility', 'visible'); $('.navpage-right').css('display', 'block'); var takeover = $('#nav_edit_favorites_takeover'); if (takeover.length) { takeover.velocity({'left' : '-100%'}, { easing : 'easeOutQuad', complete : function() { $('#nav_edit_favorites_hidden').append(takeover.children().detach()); takeover.remove(); $('[aria-controls="nav_edit_favorites"]').focus(); } }); } setTimeout(function() { $('.navpage-layout').removeClass('magellan-edit-mode'); }, 400); } }); function setFavorite($el, isFavorite) { var favoriteTitle = ": " + $el.attr('data-favorite-title') if (isFavorite) { $el.addClass('state-overwrite'); $el.removeClass('icon-star-empty') .addClass('icon-star') .attr({ 'data-dynamic-title': MESSAGES.remove_from_favorites, 'aria-label': MESSAGES.remove_from_favorites + favoriteTitle }); } else { $el.removeClass('state-overwrite'); $el.removeClass('icon-star') .addClass('icon-star-empty') .attr({ 'data-dynamic-title': MESSAGES.add_to_favorites, 'aria-label': MESSAGES.add_to_favorites + favoriteTitle }); } $el.attr('aria-pressed', isFavorite); } function getFirstNavigableElement(list, start, reverse) { var selector = '#filter, a.sn-widget-list-item, button.sn-aside-group-title:not(.app-node, .expandable), a.state-active'; if (window.g_accessibility) selector += ", a.sn-aside-group-title_nav, button.sn-aside-group-title_nav"; if (!reverse) { for (var index = start; index < list.length; index++) { var el = list.get(index); if ($(el).is(selector)) return el; }; } else { for (var index = start; index >= 0; index--) { var el = list.get(index); if ($(el).is(selector)) return el; }; } } function getLastNavigableElement(list) { var selector = '#filter, a.sn-widget-list-item, .app-node, .expandable, .nav-expandable'; for (var index = (list.length - 1); index >= 0; index--) { var el = list.get(index); if ($(el).is(selector)) return el; }; } function getFirstNavigableParent(list, start, reverse) { var el = list.get(start); if ($(el).is('.app-node')) return list.get(0); if ($(el).is('.nav-expandable, .expandable')) { for (var index = (start - 1); index >= 0; index--) { var el = list.get(index); if ($(el).is('.app-node')) return el; }; } for (var index = start - 1; index >= 0; index--) { var el = list.get(index); if ($(el).is('.app-node, .nav-expandable, .expandable')) return el; }; } window.top.Magellan = (function() { this.favorite = (function() { var current; return { current : current }; })(); return this; }).call(window.top.Magellan); }); ; /*! RESOURCE: /scripts/app.magellan/app.js */ angular.module('Magellan', ['sn.base', 'sn.common', 'sn.dragdrop','sn.timeAgo','heisenberg','ng.shims.placeholder', 'Magellan.createFavorite']) .constant('VIEW_NAMES', { History:'history', AllApps: 'allApps', Favorites: 'favorites', Filtered: 'filtered' }).config([ '$locationProvider', function($locationProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false, rewriteLinks: false }); }]).config(['$compileProvider', function($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|javascript):/); }]); ; /*! RESOURCE: /scripts/app.magellan/factory.magellan_Endpoint.js */ angular.module('Magellan').factory('magellan_Endpoint', function($http){ return { Navigator: { getApplications: function() { var url = '/api/now/ui/navigator'; return $http.get(url).then(function(response) { if ((!response.data || !response.data.result) && response.status === 202) { return $http.get(url).then(function(response) { return response.data.result; }); } return response.data.result; }); }, getApplicationsAndFavorites: function() { var url = '/api/now/ui/navigator/favorites'; return $http.get(url).then(function(response) { if ((!response.data || !response.data.result) && response.status === 202) { return $http.get(url).then(function(response) { return response.data.result; }); } return response.data.result; }); } }, Favorites: { create: function(favorite) { return $http.post('/api/now/ui/favorite', favorite).then(function(response) { return response.data.result; }); }, get: function(){ return $http.get('/api/now/ui/favorite').then(function(response){ return response.data.result; }); }, remove: function(id, group) { return $http.delete('/api/now/ui/favorite?id=' + id + '&group=' + group).then(function(response) { }); } }, Groups: { update: function(favoritesList) { return $http.put('/api/now/ui/favorite/multiple', {'favorites' : favoritesList}).then(function(response) { return response; }); } }, NavigatorHistory: { getHistory: function() { return $http.get('/api/now/ui/history').then(function(response) { return response; }); }, create: function() { return $http.post('/api/now/ui/history').then(function(response) { return response; }); } } }; }); ; /*! RESOURCE: /scripts/app.magellan/factory.magellan_FavoritesList.js */ angular.module('Magellan').factory('magellan_FavoritesList', ['$rootScope', '$q', 'magellan_Endpoint', 'snCustomEvent', 'glideUrlBuilder', 'urlTools', function($rootScope, $q, magellan_Endpoint, snCustomEvent, glideUrlBuilder, urlTools) { var favoritesList = []; var currentFavorite; function Favorite(favorite) { var favoriteUrl = buildFavoritesURL(favorite); var urlRelationships = getUrlRelationships(favoriteUrl); return { id : favorite.id, order : favorite.order, title : favorite.title, type : favorite.type, table : favorite.table, targetSysId : favorite.targetSysId, color : favorite.color, group : favorite.group, image : favorite.image, icon : favorite.icon, flyout : favorite.flyout, url : favoriteUrl, urlRelationships: urlRelationships, filtered : favorite.filtered, applicationId : favorite.applicationId, favorites : buildFavoritesList(favorite.favorites), open : favorite.open, windowName : favorite.windowName, module : favorite.module, separator : favorite.separator }; } function buildFavoritesList(favorites) { if (favorites && favorites.length > 0) { var list = []; for (var i = 0; i < favorites.length; i++) { var favorite = favorites[i]; if(!favorite.icon && !favorite.separator) favorite.icon = "article-document"; if(!favorite.color && !favorite.separator) favorite.color = "normal"; var favObj = new Favorite(favorite); list.push(favObj); if (favObj.separator && !favObj.title) { list.push.apply(list, favObj.favorites); favObj.favorites = []; } } return list; } return []; } function buildFavoritesURL(favorite) { if (typeof favorite === 'undefined') return; if (favorite.type !== 'LIST') return favorite.url; var url = glideUrlBuilder.newGlideUrl(favorite.url); url.encode = false; url.addParam('sysparm_clear_stack', 'true'); return url.getURL(); } function getUrlRelationships(url) { return url && urlTools.isUrlExternal(url) ? 'noopener noreferrer' : null; } function filter(filterText) { var i, j, k, list, subList, showParent, showSeparator; if (typeof filterText === 'undefined' || filterText.length === 0) { clearFiltered(); return false; } filterText = filterText.toLowerCase(); for (i = 0; i < favoritesList.length; i++) { if (hasText(favoritesList[i], filterText)) { showListSection(favoritesList[i]); } else { favoritesList[i].filtered = true; showParent = false; if (favoritesList[i].favorites && favoritesList[i].favorites.length) { list = favoritesList[i].favorites; for (j = 0; j < list.length; j++) { if (hasText(list[j], filterText)) { showListSection(list[j]); showParent = true; } else { list[j].filtered = true; showSeparator = false; if (list[j].favorites && list[j].favorites.length) { subList = list[j].favorites; for (k = 0; k < subList.length; k++) { if (hasText(subList[k], filterText)) { showListSection(subList[k]); showParent = true; showSeparator = true; } else { subList[k].filtered = true; } } if (showSeparator) { list[j].filtered = false; } } } } if (showParent) { favoritesList[i].filtered = false; } } } } return true; } function showListSection(favorite) { if (typeof favorite === 'undefined') { return; } var i, j, sublist, list; favorite.filtered = false; if (favorite.favorites && favorite.favorites.length) { list = favorite.favorites; for (i = 0; i < list.length; i++) { list[i].filtered = false; if (list[i].favorites && list[i].favorites.length) { subList = list[i].favorites; for (j = 0; j < subList.length; j++) { subList[j].filtered = false; } } } } } function hasText(favorite, filterText) { return favorite.title && favorite.title.toLowerCase().indexOf(filterText) != -1; } function clearFiltered() { for (var i = 0; i < favoritesList.length; i++) { favoritesList[i].filtered = undefined; if (favoritesList[i].favorites && favoritesList[i].favorites.length) { var list = favoritesList[i].favorites; for (var j = 0; j < list.length; j++) { list[j].filtered = undefined; if (list[j].favorites && list[j].favorites.length) { var subList = list[j].favorites; for (var k = 0; k < subList.length; k++) { subList[k].filtered = undefined; } } } } } } function loadData() { var deferred = $q.defer(); magellan_Endpoint.Favorites.get().then(function(result) { populate(result.list); deferred.resolve(); }, function() { deferred.reject(); }); return deferred.promise; } function populate(favorites) { window.NOW = window.NOW || {}; window.NOW.favoritesList = buildFavoritesList(favorites); favoritesList = buildFavoritesList(favorites); if (favoritesList) { currentFavorite = favoritesList[0]; } else { currentFavorite = {}; } if (window.top && window.top.Magellan && window.top.Magellan.favorite) { window.top.Magellan.current = favoritesList; } $rootScope.$emit('magellan_FavoritesList.change', favoritesList); snCustomEvent.fireAll('magellan_FavoritesList.change', favoritesList); } function update(favorites) { magellan_Endpoint.Groups.update(favorites).then(function(result) { populate(favorites); }); } function add(favorite) { magellan_Endpoint.Favorites.create(favorite).then(function(result) { snCustomEvent.fireAll('magellanNavigator:favoriteSaved', new Favorite(result.favorite)); }); } snCustomEvent.observe('magellanNavigator:createFavorite', function(favorite) { add(favorite); }); snCustomEvent.observe('magellanNavigator:favoriteSaved', function(favorite) { addFavorite(new Favorite(favorite)); }); snCustomEvent.observe('magellanNavigator:favoriteGroupSaved', function(favorite) { addFavorite(new Favorite(favorite)); }); snCustomEvent.observe('magellanNavigator:favoriteGroupRemoved', function(id) { for (var i = 0; i < favoritesList.length; i++) { if (favoritesList[i].applicationId && favoritesList[i].applicationId == id) { removeModulesFromList(favoritesList[i]); break; } } for (i = 0; i < favoritesList.length; i++) { if (favoritesList[i].applicationId && favoritesList[i].applicationId == id) { favoritesList.splice(i, 1); populate(favoritesList); return; } } }); snCustomEvent.observe('magellanNavigator:favoriteModuleRemoved', function(id) { var removing = true; while (removing) { removing = removeModule(id); } }); snCustomEvent.observe('magellanNavigator:favoriteRemoved', function(id) { var removing = true; while (removing) { removing = removeID(id); } }); function removeID(id) { return removeFavorite('id', id); } function removeModule(id) { return removeFavorite('module', id); } function removeFavorite(prop, id) { for (var i = 0; i < favoritesList.length; i++) { if (favoritesList[i][prop] && favoritesList[i][prop] == id) { favoritesList.splice(i, 1); populate(favoritesList); return true; } if (favoritesList[i].favorites && favoritesList[i].favorites.length) { var list = favoritesList[i].favorites; for (var j = 0; j < list.length; j++) { if (list[j][prop] && list[j][prop] == id) { list.splice(j, 1); populate(favoritesList); return true; } if (list[j].favorites && list[j].favorites.length) { var subList = list[j].favorites; for (var k = 0; k < subList.length; k++) { if (subList[k][prop] && subList[k][prop] == id) { subList.splice(k, 1); populate(favoritesList); return true; } } } } } } return false; } function getByUrl(url) { var list = favoritesList; for (var i = 0; i < list.length; i++) { if (list[i].url == url) { return list[i]; } } } function getByTableTargetAndType(params) { var list = favoritesList; for (var i = 0; i < list.length; i++) { if (list[i].table == params.table && list[i].targetSysId == params.targetSysId && list[i].type == params.type) { return list[i]; } } } function remove(favorite) { var deferred = $q.defer(); if (favorite.group && favorite.applicationId) { snCustomEvent.fireAll('magellanNavigator:unstarFavoritedGroup', favorite.applicationId); } if (favorite.module) { snCustomEvent.fireAll('magellanNavigator:favoritedModuleRemoved', favorite); } snCustomEvent.fireAll('magellanNavigator:favoriteRemoved', favorite.id); magellan_Endpoint.Favorites.remove(favorite.id, favorite.group).then(function() { removeFavoriteFromList(favorite); populate(favoritesList); deferred.resolve(); }, function() { deferred.reject(); }); return deferred.promise; } function addFavorite(favorite) { var i; if (!favorite.id) { return; } var list = favoritesList; for (i = 0; i < list.length; i++) { if (list[i].id == favorite.id) { list[i] = new Favorite(favorite); populate(list); return; } if (list[i].favorites) { for (var j = 0; j < list[i].favorites.length; j++) { if (list[i].favorites[j].id == favorite.id) { list[i].favorites[j] = new Favorite(favorite); populate(list); return; } } } } list.push(new Favorite(favorite)); populate(list); } function removeFavoriteFromList(favorite) { if (favorite && favorite.id) { removeFavorite('id', favorite.id); } } function removeModulesFromList(favorite) { var removing; if (favorite && favorite.favorites) { var list = favorite.favorites; for (var i = 0; i < list.length; i++) { removing = true; while (removing) { removing = removeModule(list[i].module); } } } } function setOpen(id) { var f = findFavoriteById(id); if (f) { f.open = true; } } function setClosed(id) { var f = findFavoriteById(id); if (f) { f.open = false; } } function findFavoriteById(id) { var list = favoritesList; for (var i = 0; i < list.length; i++) { if (list[i].id == id) { return list[i]; } if (list[i].favorites) { for (var j = 0; j < list[i].favorites.length; j++) { if (list[i].favorites[j].id == id) { return list[i].favorites[j]; } if (list[i].favorites[j].favorites && list[i].favorites[j].favorites.length) { var subList = list[i].favorites[j].favorites; for (var k = 0; k < subList.length; k++) { if (subList[k].id == id) { return subList[k]; } } } } } } } return { getByUrl : getByUrl, getByTableTargetAndType : getByTableTargetAndType, add : add, update : update, remove : remove, loadData : loadData, filter : filter, populate : populate, setOpen : setOpen, setClosed : setClosed, get favoritesList() { return favoritesList; }, currentFavorite : currentFavorite }; }]); ; /*! RESOURCE: /scripts/app.magellan/factory.magellan_Permalink.js */ angular.module('Magellan').factory('magellan_Permalink', ['snCustomEvent', '$location', '$timeout', function(snCustomEvent, $location, $timeout) { return { init: function(){ var originalTitle, formattedTitle; var setLocation = function(obj){ if (typeof obj.relativePath == 'string' && obj.relativePath != '') $timeout(function(){ $location.path('nav_to.do').search({ uri: obj.relativePath.replace(/%2F/gi, '/') }).replace(); }, 10); setTitle(obj.title); }; var setTitle = function(title){ if (typeof title == 'string' && title != '' && title != originalTitle) { if (title.indexOf(formattedTitle) == -1) title += formattedTitle; document.title = title; } else document.title = originalTitle; }; var initTitle = function(title){ originalTitle = title; formattedTitle = ' | ' + title; }; initTitle(document.title); snCustomEvent.observe('magellanNavigator.permalink.set', function(obj) { if (obj) setLocation(obj); }); snCustomEvent.observe('glide.product.name', function(value) { if (typeof value === "undefined" || value == "") value = 'ServiceNow'; initTitle(value); setTitle(value); }); } }; }]); ; /*! RESOURCE: /scripts/app.magellan/factory.magellan_HistoryList.js */ angular.module('Magellan').factory('magellan_HistoryList', ['snCustomEvent', '$rootScope', 'glideUrlBuilder', function(snCustomEvent, $rootScope, glideUrlBuilder) { var historyList = []; function NavigatorHistory(history) { this.id = history.id; this.title = history.title; this.targetSysId = history.targetSysId; this.table = history.table; this.url = history.url; this.prettyTitle = history.prettyTitle; this.description = history.description; this.createdString = history.createdString; this.timestamp = history.timestamp; this.timestampOffset = history.timestampOffset; } NavigatorHistory.prototype.getCreatedDate = function() { return new Date(this.timestamp).getTime(); }; function populate(list) { historyList = []; for (var i = 0; i < list.length; i++) { historyList.push(new NavigatorHistory(list[i])); } } function add(history) { removeDuplicates(history); historyList.unshift(new NavigatorHistory(history)); $rootScope.$broadcast('magellan_HistoryList.change', historyList); } function removeDuplicates(history) { if (history.timestampOffset) { for (var i = 0; i < historyList.length; i++) { var compare = historyList[i]; if (compare.timestamp > history.timestampOffset) { if (sameUrl(compare.url, history.url)) { historyList.splice(i, 1); } } else { break; } } } } function sameUrl(a, b) { var blacklist; if (typeof a !== 'string' || typeof b !== 'string') { return false; } a = a.replace('/', ''); b = b.replace('/', ''); if (window.top && window.top.Magellan && window.top.Magellan.globals && window.top.Magellan.globals.paramBlacklist) { blacklist = window.top.Magellan.globals.paramBlacklist; } if (blacklist) { var urlA = glideUrlBuilder.newGlideUrl(a); var urlB = glideUrlBuilder.newGlideUrl(b); var keys = Object.keys(jQuery.extend({}, urlA.getParams(), urlB.getParams())); for (var i = 0; i < keys.length; i++) { key = keys[i]; if (blacklist && blacklist.indexOf(key) != -1) { continue; } if (urlA.getParam(key) == urlB.getParam(key)) { continue; } return false; } return urlA.contextPath === urlB.contextPath; } else { return a === b; } } snCustomEvent.observe('magellanNavigator.historyAdded', function(data) { add(data.history); }); return { get historyList() { return historyList; }, populate : populate, add : add }; }]); ; /*! RESOURCE: /scripts/app.magellan/controller.MagellanCtrl.js */ angular.module('Magellan').controller('MagellanCtrl', function( $scope, $rootScope, $element, i18n, magellan_Endpoint, magellan_FavoritesList, magellan_HistoryList, $timeout, snCustomEvent, userPreferences, VIEW_NAMES, keyboardRegistry, magellan_Permalink, $animate, snTabActivity, concourseNavigatorService ) { 'use strict'; snTabActivity.setAppName("magellan"); $animate.enabled($element, false); magellan_Permalink.init(); var ActiveViewPrefKey = 'navigator.activeView'; var CollapsedNavPrefKey = 'navigator.collapsed'; var animatingEditPane = false; $scope.views = [ { viewName: VIEW_NAMES.AllApps, icon: "icon-all-apps", title: i18n.getMessage("All applications"), isEnabled: true }, { viewName: VIEW_NAMES.Favorites, icon: "icon-star", title: i18n.getMessage("Favorites"), isEnabled: true }, { viewName: VIEW_NAMES.History, icon: "icon-history", title: i18n.getMessage("Your history"), isEnabled: true, isActive: false } ]; $scope.navigatorLoaded = false; $scope.editMode = false; $scope.isCollapsed = false; $scope.filterText = ''; $scope.defaultView = loadDefaultView(); $scope.isAccessibilityEnabled = window.g_accessibility; $scope.data = { isLoading: true, favoritesList: magellan_FavoritesList.favoritesList, currentFavorite: magellan_FavoritesList.currentFavorite, historyList : magellan_HistoryList.historyList }; $scope.changeActiveView = function(viewName, applyFocus) { angular.element("#"+$scope.activeView+"_tab").attr('tabindex', -1); $scope.activeView = viewName; if (applyFocus) { angular.element("#"+$scope.activeView+"_tab").attr('tabindex', 0).focus(); } $scope.filterTextValue('', false); if ([VIEW_NAMES.AllApps, VIEW_NAMES.Favorites].indexOf(viewName) != -1) userPreferences.setPreference('navigator.activeView', viewName); }; $scope.keyChangeActiveView = function(e) { if (!(e.keyCode == 39 || e.keyCode == 37)) return; e.preventDefault(); for (var i = 0; i < $scope.views.length; i++) { if ($scope.views[i].viewName == $scope.activeView) { if (e.keyCode == 39) $scope.changeActiveView($scope.views[(i+1) % $scope.views.length].viewName, true); else if (e.keyCode == 37) $scope.changeActiveView($scope.views[(i-1 + $scope.views.length) % $scope.views.length].viewName, true); return; } } } $scope.navigate = function(url, target){ if (url) { if (target && target != 'gsft_main') { window.open(url, target); } else { jQuery('#gsft_main').attr('src', url); snCustomEvent.fire("glide:nav_open_url", { url: url, openInForm: false }); } } }; $scope.clearFilterText = function() { $scope.filterTextValue(''); $scope.focusFilter(); }; $scope.toggleCollapse = function(toggleBodyClass, collapsed){ if (!$scope.editMode) { if (typeof collapsed !== 'undefined') { $scope.isCollapsed = collapsed; } else { $scope.isCollapsed = !$scope.isCollapsed; } if ($scope.isCollapsed == true) userPreferences.setPreference('navigator.collapsed', "yes"); else userPreferences.setPreference('navigator.collapsed', "no"); if (toggleBodyClass) jQuery('#nav_west_north, #nav_west_center').hide(); jQuery('.navpage-layout').toggleClass('navpage-nav-collapsed'); $timeout(function() { jQuery('#nav_west_north, #nav_west_center').fadeIn(400); }, 200); if ($scope.isCollapsed) { $scope.preservedView = $scope.activeView; $scope.changeActiveView(VIEW_NAMES.Favorites, true); jQuery(document).trigger('nav.collapsed'); } else{ $scope.activeView = "allApps"; jQuery(document).trigger('nav.expanding'); $timeout(function() { if (angular.isDefined($scope.preservedView)) { $scope.changeActiveView($scope.preservedView, false); } jQuery(document).trigger('nav.expanded'); }, 350); } } }; $scope.openNavigator = function(toggleBodyClass) { if ($scope.isCollapsed && !$scope.editMode) { $scope.toggleCollapse(toggleBodyClass, false); } }; snCustomEvent.on('magellan_collapse.toggle', function() { $scope.toggleCollapse(true); }); $scope.setNavigatingState = function(state) { top.NOW.magellan && top.NOW.magellan.setNavigatingState && top.NOW.magellan.setNavigatingState(state); }; concourseNavigatorService.onChangeVisibility(function() { $timeout(function() { filterFavorites(); }); }); loadData(); function loadData(){ magellan_Endpoint.Navigator.getApplicationsAndFavorites().then(function(result) { concourseNavigatorService.applications = result.applications; if (result.favorites) { magellan_FavoritesList.populate(result.favorites); $scope.data.favoritesList = magellan_FavoritesList.favoritesList; $scope.data.currentFavorite = magellan_FavoritesList.currentFavorite; } if (result.history) { magellan_HistoryList.populate(result.history); $scope.data.historyList = magellan_HistoryList.historyList; } $scope.data.isLoading = false; filterFavorites(); toggleNavPaneVisibility(result.applications); }); } snCustomEvent.on('navigator.refresh', function() { loadData(); }); function filterFavorites() { magellan_FavoritesList.filter($scope.filterText); render(); } function render() { $scope.data.favoritesList = magellan_FavoritesList.favoritesList; if ($scope.filterText !== '') { $scope.activeView = VIEW_NAMES.Filtered; jQuery('#gsft_nav .nav-favorites-list .collapse').addClass("in").css("height", "auto"); } else { if ($scope.activeView == VIEW_NAMES.Filtered) { $scope.activeView = $scope.defaultView; } } } function loadDefaultView(){ userPreferences.getPreference(ActiveViewPrefKey).then(function(resp) { if (resp && resp != '' && resp != 'null') $scope.defaultView = resp; }); userPreferences.getPreference(CollapsedNavPrefKey).then(function(resp) { if (resp && resp != '' && resp != 'null') { if(resp == "yes") $scope.toggleCollapse(true); } }); return VIEW_NAMES.AllApps; } $scope.focusFilter = function(){ if ($scope.isCollapsed) { $scope.toggleCollapse(true); $timeout(function(){ angular.element('#filter').focus(); },400); } else { $timeout(function(){ angular.element('#filter').focus(); }); } }; $scope.toggleEditMode = function() { if (animatingEditPane) { return; } animatingEditPane = true; setTimeout(function() { animatingEditPane = false; }, 410); if($scope.editMode) { magellan_FavoritesList.update($scope.data.favoritesList); $scope.changeActiveView($scope.currentActiveView, true); } else { $scope.currentActiveView = $scope.activeView; $scope.changeActiveView('favorites', true); } $scope.editMode = !$scope.editMode; $rootScope.$broadcast('magellan_EditMode.change', $scope.editMode); snCustomEvent.fireAll('magellan_EditMode.change', $scope.editMode); }; $rootScope.$on('magellan_closeEditFavorites', function() { $scope.editMode = false; $rootScope.$broadcast('magellan_EditMode.change', $scope.editMode); snCustomEvent.fireAll('magellan_EditMode.change', $scope.editMode); }); $rootScope.$on('magellan_FavoritesList.change', function() { if(!$scope.$$phase) { $scope.$apply(render()); } }); $rootScope.$on('magellan_HistoryList.change', function() { if(!$scope.$$phase) { $scope.$apply(render()); } }); function _applyUtil($scope, f) { if (!$scope.$$phase) { $scope.$apply(f); } else { f(); } } $rootScope.$on('applicationTree.rendered', function() { if (!$scope.navigatorLoaded) { _applyUtil($scope, function () { $scope.navigatorLoaded = true; $scope.activeView = $scope.defaultView; snCustomEvent.fire('nav.loaded'); }); } }); $scope.$on('nav.toggleCollapse', function() { if (jQuery('.navpage-layout').hasClass('navpage-nav-collapsed')){ $scope.$apply(function(){ $scope.toggleCollapse(false); }) } }); function toggleNavPaneVisibility(applications) { if (applications.length === 0) $scope.$emit('nav.emptyNav'); else $scope.$emit('nav.notEmptyNav'); } $scope.$on('nav.emptyNav', function() { angular.element('.navpage-layout').addClass('navpage-nav-hidden'); }); $scope.$on('nav.notEmptyNav', function() { angular.element('.navpage-layout').removeClass('navpage-nav-hidden'); }) }); ; /*! RESOURCE: /scripts/app.magellan/directive.magellanFavoritesList.js */ angular.module('Magellan').directive('magellanFavoritesList', ['getTemplateUrl', '$timeout', 'snCustomEvent', 'userPreferences', 'magellan_FavoritesList', 'i18n', function(getTemplateUrl, $timeout, snCustomEvent, userPreferences, magellan_FavoritesList, i18n) { return { restrict: 'E', templateUrl: getTemplateUrl('magellan_favorites_list.xml'), scope: { currentFavorite : '=', favoritesList : '=', isLoading: '=', editMode : '=', isCollapsed : '=', activeView : '=' }, controller: function($scope, $rootScope, $element) { var messages = { up: 'Item moved up', down: 'Item moved down', top: 'Item moved to top', bottom: 'Item moved to bottom' }; i18n.getMessages([ messages.up, messages.down, messages.top, messages.bottom ], function(translations) { for (var key in messages) { var messageToTranslate = messages[key]; messages[key] = translations[messageToTranslate]; } }); $scope.remove = function(favorite, evt) { var key = favorite.group ? 'Group of Favorites Removed: {0}' : 'Favorite Removed: {0}'; $scope.ariaMessageFavoriteRemoved = i18n.format(i18n.getMessage(key), favorite.title); var $elem = angular.element(evt.target); if ($elem.data('bs.tooltip')) $elem.tooltip('destroy'); magellan_FavoritesList.remove(favorite); if (typeof evt != 'undefined') { evt.preventDefault(); } var favoriteTab = angular.element('#favorites_tab'); if (favoriteTab.hasClass('state-active')) { favoriteTab.focus(); } else { var input = angular.element('#filter'); input.focus(); } } $scope.sortableOptions = { disabled : true, axis: 'y' }; $scope.updateCurrentFavorite = function(favorite) { if (favorite.separator) return; $scope.currentFavorite = favorite; $rootScope.$broadcast('currentFavorite.changed'); }; $scope.checkEditMode = function($event) { if ($scope.editMode) { $event.preventDefault(); } }; $scope.favoriteFiltered = function() { if ($scope.activeView !== 'filtered') { return false; } var favFiltered = false; $scope.favoritesList.forEach(function(fav) { if (fav.filtered === false) { favFiltered = true; } }); return favFiltered; } $rootScope.$on('magellan_FavoritesList.change', function(evt, list) { $scope.favoritesList = list; }); $rootScope.$on('magellan_EditMode.change', function(evt, mode) { $scope.sortableOptions.disabled = !mode; }); var deactivateKeyboardReorderPromise = null; $scope.onDragHandleBlur = function() { $scope.focusFavorite = null; deactivateKeyboardReorderPromise = $timeout(function() { $scope.isKeyboardReorderActive = false; }, 0); }; function activateKeyboardReorder() { if (deactivateKeyboardReorderPromise) { $timeout.cancel(deactivateKeyboardReorderPromise); } $scope.isKeyboardReorderActive = true; } $scope.onDragHandleFocus = function(favorite) { $scope.focusFavorite = favorite; }; $scope.onDragHandleKeydown = function($event, originIndex) { var numFavorites = $scope.favoritesList.length; if (numFavorites < 1) { return; } var keyCode = $event.keyCode; if (!$scope.isKeyboardReorderActive) { if (keyCode === 13) { activateKeyboardReorder(); } return; } if (keyCode === 27 || keyCode === 13) { $scope.isKeyboardReorderActive = false; return; } $event.preventDefault(); $event.stopPropagation(); var isUp = keyCode === 38, isDown = keyCode === 40, isFirst = originIndex === 0, lastIndex = numFavorites - 1, isLast = originIndex === lastIndex; if (!isUp && !isDown || (isFirst && isUp) || (isLast && isDown)) { return; } var destinationIndex = isUp ? originIndex - 1 : originIndex + 1, itemMoved = $scope.favoritesList[originIndex], itemDisplaced = $scope.favoritesList[destinationIndex]; $scope.favoritesList[originIndex] = itemDisplaced; $scope.favoritesList[destinationIndex] = itemMoved; if (isUp) { $scope.ariaMessageFavoriteMoved = destinationIndex === 0 ? messages.top : messages.up; } else { $scope.ariaMessageFavoriteMoved = destinationIndex === lastIndex ? messages.bottom : messages.down; } $timeout(function() { activateKeyboardReorder(); $event.target.focus(); }, 0, false); }; $scope.onDragHandleKeypress = function($event) { if ($event.keyCode === 13) { $event.preventDefault(); $event.stopPropagation(); } }; $rootScope.$on('currentFavorite.changed', function(favorite) { angular.element('#favorite-title').focus(); }); }, link : function(scope, element) { var collapsedId, expandedId; jQuery(element).on('show.bs.collapse', function(e) { $timeout(function() { var $this = jQuery(e.target).siblings('[data-sn-toggle="collapse"]'); var id = $this.data('id'); $this.addClass('expanded '); if (id && id !== expandedId) { magellan_FavoritesList.setOpen(id); userPreferences.setPreference('favorite.' + id + '.expanded', 'true'); userPreferences.setPreference('favorite.' + id + '.collapsed', ''); collapsedId = ''; expandedId = id; } }, 200); }); jQuery(element).on('hide.bs.collapse', function(e) { $timeout(function() { var $this = jQuery(e.target).siblings('[data-sn-toggle="collapse"]'); var id = $this.data('id'); $this.removeClass('expanded'); if (id && id !== collapsedId) { magellan_FavoritesList.setClosed(id); userPreferences.setPreference('favorite.' + id + '.expanded', ''); userPreferences.setPreference('favorite.' + id + '.collapsed', 'true'); expandedId = ''; collapsedId = id; } }, 200); }); scope.init = function(first, favorite) { scope.addTooltip(first); scope.updateCurrentFavorite(favorite); }; scope.addTooltip = function(first) { if (first) { $timeout(function() { jQuery(element).find('.icon').tooltip({placement: 'right', container: 'body'}); jQuery(element).find('.nav-icon').on('show.bs.tooltip', function() { if (!scope.$parent.isCollapsed) { return false; } }); }); } }; } }; }]); ; /*! RESOURCE: /scripts/app.magellan/directive.magellanEditFavorites.js */ angular.module('Magellan').directive('magellanEditFavorites', ['getTemplateUrl', 'magellan_FavoritesList', 'userPreferences', function(getTemplateUrl, magellan_FavoritesList, userPreferences) { return { restrict: 'E', templateUrl: getTemplateUrl('magellan_edit_favorites.xml'), scope : { favoritesList : '=', currentFavorite : '=' }, controller: function($scope, $rootScope) { userPreferences.getPreference('glide.ui.edit_favorites.hide_confirm').then(function(hideConfirm) { $scope.hideConfirm = hideConfirm == "true" ? true : false; }); $rootScope.$on('magellanColorPicker:colorSelected', function(evt, color) { if ($scope.currentFavorite) { if ($scope.currentFavorite.group && $scope.currentFavorite.favorites) { for (var i = 0; i < $scope.currentFavorite.favorites.length; i++) { $scope.currentFavorite.favorites[i].color = color; } } else { $scope.currentFavorite.color = color; } } }); $rootScope.$on('magellanIconPicker:iconSelected', function(evt, icon) { if ($scope.currentFavorite) { $scope.currentFavorite.icon = icon; } }); $scope.contains = function(id) { for (var i = 0; i < $scope.favoritesList; i++) { if (id == $scope.favoritesList[i].id) { return true; } } return false; }; $rootScope.$on('magellan_FavoritesList.updateFavorites', function() { $scope.updateFavorites(); }); $scope.updateFavorites = function() { magellan_FavoritesList.update($scope.favoritesList); $rootScope.$broadcast('magellan_closeEditFavorites'); }; $rootScope.$on('magellan_FavoritesList.change', function() { if (!$scope.currentFavorite || !$scope.currentFavorite.id) { $scope.currentFavorite = magellan_FavoritesList.currentFavorite; } }); $scope.removeFavorite = function() { magellan_FavoritesList.remove($scope.currentFavorite).then(function() { jQuery('.popover').popover('hide'); $scope.favoritesList = magellan_FavoritesList.favoritesList; $scope.currentFavorite = magellan_FavoritesList.currentFavorite; if (!$scope.favoritesList || $scope.favoritesList.length === 0) { $rootScope.$broadcast('magellan_closeEditFavorites'); } }); }; }, link : function(scope, element) { element.on('change', '[name=hide-confirm]', function() { var hideConfirm = angular.element(this).prop('checked'); scope.hideConfirm = hideConfirm; if (hideConfirm) { userPreferences.setPreference('glide.ui.edit_favorites.hide_confirm', 'true'); scope.removeFavorite(); } else { userPreferences.setPreference('glide.ui.edit_favorites.hide_confirm', ''); } }); } }; }]); ; /*! RESOURCE: /scripts/app.magellan/directive.magellanNavigationFilter.js */ angular.module('Magellan').directive('magellanNavigationFilter', function( $rootScope, glideUrlBuilder, $window, snCustomEvent, $timeout, concourseNavigatorService ) { return { restrict: 'A', template: '', link: function(scope, element) { var selectedIndex = 0; var selectedElement = null; var shortcutCallback = null; var collection = []; var nav = $j('#nav_west_center'); scope.filterText = ''; scope.shortcutTooltip = ''; element.on('focus', function() { $timeout(function() { element.select(); }, 10); }); scope.clearHighlight = function() { angular.element('#gsft_nav a.state-active').removeClass('state-active'); }; var _$navRoot; function _focusFirstItem() { if (!_$navRoot) { _$navRoot = $window.jQuery('#gsft_nav'); } $timeout(function() { $window.requestAnimationFrame(function() { _$navRoot.find('.state-active').removeClass('state-active'); var $visibleItems = _$navRoot.find('a.sn-widget-list-item:visible'); if ($visibleItems.length) { $visibleItems.eq(0).addClass('state-active'); } }); }, 100); } scope.filterTextValue = function(newValue, highlightFirstItem) { if (angular.isDefined(newValue)) { concourseNavigatorService.filterTerm = newValue; scope.filterText = newValue; clearShortcutPreview(); if (handleNavFilterExtension(scope.filterText)) { return; } handleShortcuts(scope.filterText); if (highlightFirstItem === undefined || highlightFirstItem) _focusFirstItem(); } return scope.filterText; }; scope.handleEnterKeypress = function($event) { if (!selectedElement) { var $selected = $window.jQuery('#gsft_nav').find('.state-active'); if ($selected.length) { selectedElement = $selected.get(0); } } if (handleEnterKeypressEvent($event)) { reset(); } handleShortcutCallback(); }; var DETECT_JAVASCRIPT = /^javascript:/; function handleEnterKeypressEvent($event) { if (!selectedElement || !selectedElement.href) { return false; } if (DETECT_JAVASCRIPT.test(selectedElement.href)) { $window.location.href = selectedElement.href; return true; } else { scope.navigate(selectedElement.href, selectedElement.getAttribute('target')); $event.preventDefault(); return true; } } function handleShortcutCallback() { if (!shortcutCallback) return; shortcutCallback(); scope.filterTextValue(''); clearShortcutPreview(); } function handleNavFilterExtension(val) { try { if (typeof $window.navFilterExtension === "function" && $window.navFilterExtension(val, msg)) return true; } catch (e) { jslog("Error in UI Script navFilterExtension - " + e); } } function handleShortcuts(filterText) { var tooltip = ''; var table = ''; shortcutCallback = null; if (filterText.length < 5) return; if (filterText.endsWith('.form')) { table = filterText.replace('.form', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open the ' + table + ' form'; shortcutCallback = function(){ scope.navigate(glideUrlBuilder.getCancelableLink(table + '.do?sys_id=-1')); }; } else if (filterText.endsWith('.list')) { table = filterText.replace('.list', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open the ' + table + ' list'; shortcutCallback = function(){ scope.navigate(glideUrlBuilder.getCancelableLink(table + '_list.do')); }; } else if (filterText.endsWith('.config')) { table = filterText.replace('.config', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open the ' + table + ' configuration'; shortcutCallback = function(){ scope.navigate(glideUrlBuilder.getCancelableLink(buildTableConfigURL(table))); }; } else if (filterText.endsWith('.filter')) { table = filterText.replace('.filter', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open an empty ' + table + ' list'; shortcutCallback = function() { scope.navigate(glideUrlBuilder.getCancelableLink(table + '_list.do?sysparm_filter_only=true')); }; } else if (filterText.endsWith('.FORM')) { table = filterText.replace('.FORM', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open the ' + table + ' form in a new window'; shortcutCallback = function(){ $window.open(glideUrlBuilder.newGlideUrl(table + '.do?sys_id=-1').getURL()); }; } else if (filterText.endsWith('.LIST')) { table = filterText.replace('.LIST', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open the ' + table + ' list in a new window'; shortcutCallback = function(){ $window.open(glideUrlBuilder.newGlideUrl(table + '_list.do').getURL()); }; } else if (filterText.endsWith('.CONFIG')) { table = filterText.replace('.CONFIG', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open the ' + table + ' configuration in a new window'; shortcutCallback = function(){ $window.open(buildTableConfigURL(table)); }; } else if (filterText.endsWith('.FILTER')) { table = filterText.replace('.FILTER', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open an empty ' + table + ' list in a new window'; shortcutCallback = function(){ $window.open(glideUrlBuilder.newGlideUrl(table + '_list.do?sysparm_filter_only=true').getURL()); }; } else if (filterText.endsWith('_list.do')) { table = filterText.replace('_list.do', '').toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open the ' + table + ' list'; shortcutCallback = function(){ scope.navigate(table + '_list.do'); }; } else if (filterText.endsWith('.do')) { var path = filterText.toLowerCase().replace(/ /g, ''); tooltip = 'Press enter to open ' + path; shortcutCallback = function(){ scope.navigate(path + "?sys_id=-1"); }; } top.NOW.magellan && top.NOW.magellan.setNavigatingState && top.NOW.magellan.setNavigatingState(true); if (tooltip != '') previewShortcut(tooltip); scope.shortcutTooltip = tooltip; scope.shortcutCallback = shortcutCallback; } function buildTableConfigURL(table){ var url = glideUrlBuilder.newGlideUrl('personalize_all.do'); url.addParam('sysparm_rules_table', table); url.addParam('sysparm_rules_label', table); return url.getURL(); } function previewShortcut(title) { var placement = document.documentElement.getAttribute('dir') == 'rtl' ? 'left' : 'right'; jQuery(element).tooltip({placement: placement, container: 'body', trigger: 'manual', title: title}).tooltip('show'); scope.isPreviewOpen = true; } function clearShortcutPreview() { if (scope.isPreviewOpen) { jQuery(element).tooltip('destroy'); scope.isPreviewOpen = false; shortcutCallback = null; } } function setSelected(index) { var element; if (index != selectedIndex) { jQuery(selectedElement).removeClass('state-active'); selectedIndex = index; selectedElement = collection[index]; element = jQuery(selectedElement); element.addClass('state-active'); } } function reset() { selectedIndex = -1; if (selectedElement) { jQuery(selectedElement).removeClass('state-active'); selectedElement = null; } collection = []; } $rootScope.$on('applicationTree.rendered', function() { reset(); if (scope.data.filteredApplications && scope.data.filteredApplications.length > 0 && scope.filterText.length > 0) { setTimeout(function() { collection = jQuery('#gsft_nav').find('a.sn-widget-list-item'); if (collection.length > 0) for (var i = 0; i < collection.length; i++) { if (collection[i].href && collection[i].href != 'javascript:void(0)') { setSelected(i); nav.scrollTop(0); break; } } }, 10); } if (scope.filterText === '') { clearShortcutPreview(); } }); jQuery('.nav-body').on('click', 'a', function() { if (jQuery(this).attr('href') != '#') { reset(); } }); } }; }); ; /*! RESOURCE: /scripts/app.magellan/directive.magellanHistoryCompact.js */ angular.module('Magellan').directive('magellanHistoryCompact', ['getTemplateUrl', 'timeAgo', '$timeout', function(getTemplateUrl, timeAgo, $timeout){ return { restrict: 'E', templateUrl: getTemplateUrl('magellan_history_compact.xml'), scope: { historyList: '=', isLoading: '=' }, controller: function($scope) { var FIVE_MIN = 15 * 60 * 1000; var interval = 1; var now = new Date().getTime(); var timestampLookup = {}; var currentTimeAgo = ""; $scope.titleCharacterLimit = 40; $scope.clearHourCount = function(index) { if (index === 0) { interval = 1; now = new Date().getTime(); timestampLookup = {}; currentTimeAgo = ""; } }; $scope.checkForHeader = function(createDate) { if (typeof timestampLookup[createDate] == 'undefined') { var diff = now - createDate; var comparitor = FIVE_MIN * interval; if (diff > comparitor && timeAgo.toWords(diff) != currentTimeAgo) { interval += 1; currentTimeAgo = timeAgo.toWords(diff); timestampLookup[createDate] = currentTimeAgo.charAt(0).toUpperCase() + currentTimeAgo.slice(1); return true; } timestampLookup[createDate] = false; return false; } else { return timestampLookup[createDate]; } }; $scope.getHourCount = function(createDate) { return timestampLookup[createDate]; }; }, link : function(scope, element) { scope.historyInit = function(index, last) { scope.clearHourCount(index); scope.addTooltip(last); }; scope.addTooltip = function(last) { if (last) { $timeout(function() { jQuery(element).find('a').tooltip({placement: 'right', container: 'body'}); jQuery(element).on('click', 'a', function(evt) { jQuery(this).tooltip('hide'); }) }) } }; } }; }]); ; /*! RESOURCE: /scripts/sn.dragdrop/_sn.dragdrop.js */ /*! RESOURCE: /scripts/sn.dragdrop/jquery-ui-dragdrop.min.js */ /*! jQuery UI - v1.11.0 - 2014-07-03 * http://jqueryui.com * Includes: core.js, widget.js, mouse.js, draggable.js, droppable.js, resizable.js, selectable.js, sortable.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,s){var a,n,o,r=t.nodeName.toLowerCase();return"area"===r?(a=t.parentNode,n=a.name,t.href&&n&&"map"===a.nodeName.toLowerCase()?(o=e("img[usemap=#"+n+"]")[0],!!o&&i(o)):!1):(/input|select|textarea|button|object/.test(r)?!t.disabled:"a"===r?t.href||s:s)&&i(t)}function i(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.0",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(){var t=this.css("position"),i="absolute"===t,s=this.parents().filter(function(){var t=e(this);return i&&"static"===t.css("position")?!1:/(auto|scroll)/.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==t&&s.length?s:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),a=isNaN(s);return(a||s>=0)&&t(i,!a)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(t,i,s,n){return e.each(a,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),n&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var a="Width"===i?["Left","Right"]:["Top","Bottom"],n=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(n,s(this,t)+"px")})},e.fn["outer"+i]=function(t,a){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(n,s(this,t,!0,a)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,a=e(this[0]);a.length&&a[0]!==document;){if(i=a.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(a.css("zIndex"),10),!isNaN(s)&&0!==s))return s;a=a.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var a,n=e.ui[t].prototype;for(a in s)n.plugins[a]=n.plugins[a]||[],n.plugins[a].push([i,s[a]])},call:function(e,t,i,s){var a,n=e.plugins[t];if(n&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(a=0;n.length>a;a++)e.options[n[a][0]]&&n[a][1].apply(e.element,i)}};var s=0,a=Array.prototype.slice;e.cleanData=function(t){return function(i){for(var s,a=0;null!=(s=i[a]);a++)try{e(s).triggerHandler("remove")}catch(n){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var a,n,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],a=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][a.toLowerCase()]=function(t){return!!e.data(t,a)},e[l]=e[l]||{},n=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,n,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},a=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,n=this._superApply;return this._super=e,this._superApply=a,t=s.apply(this,arguments),this._super=i,this._superApply=n,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:n?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:a}),n?(e.each(n._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,n=a.call(arguments,1),o=0,r=n.length;r>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(n){var o="string"==typeof n,r=a.call(arguments,1),h=this;return n=!o&&r.length?e.widget.extend.apply(null,[n].concat(r)):n,o?this.each(function(){var i,a=e.data(this,s);return"instance"===n?(h=a,!1):a?e.isFunction(a[n])&&"_"!==n.charAt(0)?(i=a[n].apply(a,r),i!==a&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+n+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+n+"'")}):this.each(function(){var t=e.data(this,s);t?(t.option(n||{}),t._init&&t._init()):e.data(this,s,new i(n,this))}),h}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=s++,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(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),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.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(t,i){var s,a,n,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(a=o[t]=e.widget.extend({},this.options[t]),n=0;s.length-1>n;n++)a[s[n]]=a[s[n]]||{},a=a[s[n]];if(t=s.pop(),1===arguments.length)return void 0===a[t]?null:a[t];a[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),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,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var a,n=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=a=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,a=this.widget()),e.each(s,function(s,o){function r(){return t||n.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?n[o]:o).apply(n,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+n.eventNamespace,u=h[2];u?a.delegate(u,l,r):i.bind(l,r)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,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,i,s){var a,n,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],n=i.originalEvent)for(a in n)a in i||(i[a]=n[a]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,a,n){"string"==typeof a&&(a={effect:a});var o,r=a?a===!0||"number"==typeof a?i:a.effect||i:t;a=a||{},"number"==typeof a&&(a={duration:a}),o=!e.isEmptyObject(a),a.complete=n,a.delay&&s.delay(a.delay),o&&e.effects&&e.effects.effect[r]?s[t](a):r!==t&&s[r]?s[r](a.duration,a.easing,n):s.queue(function(i){e(this)[t](),n&&n.call(s[0]),i()})}}),e.widget;var n=!1;e(document).mouseup(function(){n=!1}),e.widget("ui.mouse",{version:"1.11.0",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(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!n){this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var i=this,s=1===t.which,a="string"==typeof this.options.cancel&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;return s&&!a&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(t)!==!1,!this._mouseStarted)?(t.preventDefault(),!0):(!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return i._mouseMove(e)},this._mouseUpDelegate=function(e){return i._mouseUp(e)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),n=!0,!0)):!0}},_mouseMove:function(t){return e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button?this._mouseUp(t):t.which?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 this.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)),n=!1,!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(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),e.widget("ui.draggable",e.ui.mouse,{version:"1.11.0",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,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?: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._setHandleClassName(),this._mouseInit()},_setOption:function(e,t){this._super(e,t),"handle"===e&&this._setHandleClassName()},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(t){var i=this.document[0],s=this.options;try{i.activeElement&&"body"!==i.activeElement.nodeName.toLowerCase()&&e(i.activeElement).blur()}catch(a){}return this.helper||s.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(e(s.iframeFix===!0?"iframe":s.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 i=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.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,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,!1),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",t,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var i=this,s=!1;return e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",t)!==!1&&i._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!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),this.element.focus(),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){return this.options.handle?!!e(t.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this._removeHandleClassName(),e(this.options.handle||this.element).addClass("ui-draggable-handle")},_removeHandleClassName:function(){this.element.find(".ui-draggable-handle").addBack().removeClass("ui-draggable-handle")},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return s.parents("body").length||s.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s[0]===this.element[0]||/(fixed|absolute)/.test(s.css("position"))||s.css("position","absolute"),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(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)},_isRootNode:function(e){return/(html|body)/i.test(e.tagName)||e===this.document[0]},_getParentOffset:function(){var t=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var e=this.element.position(),t=this._isRootNode(this.scrollParent[0]);return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+(t?0:this.scrollParent.scrollTop()),left:e.left-(parseInt(this.helper.css("left"),10)||0)+(t?0:this.scrollParent.scrollLeft())}},_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,i,s,a=this.options,n=this.document[0];return this.relative_container=null,a.containment?"window"===a.containment?(this.containment=[e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,e(window).scrollLeft()+e(window).width()-this.helperProportions.width-this.margins.left,e(window).scrollTop()+(e(window).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===a.containment?(this.containment=[0,0,e(n).width()-this.helperProportions.width-this.margins.left,(e(n).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):a.containment.constructor===Array?(this.containment=a.containment,void 0):("parent"===a.containment&&(a.containment=this.helper[0].parentNode),i=e(a.containment),s=i[0],s&&(t="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(t?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(e,t){t||(t=this.position);var i="absolute"===e?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:t.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:t.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(e,t){var i,s,a,n,o=this.options,r=this._isRootNode(this.scrollParent[0]),h=e.pageX,l=e.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),t&&(this.containment&&(this.relative_container?(s=this.relative_container.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,e.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),e.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),e.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),e.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),o.grid&&(a=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=i?a-this.offset.click.top>=i[1]||a-this.offset.click.top>i[3]?a:a-this.offset.click.top>=i[1]?a-o.grid[1]:a+o.grid[1]:a,n=o.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,h=i?n-this.offset.click.left>=i[0]||n-this.offset.click.left>i[2]?n:n-this.offset.click.left>=i[0]?n-o.grid[0]:n+o.grid[0]:n),"y"===o.axis&&(h=this.originalPageX),"x"===o.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_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,this.destroyOnClear&&this.destroy()},_trigger:function(t,i,s){return s=s||this._uiHash(),e.ui.plugin.call(this,t,[i,s,this],!0),"drag"===t&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,i,s){var a=s.options,n=e.extend({},i,{item:s.element});s.sortables=[],e(a.connectToSortable).each(function(){var i=e(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",t,n))})},stop:function(t,i,s){var a=e.extend({},i,{item:s.element});e.each(s.sortables,function(){this.instance.isOver?(this.instance.isOver=0,s.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,"original"===s.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,a))})},drag:function(t,i,s){var a=this;e.each(s.sortables,function(){var n=!1,o=this;this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(n=!0,e.each(s.sortables,function(){return this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.contains(o.instance.element[0],this.instance.element[0])&&(n=!1),n})),n?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(a).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=s.offset.click.top,this.instance.offset.click.left=s.offset.click.left,this.instance.offset.parent.left-=s.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=s.offset.parent.top-this.instance.offset.parent.top,s._trigger("toSortable",t),s.dropped=this.instance.element,s.currentItem=s.element,this.instance.fromOutside=s),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(),s._trigger("fromSortable",t),s.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,i,s){var a=e("body"),n=s.options;a.css("cursor")&&(n._cursor=a.css("cursor")),a.css("cursor",n.cursor)},stop:function(t,i,s){var a=s.options;a._cursor&&e("body").css("cursor",a._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,i,s){var a=e(i.helper),n=s.options;a.css("opacity")&&(n._opacity=a.css("opacity")),a.css("opacity",n.opacity)},stop:function(t,i,s){var a=s.options;a._opacity&&e(i.helper).css("opacity",a._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(e,t,i){i.scrollParent[0]!==i.document[0]&&"HTML"!==i.scrollParent[0].tagName&&(i.overflowOffset=i.scrollParent.offset())},drag:function(t,i,s){var a=s.options,n=!1,o=s.document[0];s.scrollParent[0]!==o&&"HTML"!==s.scrollParent[0].tagName?(a.axis&&"x"===a.axis||(s.overflowOffset.top+s.scrollParent[0].offsetHeight-t.pageY<a.scrollSensitivity?s.scrollParent[0].scrollTop=n=s.scrollParent[0].scrollTop+a.scrollSpeed:t.pageY-s.overflowOffset.top<a.scrollSensitivity&&(s.scrollParent[0].scrollTop=n=s.scrollParent[0].scrollTop-a.scrollSpeed)),a.axis&&"y"===a.axis||(s.overflowOffset.left+s.scrollParent[0].offsetWidth-t.pageX<a.scrollSensitivity?s.scrollParent[0].scrollLeft=n=s.scrollParent[0].scrollLeft+a.scrollSpeed:t.pageX-s.overflowOffset.left<a.scrollSensitivity&&(s.scrollParent[0].scrollLeft=n=s.scrollParent[0].scrollLeft-a.scrollSpeed))):(a.axis&&"x"===a.axis||(t.pageY-e(o).scrollTop()<a.scrollSensitivity?n=e(o).scrollTop(e(o).scrollTop()-a.scrollSpeed):e(window).height()-(t.pageY-e(o).scrollTop())<a.scrollSensitivity&&(n=e(o).scrollTop(e(o).scrollTop()+a.scrollSpeed))),a.axis&&"y"===a.axis||(t.pageX-e(o).scrollLeft()<a.scrollSensitivity?n=e(o).scrollLeft(e(o).scrollLeft()-a.scrollSpeed):e(window).width()-(t.pageX-e(o).scrollLeft())<a.scrollSensitivity&&(n=e(o).scrollLeft(e(o).scrollLeft()+a.scrollSpeed)))),n!==!1&&e.ui.ddmanager&&!a.dropBehaviour&&e.ui.ddmanager.prepareOffsets(s,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,i,s){var a=s.options;s.snapElements=[],e(a.snap.constructor!==String?a.snap.items||":data(ui-draggable)":a.snap).each(function(){var t=e(this),i=t.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:i.top,left:i.left})})},drag:function(t,i,s){var a,n,o,r,h,l,u,d,c,p,f=s.options,m=f.snapTolerance,g=i.offset.left,v=g+s.helperProportions.width,y=i.offset.top,b=y+s.helperProportions.height;for(c=s.snapElements.length-1;c>=0;c--)h=s.snapElements[c].left,l=h+s.snapElements[c].width,u=s.snapElements[c].top,d=u+s.snapElements[c].height,h-m>v||g>l+m||u-m>b||y>d+m||!e.contains(s.snapElements[c].item.ownerDocument,s.snapElements[c].item)?(s.snapElements[c].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=!1):("inner"!==f.snapMode&&(a=m>=Math.abs(u-b),n=m>=Math.abs(d-y),o=m>=Math.abs(h-v),r=m>=Math.abs(l-g),a&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top-s.margins.top),n&&(i.position.top=s._convertPositionTo("relative",{top:d,left:0}).top-s.margins.top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left-s.margins.left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left-s.margins.left)),p=a||n||o||r,"outer"!==f.snapMode&&(a=m>=Math.abs(u-y),n=m>=Math.abs(d-b),o=m>=Math.abs(h-g),r=m>=Math.abs(l-v),a&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top-s.margins.top),n&&(i.position.top=s._convertPositionTo("relative",{top:d-s.helperProportions.height,left:0}).top-s.margins.top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left-s.margins.left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left-s.margins.left)),!s.snapElements[c].snapping&&(a||n||o||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=a||n||o||r||p)}}),e.ui.plugin.add("draggable","stack",{start:function(t,i,s){var a,n=s.options,o=e.makeArray(e(n.stack)).sort(function(t,i){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(i).css("zIndex"),10)||0)});o.length&&(a=parseInt(e(o[0]).css("zIndex"),10)||0,e(o).each(function(t){e(this).css("zIndex",a+t)}),this.css("zIndex",a+o.length))}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,i,s){var a=e(i.helper),n=s.options;a.css("zIndex")&&(n._zIndex=a.css("zIndex")),a.css("zIndex",n.zIndex)},stop:function(t,i,s){var a=s.options;a._zIndex&&e(i.helper).css("zIndex",a._zIndex)}}),e.ui.draggable,e.widget("ui.droppable",{version:"1.11.0",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=e.isFunction(s)?s:function(e){return e.is(s)},this.proportions=function(){return arguments.length?(t=arguments[0],void 0):t?t:t={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this.element.addClass("ui-droppable")},_addToManager:function(t){e.ui.ddmanager.droppables[t]=e.ui.ddmanager.droppables[t]||[],e.ui.ddmanager.droppables[t].push(this)},_splice:function(e){for(var t=0;e.length>t;t++)e[t]===this&&e.splice(t,1) },_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];this._splice(t),this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,i){if("accept"===t)this.accept=e.isFunction(i)?i:function(e){return e.is(i)};else if("scope"===t){var s=e.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(t,i)},_activate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",t,this.ui(i))},_deactivate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",t,this.ui(i))},_over:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(i)))},_out:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(i)))},_drop:function(t,i){var s=i||e.ui.ddmanager.current,a=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=e(this).droppable("instance");return t.options.greedy&&!t.options.disabled&&t.options.scope===s.options.scope&&t.accept.call(t.element[0],s.currentItem||s.element)&&e.ui.intersect(s,e.extend(t,{offset:t.element.offset()}),t.options.tolerance)?(a=!0,!1):void 0}),a?!1:this.accept.call(this.element[0],s.currentItem||s.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(s)),this.element):!1):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(){function e(e,t,i){return e>=t&&t+i>e}return function(t,i,s){if(!i.offset)return!1;var a,n,o=(t.positionAbs||t.position.absolute).left,r=(t.positionAbs||t.position.absolute).top,h=o+t.helperProportions.width,l=r+t.helperProportions.height,u=i.offset.left,d=i.offset.top,c=u+i.proportions().width,p=d+i.proportions().height;switch(s){case"fit":return o>=u&&c>=h&&r>=d&&p>=l;case"intersect":return o+t.helperProportions.width/2>u&&c>h-t.helperProportions.width/2&&r+t.helperProportions.height/2>d&&p>l-t.helperProportions.height/2;case"pointer":return a=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,n=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,e(n,d,i.proportions().height)&&e(a,u,i.proportions().width);case"touch":return(r>=d&&p>=r||l>=d&&p>=l||d>r&&l>p)&&(o>=u&&c>=o||h>=u&&c>=h||u>o&&h>c);default:return!1}}}(),e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,i){var s,a,n=e.ui.ddmanager.droppables[t.options.scope]||[],o=i?i.type:null,r=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(s=0;n.length>s;s++)if(!(n[s].options.disabled||t&&!n[s].accept.call(n[s].element[0],t.currentItem||t.element))){for(a=0;r.length>a;a++)if(r[a]===n[s].element[0]){n[s].proportions().height=0;continue e}n[s].visible="none"!==n[s].element.css("display"),n[s].visible&&("mousedown"===o&&n[s]._activate.call(n[s],i),n[s].offset=n[s].element.offset(),n[s].proportions({width:n[s].element[0].offsetWidth,height:n[s].element[0].offsetHeight}))}},drop:function(t,i){var s=!1;return e.each((e.ui.ddmanager.droppables[t.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(t,i){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)})},drag:function(t,i){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,i),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,a,n,o=e.ui.intersect(t,this,this.options.tolerance),r=!o&&this.isover?"isout":o&&!this.isover?"isover":null;r&&(this.options.greedy&&(a=this.options.scope,n=this.element.parents(":data(ui-droppable)").filter(function(){return e(this).droppable("instance").options.scope===a}),n.length&&(s=e(n[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(t,i){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)}},e.ui.droppable,e.widget("ui.resizable",e.ui.mouse,{version:"1.11.0",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:90,resize:null,start:null,stop:null},_num:function(e){return parseInt(e,10)||0},_isNumber:function(e){return!isNaN(parseInt(e,10))},_hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",a=!1;return t[s]>0?!0:(t[s]=1,a=t[s]>0,t[s]=0,a)},_create:function(){var t,i,s,a,n,o=this,r=this.options;if(this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.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("ui-resizable",this.element.resizable("instance")),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=r.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"),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={},i=0;t.length>i;i++)s=e.trim(t[i]),n="ui-resizable-"+s,a=e("<div class='ui-resizable-handle "+n+"'></div>"),a.css({zIndex:r.zIndex}),"se"===s&&a.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(a);this._renderAxis=function(t){var i,s,a,n;t=t||this.element;for(i in this.handles)this.handles[i].constructor===String&&(this.handles[i]=this.element.children(this.handles[i]).first().show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(s=e(this.handles[i],this.element),n=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),a=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),t.css(a,n),this._proportionallyResize()),e(this.handles[i]).length},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=a&&a[1]?a[1]:"se")}),r.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(e(this).removeClass("ui-resizable-autohide"),o._handles.show())}).mouseleave(function(){r.disabled||o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,i=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()};return this.elementIsWrapper&&(i(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(t){var i,s,a=!1;for(i in this.handles)s=e(this.handles[i])[0],(s===t.target||e.contains(s,t.target))&&(a=!0);return!this.options.disabled&&a},_mouseStart:function(t){var i,s,a,n=this.options,o=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),n.containment&&(i+=e(n.containment).scrollLeft()||0,s+=e(n.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:o.width(),height:o.height()},this.originalSize=this._helper?{width:o.outerWidth(),height:o.outerHeight()}:{width:o.width(),height:o.height()},this.originalPosition={left:i,top:s},this.sizeDiff={width:o.outerWidth()-o.width(),height:o.outerHeight()-o.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof n.aspectRatio?n.aspectRatio:this.originalSize.width/this.originalSize.height||1,a=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor","auto"===a?this.axis+"-resize":a),o.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var i,s=this.helper,a={},n=this.originalMousePosition,o=this.axis,r=t.pageX-n.left||0,h=t.pageY-n.top||0,l=this._change[o];return this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height},l?(i=l.apply(this,[t,r,h]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(i=this._updateRatio(i,t)),i=this._respectSize(i,t),this._updateCache(i),this._propagate("resize",t),this.position.top!==this.prevPosition.top&&(a.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(a.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(a.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(a.height=this.size.height+"px"),s.css(a),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(a)||this._trigger("resize",t,this.ui()),!1):!1},_mouseStop:function(t){this.resizing=!1;var i,s,a,n,o,r,h,l=this.options,u=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),a=s&&this._hasScroll(i[0],"left")?0:u.sizeDiff.height,n=s?0:u.sizeDiff.width,o={width:u.helper.width()-n,height:u.helper.height()-a},r=parseInt(u.element.css("left"),10)+(u.position.left-u.originalPosition.left)||null,h=parseInt(u.element.css("top"),10)+(u.position.top-u.originalPosition.top)||null,l.animate||this.element.css(e.extend(o,{top:h,left:r})),u.helper.height(u.size.height),u.helper.width(u.size.width),this._helper&&!l.animate&&this._proportionallyResize()),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,i,s,a,n,o=this.options;n={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:1/0,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:1/0},(this._aspectRatio||e)&&(t=n.minHeight*this.aspectRatio,s=n.minWidth/this.aspectRatio,i=n.maxHeight*this.aspectRatio,a=n.maxWidth/this.aspectRatio,t>n.minWidth&&(n.minWidth=t),s>n.minHeight&&(n.minHeight=s),n.maxWidth>i&&(n.maxWidth=i),n.maxHeight>a&&(n.maxHeight=a)),this._vBoundaries=n},_updateCache:function(e){this.offset=this.helper.offset(),this._isNumber(e.left)&&(this.position.left=e.left),this._isNumber(e.top)&&(this.position.top=e.top),this._isNumber(e.height)&&(this.size.height=e.height),this._isNumber(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,i=this.size,s=this.axis;return this._isNumber(e.height)?e.width=e.height*this.aspectRatio:this._isNumber(e.width)&&(e.height=e.width/this.aspectRatio),"sw"===s&&(e.left=t.left+(i.width-e.width),e.top=null),"nw"===s&&(e.top=t.top+(i.height-e.height),e.left=t.left+(i.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,i=this.axis,s=this._isNumber(e.width)&&t.maxWidth&&t.maxWidth<e.width,a=this._isNumber(e.height)&&t.maxHeight&&t.maxHeight<e.height,n=this._isNumber(e.width)&&t.minWidth&&t.minWidth>e.width,o=this._isNumber(e.height)&&t.minHeight&&t.minHeight>e.height,r=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,l=/sw|nw|w/.test(i),u=/nw|ne|n/.test(i);return n&&(e.width=t.minWidth),o&&(e.height=t.minHeight),s&&(e.width=t.maxWidth),a&&(e.height=t.maxHeight),n&&l&&(e.left=r-t.minWidth),s&&l&&(e.left=r-t.maxWidth),o&&u&&(e.top=h-t.minHeight),a&&u&&(e.top=h-t.maxHeight),e.width||e.height||e.left||!e.top?e.width||e.height||e.top||!e.left||(e.left=null):e.top=null,e},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var e,t,i,s,a,n=this.helper||this.element;for(e=0;this._proportionallyResizeElements.length>e;e++){if(a=this._proportionallyResizeElements[e],!this.borderDif)for(this.borderDif=[],i=[a.css("borderTopWidth"),a.css("borderRightWidth"),a.css("borderBottomWidth"),a.css("borderLeftWidth")],s=[a.css("paddingTop"),a.css("paddingRight"),a.css("paddingBottom"),a.css("paddingLeft")],t=0;i.length>t;t++)this.borderDif[t]=(parseInt(i[t],10)||0)+(parseInt(s[t],10)||0);a.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,i=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,i){var s=this.originalSize,a=this.originalPosition;return{top:a.top+i,height:s.height-i}},s:function(e,t,i){return{height:this.originalSize.height+i}},se:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},sw:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,i,s]))},ne:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},nw:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,i,s]))}},_propagate:function(t,i){e.ui.plugin.call(this,t,[i,this.ui()]),"resize"!==t&&this._trigger(t,i,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,prevSize:this.prevSize,prevPosition:this.prevPosition}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var i=e(this).resizable("instance"),s=i.options,a=i._proportionallyResizeElements,n=a.length&&/textarea/i.test(a[0].nodeName),o=n&&i._hasScroll(a[0],"left")?0:i.sizeDiff.height,r=n?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-o},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,u=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(e.extend(h,u&&l?{top:u,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};a&&a.length&&e(a[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,i,s,a,n,o,r,h=e(this).resizable("instance"),l=h.options,u=h.element,d=l.containment,c=d instanceof e?d.get(0):/parent/.test(d)?u.parent().get(0):d;c&&(h.containerElement=e(c),/document/.test(d)||d===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(c),i=[],e(["Top","Right","Left","Bottom"]).each(function(e,s){i[e]=h._num(t.css("padding"+s))}),h.containerOffset=t.offset(),h.containerPosition=t.position(),h.containerSize={height:t.innerHeight()-i[3],width:t.innerWidth()-i[1]},s=h.containerOffset,a=h.containerSize.height,n=h.containerSize.width,o=h._hasScroll(c,"left")?c.scrollWidth:n,r=h._hasScroll(c)?c.scrollHeight:a,h.parentData={element:c,left:s.left,top:s.top,width:o,height:r}))},resize:function(t,i){var s,a,n,o,r=e(this).resizable("instance"),h=r.options,l=r.containerOffset,u=r.position,d=r._aspectRatio||t.shiftKey,c={top:0,left:0},p=r.containerElement,f=!0;p[0]!==document&&/static/.test(p.css("position"))&&(c=l),u.left<(r._helper?l.left:0)&&(r.size.width=r.size.width+(r._helper?r.position.left-l.left:r.position.left-c.left),d&&(r.size.height=r.size.width/r.aspectRatio,f=!1),r.position.left=h.helper?l.left:0),u.top<(r._helper?l.top:0)&&(r.size.height=r.size.height+(r._helper?r.position.top-l.top:r.position.top),d&&(r.size.width=r.size.height*r.aspectRatio,f=!1),r.position.top=r._helper?l.top:0),r.offset.left=r.parentData.left+r.position.left,r.offset.top=r.parentData.top+r.position.top,s=Math.abs((r._helper?r.offset.left-c.left:r.offset.left-l.left)+r.sizeDiff.width),a=Math.abs((r._helper?r.offset.top-c.top:r.offset.top-l.top)+r.sizeDiff.height),n=r.containerElement.get(0)===r.element.parent().get(0),o=/relative|absolute/.test(r.containerElement.css("position")),n&&o&&(s-=Math.abs(r.parentData.left)),s+r.size.width>=r.parentData.width&&(r.size.width=r.parentData.width-s,d&&(r.size.height=r.size.width/r.aspectRatio,f=!1)),a+r.size.height>=r.parentData.height&&(r.size.height=r.parentData.height-a,d&&(r.size.width=r.size.height*r.aspectRatio,f=!1)),f||(r.position.left=i.prevPosition.left,r.position.top=i.prevPosition.top,r.size.width=i.prevSize.width,r.size.height=i.prevSize.height)},stop:function(){var t=e(this).resizable("instance"),i=t.options,s=t.containerOffset,a=t.containerPosition,n=t.containerElement,o=e(t.helper),r=o.offset(),h=o.outerWidth()-t.sizeDiff.width,l=o.outerHeight()-t.sizeDiff.height;t._helper&&!i.animate&&/relative/.test(n.css("position"))&&e(this).css({left:r.left-a.left-s.left,width:h,height:l}),t._helper&&!i.animate&&/static/.test(n.css("position"))&&e(this).css({left:r.left-a.left-s.left,width:h,height:l})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).resizable("instance"),i=t.options,s=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};"object"!=typeof i.alsoResize||i.alsoResize.parentNode?s(i.alsoResize):i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)})},resize:function(t,i){var s=e(this).resizable("instance"),a=s.options,n=s.originalSize,o=s.originalPosition,r={height:s.size.height-n.height||0,width:s.size.width-n.width||0,top:s.position.top-o.top||0,left:s.position.left-o.left||0},h=function(t,s){e(t).each(function(){var t=e(this),a=e(this).data("ui-resizable-alsoresize"),n={},o=s&&s.length?s:t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var i=(a[t]||0)+(r[t]||0);i&&i>=0&&(n[t]=i||null)}),t.css(n)})};"object"!=typeof a.alsoResize||a.alsoResize.nodeType?h(a.alsoResize):e.each(a.alsoResize,function(e,t){h(e,t)})},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).resizable("instance"),i=t.options,s=t.size;t.ghost=t.originalElement.clone(),t.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("string"==typeof i.ghost?i.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).resizable("instance"),i=t.options,s=t.size,a=t.originalSize,n=t.originalPosition,o=t.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=r[0]||1,l=r[1]||1,u=Math.round((s.width-a.width)/h)*h,d=Math.round((s.height-a.height)/l)*l,c=a.width+u,p=a.height+d,f=i.maxWidth&&c>i.maxWidth,m=i.maxHeight&&p>i.maxHeight,g=i.minWidth&&i.minWidth>c,v=i.minHeight&&i.minHeight>p;i.grid=r,g&&(c+=h),v&&(p+=l),f&&(c-=h),m&&(p-=l),/^(se|s|e)$/.test(o)?(t.size.width=c,t.size.height=p):/^(ne)$/.test(o)?(t.size.width=c,t.size.height=p,t.position.top=n.top-d):/^(sw)$/.test(o)?(t.size.width=c,t.size.height=p,t.position.left=n.left-u):(p-l>0?(t.size.height=p,t.position.top=n.top-d):(t.size.height=l,t.position.top=n.top+a.height-l),c-h>0?(t.size.width=c,t.position.left=n.left-u):(t.size.width=h,t.position.left=n.left+a.width-h))}}),e.ui.resizable,e.widget("ui.selectable",e.ui.mouse,{version:"1.11.0",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(i.options.filter,i.element[0]),t.addClass("ui-selectee"),t.each(function(){var t=e(this),i=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:i.left,top:i.top,right:i.left+t.outerWidth(),bottom:i.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=t.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 i=this,s=this.options;this.opos=[t.pageX,t.pageY],this.options.disabled||(this.selectees=e(s.filter,this.element[0]),this._trigger("start",t),e(s.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=e.data(this,"selectable-item");s.startselected=!0,t.metaKey||t.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",t,{unselecting:s.element}))}),e(t.target).parents().addBack().each(function(){var s,a=e.data(this,"selectable-item");return a?(s=!t.metaKey&&!t.ctrlKey||!a.$element.hasClass("ui-selected"),a.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),a.unselecting=!s,a.selecting=s,a.selected=s,s?i._trigger("selecting",t,{selecting:a.element}):i._trigger("unselecting",t,{unselecting:a.element}),!1):void 0}))},_mouseDrag:function(t){if(this.dragged=!0,!this.options.disabled){var i,s=this,a=this.options,n=this.opos[0],o=this.opos[1],r=t.pageX,h=t.pageY;return n>r&&(i=r,r=n,n=i),o>h&&(i=h,h=o,o=i),this.helper.css({left:n,top:o,width:r-n,height:h-o}),this.selectees.each(function(){var i=e.data(this,"selectable-item"),l=!1;i&&i.element!==s.element[0]&&("touch"===a.tolerance?l=!(i.left>r||n>i.right||i.top>h||o>i.bottom):"fit"===a.tolerance&&(l=i.left>n&&r>i.right&&i.top>o&&h>i.bottom),l?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",t,{selecting:i.element}))):(i.selecting&&((t.metaKey||t.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",t,{unselecting:i.element}))),i.selected&&(t.metaKey||t.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",t,{unselecting:i.element})))))}),!1}},_mouseStop:function(t){var i=this;return this.dragged=!1,e(".ui-unselecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",t,{unselected:s.element})}),e(".ui-selecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",t,{selected:s.element})}),this._trigger("stop",t),this.helper.remove(),!1}}),e.widget("ui.sortable",e.ui.mouse,{version:"1.11.0",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,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(e,t,i){return e>=t&&t+i>e},_isFloating:function(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===e.axis||this._isFloating(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(e,t){this._super(e,t),"handle"===e&&this._setHandleClassName()},_setHandleClassName:function(){this.element.find(".ui-sortable-handle").removeClass("ui-sortable-handle"),e.each(this.items,function(){(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item).addClass("ui-sortable-handle")})},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").find(".ui-sortable-handle").removeClass("ui-sortable-handle"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(t,i){var s=null,a=!1,n=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(t),e(t.target).parents().each(function(){return e.data(this,n.widgetName+"-item")===n?(s=e(this),!1):void 0}),e.data(t.target,n.widgetName+"-item")===n&&(s=e(t.target)),s?!this.options.handle||i||(e(this.options.handle,s).find("*").addBack().each(function(){this===t.target&&(a=!0)}),a)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(t,i,s){var a,n,o=this.options;if(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,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(n=this.document.find("body"),this.storedCursor=n.css("cursor"),n.css("cursor",o.cursor),this.storedStylesheet=e("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(n)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(a=this.containers.length-1;a>=0;a--)this.containers[a]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var i,s,a,n,o=this.options,r=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+o.scrollSpeed:t.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+o.scrollSpeed:t.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(t.pageY-e(document).scrollTop()<o.scrollSensitivity?r=e(document).scrollTop(e(document).scrollTop()-o.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<o.scrollSensitivity&&(r=e(document).scrollTop(e(document).scrollTop()+o.scrollSpeed)),t.pageX-e(document).scrollLeft()<o.scrollSensitivity?r=e(document).scrollLeft(e(document).scrollLeft()-o.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<o.scrollSensitivity&&(r=e(document).scrollLeft(e(document).scrollLeft()+o.scrollSpeed))),r!==!1&&e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],a=s.item[0],n=this._intersectsWithPointer(s),n&&s.instance===this.currentContainer&&a!==this.currentItem[0]&&this.placeholder[1===n?"next":"prev"]()[0]!==a&&!e.contains(this.placeholder[0],a)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],a):!0)){if(this.direction=1===n?"down":"up","pointer"!==this.options.tolerance&&!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,i){if(t){if(e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t),this.options.revert){var s=this,a=this.placeholder.offset(),n=this.options.axis,o={};n&&"x"!==n||(o.left=a.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),n&&"y"!==n||(o.top=a.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,e(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){s._clear(t)})}else this._clear(t,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?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]),"original"!==this.options.helper&&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 i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},e(i).each(function(){var i=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);i&&s.push((t.key||i[1]+"[]")+"="+(t.key&&t.expression?i[1]:i[2]))}),!s.length&&t.key&&s.push(t.key+"="),s.join("&")},toArray:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},i.each(function(){s.push(e(t.item||this).attr(t.attribute||"id")||"")}),s},_intersectsWith:function(e){var t=this.positionAbs.left,i=t+this.helperProportions.width,s=this.positionAbs.top,a=s+this.helperProportions.height,n=e.left,o=n+e.width,r=e.top,h=r+e.height,l=this.offset.click.top,u=this.offset.click.left,d="x"===this.options.axis||s+l>r&&h>s+l,c="y"===this.options.axis||t+u>n&&o>t+u,p=d&&c;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?p:t+this.helperProportions.width/2>n&&o>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>a-this.helperProportions.height/2},_intersectsWithPointer:function(e){var t="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),i="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),s=t&&i,a=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return s?this.floating?n&&"right"===n||"down"===a?2:1:a&&("down"===a?2:1):!1},_intersectsWithSides:function(e){var t=this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),s=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return this.floating&&a?"right"===a&&i||"left"===a&&!i:s&&("down"===s&&t||"up"===s&&!t)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function i(){r.push(this)}var s,a,n,o,r=[],h=[],l=this._connectWith();if(l&&t)for(s=l.length-1;s>=0;s--)for(n=e(l[s]),a=n.length-1;a>=0;a--)o=e.data(n[a],this.widgetFullName),o&&o!==this&&!o.options.disabled&&h.push([e.isFunction(o.options.items)?o.options.items.call(o.element):e(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);for(h.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]),s=h.length-1;s>=0;s--)h[s][0].each(i);return e(r)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var i=0;t.length>i;i++)if(t[i]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var i,s,a,n,o,r,h,l,u=this.items,d=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],c=this._connectWith();if(c&&this.ready)for(i=c.length-1;i>=0;i--)for(a=e(c[i]),s=a.length-1;s>=0;s--)n=e.data(a[s],this.widgetFullName),n&&n!==this&&!n.options.disabled&&(d.push([e.isFunction(n.options.items)?n.options.items.call(n.element[0],t,{item:this.currentItem}):e(n.options.items,n.element),n]),this.containers.push(n));for(i=d.length-1;i>=0;i--)for(o=d[i][1],r=d[i][0],s=0,l=r.length;l>s;s++)h=e(r[s]),h.data(this.widgetName+"-item",o),u.push({item:h,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,a,n;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(a=this.options.toleranceElement?e(this.options.toleranceElement,s.item):s.item,t||(s.width=a.outerWidth(),s.height=a.outerHeight()),n=a.offset(),s.left=n.left,s.top=n.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)n=this.containers[i].element.offset(),this.containers[i].containerCache.left=n.left,this.containers[i].containerCache.top=n.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(t){t=t||this;var i,s=t.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=t.currentItem[0].nodeName.toLowerCase(),a=e("<"+s+">",t.document[0]).addClass(i||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?t.currentItem.children().each(function(){e("<td> </td>",t.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(a)}):"img"===s&&a.attr("src",t.currentItem.attr("src")),i||a.css("visibility","hidden"),a},update:function(e,a){(!i||s.forcePlaceholderSize)&&(a.height()||a.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),a.width()||a.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10)))}}),t.placeholder=e(s.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),s.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var i,s,a,n,o,r,h,l,u,d,c=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(c&&e.contains(this.containers[i].element[0],c.element[0]))continue;c=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0);if(c)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(a=1e4,n=null,u=c.floating||this._isFloating(this.currentItem),o=u?"left":"top",r=u?"width":"height",d=u?"clientX":"clientY",s=this.items.length-1;s>=0;s--)e.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[o],l=!1,t[d]-h>this.items[s][r]/2&&(l=!0),a>Math.abs(t[d]-h)&&(a=Math.abs(t[d]-h),n=this.items[s],this.direction=l?"up":"down"));if(!n&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return;n?this._rearrange(t,n,null,!0):this._rearrange(t,null,this.containers[p].element,!0),this._trigger("change",t,this._uiHash()),this.containers[p]._trigger("change",t,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||e("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[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")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(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();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){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,i,s,a=this.options;"parent"===a.containment&&(a.containment=this.helper[0].parentNode),("document"===a.containment||"window"===a.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===a.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===a.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(a.containment)||(t=e(a.containment)[0],i=e(a.containment).offset(),s="hidden"!==e(t).css("overflow"),this.containment=[i.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,a="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,n=/(html|body)/i.test(a[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():n?0:a.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():n?0:a.scrollLeft())*s}},_generatePosition:function(t){var i,s,a=this.options,n=t.pageX,o=t.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(n=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]&&(n=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),a.grid&&(i=this.originalPageY+Math.round((o-this.originalPageY)/a.grid[1])*a.grid[1],o=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-a.grid[1]:i+a.grid[1]:i,s=this.originalPageX+Math.round((n-this.originalPageX)/a.grid[0])*a.grid[0],n=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-a.grid[0]:s+a.grid[0]:s)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:n-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(e,t,i,s){i?i[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var a=this.counter;this._delay(function(){a===this.counter&&this.refreshPositions(!s)})},_clear:function(e,t){function i(e,t,i){return function(s){i._trigger(e,s,t._uiHash(t))}}this.reverting=!1;var s,a=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!t&&a.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]||t||a.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(t||(a.push(function(e){this._trigger("remove",e,this._uiHash())}),a.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),a.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)t||a.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(a.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!t){for(this._trigger("beforeStop",e,this._uiHash()),s=0;a.length>s;s++)a[s].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!1}if(t||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!t){for(s=0;a.length>s;s++)a[s].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var i=t||this;return{helper:i.helper,placeholder:i.placeholder||e([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:t?t.element:null}}})}); /*! RESOURCE: /scripts/sn.dragdrop/jquery.ui.touch-punch.min.js */ /* * jQuery UI Touch Punch 0.2.2 * * Copyright 2011, Dave Furfero * Dual licensed under the MIT or GPL Version 2 licenses. * * Depends: * jquery.ui.widget.js * jquery.ui.mouse.js */ (function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery); /*! RESOURCE: /scripts/sn.dragdrop/angular-dragdrop.js */ (function (window, angular, $, undefined) { 'use strict'; var jqyoui = angular.module('ngDragDrop', []).service('ngDragDropService', ['$timeout', '$parse', function($timeout, $parse) { this.callEventCallback = function (scope, callbackName, event, ui) { if (!callbackName) return; var objExtract = extract(callbackName), callback = objExtract.callback, constructor = objExtract.constructor, args = [event, ui].concat(objExtract.args); scope.$apply((scope[callback] || scope[constructor][callback]).apply(scope, args)); function extract(callbackName) { var atStartBracket = callbackName.indexOf('(') !== -1 ? callbackName.indexOf('(') : callbackName.length, atEndBracket = callbackName.lastIndexOf(')') !== -1 ? callbackName.lastIndexOf(')') : callbackName.length, args = callbackName.substring(atStartBracket + 1, atEndBracket), constructor = callbackName.match(/^[^.]+.\s*/)[0].slice(0, -1); constructor = scope[constructor] && typeof scope[constructor].constructor === 'function' ? constructor : null; return { callback: callbackName.substring(constructor && constructor.length + 1 || 0, atStartBracket), args: (args && args.split(',') || []).map(function(item) { return $parse(item)(scope); }), constructor: constructor } } }; this.invokeDrop = function ($draggable, $droppable, event, ui) { var dragModel = '', dropModel = '', dragSettings = {}, dropSettings = {}, jqyoui_pos = null, dragItem = {}, dropItem = {}, dragModelValue, dropModelValue, $droppableDraggable = null, droppableScope = $droppable.scope(), draggableScope = $draggable.scope(); dragModel = $draggable.ngattr('ng-model'); dropModel = $droppable.ngattr('ng-model'); dragModelValue = draggableScope.$eval(dragModel); dropModelValue = droppableScope.$eval(dropModel); $droppableDraggable = $droppable.find('[jqyoui-draggable]:last,[data-jqyoui-draggable]:last'); dropSettings = droppableScope.$eval($droppable.attr('jqyoui-droppable') || $droppable.attr('data-jqyoui-droppable')) || []; dragSettings = draggableScope.$eval($draggable.attr('jqyoui-draggable') || $draggable.attr('data-jqyoui-draggable')) || []; dragSettings.index = this.fixIndex(draggableScope, dragSettings, dragModelValue); dropSettings.index = this.fixIndex(droppableScope, dropSettings, dropModelValue); jqyoui_pos = angular.isArray(dragModelValue) ? dragSettings.index : null; dragItem = angular.copy(angular.isArray(dragModelValue) ? dragModelValue[jqyoui_pos] : dragModelValue); if (angular.isArray(dropModelValue) && dropSettings && dropSettings.index !== undefined) { dropItem = dropModelValue[dropSettings.index]; } else if (!angular.isArray(dropModelValue)) { dropItem = dropModelValue; } else { dropItem = {}; } dropItem = angular.copy(dropItem); if (dragSettings.animate === true) { this.move($draggable, $droppableDraggable.length > 0 ? $droppableDraggable : $droppable, null, 'fast', dropSettings, null); this.move($droppableDraggable.length > 0 && !dropSettings.multiple ? $droppableDraggable : [], $draggable.parent('[jqyoui-droppable],[data-jqyoui-droppable]'), jqyoui.startXY, 'fast', dropSettings, angular.bind(this, function() { $timeout(angular.bind(this, function() { $draggable.css({'position': 'relative', 'left': '', 'top': ''}); $droppableDraggable.css({'position': 'relative', 'left': '', 'top': '', 'display': ''}); this.mutateDraggable(draggableScope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable); this.mutateDroppable(droppableScope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos); this.callEventCallback(droppableScope, dropSettings.onDrop, event, ui); })); })); } else { $timeout(angular.bind(this, function() { this.mutateDraggable(draggableScope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable); this.mutateDroppable(droppableScope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos); this.callEventCallback(droppableScope, dropSettings.onDrop, event, ui); })); } }; this.move = function($fromEl, $toEl, toPos, duration, dropSettings, callback) { if ($fromEl.length === 0) { if (callback) { window.setTimeout(function() { callback(); }, 300); } return false; } var zIndex = 9999, fromPos = $fromEl[dropSettings.containment || 'offset'](), wasVisible = $toEl && $toEl.is(':visible'), hadNgHideCls = $toEl.hasClass('ng-hide'); if (toPos === null && $toEl.length > 0) { if (($toEl.attr('jqyoui-draggable') || $toEl.attr('data-jqyoui-draggable')) !== undefined && $toEl.ngattr('ng-model') !== undefined && $toEl.is(':visible') && dropSettings && dropSettings.multiple) { toPos = $toEl[dropSettings.containment || 'offset'](); if (dropSettings.stack === false) { toPos.left+= $toEl.outerWidth(true); } else { toPos.top+= $toEl.outerHeight(true); } } else { if (hadNgHideCls) $toEl.removeClass('ng-hide'); toPos = $toEl.css({'visibility': 'hidden', 'display': 'block'})[dropSettings.containment || 'offset'](); $toEl.css({'visibility': '','display': wasVisible ? 'block' : 'none'}); } } $fromEl.css({'position': 'absolute', 'z-index': zIndex}) .css(fromPos) .animate(toPos, duration, function() { if (hadNgHideCls) $toEl.addClass('ng-hide'); if (callback) callback(); }); }; this.mutateDroppable = function(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos) { var dropModelValue = scope.$eval(dropModel); scope.dndDragItem = dragItem; if (angular.isArray(dropModelValue)) { if (dropSettings && dropSettings.index >= 0) { dropModelValue[dropSettings.index] = dragItem; } else { dropModelValue.push(dragItem); } if (dragSettings && dragSettings.placeholder === true) { dropModelValue[dropModelValue.length - 1]['jqyoui_pos'] = jqyoui_pos; } } else { $parse(dropModel + ' = dndDragItem')(scope); if (dragSettings && dragSettings.placeholder === true) { dropModelValue['jqyoui_pos'] = jqyoui_pos; } } }; this.mutateDraggable = function(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable) { var isEmpty = angular.equals(dropItem, {}), dragModelValue = scope.$eval(dragModel); scope.dndDropItem = dropItem; if (dragSettings && dragSettings.placeholder) { if (dragSettings.placeholder != 'keep'){ if (angular.isArray(dragModelValue) && dragSettings.index !== undefined) { dragModelValue[dragSettings.index] = dropItem; } else { $parse(dragModel + ' = dndDropItem')(scope); } } } else { if (angular.isArray(dragModelValue)) { if (isEmpty) { if (dragSettings && ( dragSettings.placeholder !== true && dragSettings.placeholder !== 'keep' )) { dragModelValue.splice(dragSettings.index, 1); } } else { dragModelValue[dragSettings.index] = dropItem; } } else { $parse(dragModel + ' = dndDropItem')(scope); if (scope.$parent) { $parse(dragModel + ' = dndDropItem')(scope.$parent); } } } $draggable.css({'z-index': '', 'left': '', 'top': ''}); }; this.fixIndex = function(scope, settings, modelValue) { if (settings.applyFilter && angular.isArray(modelValue) && modelValue.length > 0) { var dragModelValueFiltered = scope[settings.applyFilter](), lookup = dragModelValueFiltered[settings.index], actualIndex = undefined; modelValue.forEach(function(item, i) { if (angular.equals(item, lookup)) { actualIndex = i; } }); return actualIndex; } return settings.index; }; }]).directive('jqyouiDraggable', ['ngDragDropService', function(ngDragDropService) { return { require: '?jqyouiDroppable', restrict: 'A', link: function(scope, element, attrs) { var dragSettings, jqyouiOptions, zIndex; var updateDraggable = function(newValue, oldValue) { if (newValue) { dragSettings = scope.$eval(element.attr('jqyoui-draggable') || element.attr('data-jqyoui-draggable')) || {}; jqyouiOptions = scope.$eval(attrs.jqyouiOptions) || {}; element .draggable({disabled: false}) .draggable(jqyouiOptions) .draggable({ start: function(event, ui) { zIndex = angular.element(jqyouiOptions.helper ? ui.helper : this).css('z-index'); angular.element(jqyouiOptions.helper ? ui.helper : this).css('z-index', 9999); jqyoui.startXY = angular.element(this)[dragSettings.containment || 'offset'](); ngDragDropService.callEventCallback(scope, dragSettings.onStart, event, ui); }, stop: function(event, ui) { angular.element(jqyouiOptions.helper ? ui.helper : this).css('z-index', zIndex); ngDragDropService.callEventCallback(scope, dragSettings.onStop, event, ui); }, drag: function(event, ui) { ngDragDropService.callEventCallback(scope, dragSettings.onDrag, event, ui); } }); } else { element.draggable({disabled: true}); } }; scope.$watch(function() { return scope.$eval(attrs.drag); }, updateDraggable); updateDraggable(); element.on('$destroy', function() { if(element.data('ui-draggable')) element.draggable('destroy'); }); } }; }]).directive('jqyouiDroppable', ['ngDragDropService', function(ngDragDropService) { return { restrict: 'A', priority: 1, link: function(scope, element, attrs) { var dropSettings; var updateDroppable = function(newValue, oldValue) { if (newValue) { dropSettings = scope.$eval(angular.element(element).attr('jqyoui-droppable') || angular.element(element).attr('data-jqyoui-droppable')) || {}; element .droppable({disabled: false}) .droppable(scope.$eval(attrs.jqyouiOptions) || {}) .droppable({ over: function(event, ui) { ngDragDropService.callEventCallback(scope, dropSettings.onOver, event, ui); }, out: function(event, ui) { ngDragDropService.callEventCallback(scope, dropSettings.onOut, event, ui); }, drop: function(event, ui) { if (angular.element(ui.draggable).ngattr('ng-model') && attrs.ngModel) { ngDragDropService.invokeDrop(angular.element(ui.draggable), angular.element(this), event, ui); } else { ngDragDropService.callEventCallback(scope, dropSettings.onDrop, event, ui); } } }); } else { element.droppable({disabled: true}); } }; scope.$watch(function() { return scope.$eval(attrs.drop); }, updateDroppable); updateDroppable(); element.on('$destroy', function() { if(element.data('ui-droppable')) element.droppable('destroy'); }); } }; }]); $.fn.ngattr = function(name, value) { var element = angular.element(this).get(0); return element.getAttribute(name) || element.getAttribute('data-' + name); }; })(window, window.angular, window.jQuery); ; /*! RESOURCE: /scripts/sn.dragdrop/ui-sortable.js */ angular.module('ui.sortable', []) .value('uiSortableConfig',{}) .directive('uiSortable', [ 'uiSortableConfig', '$timeout', '$log', function(uiSortableConfig, $timeout, $log) { return { require: '?ngModel', scope: { ngModel: '=', uiSortable: '=' }, link: function(scope, element, attrs, ngModel) { var savedNodes; function combineCallbacks(first,second){ if(second && (typeof second === 'function')) { return function() { first.apply(this, arguments); second.apply(this, arguments); }; } return first; } function getSortableWidgetInstance(element) { var data = element.data('ui-sortable'); if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') { return data; } return null; } function hasSortingHelper (element, ui) { var helperOption = element.sortable('option','helper'); return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed()); } function isFloating (item) { return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display')); } function getElementScope(elementScopes, element) { var result = null; for (var i = 0; i < elementScopes.length; i++) { var x = elementScopes[i]; if (x.element[0] === element[0]) { result = x.scope; break; } } return result; } function afterStop(e, ui) { ui.item.sortable._destroy(); } var opts = {}; var directiveOpts = { 'ui-floating': undefined }; var callbacks = { receive: null, remove:null, start:null, stop:null, update:null }; var wrappers = { helper: null }; angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable); if (!angular.element.fn || !angular.element.fn.jquery) { $log.error('ui.sortable: jQuery should be included before AngularJS!'); return; } if (ngModel) { scope.$watch('ngModel.length', function() { $timeout(function() { if (!!getSortableWidgetInstance(element)) { element.sortable('refresh'); } }, 0, false); }); callbacks.start = function(e, ui) { if (opts['ui-floating'] === 'auto') { var siblings = ui.item.siblings(); var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target)); sortableWidgetInstance.floating = isFloating(siblings); } ui.item.sortable = { model: ngModel.$modelValue[ui.item.index()], index: ui.item.index(), source: ui.item.parent(), sourceModel: ngModel.$modelValue, cancel: function () { ui.item.sortable._isCanceled = true; }, isCanceled: function () { return ui.item.sortable._isCanceled; }, isCustomHelperUsed: function () { return !!ui.item.sortable._isCustomHelperUsed; }, _isCanceled: false, _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed, _destroy: function () { angular.forEach(ui.item.sortable, function(value, key) { ui.item.sortable[key] = undefined; }); } }; }; callbacks.activate = function(e, ui) { savedNodes = element.contents(); var placeholder = element.sortable('option','placeholder'); if (placeholder && placeholder.element && typeof placeholder.element === 'function') { var phElement = placeholder.element(); phElement = angular.element(phElement); var excludes = element.find('[class="' + phElement.attr('class') + '"]:not([ng-repeat], [data-ng-repeat])'); savedNodes = savedNodes.not(excludes); } var connectedSortables = ui.item.sortable._connectedSortables || []; connectedSortables.push({ element: element, scope: scope }); ui.item.sortable._connectedSortables = connectedSortables; }; callbacks.update = function(e, ui) { if(!ui.item.sortable.received) { ui.item.sortable.dropindex = ui.item.index(); var droptarget = ui.item.parent(); ui.item.sortable.droptarget = droptarget; var droptargetScope = getElementScope(ui.item.sortable._connectedSortables, droptarget); ui.item.sortable.droptargetModel = droptargetScope.ngModel; element.sortable('cancel'); } if (hasSortingHelper(element, ui) && !ui.item.sortable.received && element.sortable( 'option', 'appendTo' ) === 'parent') { savedNodes = savedNodes.not(savedNodes.last()); } savedNodes.appendTo(element); if(ui.item.sortable.received) { savedNodes = null; } if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) { scope.$apply(function () { ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0, ui.item.sortable.moved); }); } }; callbacks.stop = function(e, ui) { if(!ui.item.sortable.received && ('dropindex' in ui.item.sortable) && !ui.item.sortable.isCanceled()) { scope.$apply(function () { ngModel.$modelValue.splice( ui.item.sortable.dropindex, 0, ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]); }); } else { if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) && !angular.equals(element.contents(), savedNodes)) { if (hasSortingHelper(element, ui) && element.sortable( 'option', 'appendTo' ) === 'parent') { savedNodes = savedNodes.not(savedNodes.last()); } savedNodes.appendTo(element); } } savedNodes = null; }; callbacks.receive = function(e, ui) { ui.item.sortable.received = true; }; callbacks.remove = function(e, ui) { if (!('dropindex' in ui.item.sortable)) { element.sortable('cancel'); ui.item.sortable.cancel(); } if (!ui.item.sortable.isCanceled()) { scope.$apply(function () { ui.item.sortable.moved = ngModel.$modelValue.splice( ui.item.sortable.index, 1)[0]; }); } }; wrappers.helper = function (inner) { if (inner && typeof inner === 'function') { return function (e, item) { var innerResult = inner.apply(this, arguments); item.sortable._isCustomHelperUsed = item !== innerResult; return innerResult; }; } return inner; }; scope.$watch('uiSortable', function(newVal ) { var sortableWidgetInstance = getSortableWidgetInstance(element); if (!!sortableWidgetInstance) { angular.forEach(newVal, function(value, key) { if (key in directiveOpts) { if (key === 'ui-floating' && (value === false || value === true)) { sortableWidgetInstance.floating = value; } opts[key] = value; return; } if (callbacks[key]) { if( key === 'stop' ){ value = combineCallbacks( value, function() { scope.$apply(); }); value = combineCallbacks(value, afterStop); } value = combineCallbacks(callbacks[key], value); } else if (wrappers[key]) { value = wrappers[key](value); } opts[key] = value; element.sortable('option', key, value); }); } }, true); angular.forEach(callbacks, function(value, key) { opts[key] = combineCallbacks(value, opts[key]); if( key === 'stop' ){ opts[key] = combineCallbacks(opts[key], afterStop); } }); } else { $log.info('ui.sortable: ngModel not provided!', element); } element.sortable(opts); } }; } ]); ; /*! RESOURCE: /scripts/sn.dragdrop/_dragdrop.js */ angular.module("sn.dragdrop", ["ngDragDrop", "ui.sortable"]); ; /*! RESOURCE: /scripts/sn.dragdrop/directive.sn-draggable.js */ angular.module("sn.dragdrop").directive("snDraggable", function($compile, $parse, jqyouiDraggableDirective) { "use strict"; function isMobile() { if( 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)) { return true; } else { return false; } } function link(scope, element, attrs) { function handleNativeStart(e) { if (attrs.dndCustomPayload) { var payload = $parse(attrs.dndCustomPayload)(scope); e.originalEvent.dataTransfer.setData('text', angular.toJson(payload)); } else { var type = attrs.snDraggable; var payload = $parse(attrs.dndPayload)(scope); e.originalEvent.dataTransfer.setData('text', angular.toJson({ type: type, payload: payload })); } } scope.handleJQueryStart = function(element, ui) { if (attrs.dndCustomPayload) { var payload = $parse(attrs.dndCustomPayload)(scope); ui.helper.data("dnd-payload", angular.toJson(payload)); } else { var payload = $parse(attrs.dndPayload)(scope); var type = attrs.snDraggable; ui.helper.data("dnd-payload", angular.toJson({ type: type, payload: payload })); } } if (isMobile()) { jqyouiDraggableDirective[0].link(scope, element, attrs); } else { element.bind('dragstart', handleNativeStart); } } return { restrict: "A", compile: function(tElement, tAttrs) { if (isMobile()) { var jqyouiOptions = { helper: tAttrs.dndHelper || 'clone', revert: tAttrs.dndRevert || 'invalid' }; var draggableOptions = { onStart: "handleJQueryStart", helper: tAttrs.dndPlaceholder || 'keep' }; tAttrs.$set("drag", "true"); tAttrs.$set("jqyouiOptions", angular.toJson(jqyouiOptions)); tElement.attr("jqyoui-draggable", angular.toJson(draggableOptions)); } else { tAttrs.$set("draggable", "true"); } return link; } } }) ; /*! RESOURCE: /scripts/sn.dragdrop/directive.sn-droptarget.js */ angular.module("sn.dragdrop").directive("snDroptarget", function($compile, $parse, jqyouiDroppableDirective, $rootScope) { "use strict"; function isMobile() { if( 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)) { return true; } else { return false; } } function link(scope, element, attrs) { var dropHandler = $parse(attrs.dndOnDrop); var fileHandler; var overHandler; var outHandler; var parentWindow; var targetWindow; if (attrs.dndOnFile) fileHandler = $parse(attrs.dndOnFile); if (attrs.dndOnOver) overHandler = $parse(attrs.dndOnOver); if (attrs.dndOnOut) outHandler = $parse(attrs.dndOnOut); var enterCount = 0; element.bind("dragstart",function(e) { parentWindow = e.currentTarget; }) element.bind("dragenter", function(e) { if (e.preventDefault) e.preventDefault(); enterCount++; if (enterCount > 1) return; e.originalEvent.dataTransfer.dropEffect = 'move'; element.addClass('sn-droptarget-hover'); if (parentWindow !== e.currentTarget && overHandler) { scope.$apply( overHandler(scope, { element: element, ui: {} }) ); } }) element.bind("dragleave", function(e) { enterCount--; if (enterCount > 0) return; element.removeClass('sn-droptarget-hover'); enterCount = 0; if (outHandler) { scope.$apply( outHandler(scope, { element: element, ui: {} }) ); } }) element.bind("drop", function(e) { e.preventDefault(); e.stopPropagation(); element.removeClass('sn-droptarget-hover'); enterCount = 0; targetWindow = e.currentTarget; if(parentWindow === targetWindow) { return; } var dt = e.originalEvent.dataTransfer; if (!dt || isMobile()) return; if (fileHandler && dt.files.length > 0) { var text = dt.getData("text"); scope.$apply(function() { fileHandler(scope, { files: dt.files }) }); return; } var data = {}; try { data = angular.fromJson(dt.getData("text")); } catch(e) { data.payload = dt.getData("text"); data.type = (data.payload.substring(0, 7) === 'http://' || data.payload.substring(0, 8) === 'https://') ? 'link' : 'text'; } scope.$apply( dropHandler(scope, { element: element, ui: {}, data: data }) ); }) element.bind("dragover", function(e) { return false; }) element.bind("dragend", function(e) { parentWindow = undefined; return; }) scope.onDrop = function(event, ui) { angular.element(event.target).removeClass('sn-droptarget-hover'); var data = angular.fromJson(ui.helper.data("dnd-payload")); dropHandler(scope, { element: event.target, ui: ui, data: data }); } scope.onOver = function(event, ui) { angular.element(event.target).addClass('sn-droptarget-hover'); if (overHandler) { overHandler(scope, { element: element, ui: {} }) } } scope.onOut = function(event, ui) { angular.element(event.target).removeClass('sn-droptarget-hover'); if (outHandler) { outHandler(scope, { element: element, ui: {} }) } } jqyouiDroppableDirective[0].link(scope, element, attrs) } return { restrict: "A", compile: function(tElement, tAttrs) { if (isMobile()) { var options = { onDrop: "onDrop", onOver: "onOver", onOut: "onOut", multiple: tAttrs.snMultiple }; tAttrs.$set("drop", "true"); tElement.attr("jqyoui-droppable", angular.toJson(options)); } return link; } } }) ; /*! RESOURCE: /scripts/sn.dragdrop/directive.sn-sortable.js */ angular.module("sn.dragdrop").directive("snSortable", function(uiSortableDirective) { "use strict"; return { require: uiSortableDirective[0].require, scope: { ngModel: '=', uiSortable: '=' }, compile: function(tElement, tAttrs) { var options = tAttrs.snSortable || angular.toJson({ connectWith: tAttrs.sortableContainer }); tAttrs.$set("uiSortable", options); return uiSortableDirective[0].link; } }; }) ; /*! RESOURCE: /scripts/sn.dragdrop/directive.snDragEventBlocker.js */ angular.module("sn.dragdrop").directive("snDragEventBlocker", function() { "use strict"; return { restrict: "A", link: function(scope, element) { element.bind("dragenter", killEvent) element.bind("dragover", killEvent); element.bind("drop", killEvent); element.bind("dragleave", killEvent) function killEvent(e) { if (e.stopPropagation) e.stopPropagation(); if (e.preventDefault) e.preventDefault(); return false; } } } }) ; ; /*! RESOURCE: /scripts/thirdparty/angular-placeholder.min.js */ /*! angular-shims-placeholder - v0.4.2 - 2015-05-11 * https://github.com/cvn/angular-shims-placeholder * Copyright (c) 2015 Chad von Nau; Licensed MIT */ !function(a,b){"use strict";a.module("ng.shims.placeholder",[]).service("placeholderSniffer",["$document",function(a){this.emptyClassName="empty",this.hasPlaceholder=function(){var b=a[0].createElement("input");return void 0!==b.placeholder}}]).directive("placeholder",["$timeout","$document","$interpolate","$injector","placeholderSniffer",function(c,d,e,f,g){if(g.hasPlaceholder())return{};var h=!1,i=parseFloat(a.version.full);try{var j=f.get("$animate")}catch(k){}return{restrict:"A",require:"?ngModel",priority:i>=1.2?110:-10,link:function(f,k,l,m){function n(){var a=k.val();k.hasClass(M)&&a&&a===L||o(function(){p(a)})}function o(a){b.documentMode<=11?c(a,0):a()}function p(a){a||0===a||H===b.activeElement?(k.removeClass(M),k.val(a)):(k.addClass(M),k.val(K?"":L)),K&&(v(),j&&w())}function q(){return m?f.$eval(l.ngModel)||"":r()||""}function r(){var a=k.val();return a===l.placeholder&&(a=""),a}function s(a){k.hasClass(M)&&k.val()===L&&k.val(""),L=a,n()}function t(a,b){b?a.attr("unselectable","on"):a.removeAttr("unselectable")}function u(){F=a.element('<input type="text" value="'+L+'"/>'),y(),A(F),F.addClass(M).bind("focus",D),H.parentNode.insertBefore(F[0],H);for(var b=[l.ngDisabled,l.ngReadonly,l.ngRequired,l.ngShow,l.ngHide],c=0;c<b.length;c++)b[c]&&f.$watch(b[c],x)}function v(){y(),E()?A(F):k.hasClass(M)&&H!==b.activeElement?B():C()}function w(){i>=1.3?j.addClass(k,"").then(v):j.addClass(k,"",v)}function x(){j?w():v()}function y(){F.val(L),F.attr("class",k.attr("class")||"").attr("style",k.attr("style")||"").prop("disabled",k.prop("disabled")).prop("readOnly",k.prop("readOnly")).prop("required",k.prop("required")),t(F,"on"===k.attr("unselectable"))}function z(a){i>=1.2?a.removeClass(N):a.css("display","")}function A(a){i>=1.2?a.addClass(N):a.css("display","none")}function B(){A(k),z(F)}function C(){A(F),z(k)}function D(){C(),H.focus()}function E(){var a="undefined"!=typeof l.ngShow,b="undefined"!=typeof l.ngHide;return a||b?a&&!f.$eval(l.ngShow)||b&&f.$eval(l.ngHide):!1}var F,G=q(),H=k[0],I=H.nodeName.toLowerCase(),J="input"===I||"textarea"===I,K="password"===l.type,L=l.placeholder,M=g.emptyClassName,N="ng-hide";J&&(l.$observe("placeholder",function(a){s(a)}),K&&u(),p(G),k.bind("focus",function(){k.hasClass(M)&&(k.val(""),k.removeClass(M),H.select())}),k.bind("blur",n),m||k.bind("change",function(){s(e(k.attr("placeholder"))(f))}),m&&(m.$render=function(){p(m.$viewValue),H!==b.activeElement||k.val()||H.select()}),h||(d.bind("selectstart",function(b){var c=a.element(b.target);c.hasClass(M)&&c.prop("disabled")&&b.preventDefault()}),h=!0))}}}])}(window.angular,window.document); /*! RESOURCE: /scripts/create_favorite/_module.js */ angular.module('Magellan.createFavorite', ['sn.common.util']); ; /*! RESOURCE: /scripts/create_favorite/directive.magellanColorPicker.js */ angular.module('Magellan.createFavorite').directive('magellanColorPicker', ['getTemplateUrl', function(getTemplateUrl) { return { restrict : 'E', templateUrl : getTemplateUrl('magellan_color_picker.xml'), scope : { activeColor : '=' }, controller : function($scope, $rootScope, $http, $timeout) { if (window.top && window.top.Magellan && window.top.Magellan.globals && window.top.Magellan.globals.navColors) { $scope.colors = window.top.Magellan.globals.navColors; } else { $http.get('/api/now/ui/favorite/iconsandcolors').then(function(response) { if (response && response.data && response.data.result) { if (response.data.result.colors) { window.top.Magellan = window.top.Magellan || {}; window.top.Magellan.globals = window.top.Magellan.globals || {}; window.top.Magellan.globals.navColors = JSON.parse(response.data.result.colors); $scope.colors = window.top.Magellan.globals.navColors; } } }); } $rootScope.$on("currentFavorite.changed", function(e) { $scope.init(); }); $scope.capitalize = function(string) { return string.charAt(0).toUpperCase() + string.slice(1); } $scope.init = function() { $timeout(function() { if (!document.getElementById('magellan-color-group')) return; $scope.colorGroup = new RadioGroup(document.getElementById('magellan-color-group')).init(); angular.element('.color-option').each(function(i,e) { deSelectColor(e); }); if (!$scope.activeColor) selectColor(angular.element('.color-option').first()); if ($scope.activeColor === "normal") selectColor(angular.element('.color-option')[1]); else selectColor(angular.element('.color-bg-' + $scope.activeColor).first()); }, 150); } selectColor = function($el) { if (!$el.attr) $el = angular.element($el); $el.attr('tabindex', 0); $el.attr('aria-checked', true); if (!$el.hasClass('icon-check')) $el.addClass('icon-check'); } deSelectColor = function($el) { if (!$el.attr) $el = angular.element($el); $el.attr('tabindex', '-1'); $el.attr('aria-checked', false); $el.removeClass('icon-check'); } $scope.init(); $scope.changeColor = function(newValue, oldValue) { var previousValue = oldValue ? oldValue : $scope.activeColor; if (newValue != previousValue) { angular.element('.color-option').each(function(i,e) { deSelectColor(e); }); $rootScope.$broadcast('magellanColorPicker:colorSelected', newValue); } }; } } }]); ; /*! RESOURCE: /scripts/create_favorite/directive.magellanIconPicker.js */ angular.module('Magellan.createFavorite').directive('magellanIconPicker', ['getTemplateUrl', function(getTemplateUrl) { return { restrict: 'E', templateUrl : getTemplateUrl('magellan_icon_picker.xml'), scope: { activeColor : '=', activeIcon : '=' }, controller : function($scope, $rootScope, $http, $timeout) { if (window.top && window.top.Magellan && window.top.Magellan.globals && window.top.Magellan.globals.navIcons) { $scope.icons = window.top.Magellan.globals.navIcons; } else { $http.get('/api/now/ui/favorite/iconsandcolors').then(function(response) { if (response && response.data && response.data.result) { if (response.data.result.icons) { window.top.Magellan = window.top.Magellan || {}; window.top.Magellan.globals = window.top.Magellan.globals || {}; window.top.Magellan.globals.navIcons = JSON.parse(response.data.result.icons); $scope.icons = window.top.Magellan.globals.navIcons; } } }); } $scope.updateIcon = function($event, icon) { $event.preventDefault( ); $event.stopImmediatePropagation( ); $scope.activeIcon = icon; $rootScope.$broadcast('magellanIconPicker:iconSelected', icon); }; $rootScope.$on("currentFavorite.changed", function(e) { $scope.init(); }); $scope.init = function() { $timeout(function() { if (!document.getElementById('magellan-icon-group')) return; $scope.colorGroup = new RadioGroup(document.getElementById('magellan-icon-group')).init(); angular.element('.option-icon').each(function(i,e) { var $el = angular.element(e); $el.attr('tabindex', '-1'); $el.attr('aria-checked', false); if (($el).hasClass('selected')) highlightIcon($el); }); if (angular.element('.option-icon.selected').length === 0) highlightIcon(angular.element('.option-icon').first()); }, 150); } $scope.capitalize = function(string) { return string.charAt(0).toUpperCase() + string.slice(1); } highlightIcon = function($el) { if (!$el.attr) $el = angular.element($el); $el.attr('tabindex', 0); $el.attr('aria-checked', true); } $scope.init(); $rootScope.$on('magellanColorPicker:colorSelected', function(evt, color) { $scope.activeColor = color; }); } } }]); ; /*! RESOURCE: /scripts/app.magellan/fast/js_includes_fast.js */ /*! RESOURCE: /scripts/app.magellan/fast/directive.concourseApplicationTree.js */ angular.module('Magellan').directive('concourseApplicationTree', function( $q, $timeout, getTemplateUrl, $rootScope, concourseNavigatorService, $window, i18n ) { 'use strict'; var DEBUG_LOG = 'concourseApplicationTree'; var DEBUG_METRICS = concourseNavigatorService.DEBUG_METRICS; var TYPE_APP = 'APP'; var TYPE_MODULE = 'MODULE'; var TYPE_SEPARATOR = 'SEPARATOR'; var TYPE_PARENT = 'PARENT'; var ITEM_HEIGHT = 40; return { restrict: 'E', templateUrl: getTemplateUrl('concourse_application_tree.xml'), scope: { }, controller: function($scope) { var CLIENT_HEIGHT = _getClientHeight(); var applicationHeights = {}; var applicationScrollTop = []; $scope.renderApplicationsOnScreen = renderApplicationsOnScreen; $scope.renderAllApplications = renderAllApplications; $scope.closeAllApplications = closeAllApplications; $scope.isMaxScroll = isMaxScroll; $scope.getApplicationStyles = getApplicationStyles; $scope.getModuleDisplayType = _getModuleDisplayType; $scope.canEdit = concourseNavigatorService.canEdit; $scope.delegateTreeClick = function($event) { var $target = angular.element($event.target); if ($target.hasClass('app-node') || $target.parent().hasClass('app-node')) { var scope = $target.scope(); if (scope.application) { scope.application.inView = true; _initializeLazyRender($scope.applications); $timeout(function() { renderApplicationsOnScreen(); }); } } }; function getApplicationStyles(app) { var min = getApplicationMinHeight(app); return min > ITEM_HEIGHT ? {minHeight: min} : {}; } function getApplicationMinHeight(app) { if (app.open && !app.inView) { var moduleCount = app.modules.length; return ITEM_HEIGHT + moduleCount * ITEM_HEIGHT; } return ITEM_HEIGHT; } function isMaxScroll(top) { return top > applicationScrollTop[applicationScrollTop.length - 1] - CLIENT_HEIGHT; } var lastScrollTop = 0; function renderApplicationsOnScreen(scrollTop) { if (!$scope.applications) { return; } if (angular.isUndefined(scrollTop)) { scrollTop = lastScrollTop; } else { lastScrollTop = scrollTop; } var FUDGE = CLIENT_HEIGHT * 2; var toRender = []; for (var i = 0, iM = applicationScrollTop.length; i < iM; i++) { if (scrollTop > applicationScrollTop[i] - FUDGE) { var app = $scope.applications[i]; if (app.open && !app.inView) { toRender.push(app); } } } _renderMissingApplications(toRender); } function renderAllApplications() { if (!$scope.applications) { return $q.when(true); } return _renderMissingApplications($scope.applications, true).then(function() { return $timeout(angular.noop); }); } function closeAllApplications() { if (!$scope.applications) { return $q.when(true); } return $timeout(function() { $scope.applications.forEach(function(app) { app.open = false; }); }); } concourseNavigatorService.onChangeApps(function(newTree) { _initializeLazyRender(newTree); _renderTree(newTree); }); function _initializeLazyRender(t) { DEBUG_METRICS && console.time(DEBUG_LOG + ':Init lazy render'); var scrollTop = 0; t.forEach(function(app, index) { var counts = concourseNavigatorService.getVisibleModuleCountByType(app); var applicationHeight = ITEM_HEIGHT + (counts.modules * ITEM_HEIGHT); applicationScrollTop[index] = scrollTop; scrollTop += applicationHeights[index] = applicationHeight; }); for (var i = 0, iM = t.length ; i < iM; i++) { t[i].inView = true; } DEBUG_METRICS && console.timeEnd(DEBUG_LOG + ':Init lazy render'); } function _getClientHeight() { var clientHeight; if (typeof document.documentElement !== 'undefined') { clientHeight = document.documentElement.clientHeight; } if (typeof clientHeight === 'undefined') { clientHeight = 1024; } return clientHeight; } function _renderTree(t) { DEBUG_METRICS && console.time(DEBUG_LOG + ':Render'); $scope.applications = t; buildAppTree(); DEBUG_METRICS && console.timeEnd(DEBUG_LOG + ':Render'); $rootScope.$emit('applicationTree.rendered'); } function updateForScreenReader(numFilteredResults) { var results = i18n.format(i18n.getMessage('Items found: {0}'), numFilteredResults); var ariaLiveNode = document.querySelector('#nav-filter-aria-live'); var spanNode = angular.element('<span/>').text(results)[0]; ariaLiveNode.appendChild(spanNode); $timeout(function() { ariaLiveNode.removeChild(spanNode); }, 2000, false); } var FRAME_SIZE = 200; concourseNavigatorService.onChangeVisibility(function(result) { var itemsVisibility = result.items; var apps = result.apps; var numVisibleModules = result.numVisibleModules; if (numVisibleModules !== void 0) { updateForScreenReader(numVisibleModules); } _renderMissingApplications(apps, true).then(function() { for (var i = 0, iM = itemsVisibility.length; (i * FRAME_SIZE) < iM; i++) { (function(frameIndex) { $window.requestAnimationFrame(function() { DEBUG_METRICS && console.time(DEBUG_LOG + ':Render frame #' + frameIndex); _updateFrameVisibility(itemsVisibility, frameIndex, FRAME_SIZE); DEBUG_METRICS && console.timeEnd(DEBUG_LOG + ':Render frame #' + frameIndex); }); })(i); } }); }); function _renderMissingApplications(apps, verifyInview) { DEBUG_METRICS && console.time(DEBUG_LOG + ':Render missing applications'); if (verifyInview) { var missing = []; apps.forEach(function(app) { if (!app.inView) { missing.push(app); } }); apps = missing; } if (apps.length > 0) { return $timeout(function() { apps.forEach(function(app) { app.inView = true; }); $timeout(function() { DEBUG_METRICS && console.timeEnd(DEBUG_LOG + ':Render missing applications'); }); }); } else { DEBUG_METRICS && console.timeEnd(DEBUG_LOG + ':Render missing applications'); return $q.when(true); } } function _updateFrameVisibility(itemsVisibility, frameIndex, frameSize) { var itemVisibility; var itemKey; var $el; var $firstChild; var el; var elDisplay; for (var i = frameIndex * frameSize, iM = i + frameSize; i < iM; i++) { itemVisibility = itemsVisibility[i]; if (!itemVisibility) { return; } itemKey = (itemVisibility.id || "").split("_").pop(); concourseNavigatorService.setVisibilityForKey(itemKey, itemVisibility.visible); $el = angular.element('#' + itemVisibility.id); switch (itemVisibility.type) { case TYPE_APP: _setMenuState($el, itemVisibility.open); break; case TYPE_PARENT: $firstChild = $el.children('div'); _setMenuState($firstChild, itemVisibility.open); break; } el = $el[0]; if (!el) { continue; } elDisplay = itemVisibility.visible ? '' : 'none'; el.style.display = elDisplay; } } function _setMenuState($el, isOpen) { if (isOpen) { $el.children('a.collapsed').removeClass('collapsed').addClass('nav-open-state'); $el.children('ul.collapse').addClass('in').css('height', ''); } else { $el.children('a.nav-open-state').removeClass('nav-open-state').addClass('collapsed'); $el.children('ul.collapse').removeClass('in').css('height', '0px'); } $el.children('a').attr('aria-expanded', isOpen); } function _getModuleDisplayType(module) { switch (module.type) { case TYPE_SEPARATOR: return 'NONE'; case TYPE_APP: return TYPE_APP; case TYPE_PARENT: return TYPE_PARENT; default: return TYPE_MODULE; } } function setText(elem, value) { if (typeof elem.textContent !== "undefined") { elem.textContent = value; } else { elem.innerText = value; } } var APPLICATION_LI_WIDGET = document.createElement('li'); APPLICATION_LI_WIDGET.className = 'sn-widget'; var APPLICATION_ANCHOR = document.createElement('a'); APPLICATION_ANCHOR.className = 'app-node sn-aside-group-title sn-aside-group-title_selectable sn-aside-group-title_nav sn-aside-group-title_hidden nav-application-overwrite'; APPLICATION_ANCHOR.setAttribute('href', 'javascript:void(0)'); APPLICATION_ANCHOR.setAttribute('role', 'button'); APPLICATION_ANCHOR.setAttribute('data-sn-toggle', 'collapse'); var EDIT_APP_BUTTON = document.createElement('button'); EDIT_APP_BUTTON.setAttribute('type', 'button'); EDIT_APP_BUTTON.setAttribute('role', 'link'); EDIT_APP_BUTTON.className = 'sn-aside-btn btn btn-icon sn-aside-btn_control state-overwrite-hidden icon-edit nav-edit-app nav-app-button app-action-icon-btn'; EDIT_APP_BUTTON.setAttribute('onclick', 'javascript:void(0)'); var FAV_APP_BUTTON = document.createElement('button'); FAV_APP_BUTTON.setAttribute('type', 'button'); FAV_APP_BUTTON.className = 'sn-aside-btn btn btn-icon sn-aside-btn_control nav-favorite-app nav-app-button app-action-icon-btn'; var MODULE_LIST_UL = document.createElement('ul'); MODULE_LIST_UL.className = 'sn-widget-list_v2 sn-widget-list_dense collapse'; var LI_WIDGET = document.createElement('li'); var MODULE_DIV_WIDGET = document.createElement('div'); MODULE_DIV_WIDGET.className = 'sn-widget-list_v2 sn-widget-list_dense'; var TOGGLE_FOLD_ANCHOR_WIDGET = document.createElement('a'); TOGGLE_FOLD_ANCHOR_WIDGET.className = 'nav-expandable sn-aside-group-title sn-aside-group-title_selectable sn-aside-group-title_nav'; TOGGLE_FOLD_ANCHOR_WIDGET.setAttribute('href', 'javascript:void(0)'); TOGGLE_FOLD_ANCHOR_WIDGET.setAttribute('role', 'button'); TOGGLE_FOLD_ANCHOR_WIDGET.setAttribute('data-sn-toggle', 'collapse'); var SIDE_SPAN_WIDGET = document.createElement('span'); SIDE_SPAN_WIDGET.className = 'sn-aside-btn icon-vcr-right'; var SUB_MODULE_UL_WIDGET = document.createElement('ul'); SUB_MODULE_UL_WIDGET.className = 'sn-widget-list_v2 sn-widget-list_dense collapse'; var EDIT_MODULE_BUTTON = document.createElement('button'); EDIT_MODULE_BUTTON.className = 'btn btn-icon sn-widget-list-action state-disable-animation icon-edit nav-edit-module module-action-icon-btn'; EDIT_MODULE_BUTTON.setAttribute('onclick', 'javascript:void(0)'); EDIT_MODULE_BUTTON.setAttribute('type', 'button'); EDIT_MODULE_BUTTON.setAttribute('role', 'link'); EDIT_MODULE_BUTTON.setAttribute('data-dynamic-title', i18n.getMessage('Edit Module')); var FAV_MODULE_BUTTON = document.createElement('button'); FAV_MODULE_BUTTON.className = 'btn btn-icon sn-widget-list-action nav-favorite-module module-action-icon-btn'; FAV_MODULE_BUTTON.setAttribute('onclick', 'javascript:void(0)'); FAV_MODULE_BUTTON.setAttribute('type', 'button'); function buildAppTree() { var applicationTree = document.querySelector('#concourse_application_tree'); applicationTree.innerHTML = ''; for (var i = 0; i < $scope.applications.length; i++) { var application = $scope.applications[i]; applicationTree.appendChild(buildApp(application)); } } function buildApp(application) { var applicationElement = APPLICATION_LI_WIDGET.cloneNode(false); applicationElement.setAttribute('id', 'concourse_application_' + application.id); var applicationLink = APPLICATION_ANCHOR.cloneNode(false); applicationElement.appendChild(applicationLink); if (application.favorited) { applicationLink.className += ' state-overwrite'; } applicationLink.setAttribute('data-target', '#collapseId' + application.id); if (application.open) { applicationLink.setAttribute('aria-controls', 'collapseId' + application.id); } applicationLink.setAttribute('aria-expanded', application.open); applicationLink.setAttribute('data-id', application.id); if (application.hint) { applicationLink.setAttribute('title', application.hint); } else { applicationLink.setAttribute('data-tooltip-overflow-only', 'true'); applicationLink.setAttribute('data-omit-aria-describedby', 'true'); } applicationLink.setAttribute('data-placement', 'right'); var titleElement = document.createElement('span'); titleElement.setAttribute('data-tooltip-overflow-only-text', 'true'); applicationLink.appendChild(titleElement); setText(titleElement, application.title); if ($scope.canEdit()) { var editButton = EDIT_APP_BUTTON.cloneNode(false); applicationElement.appendChild(editButton); editButton.setAttribute('title', i18n.getMessage('Edit Application')); editButton.setAttribute('aria-label', i18n.getMessage('Edit Application') + ': ' + application.title); editButton.setAttribute('data-id', application.id); } var favButton = FAV_APP_BUTTON.cloneNode(false); applicationElement.appendChild(favButton); if (application.favorited) { favButton.className += ' icon-star state-overwrite' } else { favButton.className += ' icon-star-empty'; } favButton.setAttribute('aria-pressed', application.favorited); favButton.setAttribute('data-id', application.id); favButton.setAttribute('data-favorite-title', application.title); favButton.setAttribute('aria-label', (application.favorited ? i18n.getMessage('Remove from Favorites') : i18n.getMessage('Add to Favorites')) + ': ' + application.title); favButton.setAttribute('data-dynamic-title', application.favorited ? i18n.getMessage('Remove from Favorites') : i18n.getMessage('Add to Favorites')); applicationElement.appendChild(buildModuleList(application)); return applicationElement; } function buildModuleList(application) { var moduleListContainer = MODULE_LIST_UL.cloneNode(false); moduleListContainer.setAttribute('id', 'collapseId' + application.id); moduleListContainer.setAttribute('aria-label', i18n.getMessage('Modules for Application') + ': ' + application.title); if (application.open) { moduleListContainer.className += ' in'; } for (var j = 0; j < application.modules.length; j++) { var module = application.modules[j]; var moduleElement = LI_WIDGET.cloneNode(false); moduleListContainer.appendChild(moduleElement); moduleElement.setAttribute('id', 'concourse_module_' + module.id); var moduleDiv = MODULE_DIV_WIDGET.cloneNode(false); moduleElement.appendChild(moduleDiv); var moduleDisplayType = $scope.getModuleDisplayType(module); if (moduleDisplayType === 'PARENT') { var toggleFoldLink = TOGGLE_FOLD_ANCHOR_WIDGET.cloneNode(false); moduleDiv.appendChild(toggleFoldLink); toggleFoldLink.setAttribute('data-target', '#collapseId' + module.id); toggleFoldLink.setAttribute('aria-controls', 'collapseId' + module.id); toggleFoldLink.setAttribute('aria-expanded', module.open); toggleFoldLink.setAttribute('data-id', module.id); if (module.open) { toggleFoldLink.className += ' nav-open-state'; } else { toggleFoldLink.className += ' collapsed'; } if (module.hint) { toggleFoldLink.setAttribute('title', module.hint); } else { toggleFoldLink.setAttribute('data-tooltip-overflow-only', 'true'); toggleFoldLink.setAttribute('data-omit-aria-describedby', 'true'); } toggleFoldLink.setAttribute('data-placement', 'right'); var sideSpan = SIDE_SPAN_WIDGET.cloneNode(false); toggleFoldLink.appendChild(sideSpan); var titleSpan = document.createElement('span'); titleSpan.setAttribute('data-tooltip-overflow-only-text', 'true'); setText(titleSpan, module.title); toggleFoldLink.appendChild(titleSpan); var subModuleList = SUB_MODULE_UL_WIDGET.cloneNode(false); moduleDiv.appendChild(subModuleList); subModuleList.setAttribute('id', 'collapseId' + module.id); subModuleList.setAttribute('aria-label', i18n.getMessage('Submodules for Module') + ': ' + module.title); if (module.open) { subModuleList.className += ' in'; } for (var k = 0; k < module.modules.length; k++) { var subModule = module.modules[k]; var subModuleElement = document.createElement('li'); subModuleList.appendChild(subModuleElement); subModuleElement.setAttribute('id', 'concourse_module_' + subModule.id); subModuleElement.appendChild(buildModule(subModule)); } } else if (moduleDisplayType === 'MODULE') { moduleDiv.appendChild(buildModule(module)); } if (module.type === 'SEPARATOR') { moduleElement.className += ' sn-widget-list-divider'; var srSpan = document.createElement('span') srSpan.className = 'sr-only'; srSpan.innerHTML = i18n.getMessage('Separator'); moduleDiv.appendChild(srSpan); } } return moduleListContainer; } function accessibilityEnabled() { return Boolean(window.g_accessibility); } function buildModule(module) { var container = document.createElement('div'); container.setAttribute('style', 'width: 100%'); var anchor = document.createElement('a'); container.appendChild(anchor); var classes = ['sn-widget-list-item', 'sn-widget-list-item_hidden-action', 'module-node']; if (accessibilityEnabled()) { classes.push('accessible-nav-focus'); classes.push('default-focus-outline'); } anchor.className = classes.join(' '); anchor.setAttribute('href', module.uri); anchor.setAttribute('target', module.windowName); anchor.setAttribute('id', module.id); var h = module.hint || ''; if (module.windowName !== 'gsft_main') { if (h) h += " - "; h += i18n.getMessage('Link opens in new window'); } if (h) { anchor.setAttribute('title', h); } else { anchor.setAttribute('data-tooltip-overflow-only', 'true'); anchor.setAttribute('data-omit-aria-describedby', 'true'); } anchor.setAttribute('data-placement', 'right'); if (module.uriRelationships) anchor.setAttribute('rel', module.uriRelationships); var titleOuterDiv = document.createElement('div'); anchor.appendChild(titleOuterDiv); titleOuterDiv.className = 'sn-widget-list-content'; titleOuterDiv.setAttribute('data-id', module.id); var titleInnerDiv = document.createElement('div'); titleOuterDiv.appendChild(titleInnerDiv); titleInnerDiv.className = 'sn-widget-list-title'; titleInnerDiv.setAttribute('data-tooltip-overflow-only-text', 'true'); setText(titleInnerDiv, module.title); if ($scope.canEdit()) { var editDiv = document.createElement('div'); container.appendChild(editDiv); editDiv.className = 'sn-widget-list-content sn-widget-list-content_static sn-widget-list-content_actions sn-widget-list-content_hidden nav-content_hidden state-disable-animation ie9-hook'; var editButton = EDIT_MODULE_BUTTON.cloneNode(false); editDiv.appendChild(editButton); editButton.setAttribute('aria-label', i18n.getMessage('Edit Module') + ': ' + module.title); editButton.setAttribute('data-id', module.id); } var favDiv = document.createElement('div'); container.appendChild(favDiv); favDiv.className = 'sn-widget-list-content sn-widget-list-content_static sn-widget-list-content_actions sn-widget-list-content_hidden nav-content_hidden state-disable-animation'; var favButton = FAV_MODULE_BUTTON.cloneNode(false); favDiv.appendChild(favButton); if (module.favorited) { favButton.className += ' icon-star state-overwrite'; } else { favButton.className += ' icon-star-empty'; } favButton.setAttribute('data-id', module.id); favButton.setAttribute('data-favorite-title', module.title); favButton.setAttribute('data-dynamic-title', module.favorited ? i18n.getMessage('Remove from Favorites') : i18n.getMessage('Add to Favorites')); favButton.setAttribute('aria-label', (module.favorited ? i18n.getMessage('Remove from Favorites') : i18n.getMessage('Add to Favorites')) + ': ' + module.title); favButton.setAttribute('aria-pressed', module.favorited); return container; } }, link: function(scope, element) { var $scrollContainer = angular.element('#nav_west_center'); var maxScroll = 0; $scrollContainer.on('scroll', scrollHandler); function unbindScrollHandler() { $scrollContainer.off('scroll', scrollHandler); } function scrollHandler(e) { var top = $scrollContainer.scrollTop(); if (top > maxScroll) { maxScroll = top; scope.renderApplicationsOnScreen(top); if (scope.isMaxScroll(top)) { unbindScrollHandler(); } } } angular.element(element).on('show.bs.collapse', function(e) { var $this = angular.element(e.target).siblings('[data-sn-toggle="collapse"]'); $this.addClass('nav-open-state'); $this.attr('aria-expanded', 'true'); var type = $this.hasClass('app-node') ? TYPE_APP : TYPE_PARENT; var id = $this.data('id'); concourseNavigatorService.setOpenState(type, id, true); }); angular.element(element).on('hide.bs.collapse', function(e) { var $this = angular.element(e.target).siblings('[data-sn-toggle="collapse"]'); $this.removeClass('nav-open-state'); $this.attr('aria-expanded', 'false'); var type = $this.hasClass('app-node') ? TYPE_APP : TYPE_PARENT; var id = $this.data('id'); concourseNavigatorService.setOpenState(type, id, false); }); } }; }); ; /*! RESOURCE: /scripts/app.magellan/fast/directive.ngModelUpdateOnEnter.js */ angular.module('Magellan').directive('ngModelUpdateOnEnter', function() { return { restrict: 'A', require: 'ngModel', scope: { 'onEnter': '<?ngModelUpdateOnEnter' }, link: function(scope, element, attrs, ctrl) { element.on('keyup', function(ev) { if (ev.keyCode === 13) { _applyUtil(scope, function() { ctrl.$commitViewValue(); if (scope.onEnter) { scope.onEnter(ev); } }); } }); function _applyUtil($scope, f) { if (!$scope.$$phase) { $scope.$apply(f); } else { f(); } } } }; }); ; /*! RESOURCE: /scripts/app.magellan/fast/concourseNavigatorService.js */ angular.module('Magellan').factory('concourseNavigatorService', function( $q, $window, glideUrlBuilder, userPreferences, urlTools ) { 'use strict'; var DEBUG_LOG = 'concourseNavigatorService'; var DEBUG_METRICS = false; var ALLOW_SINGLE_CHAR = "" === "true"; var STATE_INITIALIZING = 'INIT'; var STATE_ALL = 'ALL'; var STATE_FILTERING = 'FILTERING'; var STATE_REMOVING_FILTERING = 'REMOVING'; var STATE_ADDING_FILTERING = 'ADDING'; var _state = STATE_INITIALIZING; var TYPE_APP = 'APP'; var TYPE_MODULE = 'MODULE'; var TYPE_SEPARATOR = 'SEPARATOR'; var TYPE_PARENT = 'PARENT'; var APP_PREFIX = 'concourse_application_'; var MODULE_PREFIX = 'concourse_module_'; var EVENT_CHANGE_APPS = 'apps'; var EVENT_CHANGE_VISIBILITY = 'visibility'; var _eventSubscribers = {}; var _navigatorApps = []; var _parentsById = {}; var _filterTerm = ''; var _filteredVisibility = {}; var FILTERED_VISIBILITY_MOD_LIMIT = 2; var IS_ADMIN = $window.NOW.user.roles && $window.NOW.user.roles.split(',').indexOf('admin') !== -1; function canEdit() { return IS_ADMIN; } function setApplications(apps) { _navigatorApps.length = 0; _parentsById = {}; DEBUG_METRICS && console.time(DEBUG_LOG + ':Create applications'); _createApplications(apps); DEBUG_METRICS && console.timeEnd(DEBUG_LOG + ':Create applications'); _fireEvent(EVENT_CHANGE_APPS, _navigatorApps); if (_state === STATE_FILTERING) { _filteredVisibility = {}; var visibilityDelta = _filterApplications(_filterTerm); _fireEvent(EVENT_CHANGE_VISIBILITY, visibilityDelta); } else { _state = STATE_ALL; } } function setOpenState(type, sysId, isOpen) { if (_state !== STATE_ALL) { return; } var key = _getKey(type, sysId); _parentsById[key].open = isOpen; switch (type) { case TYPE_APP: userPreferences.setPreference('menu.' + sysId + '.expanded', isOpen ? 'true' : ''); break; case TYPE_PARENT: userPreferences.setPreference('collapse.section.' + sysId, isOpen ? '' : 'true'); break; } } function setFilterTerm(value) { if (!angular.isString(value)) { value = ''; } if (!ALLOW_SINGLE_CHAR && value.length === 1) { return; } if (_filterTerm === value) { return; } var _isFiltering = value.length > 0; if (_isFiltering) { if (_state === STATE_ALL) { _filteredVisibility = {}; _state = STATE_ADDING_FILTERING; } } else { if (_state === STATE_FILTERING) { _state = STATE_REMOVING_FILTERING; } } DEBUG_METRICS && console.time(DEBUG_LOG + ':Get visibility delta'); var _visibilityDelta = _isFiltering ? _filterApplications(value) : _unfilterApplications(); DEBUG_METRICS && console.timeEnd(DEBUG_LOG + ':Get visibility delta'); _fireEvent(EVENT_CHANGE_VISIBILITY, _visibilityDelta); _filterTerm = value; if (_isFiltering) { _state = STATE_FILTERING; } else { _state = STATE_ALL; } } function getVisibleModuleCountByType(app) { var visibleChildren = 0; var visibleSeparators = 0; if (app.open && app.modules) { app.modules.forEach(function(module) { switch (module.type) { case TYPE_SEPARATOR: visibleSeparators++; break; default: visibleChildren++; break; } if (module.open && module.modules) { visibleChildren += module.modules.length; } }); } return { modules: visibleChildren, separators: visibleSeparators }; } function _getKey(type, sysId) { return angular.isDefined(sysId) ? type + '_' + sysId : type.type + '_' + type.id; } function _createApplications(apps) { var newApps = []; apps.forEach(function(app) { var newApp = _createApplication(app); newApps.push(newApp); var key = _getKey(newApp); _parentsById[key] = newApp; }); _navigatorApps.push.apply(_navigatorApps, newApps); } function _createApplication(application) { var open = application.open; if (angular.isUndefined(open)) { open = false; } return { id: application.id, type: TYPE_APP, title: application.title, hint: application.hint, color: application.color, favorited : application.favorited, open: open, modules: _createModules(application.modules) }; } function _createModules(modules) { var appModules = []; if (!modules || modules.length == 0) { return appModules; } modules.forEach(function(module) { var appModule = _createModule(module); appModules.push(appModule); switch (appModule.type) { case TYPE_SEPARATOR: if (angular.isUndefined(module.title) || module.title === '') { appModules.push.apply(appModules, appModule.modules); appModule.modules = []; } else { appModule.type = TYPE_PARENT; var key = _getKey(appModule); _parentsById[key] = appModule; } break; } }); return appModules; } function _createModule(module) { var moduleUri = _buildModuleURI(module); var uriRelationships = _getUriRelationships(moduleUri); var appModule = { name: module.name, filter: module.filter, type: module.type, id: module.id, title: module.title, hint: module.hint, viewName : module.viewName, uri: moduleUri, uriRelationships: uriRelationships, open: module.open, windowName: module.windowName || 'gsft_main', favorited: module.favorited, modules: _createModules(module.modules) }; return appModule; } function _buildModuleURI(module){ if (typeof module === 'undefined') { return; } if (module.type === 'FILTER') { module.uri = module.name + "_list.do?sysparm_view=" + module.viewName + "&sysparm_filter_only=true&sysparm_query=" + module.filter; } var uri = module.cancelable === 'true' ? glideUrlBuilder.getCancelableLink(module.uri) : module.uri; if (module.type !== 'LIST') { return uri; } return _appendClearStack(uri); } function _getUriRelationships(uri) { return uri && urlTools.isUrlExternal(uri) ? 'noopener noreferrer' : null; } function _appendClearStack(link){ var nextChar = link.indexOf('?') > -1 ? '&' : '?'; link += nextChar + "sysparm_clear_stack=true"; return link; } function _unfilterApplications() { var visibilityDelta = []; _navigatorApps.forEach(function(app) { _restoreVisibility(app, visibilityDelta); _eachChild(app, function(module) { _restoreVisibility(module, visibilityDelta); }); }); return { items: visibilityDelta, apps: [] }; } function _filterApplications(filterText) { filterText = filterText.toLowerCase(); var filteredItems = []; var visibleApps = []; var numVisibleModules = [0]; _navigatorApps.forEach(function(app) { var showApp = _computeFilteredVisibility(filterText, app, filteredItems, numVisibleModules); if (showApp) { visibleApps.push(app); } _setFilteredVisibility(app, showApp, filteredItems); }); return { items: filteredItems, apps: visibleApps, numVisibleModules: numVisibleModules[0] }; } function _computeFilteredVisibility(filterText, parent, filteredItems, numVisibleModules) { var excludedTypes = [TYPE_APP, TYPE_SEPARATOR, TYPE_PARENT]; var showParent = false; if (angular.isDefined(parent.title) && parent.title.toLowerCase().indexOf(filterText) >= 0) { showParent = true; if (excludedTypes.indexOf(parent.type) === -1) { numVisibleModules[0]++; } } if (showParent) { _eachChild(parent, function(child) { if (excludedTypes.indexOf(child.type) === -1) { numVisibleModules[0]++; } _setFilteredVisibility(child, true, filteredItems); }); } else { _eachChild(parent, function(child) { var showChild = _computeFilteredVisibility(filterText, child, filteredItems, numVisibleModules); _setFilteredVisibility(child, showChild, filteredItems); if (showChild) { showParent = true; } }, true); } return showParent; } function _eachChild(app, iterator, directChildrenOnly) { var modules = app.modules; if (!modules || modules.length === 0) { return; } modules.forEach(function(module) { iterator(module, app); if (!directChildrenOnly) { _eachChild(module, iterator); } }); } function _restoreVisibility(item, delta) { delta.push({ type: item.type, id: (item.type === TYPE_APP ? APP_PREFIX : MODULE_PREFIX) + item.id, visible: true, open: item.open }); } function _setFilteredVisibility(item, visible, delta) { var key = item.id; switch (_state) { case STATE_REMOVING_FILTERING: case STATE_INITIALIZING: case STATE_ALL: throw 'Should not be called in this state'; case STATE_ADDING_FILTERING: case STATE_FILTERING: var cachedItem = _filteredVisibility[key]; var isVisible = cachedItem && cachedItem.state === visible; var isHandled = cachedItem && cachedItem.modifiedCount >= FILTERED_VISIBILITY_MOD_LIMIT; if (isVisible && isHandled) { return; } break; } delta.push({ type: item.type, id: (item.type === TYPE_APP ? APP_PREFIX : MODULE_PREFIX) + item.id, visible: visible, open: visible }); } function setVisibilityForKey(key, visible) { var item; if (!key) { return; } if ( angular.isUndefined(_filteredVisibility[key]) ) { _filteredVisibility[key] = { modifiedCount: 0 }; } item = _filteredVisibility[key]; if (item.state === visible) { item.modifiedCount++; } else { item.state = visible item.modifiedCount = 0; } return item; } function _addEventSubscriber(type, subscriber) { if (!_eventSubscribers[type]) { _eventSubscribers[type] = []; } _eventSubscribers[type].push(subscriber); } function _fireEvent(type, data) { var subscribers = _eventSubscribers[type]; if (subscribers && subscribers.length) { subscribers.forEach(function(subscriber) { subscriber(data); }); } } return { get DEBUG_METRICS() { return DEBUG_METRICS; }, set filterTerm(value) { setFilterTerm(value); }, set applications(apps) { setApplications(apps); }, get applications() { return _navigatorApps; }, setVisibilityForKey: setVisibilityForKey, getVisibleModuleCountByType: getVisibleModuleCountByType, canEdit: canEdit, setOpenState: setOpenState, onChangeApps: function(subscriber) { _addEventSubscriber(EVENT_CHANGE_APPS, subscriber); if (_navigatorApps.length) { subscriber(_navigatorApps); } }, onChangeVisibility: function(subscriber) { _addEventSubscriber(EVENT_CHANGE_VISIBILITY, subscriber); } }; }); ; ; ; /*! RESOURCE: /scripts/sn.dragdrop/ng_jqdnd_includes.js */ /*! RESOURCE: /scripts/sn.dragdrop/_sn.dragdrop.js */ /*! RESOURCE: /scripts/sn.dragdrop/jquery-ui-dragdrop.min.js */ /*! jQuery UI - v1.11.0 - 2014-07-03 * http://jqueryui.com * Includes: core.js, widget.js, mouse.js, draggable.js, droppable.js, resizable.js, selectable.js, sortable.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,s){var a,n,o,r=t.nodeName.toLowerCase();return"area"===r?(a=t.parentNode,n=a.name,t.href&&n&&"map"===a.nodeName.toLowerCase()?(o=e("img[usemap=#"+n+"]")[0],!!o&&i(o)):!1):(/input|select|textarea|button|object/.test(r)?!t.disabled:"a"===r?t.href||s:s)&&i(t)}function i(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.0",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(){var t=this.css("position"),i="absolute"===t,s=this.parents().filter(function(){var t=e(this);return i&&"static"===t.css("position")?!1:/(auto|scroll)/.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==t&&s.length?s:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),a=isNaN(s);return(a||s>=0)&&t(i,!a)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(t,i,s,n){return e.each(a,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),n&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var a="Width"===i?["Left","Right"]:["Top","Bottom"],n=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(n,s(this,t)+"px")})},e.fn["outer"+i]=function(t,a){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(n,s(this,t,!0,a)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,a=e(this[0]);a.length&&a[0]!==document;){if(i=a.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(a.css("zIndex"),10),!isNaN(s)&&0!==s))return s;a=a.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var a,n=e.ui[t].prototype;for(a in s)n.plugins[a]=n.plugins[a]||[],n.plugins[a].push([i,s[a]])},call:function(e,t,i,s){var a,n=e.plugins[t];if(n&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(a=0;n.length>a;a++)e.options[n[a][0]]&&n[a][1].apply(e.element,i)}};var s=0,a=Array.prototype.slice;e.cleanData=function(t){return function(i){for(var s,a=0;null!=(s=i[a]);a++)try{e(s).triggerHandler("remove")}catch(n){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var a,n,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],a=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][a.toLowerCase()]=function(t){return!!e.data(t,a)},e[l]=e[l]||{},n=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,n,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},a=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,n=this._superApply;return this._super=e,this._superApply=a,t=s.apply(this,arguments),this._super=i,this._superApply=n,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:n?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:a}),n?(e.each(n._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,n=a.call(arguments,1),o=0,r=n.length;r>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(n){var o="string"==typeof n,r=a.call(arguments,1),h=this;return n=!o&&r.length?e.widget.extend.apply(null,[n].concat(r)):n,o?this.each(function(){var i,a=e.data(this,s);return"instance"===n?(h=a,!1):a?e.isFunction(a[n])&&"_"!==n.charAt(0)?(i=a[n].apply(a,r),i!==a&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+n+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+n+"'")}):this.each(function(){var t=e.data(this,s);t?(t.option(n||{}),t._init&&t._init()):e.data(this,s,new i(n,this))}),h}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=s++,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(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),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.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(t,i){var s,a,n,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(a=o[t]=e.widget.extend({},this.options[t]),n=0;s.length-1>n;n++)a[s[n]]=a[s[n]]||{},a=a[s[n]];if(t=s.pop(),1===arguments.length)return void 0===a[t]?null:a[t];a[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),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,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var a,n=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=a=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,a=this.widget()),e.each(s,function(s,o){function r(){return t||n.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?n[o]:o).apply(n,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+n.eventNamespace,u=h[2];u?a.delegate(u,l,r):i.bind(l,r)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,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,i,s){var a,n,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],n=i.originalEvent)for(a in n)a in i||(i[a]=n[a]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,a,n){"string"==typeof a&&(a={effect:a});var o,r=a?a===!0||"number"==typeof a?i:a.effect||i:t;a=a||{},"number"==typeof a&&(a={duration:a}),o=!e.isEmptyObject(a),a.complete=n,a.delay&&s.delay(a.delay),o&&e.effects&&e.effects.effect[r]?s[t](a):r!==t&&s[r]?s[r](a.duration,a.easing,n):s.queue(function(i){e(this)[t](),n&&n.call(s[0]),i()})}}),e.widget;var n=!1;e(document).mouseup(function(){n=!1}),e.widget("ui.mouse",{version:"1.11.0",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(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!n){this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var i=this,s=1===t.which,a="string"==typeof this.options.cancel&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;return s&&!a&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(t)!==!1,!this._mouseStarted)?(t.preventDefault(),!0):(!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return i._mouseMove(e)},this._mouseUpDelegate=function(e){return i._mouseUp(e)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),n=!0,!0)):!0}},_mouseMove:function(t){return e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button?this._mouseUp(t):t.which?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 this.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)),n=!1,!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(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),e.widget("ui.draggable",e.ui.mouse,{version:"1.11.0",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,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?: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._setHandleClassName(),this._mouseInit()},_setOption:function(e,t){this._super(e,t),"handle"===e&&this._setHandleClassName()},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(t){var i=this.document[0],s=this.options;try{i.activeElement&&"body"!==i.activeElement.nodeName.toLowerCase()&&e(i.activeElement).blur()}catch(a){}return this.helper||s.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(e(s.iframeFix===!0?"iframe":s.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 i=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.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,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,!1),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",t,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var i=this,s=!1;return e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",t)!==!1&&i._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!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),this.element.focus(),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){return this.options.handle?!!e(t.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this._removeHandleClassName(),e(this.options.handle||this.element).addClass("ui-draggable-handle")},_removeHandleClassName:function(){this.element.find(".ui-draggable-handle").addBack().removeClass("ui-draggable-handle")},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return s.parents("body").length||s.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s[0]===this.element[0]||/(fixed|absolute)/.test(s.css("position"))||s.css("position","absolute"),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(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)},_isRootNode:function(e){return/(html|body)/i.test(e.tagName)||e===this.document[0]},_getParentOffset:function(){var t=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var e=this.element.position(),t=this._isRootNode(this.scrollParent[0]);return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+(t?0:this.scrollParent.scrollTop()),left:e.left-(parseInt(this.helper.css("left"),10)||0)+(t?0:this.scrollParent.scrollLeft())}},_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,i,s,a=this.options,n=this.document[0];return this.relative_container=null,a.containment?"window"===a.containment?(this.containment=[e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,e(window).scrollLeft()+e(window).width()-this.helperProportions.width-this.margins.left,e(window).scrollTop()+(e(window).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===a.containment?(this.containment=[0,0,e(n).width()-this.helperProportions.width-this.margins.left,(e(n).height()||n.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):a.containment.constructor===Array?(this.containment=a.containment,void 0):("parent"===a.containment&&(a.containment=this.helper[0].parentNode),i=e(a.containment),s=i[0],s&&(t="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(t?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(e,t){t||(t=this.position);var i="absolute"===e?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:t.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:t.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(e,t){var i,s,a,n,o=this.options,r=this._isRootNode(this.scrollParent[0]),h=e.pageX,l=e.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),t&&(this.containment&&(this.relative_container?(s=this.relative_container.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,e.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),e.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),e.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),e.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),o.grid&&(a=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=i?a-this.offset.click.top>=i[1]||a-this.offset.click.top>i[3]?a:a-this.offset.click.top>=i[1]?a-o.grid[1]:a+o.grid[1]:a,n=o.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,h=i?n-this.offset.click.left>=i[0]||n-this.offset.click.left>i[2]?n:n-this.offset.click.left>=i[0]?n-o.grid[0]:n+o.grid[0]:n),"y"===o.axis&&(h=this.originalPageX),"x"===o.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_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,this.destroyOnClear&&this.destroy()},_trigger:function(t,i,s){return s=s||this._uiHash(),e.ui.plugin.call(this,t,[i,s,this],!0),"drag"===t&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,i,s){var a=s.options,n=e.extend({},i,{item:s.element});s.sortables=[],e(a.connectToSortable).each(function(){var i=e(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",t,n))})},stop:function(t,i,s){var a=e.extend({},i,{item:s.element});e.each(s.sortables,function(){this.instance.isOver?(this.instance.isOver=0,s.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,"original"===s.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,a))})},drag:function(t,i,s){var a=this;e.each(s.sortables,function(){var n=!1,o=this;this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(n=!0,e.each(s.sortables,function(){return this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.contains(o.instance.element[0],this.instance.element[0])&&(n=!1),n})),n?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(a).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=s.offset.click.top,this.instance.offset.click.left=s.offset.click.left,this.instance.offset.parent.left-=s.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=s.offset.parent.top-this.instance.offset.parent.top,s._trigger("toSortable",t),s.dropped=this.instance.element,s.currentItem=s.element,this.instance.fromOutside=s),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(),s._trigger("fromSortable",t),s.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,i,s){var a=e("body"),n=s.options;a.css("cursor")&&(n._cursor=a.css("cursor")),a.css("cursor",n.cursor)},stop:function(t,i,s){var a=s.options;a._cursor&&e("body").css("cursor",a._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,i,s){var a=e(i.helper),n=s.options;a.css("opacity")&&(n._opacity=a.css("opacity")),a.css("opacity",n.opacity)},stop:function(t,i,s){var a=s.options;a._opacity&&e(i.helper).css("opacity",a._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(e,t,i){i.scrollParent[0]!==i.document[0]&&"HTML"!==i.scrollParent[0].tagName&&(i.overflowOffset=i.scrollParent.offset())},drag:function(t,i,s){var a=s.options,n=!1,o=s.document[0];s.scrollParent[0]!==o&&"HTML"!==s.scrollParent[0].tagName?(a.axis&&"x"===a.axis||(s.overflowOffset.top+s.scrollParent[0].offsetHeight-t.pageY<a.scrollSensitivity?s.scrollParent[0].scrollTop=n=s.scrollParent[0].scrollTop+a.scrollSpeed:t.pageY-s.overflowOffset.top<a.scrollSensitivity&&(s.scrollParent[0].scrollTop=n=s.scrollParent[0].scrollTop-a.scrollSpeed)),a.axis&&"y"===a.axis||(s.overflowOffset.left+s.scrollParent[0].offsetWidth-t.pageX<a.scrollSensitivity?s.scrollParent[0].scrollLeft=n=s.scrollParent[0].scrollLeft+a.scrollSpeed:t.pageX-s.overflowOffset.left<a.scrollSensitivity&&(s.scrollParent[0].scrollLeft=n=s.scrollParent[0].scrollLeft-a.scrollSpeed))):(a.axis&&"x"===a.axis||(t.pageY-e(o).scrollTop()<a.scrollSensitivity?n=e(o).scrollTop(e(o).scrollTop()-a.scrollSpeed):e(window).height()-(t.pageY-e(o).scrollTop())<a.scrollSensitivity&&(n=e(o).scrollTop(e(o).scrollTop()+a.scrollSpeed))),a.axis&&"y"===a.axis||(t.pageX-e(o).scrollLeft()<a.scrollSensitivity?n=e(o).scrollLeft(e(o).scrollLeft()-a.scrollSpeed):e(window).width()-(t.pageX-e(o).scrollLeft())<a.scrollSensitivity&&(n=e(o).scrollLeft(e(o).scrollLeft()+a.scrollSpeed)))),n!==!1&&e.ui.ddmanager&&!a.dropBehaviour&&e.ui.ddmanager.prepareOffsets(s,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,i,s){var a=s.options;s.snapElements=[],e(a.snap.constructor!==String?a.snap.items||":data(ui-draggable)":a.snap).each(function(){var t=e(this),i=t.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:i.top,left:i.left})})},drag:function(t,i,s){var a,n,o,r,h,l,u,d,c,p,f=s.options,m=f.snapTolerance,g=i.offset.left,v=g+s.helperProportions.width,y=i.offset.top,b=y+s.helperProportions.height;for(c=s.snapElements.length-1;c>=0;c--)h=s.snapElements[c].left,l=h+s.snapElements[c].width,u=s.snapElements[c].top,d=u+s.snapElements[c].height,h-m>v||g>l+m||u-m>b||y>d+m||!e.contains(s.snapElements[c].item.ownerDocument,s.snapElements[c].item)?(s.snapElements[c].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=!1):("inner"!==f.snapMode&&(a=m>=Math.abs(u-b),n=m>=Math.abs(d-y),o=m>=Math.abs(h-v),r=m>=Math.abs(l-g),a&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top-s.margins.top),n&&(i.position.top=s._convertPositionTo("relative",{top:d,left:0}).top-s.margins.top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left-s.margins.left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left-s.margins.left)),p=a||n||o||r,"outer"!==f.snapMode&&(a=m>=Math.abs(u-y),n=m>=Math.abs(d-b),o=m>=Math.abs(h-g),r=m>=Math.abs(l-v),a&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top-s.margins.top),n&&(i.position.top=s._convertPositionTo("relative",{top:d-s.helperProportions.height,left:0}).top-s.margins.top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left-s.margins.left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left-s.margins.left)),!s.snapElements[c].snapping&&(a||n||o||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=a||n||o||r||p)}}),e.ui.plugin.add("draggable","stack",{start:function(t,i,s){var a,n=s.options,o=e.makeArray(e(n.stack)).sort(function(t,i){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(i).css("zIndex"),10)||0)});o.length&&(a=parseInt(e(o[0]).css("zIndex"),10)||0,e(o).each(function(t){e(this).css("zIndex",a+t)}),this.css("zIndex",a+o.length))}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,i,s){var a=e(i.helper),n=s.options;a.css("zIndex")&&(n._zIndex=a.css("zIndex")),a.css("zIndex",n.zIndex)},stop:function(t,i,s){var a=s.options;a._zIndex&&e(i.helper).css("zIndex",a._zIndex)}}),e.ui.draggable,e.widget("ui.droppable",{version:"1.11.0",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=e.isFunction(s)?s:function(e){return e.is(s)},this.proportions=function(){return arguments.length?(t=arguments[0],void 0):t?t:t={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this.element.addClass("ui-droppable")},_addToManager:function(t){e.ui.ddmanager.droppables[t]=e.ui.ddmanager.droppables[t]||[],e.ui.ddmanager.droppables[t].push(this)},_splice:function(e){for(var t=0;e.length>t;t++)e[t]===this&&e.splice(t,1) },_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];this._splice(t),this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,i){if("accept"===t)this.accept=e.isFunction(i)?i:function(e){return e.is(i)};else if("scope"===t){var s=e.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(t,i)},_activate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",t,this.ui(i))},_deactivate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",t,this.ui(i))},_over:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(i)))},_out:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(i)))},_drop:function(t,i){var s=i||e.ui.ddmanager.current,a=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=e(this).droppable("instance");return t.options.greedy&&!t.options.disabled&&t.options.scope===s.options.scope&&t.accept.call(t.element[0],s.currentItem||s.element)&&e.ui.intersect(s,e.extend(t,{offset:t.element.offset()}),t.options.tolerance)?(a=!0,!1):void 0}),a?!1:this.accept.call(this.element[0],s.currentItem||s.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(s)),this.element):!1):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(){function e(e,t,i){return e>=t&&t+i>e}return function(t,i,s){if(!i.offset)return!1;var a,n,o=(t.positionAbs||t.position.absolute).left,r=(t.positionAbs||t.position.absolute).top,h=o+t.helperProportions.width,l=r+t.helperProportions.height,u=i.offset.left,d=i.offset.top,c=u+i.proportions().width,p=d+i.proportions().height;switch(s){case"fit":return o>=u&&c>=h&&r>=d&&p>=l;case"intersect":return o+t.helperProportions.width/2>u&&c>h-t.helperProportions.width/2&&r+t.helperProportions.height/2>d&&p>l-t.helperProportions.height/2;case"pointer":return a=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,n=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,e(n,d,i.proportions().height)&&e(a,u,i.proportions().width);case"touch":return(r>=d&&p>=r||l>=d&&p>=l||d>r&&l>p)&&(o>=u&&c>=o||h>=u&&c>=h||u>o&&h>c);default:return!1}}}(),e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,i){var s,a,n=e.ui.ddmanager.droppables[t.options.scope]||[],o=i?i.type:null,r=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(s=0;n.length>s;s++)if(!(n[s].options.disabled||t&&!n[s].accept.call(n[s].element[0],t.currentItem||t.element))){for(a=0;r.length>a;a++)if(r[a]===n[s].element[0]){n[s].proportions().height=0;continue e}n[s].visible="none"!==n[s].element.css("display"),n[s].visible&&("mousedown"===o&&n[s]._activate.call(n[s],i),n[s].offset=n[s].element.offset(),n[s].proportions({width:n[s].element[0].offsetWidth,height:n[s].element[0].offsetHeight}))}},drop:function(t,i){var s=!1;return e.each((e.ui.ddmanager.droppables[t.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(t,i){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)})},drag:function(t,i){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,i),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,a,n,o=e.ui.intersect(t,this,this.options.tolerance),r=!o&&this.isover?"isout":o&&!this.isover?"isover":null;r&&(this.options.greedy&&(a=this.options.scope,n=this.element.parents(":data(ui-droppable)").filter(function(){return e(this).droppable("instance").options.scope===a}),n.length&&(s=e(n[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(t,i){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)}},e.ui.droppable,e.widget("ui.resizable",e.ui.mouse,{version:"1.11.0",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:90,resize:null,start:null,stop:null},_num:function(e){return parseInt(e,10)||0},_isNumber:function(e){return!isNaN(parseInt(e,10))},_hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",a=!1;return t[s]>0?!0:(t[s]=1,a=t[s]>0,t[s]=0,a)},_create:function(){var t,i,s,a,n,o=this,r=this.options;if(this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.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("ui-resizable",this.element.resizable("instance")),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=r.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"),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={},i=0;t.length>i;i++)s=e.trim(t[i]),n="ui-resizable-"+s,a=e("<div class='ui-resizable-handle "+n+"'></div>"),a.css({zIndex:r.zIndex}),"se"===s&&a.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(a);this._renderAxis=function(t){var i,s,a,n;t=t||this.element;for(i in this.handles)this.handles[i].constructor===String&&(this.handles[i]=this.element.children(this.handles[i]).first().show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(s=e(this.handles[i],this.element),n=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),a=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),t.css(a,n),this._proportionallyResize()),e(this.handles[i]).length},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=a&&a[1]?a[1]:"se")}),r.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(e(this).removeClass("ui-resizable-autohide"),o._handles.show())}).mouseleave(function(){r.disabled||o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,i=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()};return this.elementIsWrapper&&(i(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(t){var i,s,a=!1;for(i in this.handles)s=e(this.handles[i])[0],(s===t.target||e.contains(s,t.target))&&(a=!0);return!this.options.disabled&&a},_mouseStart:function(t){var i,s,a,n=this.options,o=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),n.containment&&(i+=e(n.containment).scrollLeft()||0,s+=e(n.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:o.width(),height:o.height()},this.originalSize=this._helper?{width:o.outerWidth(),height:o.outerHeight()}:{width:o.width(),height:o.height()},this.originalPosition={left:i,top:s},this.sizeDiff={width:o.outerWidth()-o.width(),height:o.outerHeight()-o.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof n.aspectRatio?n.aspectRatio:this.originalSize.width/this.originalSize.height||1,a=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor","auto"===a?this.axis+"-resize":a),o.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var i,s=this.helper,a={},n=this.originalMousePosition,o=this.axis,r=t.pageX-n.left||0,h=t.pageY-n.top||0,l=this._change[o];return this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height},l?(i=l.apply(this,[t,r,h]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(i=this._updateRatio(i,t)),i=this._respectSize(i,t),this._updateCache(i),this._propagate("resize",t),this.position.top!==this.prevPosition.top&&(a.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(a.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(a.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(a.height=this.size.height+"px"),s.css(a),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(a)||this._trigger("resize",t,this.ui()),!1):!1},_mouseStop:function(t){this.resizing=!1;var i,s,a,n,o,r,h,l=this.options,u=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),a=s&&this._hasScroll(i[0],"left")?0:u.sizeDiff.height,n=s?0:u.sizeDiff.width,o={width:u.helper.width()-n,height:u.helper.height()-a},r=parseInt(u.element.css("left"),10)+(u.position.left-u.originalPosition.left)||null,h=parseInt(u.element.css("top"),10)+(u.position.top-u.originalPosition.top)||null,l.animate||this.element.css(e.extend(o,{top:h,left:r})),u.helper.height(u.size.height),u.helper.width(u.size.width),this._helper&&!l.animate&&this._proportionallyResize()),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,i,s,a,n,o=this.options;n={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:1/0,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:1/0},(this._aspectRatio||e)&&(t=n.minHeight*this.aspectRatio,s=n.minWidth/this.aspectRatio,i=n.maxHeight*this.aspectRatio,a=n.maxWidth/this.aspectRatio,t>n.minWidth&&(n.minWidth=t),s>n.minHeight&&(n.minHeight=s),n.maxWidth>i&&(n.maxWidth=i),n.maxHeight>a&&(n.maxHeight=a)),this._vBoundaries=n},_updateCache:function(e){this.offset=this.helper.offset(),this._isNumber(e.left)&&(this.position.left=e.left),this._isNumber(e.top)&&(this.position.top=e.top),this._isNumber(e.height)&&(this.size.height=e.height),this._isNumber(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,i=this.size,s=this.axis;return this._isNumber(e.height)?e.width=e.height*this.aspectRatio:this._isNumber(e.width)&&(e.height=e.width/this.aspectRatio),"sw"===s&&(e.left=t.left+(i.width-e.width),e.top=null),"nw"===s&&(e.top=t.top+(i.height-e.height),e.left=t.left+(i.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,i=this.axis,s=this._isNumber(e.width)&&t.maxWidth&&t.maxWidth<e.width,a=this._isNumber(e.height)&&t.maxHeight&&t.maxHeight<e.height,n=this._isNumber(e.width)&&t.minWidth&&t.minWidth>e.width,o=this._isNumber(e.height)&&t.minHeight&&t.minHeight>e.height,r=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,l=/sw|nw|w/.test(i),u=/nw|ne|n/.test(i);return n&&(e.width=t.minWidth),o&&(e.height=t.minHeight),s&&(e.width=t.maxWidth),a&&(e.height=t.maxHeight),n&&l&&(e.left=r-t.minWidth),s&&l&&(e.left=r-t.maxWidth),o&&u&&(e.top=h-t.minHeight),a&&u&&(e.top=h-t.maxHeight),e.width||e.height||e.left||!e.top?e.width||e.height||e.top||!e.left||(e.left=null):e.top=null,e},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var e,t,i,s,a,n=this.helper||this.element;for(e=0;this._proportionallyResizeElements.length>e;e++){if(a=this._proportionallyResizeElements[e],!this.borderDif)for(this.borderDif=[],i=[a.css("borderTopWidth"),a.css("borderRightWidth"),a.css("borderBottomWidth"),a.css("borderLeftWidth")],s=[a.css("paddingTop"),a.css("paddingRight"),a.css("paddingBottom"),a.css("paddingLeft")],t=0;i.length>t;t++)this.borderDif[t]=(parseInt(i[t],10)||0)+(parseInt(s[t],10)||0);a.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,i=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,i){var s=this.originalSize,a=this.originalPosition;return{top:a.top+i,height:s.height-i}},s:function(e,t,i){return{height:this.originalSize.height+i}},se:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},sw:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,i,s]))},ne:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},nw:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,i,s]))}},_propagate:function(t,i){e.ui.plugin.call(this,t,[i,this.ui()]),"resize"!==t&&this._trigger(t,i,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,prevSize:this.prevSize,prevPosition:this.prevPosition}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var i=e(this).resizable("instance"),s=i.options,a=i._proportionallyResizeElements,n=a.length&&/textarea/i.test(a[0].nodeName),o=n&&i._hasScroll(a[0],"left")?0:i.sizeDiff.height,r=n?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-o},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,u=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(e.extend(h,u&&l?{top:u,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};a&&a.length&&e(a[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,i,s,a,n,o,r,h=e(this).resizable("instance"),l=h.options,u=h.element,d=l.containment,c=d instanceof e?d.get(0):/parent/.test(d)?u.parent().get(0):d;c&&(h.containerElement=e(c),/document/.test(d)||d===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(c),i=[],e(["Top","Right","Left","Bottom"]).each(function(e,s){i[e]=h._num(t.css("padding"+s))}),h.containerOffset=t.offset(),h.containerPosition=t.position(),h.containerSize={height:t.innerHeight()-i[3],width:t.innerWidth()-i[1]},s=h.containerOffset,a=h.containerSize.height,n=h.containerSize.width,o=h._hasScroll(c,"left")?c.scrollWidth:n,r=h._hasScroll(c)?c.scrollHeight:a,h.parentData={element:c,left:s.left,top:s.top,width:o,height:r}))},resize:function(t,i){var s,a,n,o,r=e(this).resizable("instance"),h=r.options,l=r.containerOffset,u=r.position,d=r._aspectRatio||t.shiftKey,c={top:0,left:0},p=r.containerElement,f=!0;p[0]!==document&&/static/.test(p.css("position"))&&(c=l),u.left<(r._helper?l.left:0)&&(r.size.width=r.size.width+(r._helper?r.position.left-l.left:r.position.left-c.left),d&&(r.size.height=r.size.width/r.aspectRatio,f=!1),r.position.left=h.helper?l.left:0),u.top<(r._helper?l.top:0)&&(r.size.height=r.size.height+(r._helper?r.position.top-l.top:r.position.top),d&&(r.size.width=r.size.height*r.aspectRatio,f=!1),r.position.top=r._helper?l.top:0),r.offset.left=r.parentData.left+r.position.left,r.offset.top=r.parentData.top+r.position.top,s=Math.abs((r._helper?r.offset.left-c.left:r.offset.left-l.left)+r.sizeDiff.width),a=Math.abs((r._helper?r.offset.top-c.top:r.offset.top-l.top)+r.sizeDiff.height),n=r.containerElement.get(0)===r.element.parent().get(0),o=/relative|absolute/.test(r.containerElement.css("position")),n&&o&&(s-=Math.abs(r.parentData.left)),s+r.size.width>=r.parentData.width&&(r.size.width=r.parentData.width-s,d&&(r.size.height=r.size.width/r.aspectRatio,f=!1)),a+r.size.height>=r.parentData.height&&(r.size.height=r.parentData.height-a,d&&(r.size.width=r.size.height*r.aspectRatio,f=!1)),f||(r.position.left=i.prevPosition.left,r.position.top=i.prevPosition.top,r.size.width=i.prevSize.width,r.size.height=i.prevSize.height)},stop:function(){var t=e(this).resizable("instance"),i=t.options,s=t.containerOffset,a=t.containerPosition,n=t.containerElement,o=e(t.helper),r=o.offset(),h=o.outerWidth()-t.sizeDiff.width,l=o.outerHeight()-t.sizeDiff.height;t._helper&&!i.animate&&/relative/.test(n.css("position"))&&e(this).css({left:r.left-a.left-s.left,width:h,height:l}),t._helper&&!i.animate&&/static/.test(n.css("position"))&&e(this).css({left:r.left-a.left-s.left,width:h,height:l})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).resizable("instance"),i=t.options,s=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};"object"!=typeof i.alsoResize||i.alsoResize.parentNode?s(i.alsoResize):i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)})},resize:function(t,i){var s=e(this).resizable("instance"),a=s.options,n=s.originalSize,o=s.originalPosition,r={height:s.size.height-n.height||0,width:s.size.width-n.width||0,top:s.position.top-o.top||0,left:s.position.left-o.left||0},h=function(t,s){e(t).each(function(){var t=e(this),a=e(this).data("ui-resizable-alsoresize"),n={},o=s&&s.length?s:t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var i=(a[t]||0)+(r[t]||0);i&&i>=0&&(n[t]=i||null)}),t.css(n)})};"object"!=typeof a.alsoResize||a.alsoResize.nodeType?h(a.alsoResize):e.each(a.alsoResize,function(e,t){h(e,t)})},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).resizable("instance"),i=t.options,s=t.size;t.ghost=t.originalElement.clone(),t.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("string"==typeof i.ghost?i.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).resizable("instance"),i=t.options,s=t.size,a=t.originalSize,n=t.originalPosition,o=t.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=r[0]||1,l=r[1]||1,u=Math.round((s.width-a.width)/h)*h,d=Math.round((s.height-a.height)/l)*l,c=a.width+u,p=a.height+d,f=i.maxWidth&&c>i.maxWidth,m=i.maxHeight&&p>i.maxHeight,g=i.minWidth&&i.minWidth>c,v=i.minHeight&&i.minHeight>p;i.grid=r,g&&(c+=h),v&&(p+=l),f&&(c-=h),m&&(p-=l),/^(se|s|e)$/.test(o)?(t.size.width=c,t.size.height=p):/^(ne)$/.test(o)?(t.size.width=c,t.size.height=p,t.position.top=n.top-d):/^(sw)$/.test(o)?(t.size.width=c,t.size.height=p,t.position.left=n.left-u):(p-l>0?(t.size.height=p,t.position.top=n.top-d):(t.size.height=l,t.position.top=n.top+a.height-l),c-h>0?(t.size.width=c,t.position.left=n.left-u):(t.size.width=h,t.position.left=n.left+a.width-h))}}),e.ui.resizable,e.widget("ui.selectable",e.ui.mouse,{version:"1.11.0",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(i.options.filter,i.element[0]),t.addClass("ui-selectee"),t.each(function(){var t=e(this),i=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:i.left,top:i.top,right:i.left+t.outerWidth(),bottom:i.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=t.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 i=this,s=this.options;this.opos=[t.pageX,t.pageY],this.options.disabled||(this.selectees=e(s.filter,this.element[0]),this._trigger("start",t),e(s.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=e.data(this,"selectable-item");s.startselected=!0,t.metaKey||t.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",t,{unselecting:s.element}))}),e(t.target).parents().addBack().each(function(){var s,a=e.data(this,"selectable-item");return a?(s=!t.metaKey&&!t.ctrlKey||!a.$element.hasClass("ui-selected"),a.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),a.unselecting=!s,a.selecting=s,a.selected=s,s?i._trigger("selecting",t,{selecting:a.element}):i._trigger("unselecting",t,{unselecting:a.element}),!1):void 0}))},_mouseDrag:function(t){if(this.dragged=!0,!this.options.disabled){var i,s=this,a=this.options,n=this.opos[0],o=this.opos[1],r=t.pageX,h=t.pageY;return n>r&&(i=r,r=n,n=i),o>h&&(i=h,h=o,o=i),this.helper.css({left:n,top:o,width:r-n,height:h-o}),this.selectees.each(function(){var i=e.data(this,"selectable-item"),l=!1;i&&i.element!==s.element[0]&&("touch"===a.tolerance?l=!(i.left>r||n>i.right||i.top>h||o>i.bottom):"fit"===a.tolerance&&(l=i.left>n&&r>i.right&&i.top>o&&h>i.bottom),l?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",t,{selecting:i.element}))):(i.selecting&&((t.metaKey||t.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",t,{unselecting:i.element}))),i.selected&&(t.metaKey||t.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",t,{unselecting:i.element})))))}),!1}},_mouseStop:function(t){var i=this;return this.dragged=!1,e(".ui-unselecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",t,{unselected:s.element})}),e(".ui-selecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",t,{selected:s.element})}),this._trigger("stop",t),this.helper.remove(),!1}}),e.widget("ui.sortable",e.ui.mouse,{version:"1.11.0",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,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(e,t,i){return e>=t&&t+i>e},_isFloating:function(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===e.axis||this._isFloating(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(e,t){this._super(e,t),"handle"===e&&this._setHandleClassName()},_setHandleClassName:function(){this.element.find(".ui-sortable-handle").removeClass("ui-sortable-handle"),e.each(this.items,function(){(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item).addClass("ui-sortable-handle")})},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").find(".ui-sortable-handle").removeClass("ui-sortable-handle"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(t,i){var s=null,a=!1,n=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(t),e(t.target).parents().each(function(){return e.data(this,n.widgetName+"-item")===n?(s=e(this),!1):void 0}),e.data(t.target,n.widgetName+"-item")===n&&(s=e(t.target)),s?!this.options.handle||i||(e(this.options.handle,s).find("*").addBack().each(function(){this===t.target&&(a=!0)}),a)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(t,i,s){var a,n,o=this.options;if(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,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(n=this.document.find("body"),this.storedCursor=n.css("cursor"),n.css("cursor",o.cursor),this.storedStylesheet=e("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(n)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(a=this.containers.length-1;a>=0;a--)this.containers[a]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var i,s,a,n,o=this.options,r=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+o.scrollSpeed:t.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+o.scrollSpeed:t.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(t.pageY-e(document).scrollTop()<o.scrollSensitivity?r=e(document).scrollTop(e(document).scrollTop()-o.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<o.scrollSensitivity&&(r=e(document).scrollTop(e(document).scrollTop()+o.scrollSpeed)),t.pageX-e(document).scrollLeft()<o.scrollSensitivity?r=e(document).scrollLeft(e(document).scrollLeft()-o.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<o.scrollSensitivity&&(r=e(document).scrollLeft(e(document).scrollLeft()+o.scrollSpeed))),r!==!1&&e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],a=s.item[0],n=this._intersectsWithPointer(s),n&&s.instance===this.currentContainer&&a!==this.currentItem[0]&&this.placeholder[1===n?"next":"prev"]()[0]!==a&&!e.contains(this.placeholder[0],a)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],a):!0)){if(this.direction=1===n?"down":"up","pointer"!==this.options.tolerance&&!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,i){if(t){if(e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t),this.options.revert){var s=this,a=this.placeholder.offset(),n=this.options.axis,o={};n&&"x"!==n||(o.left=a.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),n&&"y"!==n||(o.top=a.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,e(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){s._clear(t)})}else this._clear(t,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?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]),"original"!==this.options.helper&&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 i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},e(i).each(function(){var i=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);i&&s.push((t.key||i[1]+"[]")+"="+(t.key&&t.expression?i[1]:i[2]))}),!s.length&&t.key&&s.push(t.key+"="),s.join("&")},toArray:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},i.each(function(){s.push(e(t.item||this).attr(t.attribute||"id")||"")}),s},_intersectsWith:function(e){var t=this.positionAbs.left,i=t+this.helperProportions.width,s=this.positionAbs.top,a=s+this.helperProportions.height,n=e.left,o=n+e.width,r=e.top,h=r+e.height,l=this.offset.click.top,u=this.offset.click.left,d="x"===this.options.axis||s+l>r&&h>s+l,c="y"===this.options.axis||t+u>n&&o>t+u,p=d&&c;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?p:t+this.helperProportions.width/2>n&&o>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>a-this.helperProportions.height/2},_intersectsWithPointer:function(e){var t="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),i="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),s=t&&i,a=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return s?this.floating?n&&"right"===n||"down"===a?2:1:a&&("down"===a?2:1):!1},_intersectsWithSides:function(e){var t=this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),s=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return this.floating&&a?"right"===a&&i||"left"===a&&!i:s&&("down"===s&&t||"up"===s&&!t)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function i(){r.push(this)}var s,a,n,o,r=[],h=[],l=this._connectWith();if(l&&t)for(s=l.length-1;s>=0;s--)for(n=e(l[s]),a=n.length-1;a>=0;a--)o=e.data(n[a],this.widgetFullName),o&&o!==this&&!o.options.disabled&&h.push([e.isFunction(o.options.items)?o.options.items.call(o.element):e(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);for(h.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]),s=h.length-1;s>=0;s--)h[s][0].each(i);return e(r)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var i=0;t.length>i;i++)if(t[i]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var i,s,a,n,o,r,h,l,u=this.items,d=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],c=this._connectWith();if(c&&this.ready)for(i=c.length-1;i>=0;i--)for(a=e(c[i]),s=a.length-1;s>=0;s--)n=e.data(a[s],this.widgetFullName),n&&n!==this&&!n.options.disabled&&(d.push([e.isFunction(n.options.items)?n.options.items.call(n.element[0],t,{item:this.currentItem}):e(n.options.items,n.element),n]),this.containers.push(n));for(i=d.length-1;i>=0;i--)for(o=d[i][1],r=d[i][0],s=0,l=r.length;l>s;s++)h=e(r[s]),h.data(this.widgetName+"-item",o),u.push({item:h,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,a,n;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(a=this.options.toleranceElement?e(this.options.toleranceElement,s.item):s.item,t||(s.width=a.outerWidth(),s.height=a.outerHeight()),n=a.offset(),s.left=n.left,s.top=n.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)n=this.containers[i].element.offset(),this.containers[i].containerCache.left=n.left,this.containers[i].containerCache.top=n.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(t){t=t||this;var i,s=t.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=t.currentItem[0].nodeName.toLowerCase(),a=e("<"+s+">",t.document[0]).addClass(i||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?t.currentItem.children().each(function(){e("<td> </td>",t.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(a)}):"img"===s&&a.attr("src",t.currentItem.attr("src")),i||a.css("visibility","hidden"),a},update:function(e,a){(!i||s.forcePlaceholderSize)&&(a.height()||a.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),a.width()||a.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10)))}}),t.placeholder=e(s.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),s.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var i,s,a,n,o,r,h,l,u,d,c=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(c&&e.contains(this.containers[i].element[0],c.element[0]))continue;c=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0);if(c)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(a=1e4,n=null,u=c.floating||this._isFloating(this.currentItem),o=u?"left":"top",r=u?"width":"height",d=u?"clientX":"clientY",s=this.items.length-1;s>=0;s--)e.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[o],l=!1,t[d]-h>this.items[s][r]/2&&(l=!0),a>Math.abs(t[d]-h)&&(a=Math.abs(t[d]-h),n=this.items[s],this.direction=l?"up":"down"));if(!n&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return;n?this._rearrange(t,n,null,!0):this._rearrange(t,null,this.containers[p].element,!0),this._trigger("change",t,this._uiHash()),this.containers[p]._trigger("change",t,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||e("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[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")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(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();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){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,i,s,a=this.options;"parent"===a.containment&&(a.containment=this.helper[0].parentNode),("document"===a.containment||"window"===a.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===a.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===a.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(a.containment)||(t=e(a.containment)[0],i=e(a.containment).offset(),s="hidden"!==e(t).css("overflow"),this.containment=[i.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,a="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,n=/(html|body)/i.test(a[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():n?0:a.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():n?0:a.scrollLeft())*s}},_generatePosition:function(t){var i,s,a=this.options,n=t.pageX,o=t.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(n=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]&&(n=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),a.grid&&(i=this.originalPageY+Math.round((o-this.originalPageY)/a.grid[1])*a.grid[1],o=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-a.grid[1]:i+a.grid[1]:i,s=this.originalPageX+Math.round((n-this.originalPageX)/a.grid[0])*a.grid[0],n=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-a.grid[0]:s+a.grid[0]:s)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:n-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(e,t,i,s){i?i[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var a=this.counter;this._delay(function(){a===this.counter&&this.refreshPositions(!s)})},_clear:function(e,t){function i(e,t,i){return function(s){i._trigger(e,s,t._uiHash(t))}}this.reverting=!1;var s,a=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!t&&a.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]||t||a.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(t||(a.push(function(e){this._trigger("remove",e,this._uiHash())}),a.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),a.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)t||a.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(a.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!t){for(this._trigger("beforeStop",e,this._uiHash()),s=0;a.length>s;s++)a[s].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!1}if(t||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!t){for(s=0;a.length>s;s++)a[s].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var i=t||this;return{helper:i.helper,placeholder:i.placeholder||e([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:t?t.element:null}}})}); /*! RESOURCE: /scripts/sn.dragdrop/jquery.ui.touch-punch.min.js */ /* * jQuery UI Touch Punch 0.2.2 * * Copyright 2011, Dave Furfero * Dual licensed under the MIT or GPL Version 2 licenses. * * Depends: * jquery.ui.widget.js * jquery.ui.mouse.js */ (function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery); /*! RESOURCE: /scripts/sn.dragdrop/angular-dragdrop.js */ (function (window, angular, $, undefined) { 'use strict'; var jqyoui = angular.module('ngDragDrop', []).service('ngDragDropService', ['$timeout', '$parse', function($timeout, $parse) { this.callEventCallback = function (scope, callbackName, event, ui) { if (!callbackName) return; var objExtract = extract(callbackName), callback = objExtract.callback, constructor = objExtract.constructor, args = [event, ui].concat(objExtract.args); scope.$apply((scope[callback] || scope[constructor][callback]).apply(scope, args)); function extract(callbackName) { var atStartBracket = callbackName.indexOf('(') !== -1 ? callbackName.indexOf('(') : callbackName.length, atEndBracket = callbackName.lastIndexOf(')') !== -1 ? callbackName.lastIndexOf(')') : callbackName.length, args = callbackName.substring(atStartBracket + 1, atEndBracket), constructor = callbackName.match(/^[^.]+.\s*/)[0].slice(0, -1); constructor = scope[constructor] && typeof scope[constructor].constructor === 'function' ? constructor : null; return { callback: callbackName.substring(constructor && constructor.length + 1 || 0, atStartBracket), args: (args && args.split(',') || []).map(function(item) { return $parse(item)(scope); }), constructor: constructor } } }; this.invokeDrop = function ($draggable, $droppable, event, ui) { var dragModel = '', dropModel = '', dragSettings = {}, dropSettings = {}, jqyoui_pos = null, dragItem = {}, dropItem = {}, dragModelValue, dropModelValue, $droppableDraggable = null, droppableScope = $droppable.scope(), draggableScope = $draggable.scope(); dragModel = $draggable.ngattr('ng-model'); dropModel = $droppable.ngattr('ng-model'); dragModelValue = draggableScope.$eval(dragModel); dropModelValue = droppableScope.$eval(dropModel); $droppableDraggable = $droppable.find('[jqyoui-draggable]:last,[data-jqyoui-draggable]:last'); dropSettings = droppableScope.$eval($droppable.attr('jqyoui-droppable') || $droppable.attr('data-jqyoui-droppable')) || []; dragSettings = draggableScope.$eval($draggable.attr('jqyoui-draggable') || $draggable.attr('data-jqyoui-draggable')) || []; dragSettings.index = this.fixIndex(draggableScope, dragSettings, dragModelValue); dropSettings.index = this.fixIndex(droppableScope, dropSettings, dropModelValue); jqyoui_pos = angular.isArray(dragModelValue) ? dragSettings.index : null; dragItem = angular.copy(angular.isArray(dragModelValue) ? dragModelValue[jqyoui_pos] : dragModelValue); if (angular.isArray(dropModelValue) && dropSettings && dropSettings.index !== undefined) { dropItem = dropModelValue[dropSettings.index]; } else if (!angular.isArray(dropModelValue)) { dropItem = dropModelValue; } else { dropItem = {}; } dropItem = angular.copy(dropItem); if (dragSettings.animate === true) { this.move($draggable, $droppableDraggable.length > 0 ? $droppableDraggable : $droppable, null, 'fast', dropSettings, null); this.move($droppableDraggable.length > 0 && !dropSettings.multiple ? $droppableDraggable : [], $draggable.parent('[jqyoui-droppable],[data-jqyoui-droppable]'), jqyoui.startXY, 'fast', dropSettings, angular.bind(this, function() { $timeout(angular.bind(this, function() { $draggable.css({'position': 'relative', 'left': '', 'top': ''}); $droppableDraggable.css({'position': 'relative', 'left': '', 'top': '', 'display': ''}); this.mutateDraggable(draggableScope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable); this.mutateDroppable(droppableScope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos); this.callEventCallback(droppableScope, dropSettings.onDrop, event, ui); })); })); } else { $timeout(angular.bind(this, function() { this.mutateDraggable(draggableScope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable); this.mutateDroppable(droppableScope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos); this.callEventCallback(droppableScope, dropSettings.onDrop, event, ui); })); } }; this.move = function($fromEl, $toEl, toPos, duration, dropSettings, callback) { if ($fromEl.length === 0) { if (callback) { window.setTimeout(function() { callback(); }, 300); } return false; } var zIndex = 9999, fromPos = $fromEl[dropSettings.containment || 'offset'](), wasVisible = $toEl && $toEl.is(':visible'), hadNgHideCls = $toEl.hasClass('ng-hide'); if (toPos === null && $toEl.length > 0) { if (($toEl.attr('jqyoui-draggable') || $toEl.attr('data-jqyoui-draggable')) !== undefined && $toEl.ngattr('ng-model') !== undefined && $toEl.is(':visible') && dropSettings && dropSettings.multiple) { toPos = $toEl[dropSettings.containment || 'offset'](); if (dropSettings.stack === false) { toPos.left+= $toEl.outerWidth(true); } else { toPos.top+= $toEl.outerHeight(true); } } else { if (hadNgHideCls) $toEl.removeClass('ng-hide'); toPos = $toEl.css({'visibility': 'hidden', 'display': 'block'})[dropSettings.containment || 'offset'](); $toEl.css({'visibility': '','display': wasVisible ? 'block' : 'none'}); } } $fromEl.css({'position': 'absolute', 'z-index': zIndex}) .css(fromPos) .animate(toPos, duration, function() { if (hadNgHideCls) $toEl.addClass('ng-hide'); if (callback) callback(); }); }; this.mutateDroppable = function(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos) { var dropModelValue = scope.$eval(dropModel); scope.dndDragItem = dragItem; if (angular.isArray(dropModelValue)) { if (dropSettings && dropSettings.index >= 0) { dropModelValue[dropSettings.index] = dragItem; } else { dropModelValue.push(dragItem); } if (dragSettings && dragSettings.placeholder === true) { dropModelValue[dropModelValue.length - 1]['jqyoui_pos'] = jqyoui_pos; } } else { $parse(dropModel + ' = dndDragItem')(scope); if (dragSettings && dragSettings.placeholder === true) { dropModelValue['jqyoui_pos'] = jqyoui_pos; } } }; this.mutateDraggable = function(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable) { var isEmpty = angular.equals(dropItem, {}), dragModelValue = scope.$eval(dragModel); scope.dndDropItem = dropItem; if (dragSettings && dragSettings.placeholder) { if (dragSettings.placeholder != 'keep'){ if (angular.isArray(dragModelValue) && dragSettings.index !== undefined) { dragModelValue[dragSettings.index] = dropItem; } else { $parse(dragModel + ' = dndDropItem')(scope); } } } else { if (angular.isArray(dragModelValue)) { if (isEmpty) { if (dragSettings && ( dragSettings.placeholder !== true && dragSettings.placeholder !== 'keep' )) { dragModelValue.splice(dragSettings.index, 1); } } else { dragModelValue[dragSettings.index] = dropItem; } } else { $parse(dragModel + ' = dndDropItem')(scope); if (scope.$parent) { $parse(dragModel + ' = dndDropItem')(scope.$parent); } } } $draggable.css({'z-index': '', 'left': '', 'top': ''}); }; this.fixIndex = function(scope, settings, modelValue) { if (settings.applyFilter && angular.isArray(modelValue) && modelValue.length > 0) { var dragModelValueFiltered = scope[settings.applyFilter](), lookup = dragModelValueFiltered[settings.index], actualIndex = undefined; modelValue.forEach(function(item, i) { if (angular.equals(item, lookup)) { actualIndex = i; } }); return actualIndex; } return settings.index; }; }]).directive('jqyouiDraggable', ['ngDragDropService', function(ngDragDropService) { return { require: '?jqyouiDroppable', restrict: 'A', link: function(scope, element, attrs) { var dragSettings, jqyouiOptions, zIndex; var updateDraggable = function(newValue, oldValue) { if (newValue) { dragSettings = scope.$eval(element.attr('jqyoui-draggable') || element.attr('data-jqyoui-draggable')) || {}; jqyouiOptions = scope.$eval(attrs.jqyouiOptions) || {}; element .draggable({disabled: false}) .draggable(jqyouiOptions) .draggable({ start: function(event, ui) { zIndex = angular.element(jqyouiOptions.helper ? ui.helper : this).css('z-index'); angular.element(jqyouiOptions.helper ? ui.helper : this).css('z-index', 9999); jqyoui.startXY = angular.element(this)[dragSettings.containment || 'offset'](); ngDragDropService.callEventCallback(scope, dragSettings.onStart, event, ui); }, stop: function(event, ui) { angular.element(jqyouiOptions.helper ? ui.helper : this).css('z-index', zIndex); ngDragDropService.callEventCallback(scope, dragSettings.onStop, event, ui); }, drag: function(event, ui) { ngDragDropService.callEventCallback(scope, dragSettings.onDrag, event, ui); } }); } else { element.draggable({disabled: true}); } }; scope.$watch(function() { return scope.$eval(attrs.drag); }, updateDraggable); updateDraggable(); element.on('$destroy', function() { if(element.data('ui-draggable')) element.draggable('destroy'); }); } }; }]).directive('jqyouiDroppable', ['ngDragDropService', function(ngDragDropService) { return { restrict: 'A', priority: 1, link: function(scope, element, attrs) { var dropSettings; var updateDroppable = function(newValue, oldValue) { if (newValue) { dropSettings = scope.$eval(angular.element(element).attr('jqyoui-droppable') || angular.element(element).attr('data-jqyoui-droppable')) || {}; element .droppable({disabled: false}) .droppable(scope.$eval(attrs.jqyouiOptions) || {}) .droppable({ over: function(event, ui) { ngDragDropService.callEventCallback(scope, dropSettings.onOver, event, ui); }, out: function(event, ui) { ngDragDropService.callEventCallback(scope, dropSettings.onOut, event, ui); }, drop: function(event, ui) { if (angular.element(ui.draggable).ngattr('ng-model') && attrs.ngModel) { ngDragDropService.invokeDrop(angular.element(ui.draggable), angular.element(this), event, ui); } else { ngDragDropService.callEventCallback(scope, dropSettings.onDrop, event, ui); } } }); } else { element.droppable({disabled: true}); } }; scope.$watch(function() { return scope.$eval(attrs.drop); }, updateDroppable); updateDroppable(); element.on('$destroy', function() { if(element.data('ui-droppable')) element.droppable('destroy'); }); } }; }]); $.fn.ngattr = function(name, value) { var element = angular.element(this).get(0); return element.getAttribute(name) || element.getAttribute('data-' + name); }; })(window, window.angular, window.jQuery); ; /*! RESOURCE: /scripts/sn.dragdrop/ui-sortable.js */ angular.module('ui.sortable', []) .value('uiSortableConfig',{}) .directive('uiSortable', [ 'uiSortableConfig', '$timeout', '$log', function(uiSortableConfig, $timeout, $log) { return { require: '?ngModel', scope: { ngModel: '=', uiSortable: '=' }, link: function(scope, element, attrs, ngModel) { var savedNodes; function combineCallbacks(first,second){ if(second && (typeof second === 'function')) { return function() { first.apply(this, arguments); second.apply(this, arguments); }; } return first; } function getSortableWidgetInstance(element) { var data = element.data('ui-sortable'); if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') { return data; } return null; } function hasSortingHelper (element, ui) { var helperOption = element.sortable('option','helper'); return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed()); } function isFloating (item) { return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display')); } function getElementScope(elementScopes, element) { var result = null; for (var i = 0; i < elementScopes.length; i++) { var x = elementScopes[i]; if (x.element[0] === element[0]) { result = x.scope; break; } } return result; } function afterStop(e, ui) { ui.item.sortable._destroy(); } var opts = {}; var directiveOpts = { 'ui-floating': undefined }; var callbacks = { receive: null, remove:null, start:null, stop:null, update:null }; var wrappers = { helper: null }; angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable); if (!angular.element.fn || !angular.element.fn.jquery) { $log.error('ui.sortable: jQuery should be included before AngularJS!'); return; } if (ngModel) { scope.$watch('ngModel.length', function() { $timeout(function() { if (!!getSortableWidgetInstance(element)) { element.sortable('refresh'); } }, 0, false); }); callbacks.start = function(e, ui) { if (opts['ui-floating'] === 'auto') { var siblings = ui.item.siblings(); var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target)); sortableWidgetInstance.floating = isFloating(siblings); } ui.item.sortable = { model: ngModel.$modelValue[ui.item.index()], index: ui.item.index(), source: ui.item.parent(), sourceModel: ngModel.$modelValue, cancel: function () { ui.item.sortable._isCanceled = true; }, isCanceled: function () { return ui.item.sortable._isCanceled; }, isCustomHelperUsed: function () { return !!ui.item.sortable._isCustomHelperUsed; }, _isCanceled: false, _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed, _destroy: function () { angular.forEach(ui.item.sortable, function(value, key) { ui.item.sortable[key] = undefined; }); } }; }; callbacks.activate = function(e, ui) { savedNodes = element.contents(); var placeholder = element.sortable('option','placeholder'); if (placeholder && placeholder.element && typeof placeholder.element === 'function') { var phElement = placeholder.element(); phElement = angular.element(phElement); var excludes = element.find('[class="' + phElement.attr('class') + '"]:not([ng-repeat], [data-ng-repeat])'); savedNodes = savedNodes.not(excludes); } var connectedSortables = ui.item.sortable._connectedSortables || []; connectedSortables.push({ element: element, scope: scope }); ui.item.sortable._connectedSortables = connectedSortables; }; callbacks.update = function(e, ui) { if(!ui.item.sortable.received) { ui.item.sortable.dropindex = ui.item.index(); var droptarget = ui.item.parent(); ui.item.sortable.droptarget = droptarget; var droptargetScope = getElementScope(ui.item.sortable._connectedSortables, droptarget); ui.item.sortable.droptargetModel = droptargetScope.ngModel; element.sortable('cancel'); } if (hasSortingHelper(element, ui) && !ui.item.sortable.received && element.sortable( 'option', 'appendTo' ) === 'parent') { savedNodes = savedNodes.not(savedNodes.last()); } savedNodes.appendTo(element); if(ui.item.sortable.received) { savedNodes = null; } if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) { scope.$apply(function () { ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0, ui.item.sortable.moved); }); } }; callbacks.stop = function(e, ui) { if(!ui.item.sortable.received && ('dropindex' in ui.item.sortable) && !ui.item.sortable.isCanceled()) { scope.$apply(function () { ngModel.$modelValue.splice( ui.item.sortable.dropindex, 0, ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]); }); } else { if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) && !angular.equals(element.contents(), savedNodes)) { if (hasSortingHelper(element, ui) && element.sortable( 'option', 'appendTo' ) === 'parent') { savedNodes = savedNodes.not(savedNodes.last()); } savedNodes.appendTo(element); } } savedNodes = null; }; callbacks.receive = function(e, ui) { ui.item.sortable.received = true; }; callbacks.remove = function(e, ui) { if (!('dropindex' in ui.item.sortable)) { element.sortable('cancel'); ui.item.sortable.cancel(); } if (!ui.item.sortable.isCanceled()) { scope.$apply(function () { ui.item.sortable.moved = ngModel.$modelValue.splice( ui.item.sortable.index, 1)[0]; }); } }; wrappers.helper = function (inner) { if (inner && typeof inner === 'function') { return function (e, item) { var innerResult = inner.apply(this, arguments); item.sortable._isCustomHelperUsed = item !== innerResult; return innerResult; }; } return inner; }; scope.$watch('uiSortable', function(newVal ) { var sortableWidgetInstance = getSortableWidgetInstance(element); if (!!sortableWidgetInstance) { angular.forEach(newVal, function(value, key) { if (key in directiveOpts) { if (key === 'ui-floating' && (value === false || value === true)) { sortableWidgetInstance.floating = value; } opts[key] = value; return; } if (callbacks[key]) { if( key === 'stop' ){ value = combineCallbacks( value, function() { scope.$apply(); }); value = combineCallbacks(value, afterStop); } value = combineCallbacks(callbacks[key], value); } else if (wrappers[key]) { value = wrappers[key](value); } opts[key] = value; element.sortable('option', key, value); }); } }, true); angular.forEach(callbacks, function(value, key) { opts[key] = combineCallbacks(value, opts[key]); if( key === 'stop' ){ opts[key] = combineCallbacks(opts[key], afterStop); } }); } else { $log.info('ui.sortable: ngModel not provided!', element); } element.sortable(opts); } }; } ]); ; /*! RESOURCE: /scripts/sn.dragdrop/_dragdrop.js */ angular.module("sn.dragdrop", ["ngDragDrop", "ui.sortable"]); ; /*! RESOURCE: /scripts/sn.dragdrop/directive.sn-draggable.js */ angular.module("sn.dragdrop").directive("snDraggable", function($compile, $parse, jqyouiDraggableDirective) { "use strict"; function isMobile() { if( 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)) { return true; } else { return false; } } function link(scope, element, attrs) { function handleNativeStart(e) { if (attrs.dndCustomPayload) { var payload = $parse(attrs.dndCustomPayload)(scope); e.originalEvent.dataTransfer.setData('text', angular.toJson(payload)); } else { var type = attrs.snDraggable; var payload = $parse(attrs.dndPayload)(scope); e.originalEvent.dataTransfer.setData('text', angular.toJson({ type: type, payload: payload })); } } scope.handleJQueryStart = function(element, ui) { if (attrs.dndCustomPayload) { var payload = $parse(attrs.dndCustomPayload)(scope); ui.helper.data("dnd-payload", angular.toJson(payload)); } else { var payload = $parse(attrs.dndPayload)(scope); var type = attrs.snDraggable; ui.helper.data("dnd-payload", angular.toJson({ type: type, payload: payload })); } } if (isMobile()) { jqyouiDraggableDirective[0].link(scope, element, attrs); } else { element.bind('dragstart', handleNativeStart); } } return { restrict: "A", compile: function(tElement, tAttrs) { if (isMobile()) { var jqyouiOptions = { helper: tAttrs.dndHelper || 'clone', revert: tAttrs.dndRevert || 'invalid' }; var draggableOptions = { onStart: "handleJQueryStart", helper: tAttrs.dndPlaceholder || 'keep' }; tAttrs.$set("drag", "true"); tAttrs.$set("jqyouiOptions", angular.toJson(jqyouiOptions)); tElement.attr("jqyoui-draggable", angular.toJson(draggableOptions)); } else { tAttrs.$set("draggable", "true"); } return link; } } }) ; /*! RESOURCE: /scripts/sn.dragdrop/directive.sn-droptarget.js */ angular.module("sn.dragdrop").directive("snDroptarget", function($compile, $parse, jqyouiDroppableDirective, $rootScope) { "use strict"; function isMobile() { if( 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)) { return true; } else { return false; } } function link(scope, element, attrs) { var dropHandler = $parse(attrs.dndOnDrop); var fileHandler; var overHandler; var outHandler; var parentWindow; var targetWindow; if (attrs.dndOnFile) fileHandler = $parse(attrs.dndOnFile); if (attrs.dndOnOver) overHandler = $parse(attrs.dndOnOver); if (attrs.dndOnOut) outHandler = $parse(attrs.dndOnOut); var enterCount = 0; element.bind("dragstart",function(e) { parentWindow = e.currentTarget; }) element.bind("dragenter", function(e) { if (e.preventDefault) e.preventDefault(); enterCount++; if (enterCount > 1) return; e.originalEvent.dataTransfer.dropEffect = 'move'; element.addClass('sn-droptarget-hover'); if (parentWindow !== e.currentTarget && overHandler) { scope.$apply( overHandler(scope, { element: element, ui: {} }) ); } }) element.bind("dragleave", function(e) { enterCount--; if (enterCount > 0) return; element.removeClass('sn-droptarget-hover'); enterCount = 0; if (outHandler) { scope.$apply( outHandler(scope, { element: element, ui: {} }) ); } }) element.bind("drop", function(e) { e.preventDefault(); e.stopPropagation(); element.removeClass('sn-droptarget-hover'); enterCount = 0; targetWindow = e.currentTarget; if(parentWindow === targetWindow) { return; } var dt = e.originalEvent.dataTransfer; if (!dt || isMobile()) return; if (fileHandler && dt.files.length > 0) { var text = dt.getData("text"); scope.$apply(function() { fileHandler(scope, { files: dt.files }) }); return; } var data = {}; try { data = angular.fromJson(dt.getData("text")); } catch(e) { data.payload = dt.getData("text"); data.type = (data.payload.substring(0, 7) === 'http://' || data.payload.substring(0, 8) === 'https://') ? 'link' : 'text'; } scope.$apply( dropHandler(scope, { element: element, ui: {}, data: data }) ); }) element.bind("dragover", function(e) { return false; }) element.bind("dragend", function(e) { parentWindow = undefined; return; }) scope.onDrop = function(event, ui) { angular.element(event.target).removeClass('sn-droptarget-hover'); var data = angular.fromJson(ui.helper.data("dnd-payload")); dropHandler(scope, { element: event.target, ui: ui, data: data }); } scope.onOver = function(event, ui) { angular.element(event.target).addClass('sn-droptarget-hover'); if (overHandler) { overHandler(scope, { element: element, ui: {} }) } } scope.onOut = function(event, ui) { angular.element(event.target).removeClass('sn-droptarget-hover'); if (outHandler) { outHandler(scope, { element: element, ui: {} }) } } jqyouiDroppableDirective[0].link(scope, element, attrs) } return { restrict: "A", compile: function(tElement, tAttrs) { if (isMobile()) { var options = { onDrop: "onDrop", onOver: "onOver", onOut: "onOut", multiple: tAttrs.snMultiple }; tAttrs.$set("drop", "true"); tElement.attr("jqyoui-droppable", angular.toJson(options)); } return link; } } }) ; /*! RESOURCE: /scripts/sn.dragdrop/directive.sn-sortable.js */ angular.module("sn.dragdrop").directive("snSortable", function(uiSortableDirective) { "use strict"; return { require: uiSortableDirective[0].require, scope: { ngModel: '=', uiSortable: '=' }, compile: function(tElement, tAttrs) { var options = tAttrs.snSortable || angular.toJson({ connectWith: tAttrs.sortableContainer }); tAttrs.$set("uiSortable", options); return uiSortableDirective[0].link; } }; }) ; /*! RESOURCE: /scripts/sn.dragdrop/directive.snDragEventBlocker.js */ angular.module("sn.dragdrop").directive("snDragEventBlocker", function() { "use strict"; return { restrict: "A", link: function(scope, element) { element.bind("dragenter", killEvent) element.bind("dragover", killEvent); element.bind("drop", killEvent); element.bind("dragleave", killEvent) function killEvent(e) { if (e.stopPropagation) e.stopPropagation(); if (e.preventDefault) e.preventDefault(); return false; } } } }) ; ; ; /*! RESOURCE: /scripts/app.ng_chat/js_includes_ng_chat.js */ /*! RESOURCE: /scripts/thirdparty/ment.io/mentio.js */ (function() { 'use strict'; angular.module('mentio', []) .directive('mentio', ['mentioUtil', '$document', '$compile', '$log', '$timeout', function (mentioUtil, $document, $compile, $log, $timeout) { return { restrict: 'A', scope: { macros: '=mentioMacros', search: '&mentioSearch', select: '&mentioSelect', items: '=mentioItems', typedTerm: '=mentioTypedTerm', altId: '=mentioId', iframeElement: '=mentioIframeElement', requireLeadingSpace: '=mentioRequireLeadingSpace', suppressTrailingSpace: '=mentioSuppressTrailingSpace', selectNotFound: '=mentioSelectNotFound', trimTerm: '=mentioTrimTerm', ngModel: '=' }, controller: ["$scope", "$timeout", "$attrs", function($scope, $timeout, $attrs) { $scope.query = function (triggerChar, triggerText) { var remoteScope = $scope.triggerCharMap[triggerChar]; if ($scope.trimTerm === undefined || $scope.trimTerm) { triggerText = triggerText.trim(); } remoteScope.showMenu(); remoteScope.search({ term: triggerText }); remoteScope.typedTerm = triggerText; }; $scope.defaultSearch = function(locals) { var results = []; angular.forEach($scope.items, function(item) { if (item.label.toUpperCase().indexOf(locals.term.toUpperCase()) >= 0) { results.push(item); } }); $scope.localItems = results; }; $scope.bridgeSearch = function(termString) { var searchFn = $attrs.mentioSearch ? $scope.search : $scope.defaultSearch; searchFn({ term: termString }); }; $scope.defaultSelect = function(locals) { return $scope.defaultTriggerChar + locals.item.label; }; $scope.bridgeSelect = function(itemVar) { var selectFn = $attrs.mentioSelect ? $scope.select : $scope.defaultSelect; return selectFn({ item: itemVar }); }; $scope.setTriggerText = function(text) { if ($scope.syncTriggerText) { $scope.typedTerm = ($scope.trimTerm === undefined || $scope.trimTerm) ? text.trim() : text; } }; $scope.context = function() { if ($scope.iframeElement) { return {iframe: $scope.iframeElement}; } }; $scope.replaceText = function (text, hasTrailingSpace) { $scope.hideAll(); mentioUtil.replaceTriggerText($scope.context(), $scope.targetElement, $scope.targetElementPath, $scope.targetElementSelectedOffset, $scope.triggerCharSet, text, $scope.requireLeadingSpace, hasTrailingSpace, $scope.suppressTrailingSpace); if (!hasTrailingSpace) { $scope.setTriggerText(''); angular.element($scope.targetElement).triggerHandler('change'); if ($scope.isContentEditable()) { $scope.contentEditableMenuPasted = true; var timer = $timeout(function() { $scope.contentEditableMenuPasted = false; }, 200); $scope.$on('$destroy', function() { $timeout.cancel(timer); }); } } }; $scope.hideAll = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { $scope.triggerCharMap[key].hideMenu(); } } }; $scope.getActiveMenuScope = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { if ($scope.triggerCharMap[key].visible) { return $scope.triggerCharMap[key]; } } } return null; }; $scope.selectActive = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { if ($scope.triggerCharMap[key].visible) { $scope.triggerCharMap[key].selectActive(); } } } }; $scope.isActive = function () { for (var key in $scope.triggerCharMap) { if ($scope.triggerCharMap.hasOwnProperty(key)) { if ($scope.triggerCharMap[key].visible) { return true; } } } return false; }; $scope.isContentEditable = function() { return ($scope.targetElement.nodeName !== 'INPUT' && $scope.targetElement.nodeName !== 'TEXTAREA'); }; $scope.replaceMacro = function(macro, hasTrailingSpace) { if (!hasTrailingSpace) { $scope.replacingMacro = true; $scope.timer = $timeout(function() { mentioUtil.replaceMacroText($scope.context(), $scope.targetElement, $scope.targetElementPath, $scope.targetElementSelectedOffset, $scope.macros, $scope.macros[macro]); angular.element($scope.targetElement).triggerHandler('change'); $scope.replacingMacro = false; }, 300); $scope.$on('$destroy', function() { $timeout.cancel($scope.timer); }); } else { mentioUtil.replaceMacroText($scope.context(), $scope.targetElement, $scope.targetElementPath, $scope.targetElementSelectedOffset, $scope.macros, $scope.macros[macro]); } }; $scope.addMenu = function(menuScope) { if (menuScope.parentScope && $scope.triggerCharMap.hasOwnProperty(menuScope.triggerChar)) { return; } $scope.triggerCharMap[menuScope.triggerChar] = menuScope; if ($scope.triggerCharSet === undefined) { $scope.triggerCharSet = []; } $scope.triggerCharSet.push(menuScope.triggerChar); menuScope.setParent($scope); }; $scope.$on( 'menuCreated', function (event, data) { if ( $attrs.id !== undefined || $attrs.mentioId !== undefined ) { if ( $attrs.id === data.targetElement || ( $attrs.mentioId !== undefined && $scope.altId === data.targetElement ) ) { $scope.addMenu(data.scope); } } } ); $document.on( 'click', function () { if ($scope.isActive()) { $scope.$apply(function () { $scope.hideAll(); }); } } ); $document.on( 'keydown keypress paste', function (event) { var activeMenuScope = $scope.getActiveMenuScope(); if (activeMenuScope) { if (event.which === 9 || event.which === 13) { event.preventDefault(); activeMenuScope.selectActive(); } if (event.which === 27) { event.preventDefault(); activeMenuScope.$apply(function () { activeMenuScope.hideMenu(); }); } if (event.which === 40) { event.preventDefault(); activeMenuScope.$apply(function () { activeMenuScope.activateNextItem(); }); activeMenuScope.adjustScroll(1); } if (event.which === 38) { event.preventDefault(); activeMenuScope.$apply(function () { activeMenuScope.activatePreviousItem(); }); activeMenuScope.adjustScroll(-1); } if (event.which === 37 || event.which === 39) { event.preventDefault(); } } } ); }], link: function (scope, element, attrs, $timeout) { scope.triggerCharMap = {}; scope.targetElement = element; scope.scrollBarParents = element.parents().filter(function() { var overflow = angular.element(this).css("overflow"); return this.scrollHeight > this.clientHeight && overflow !== "hidden" && overflow !== "visible"; }); scope.scrollPosition = null; attrs.$set('autocomplete','off'); if (attrs.mentioItems) { scope.localItems = []; scope.parentScope = scope; var itemsRef = attrs.mentioSearch ? ' mentio-items="items"' : ' mentio-items="localItems"'; scope.defaultTriggerChar = attrs.mentioTriggerChar ? scope.$eval(attrs.mentioTriggerChar) : '@'; var html = '<mentio-menu' + ' mentio-search="bridgeSearch(term)"' + ' mentio-select="bridgeSelect(item)"' + itemsRef; if (attrs.mentioTemplateUrl) { html = html + ' mentio-template-url="' + attrs.mentioTemplateUrl + '"'; } html = html + ' mentio-trigger-char="\'' + scope.defaultTriggerChar + '\'"' + ' mentio-parent-scope="parentScope"' + '/>'; var linkFn = $compile(html); var el = linkFn(scope); element.parent().append(el); scope.$on('$destroy', function() { el.remove(); }); } if (attrs.mentioTypedTerm) { scope.syncTriggerText = true; } function keyHandler(event) { function stopEvent(event) { event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); } var activeMenuScope = scope.getActiveMenuScope(); if (activeMenuScope) { if (event.which === 9 || event.which === 13) { stopEvent(event); activeMenuScope.selectActive(); return false; } if (event.which === 27) { stopEvent(event); activeMenuScope.$apply(function () { activeMenuScope.hideMenu(); }); return false; } if (event.which === 40) { stopEvent(event); activeMenuScope.$apply(function () { activeMenuScope.activateNextItem(); }); activeMenuScope.adjustScroll(1); return false; } if (event.which === 38) { stopEvent(event); activeMenuScope.$apply(function () { activeMenuScope.activatePreviousItem(); }); activeMenuScope.adjustScroll(-1); return false; } if (event.which === 37 || event.which === 39) { stopEvent(event); return false; } } } scope.$watch( 'iframeElement', function(newValue) { if (newValue) { var iframeDocument = newValue.contentWindow.document; iframeDocument.addEventListener('click', function () { if (scope.isActive()) { scope.$apply(function () { scope.hideAll(); }); } } ); iframeDocument.addEventListener('keydown', keyHandler, true ); scope.$on ( '$destroy', function() { iframeDocument.removeEventListener ( 'keydown', keyHandler ); }); } } ); scope.$watch( 'ngModel', function (newValue) { if ((!newValue || newValue === '') && !scope.isActive()) { return; } if (scope.triggerCharSet === undefined) { $log.warn('Error, no mentio-items attribute was provided, ' + 'and no separate mentio-menus were specified. Nothing to do.'); return; } if (scope.contentEditableMenuPasted) { scope.contentEditableMenuPasted = false; return; } if (scope.replacingMacro) { $timeout.cancel(scope.timer); scope.replacingMacro = false; } var isActive = scope.isActive(); var isContentEditable = scope.isContentEditable(); var mentionInfo = mentioUtil.getTriggerInfo(scope.context(), scope.triggerCharSet, scope.requireLeadingSpace, isActive); if (mentionInfo !== undefined && ( !isActive || (isActive && ( (isContentEditable && mentionInfo.mentionTriggerChar === scope.currentMentionTriggerChar) || (!isContentEditable && mentionInfo.mentionPosition === scope.currentMentionPosition) ) ) ) ) { if (mentionInfo.mentionSelectedElement) { scope.targetElement = mentionInfo.mentionSelectedElement; scope.targetElementPath = mentionInfo.mentionSelectedPath; scope.targetElementSelectedOffset = mentionInfo.mentionSelectedOffset; } scope.setTriggerText(mentionInfo.mentionText); scope.currentMentionPosition = mentionInfo.mentionPosition; scope.currentMentionTriggerChar = mentionInfo.mentionTriggerChar; scope.query(mentionInfo.mentionTriggerChar, mentionInfo.mentionText); } else { var currentTypedTerm = scope.typedTerm; scope.setTriggerText(''); scope.hideAll(); var macroMatchInfo = mentioUtil.getMacroMatch(scope.context(), scope.macros); if (macroMatchInfo !== undefined) { scope.targetElement = macroMatchInfo.macroSelectedElement; scope.targetElementPath = macroMatchInfo.macroSelectedPath; scope.targetElementSelectedOffset = macroMatchInfo.macroSelectedOffset; scope.replaceMacro(macroMatchInfo.macroText, macroMatchInfo.macroHasTrailingSpace); } else if (scope.selectNotFound && currentTypedTerm && currentTypedTerm !== '') { var lastScope = scope.triggerCharMap[scope.currentMentionTriggerChar]; if (lastScope) { var text = lastScope.select({ item: {label: currentTypedTerm} }); if (typeof text.then === 'function') { text.then(scope.replaceText); } else { scope.replaceText(text, true); } } } } } ); } }; }]) .directive('mentioMenu', ['mentioUtil', '$rootScope', '$log', '$window', '$document', '$timeout', function (mentioUtil, $rootScope, $log, $window, $document, $timeout) { return { restrict: 'E', scope: { search: '&mentioSearch', select: '&mentioSelect', items: '=mentioItems', triggerChar: '=mentioTriggerChar', forElem: '=mentioFor', parentScope: '=mentioParentScope' }, templateUrl: function(tElement, tAttrs) { return tAttrs.mentioTemplateUrl !== undefined ? tAttrs.mentioTemplateUrl : 'mentio-menu.tpl.html'; }, controller: ["$scope", function ($scope) { $scope.visible = false; this.activate = $scope.activate = function (item) { $scope.activeItem = item; }; this.isActive = $scope.isActive = function (item) { return $scope.activeItem === item; }; this.selectItem = $scope.selectItem = function (item) { if (item.termLengthIsZero) { item.name = $scope.triggerChar + $scope.typedTerm } var text = $scope.select({ item: item }); if (typeof text.then === 'function') { text.then($scope.parentMentio.replaceText); } else { $scope.parentMentio.replaceText(text); } }; $scope.activateNextItem = function () { var index = $scope.items.indexOf($scope.activeItem); this.activate($scope.items[(index + 1) % $scope.items.length]); }; $scope.activatePreviousItem = function () { var index = $scope.items.indexOf($scope.activeItem); this.activate($scope.items[index === 0 ? $scope.items.length - 1 : index - 1]); }; $scope.isFirstItemActive = function () { var index = $scope.items.indexOf($scope.activeItem); return index === 0; }; $scope.isLastItemActive = function () { var index = $scope.items.indexOf($scope.activeItem); return index === ($scope.items.length - 1); }; $scope.selectActive = function () { $scope.selectItem($scope.activeItem); }; $scope.isVisible = function () { return $scope.visible; }; $scope.showMenu = function () { if (!$scope.visible) { $scope.menuElement.css("visibility", "visible"); $scope.requestVisiblePendingSearch = true; } }; $scope.setParent = function (scope) { $scope.parentMentio = scope; $scope.targetElement = scope.targetElement; }; var scopeDuplicate = $scope; $rootScope.$on('mentio.closeMenu', function () { scopeDuplicate.hideMenu(); }) }], link: function (scope, element) { element[0].parentNode.removeChild(element[0]); $document[0].body.appendChild(element[0]); scope.menuElement = element; scope.menuElement.css("visibility", "hidden"); if (scope.parentScope) { scope.parentScope.addMenu(scope); } else { if (!scope.forElem) { $log.error('mentio-menu requires a target element in tbe mentio-for attribute'); return; } if (!scope.triggerChar) { $log.error('mentio-menu requires a trigger char'); return; } $rootScope.$broadcast('menuCreated', { targetElement : scope.forElem, scope : scope }); } angular.element($window).bind( 'resize', function () { if (scope.isVisible()) { var triggerCharSet = []; triggerCharSet.push(scope.triggerChar); mentioUtil.popUnderMention(scope.parentMentio.context(), triggerCharSet, element, scope.requireLeadingSpace); } } ); scope.$watch('items', function (items) { if (items && items.length > 0) { scope.activate(items[0]); if (!scope.visible && scope.requestVisiblePendingSearch) { scope.visible = true; scope.requestVisiblePendingSearch = false; } $timeout(function() { var menu = element.find(".dropdown-menu"); if(menu.length > 0 && menu.offset().top < 0) menu.addClass("reverse"); }, 0, false); } else { scope.activate({ termLengthIsZero: true }); } }); scope.$watch('isVisible()', function (visible) { if (visible) { var triggerCharSet = []; triggerCharSet.push(scope.triggerChar); mentioUtil.popUnderMention(scope.parentMentio.context(), triggerCharSet, element, scope.requireLeadingSpace); } else { element.find(".dropdown-menu").removeClass("reverse"); } }); var prevScroll; scope.parentMentio.scrollBarParents.each(function() { angular.element(this).on("scroll.mentio", function() { if (!prevScroll) prevScroll = this.scrollTop; var scrollDiff = prevScroll - this.scrollTop; prevScroll = this.scrollTop; if (element[0].style["position"] === "absolute") { element[0].style["z-index"] = 9; element[0].style.top = (parseInt(element[0].style.top) + scrollDiff) + "px"; } }); }); scope.parentMentio.$on('$destroy', function () { element.remove(); }); scope.hideMenu = function () { scope.visible = false; element.css('display', 'none'); }; scope.adjustScroll = function (direction) { var menuEl = element[0]; var menuItemsList = menuEl.querySelector('ul'); var menuItem = menuEl.querySelector('[mentio-menu-item].active'); if (scope.isFirstItemActive()) { return menuItemsList.scrollTop = 0; } else if(scope.isLastItemActive()) { return menuItemsList.scrollTop = menuItemsList.scrollHeight; } if (direction === 1) { menuItemsList.scrollTop += menuItem.offsetHeight; } else { menuItemsList.scrollTop -= menuItem.offsetHeight; } }; } }; }]) .directive('mentioMenuItem', function () { return { restrict: 'A', scope: { item: '=mentioMenuItem' }, require: '^mentioMenu', link: function (scope, element, attrs, controller) { scope.$watch(function () { return controller.isActive(scope.item); }, function (active) { if (active) { element.addClass('active'); } else { element.removeClass('active'); } }); element.bind('mouseenter', function () { scope.$apply(function () { controller.activate(scope.item); }); }); element.bind('click', function () { controller.selectItem(scope.item); return false; }); } }; }) .filter('unsafe', ["$sce", function($sce) { return function (val) { return $sce.trustAsHtml(val); }; }]) .filter('mentioHighlight', function() { function escapeRegexp (queryToEscape) { return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } return function (matchItem, query, hightlightClass) { if (query) { var replaceText = hightlightClass ? '<span class="' + hightlightClass + '">$&</span>' : '<strong>$&</strong>'; return ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), replaceText); } else { return matchItem; } }; }); 'use strict'; angular.module('mentio') .factory('mentioUtil', ["$window", "$location", "$anchorScroll", "$timeout", function ($window, $location, $anchorScroll, $timeout) { function popUnderMention (ctx, triggerCharSet, selectionEl, requireLeadingSpace) { var coordinates; var mentionInfo = getTriggerInfo(ctx, triggerCharSet, requireLeadingSpace, false); if (mentionInfo !== undefined) { if (selectedElementIsTextAreaOrInput(ctx)) { coordinates = getTextAreaOrInputUnderlinePosition(ctx, getDocument(ctx).activeElement, mentionInfo.mentionPosition); } else { coordinates = getContentEditableCaretPosition(ctx, mentionInfo.mentionPosition); } selectionEl.css({ top: coordinates.top + 'px', left: coordinates.left + 'px', position: 'absolute', zIndex: 5000, display: 'block' }); $timeout(function(){ scrollIntoView(ctx, selectionEl); },0); } else { selectionEl.css({ display: 'none' }); } } function scrollIntoView(ctx, elem) { var reasonableBuffer = 20; var maxScrollDisplacement = 100; var clientRect; var e = elem[0]; while (clientRect === undefined || clientRect.height === 0) { clientRect = e.getBoundingClientRect(); if (clientRect.height === 0) { e = e.childNodes[0]; if (e === undefined || !e.getBoundingClientRect) { return; } } } var elemTop = clientRect.top; var elemBottom = elemTop + clientRect.height; if(elemTop < 0) { $window.scrollTo(0, $window.pageYOffset + clientRect.top - reasonableBuffer); } else if (elemBottom > $window.innerHeight) { var maxY = $window.pageYOffset + clientRect.top - reasonableBuffer; if (maxY - $window.pageYOffset > maxScrollDisplacement) { maxY = $window.pageYOffset + maxScrollDisplacement; } var targetY = $window.pageYOffset - ($window.innerHeight - elemBottom); if (targetY > maxY) { targetY = maxY; } $window.scrollTo(0, targetY); } } function selectedElementIsTextAreaOrInput (ctx) { var element = getDocument(ctx).activeElement; if (element !== null) { var nodeName = element.nodeName; var type = element.getAttribute('type'); return (nodeName === 'INPUT' && type === 'text') || nodeName === 'TEXTAREA'; } return false; } function selectElement (ctx, targetElement, path, offset) { var range; var elem = targetElement; if (path) { for (var i = 0; i < path.length; i++) { elem = elem.childNodes[path[i]]; if (elem === undefined) { return; } while (elem.length < offset) { offset -= elem.length; elem = elem.nextSibling; } if (elem.childNodes.length === 0 && !elem.length) { elem = elem.previousSibling; } } } var sel = getWindowSelection(ctx); range = getDocument(ctx).createRange(); range.setStart(elem, offset); range.setEnd(elem, offset); range.collapse(true); try{sel.removeAllRanges();}catch(error){} sel.addRange(range); targetElement.focus(); } function pasteHtml (ctx, html, startPos, endPos) { var range, sel; sel = getWindowSelection(ctx); range = getDocument(ctx).createRange(); range.setStart(sel.anchorNode, startPos); range.setEnd(sel.anchorNode, endPos); range.deleteContents(); var el = getDocument(ctx).createElement('div'); el.innerHTML = html; var frag = getDocument(ctx).createDocumentFragment(), node, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } range.insertNode(frag); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } function resetSelection (ctx, targetElement, path, offset) { var nodeName = targetElement.nodeName; if (nodeName === 'INPUT' || nodeName === 'TEXTAREA') { if (targetElement !== getDocument(ctx).activeElement) { targetElement.focus(); } } else { selectElement(ctx, targetElement, path, offset); } } function replaceMacroText (ctx, targetElement, path, offset, macros, text) { resetSelection(ctx, targetElement, path, offset); var macroMatchInfo = getMacroMatch(ctx, macros); if (macroMatchInfo.macroHasTrailingSpace) { macroMatchInfo.macroText = macroMatchInfo.macroText + '\xA0'; text = text + '\xA0'; } if (macroMatchInfo !== undefined) { var element = getDocument(ctx).activeElement; if (selectedElementIsTextAreaOrInput(ctx)) { var startPos = macroMatchInfo.macroPosition; var endPos = macroMatchInfo.macroPosition + macroMatchInfo.macroText.length; element.value = element.value.substring(0, startPos) + text + element.value.substring(endPos, element.value.length); element.selectionStart = startPos + text.length; element.selectionEnd = startPos + text.length; } else { pasteHtml(ctx, text, macroMatchInfo.macroPosition, macroMatchInfo.macroPosition + macroMatchInfo.macroText.length); } } } function replaceTriggerText (ctx, targetElement, path, offset, triggerCharSet, text, requireLeadingSpace, hasTrailingSpace, suppressTrailingSpace) { resetSelection(ctx, targetElement, path, offset); var mentionInfo = getTriggerInfo(ctx, triggerCharSet, requireLeadingSpace, true, hasTrailingSpace); if (mentionInfo !== undefined) { if (selectedElementIsTextAreaOrInput()) { var myField = getDocument(ctx).activeElement; if (!suppressTrailingSpace) { text = text + ' '; } var startPos = mentionInfo.mentionPosition; var endPos = mentionInfo.mentionPosition + mentionInfo.mentionText.length + 1; myField.value = myField.value.substring(0, startPos) + text + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + text.length; myField.selectionEnd = startPos + text.length; } else { if (!suppressTrailingSpace) { text = text + '\xA0'; } pasteHtml(ctx, text, mentionInfo.mentionPosition, mentionInfo.mentionPosition + mentionInfo.mentionText.length + 1); } } } function getNodePositionInParent (ctx, elem) { if (elem.parentNode === null) { return 0; } for (var i = 0; i < elem.parentNode.childNodes.length; i++) { var node = elem.parentNode.childNodes[i]; if (node === elem) { return i; } } } function getMacroMatch (ctx, macros) { var selected, path = [], offset; if (selectedElementIsTextAreaOrInput(ctx)) { selected = getDocument(ctx).activeElement; } else { var selectionInfo = getContentEditableSelectedPath(ctx); if (selectionInfo) { selected = selectionInfo.selected; path = selectionInfo.path; offset = selectionInfo.offset; } } var effectiveRange = getTextPrecedingCurrentSelection(ctx); if (effectiveRange !== undefined && effectiveRange !== null) { var matchInfo; var hasTrailingSpace = false; if (effectiveRange.length > 0 && (effectiveRange.charAt(effectiveRange.length - 1) === '\xA0' || effectiveRange.charAt(effectiveRange.length - 1) === ' ')) { hasTrailingSpace = true; effectiveRange = effectiveRange.substring(0, effectiveRange.length-1); } angular.forEach(macros, function (macro, c) { var idx = effectiveRange.toUpperCase().lastIndexOf(c.toUpperCase()); if (idx >= 0 && c.length + idx === effectiveRange.length) { var prevCharPos = idx - 1; if (idx === 0 || effectiveRange.charAt(prevCharPos) === '\xA0' || effectiveRange.charAt(prevCharPos) === ' ' ) { matchInfo = { macroPosition: idx, macroText: c, macroSelectedElement: selected, macroSelectedPath: path, macroSelectedOffset: offset, macroHasTrailingSpace: hasTrailingSpace }; } } }); if (matchInfo) { return matchInfo; } } } function getContentEditableSelectedPath(ctx) { var sel = getWindowSelection(ctx); var selected = sel.anchorNode; var path = []; var offset; if (selected != null) { var i; var ce = selected.contentEditable; while (selected !== null && ce !== 'true') { i = getNodePositionInParent(ctx, selected); path.push(i); selected = selected.parentNode; if (selected !== null) { ce = selected.contentEditable; } } path.reverse(); offset = sel.getRangeAt(0).startOffset; return { selected: selected, path: path, offset: offset }; } } function getTriggerInfo (ctx, triggerCharSet, requireLeadingSpace, menuAlreadyActive, hasTrailingSpace) { var selected, path, offset; if (selectedElementIsTextAreaOrInput(ctx)) { selected = getDocument(ctx).activeElement; } else { var selectionInfo = getContentEditableSelectedPath(ctx); if (selectionInfo) { selected = selectionInfo.selected; path = selectionInfo.path; offset = selectionInfo.offset; } } var effectiveRange = getTextPrecedingCurrentSelection(ctx); if (effectiveRange !== undefined && effectiveRange !== null) { var mostRecentTriggerCharPos = -1; var triggerChar; triggerCharSet.forEach(function(c) { var idx = effectiveRange.lastIndexOf(c); if (idx > mostRecentTriggerCharPos) { mostRecentTriggerCharPos = idx; triggerChar = c; } }); if (mostRecentTriggerCharPos >= 0 && ( mostRecentTriggerCharPos === 0 || !requireLeadingSpace || /[\xA0\s]/g.test ( effectiveRange.substring( mostRecentTriggerCharPos - 1, mostRecentTriggerCharPos) ) ) ) { var currentTriggerSnippet = effectiveRange.substring(mostRecentTriggerCharPos + 1, effectiveRange.length); triggerChar = effectiveRange.substring(mostRecentTriggerCharPos, mostRecentTriggerCharPos+1); var firstSnippetChar = currentTriggerSnippet.substring(0,1); var leadingSpace = currentTriggerSnippet.length > 0 && ( firstSnippetChar === ' ' || firstSnippetChar === '\xA0' ); if (hasTrailingSpace) { currentTriggerSnippet = currentTriggerSnippet.trim(); } if (!leadingSpace && (menuAlreadyActive || !(/[\xA0\s]/g.test(currentTriggerSnippet)))) { return { mentionPosition: mostRecentTriggerCharPos, mentionText: currentTriggerSnippet, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset, mentionTriggerChar: triggerChar }; } } } } function getWindowSelection(ctx) { if (!ctx) { return window.getSelection(); } else { return ctx.iframe.contentWindow.getSelection(); } } function getDocument(ctx) { if (!ctx) { return document; } else { return ctx.iframe.contentWindow.document; } } function getTextPrecedingCurrentSelection (ctx) { var text; if (selectedElementIsTextAreaOrInput(ctx)) { var textComponent = getDocument(ctx).activeElement; var startPos = textComponent.selectionStart; text = textComponent.value.substring(0, startPos); } else { var selectedElem = getWindowSelection(ctx).anchorNode; if (selectedElem != null) { var workingNodeContent = selectedElem.textContent; var selectStartOffset = getWindowSelection(ctx).getRangeAt(0).startOffset; if (selectStartOffset >= 0) { text = workingNodeContent.substring(0, selectStartOffset); } } } return text; } function getContentEditableCaretPosition (ctx, selectedNodePosition) { var markerTextChar = '\ufeff'; var markerEl, markerId = 'sel_' + new Date().getTime() + '_' + Math.random().toString().substr(2); var range; var sel = getWindowSelection(ctx); var prevRange = sel.getRangeAt(0); range = getDocument(ctx).createRange(); range.setStart(sel.anchorNode, selectedNodePosition); range.setEnd(sel.anchorNode, selectedNodePosition); range.collapse(false); markerEl = getDocument(ctx).createElement('span'); markerEl.id = markerId; markerEl.appendChild(getDocument(ctx).createTextNode(markerTextChar)); range.insertNode(markerEl); sel.removeAllRanges(); sel.addRange(prevRange); var coordinates = { left: 0, top: markerEl.offsetHeight }; localToGlobalCoordinates(ctx, markerEl, coordinates); markerEl.parentNode.removeChild(markerEl); return coordinates; } function localToGlobalCoordinates(ctx, element, coordinates) { var obj = element; var iframe = ctx ? ctx.iframe : null; while(obj) { coordinates.left += obj.offsetLeft; coordinates.top += obj.offsetTop; if (obj !== getDocument().body) { coordinates.top -= obj.scrollTop; coordinates.left -= obj.scrollLeft; } obj = obj.offsetParent; if (!obj && iframe) { obj = iframe; iframe = null; } } } function getTextAreaOrInputUnderlinePosition (ctx, element, position) { var properties = [ 'direction', 'boxSizing', 'width', 'height', 'overflowX', 'overflowY', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent', 'textDecoration', 'letterSpacing', 'wordSpacing' ]; var isFirefox = (window.mozInnerScreenX !== null); var div = getDocument(ctx).createElement('div'); div.id = 'input-textarea-caret-position-mirror-div'; getDocument(ctx).body.appendChild(div); var style = div.style; var computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle; style.whiteSpace = 'pre-wrap'; if (element.nodeName !== 'INPUT') { style.wordWrap = 'break-word'; } style.position = 'absolute'; style.visibility = 'hidden'; properties.forEach(function (prop) { style[prop] = computed[prop]; }); if (isFirefox) { style.width = (parseInt(computed.width) - 2) + 'px'; if (element.scrollHeight > parseInt(computed.height)) style.overflowY = 'scroll'; } else { style.overflow = 'hidden'; } div.textContent = element.value.substring(0, position); if (element.nodeName === 'INPUT') { div.textContent = div.textContent.replace(/\s/g, '\u00a0'); } var span = getDocument(ctx).createElement('span'); span.textContent = element.value.substring(position) || '.'; div.appendChild(span); var coordinates = { top: span.offsetTop + parseInt(computed.borderTopWidth) + parseInt(computed.fontSize), left: span.offsetLeft + parseInt(computed.borderLeftWidth) }; localToGlobalCoordinates(ctx, element, coordinates); getDocument(ctx).body.removeChild(div); return coordinates; } return { popUnderMention: popUnderMention, replaceMacroText: replaceMacroText, replaceTriggerText: replaceTriggerText, getMacroMatch: getMacroMatch, getTriggerInfo: getTriggerInfo, selectElement: selectElement, getTextAreaOrInputUnderlinePosition: getTextAreaOrInputUnderlinePosition, getTextPrecedingCurrentSelection: getTextPrecedingCurrentSelection, getContentEditableSelectedPath: getContentEditableSelectedPath, getNodePositionInParent: getNodePositionInParent, getContentEditableCaretPosition: getContentEditableCaretPosition, pasteHtml: pasteHtml, resetSelection: resetSelection, scrollIntoView: scrollIntoView }; }]); angular.module("mentio").run(["$templateCache", function($templateCache) {$templateCache.put("mentio-menu.tpl.html","<style>\n.scrollable-menu {\n height: auto;\n max-height: 300px;\n overflow: auto;\n}\n\n.menu-highlighted {\n font-weight: bold;\n}\n</style>\n<ul class=\"dropdown-menu scrollable-menu\" style=\"display:block\">\n <li mentio-menu-item=\"item\" ng-repeat=\"item in items track by $index\">\n <a class=\"text-primary\" ng-bind-html=\"item.label | mentioHighlight:typedTerm:\'menu-highlighted\' | unsafe\"></a>\n </li>\n</ul>");}]); })(); ; /*! RESOURCE: /scripts/thirdparty/typeahead/typeahead.jquery.js */ (function(root, factory) { if (typeof define === "function" && define.amd) { define("typeahead.js", [ "jquery" ], function(a0) { return factory(a0); }); } else if (typeof exports === "object") { module.exports = factory(require("jquery")); } else { factory(jQuery); } })(this, function($) { var _ = function() { "use strict"; return { isMsie: function() { return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; }, isBlankString: function(str) { return !str || /^\s*$/.test(str); }, escapeRegExChars: function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }, isString: function(obj) { return typeof obj === "string"; }, isNumber: function(obj) { return typeof obj === "number"; }, isArray: $.isArray, isFunction: $.isFunction, isObject: $.isPlainObject, isUndefined: function(obj) { return typeof obj === "undefined"; }, isElement: function(obj) { return !!(obj && obj.nodeType === 1); }, isJQuery: function(obj) { return obj instanceof $; }, toStr: function toStr(s) { return _.isUndefined(s) || s === null ? "" : s + ""; }, bind: $.proxy, each: function(collection, cb) { $.each(collection, reverseArgs); function reverseArgs(index, value) { return cb(value, index); } }, map: $.map, filter: $.grep, every: function(obj, test) { var result = true; if (!obj) { return result; } $.each(obj, function(key, val) { if (!(result = test.call(null, val, key, obj))) { return false; } }); return !!result; }, some: function(obj, test) { var result = false; if (!obj) { return result; } $.each(obj, function(key, val) { if (result = test.call(null, val, key, obj)) { return false; } }); return !!result; }, mixin: $.extend, identity: function(x) { return x; }, clone: function(obj) { return $.extend(true, {}, obj); }, getIdGenerator: function() { var counter = 0; return function() { return counter++; }; }, templatify: function templatify(obj) { return $.isFunction(obj) ? obj : template; function template() { return String(obj); } }, defer: function(fn) { setTimeout(fn, 0); }, debounce: function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments, later, callNow; later = function() { timeout = null; if (!immediate) { result = func.apply(context, args); } }; callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; }; }, throttle: function(func, wait) { var context, args, timeout, result, previous, later; previous = 0; later = function() { previous = new Date(); timeout = null; result = func.apply(context, args); }; return function() { var now = new Date(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }, stringify: function(val) { return _.isString(val) ? val : JSON.stringify(val); }, noop: function() {} }; }(); var WWW = function() { "use strict"; var defaultClassNames = { wrapper: "twitter-typeahead", input: "tt-input", hint: "tt-hint", menu: "tt-menu", dataset: "tt-dataset", suggestion: "tt-suggestion", selectable: "tt-selectable", empty: "tt-empty", open: "tt-open", cursor: "tt-cursor", highlight: "tt-highlight" }; return build; function build(o) { var www, classes; classes = _.mixin({}, defaultClassNames, o); www = { css: buildCss(), classes: classes, html: buildHtml(classes), selectors: buildSelectors(classes) }; return { css: www.css, html: www.html, classes: www.classes, selectors: www.selectors, mixin: function(o) { _.mixin(o, www); } }; } function buildHtml(c) { return { wrapper: '<span class="' + c.wrapper + '"></span>', menu: '<div class="' + c.menu + '"></div>' }; } function buildSelectors(classes) { var selectors = {}; _.each(classes, function(v, k) { selectors[k] = "." + v; }); return selectors; } function buildCss() { var css = { wrapper: { position: "relative", display: "inline-block" }, hint: { position: "absolute", top: "0", left: "0", borderColor: "transparent", boxShadow: "none", opacity: "1" }, input: { position: "relative", verticalAlign: "top", backgroundColor: "transparent" }, inputWithNoHint: { position: "relative", verticalAlign: "top" }, menu: { position: "absolute", top: "100%", left: "0", zIndex: "100", display: "none" }, ltr: { left: "0", right: "auto" }, rtl: { left: "auto", right: " 0" } }; if (_.isMsie()) { _.mixin(css.input, { backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" }); } return css; } }(); var EventBus = function() { "use strict"; var namespace, deprecationMap; namespace = "typeahead:"; deprecationMap = { render: "rendered", cursorchange: "cursorchanged", select: "selected", autocomplete: "autocompleted" }; function EventBus(o) { if (!o || !o.el) { $.error("EventBus initialized without el"); } this.$el = $(o.el); } _.mixin(EventBus.prototype, { _trigger: function(type, args) { var $e; $e = $.Event(namespace + type); (args = args || []).unshift($e); this.$el.trigger.apply(this.$el, args); return $e; }, before: function(type) { var args, $e; args = [].slice.call(arguments, 1); $e = this._trigger("before" + type, args); return $e.isDefaultPrevented(); }, trigger: function(type) { var deprecatedType; this._trigger(type, [].slice.call(arguments, 1)); if (deprecatedType = deprecationMap[type]) { this._trigger(deprecatedType, [].slice.call(arguments, 1)); } } }); return EventBus; }(); var EventEmitter = function() { "use strict"; var splitter = /\s+/, nextTick = getNextTick(); return { onSync: onSync, onAsync: onAsync, off: off, trigger: trigger }; function on(method, types, cb, context) { var type; if (!cb) { return this; } types = types.split(splitter); cb = context ? bindContext(cb, context) : cb; this._callbacks = this._callbacks || {}; while (type = types.shift()) { this._callbacks[type] = this._callbacks[type] || { sync: [], async: [] }; this._callbacks[type][method].push(cb); } return this; } function onAsync(types, cb, context) { return on.call(this, "async", types, cb, context); } function onSync(types, cb, context) { return on.call(this, "sync", types, cb, context); } function off(types) { var type; if (!this._callbacks) { return this; } types = types.split(splitter); while (type = types.shift()) { delete this._callbacks[type]; } return this; } function trigger(types) { var type, callbacks, args, syncFlush, asyncFlush; if (!this._callbacks) { return this; } types = types.split(splitter); args = [].slice.call(arguments, 1); while ((type = types.shift()) && (callbacks = this._callbacks[type])) { syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args)); asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args)); syncFlush() && nextTick(asyncFlush); } return this; } function getFlush(callbacks, context, args) { return flush; function flush() { var cancelled; for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) { cancelled = callbacks[i].apply(context, args) === false; } return !cancelled; } } function getNextTick() { var nextTickFn; if (window.setImmediate) { nextTickFn = function nextTickSetImmediate(fn) { setImmediate(function() { fn(); }); }; } else { nextTickFn = function nextTickSetTimeout(fn) { setTimeout(function() { fn(); }, 0); }; } return nextTickFn; } function bindContext(fn, context) { return fn.bind ? fn.bind(context) : function() { fn.apply(context, [].slice.call(arguments, 0)); }; } }(); var highlight = function(doc) { "use strict"; var defaults = { node: null, pattern: null, tagName: "strong", className: null, wordsOnly: false, caseSensitive: false }; return function hightlight(o) { var regex; o = _.mixin({}, defaults, o); if (!o.node || !o.pattern) { return; } o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ]; regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly); traverse(o.node, hightlightTextNode); function hightlightTextNode(textNode) { var match, patternNode, wrapperNode; if (match = regex.exec(textNode.data)) { wrapperNode = doc.createElement(o.tagName); o.className && (wrapperNode.className = o.className); patternNode = textNode.splitText(match.index); patternNode.splitText(match[0].length); wrapperNode.appendChild(patternNode.cloneNode(true)); textNode.parentNode.replaceChild(wrapperNode, patternNode); } return !!match; } function traverse(el, hightlightTextNode) { var childNode, TEXT_NODE_TYPE = 3; for (var i = 0; i < el.childNodes.length; i++) { childNode = el.childNodes[i]; if (childNode.nodeType === TEXT_NODE_TYPE) { i += hightlightTextNode(childNode) ? 1 : 0; } else { traverse(childNode, hightlightTextNode); } } } }; function getRegex(patterns, caseSensitive, wordsOnly) { var escapedPatterns = [], regexStr; for (var i = 0, len = patterns.length; i < len; i++) { escapedPatterns.push(_.escapeRegExChars(patterns[i])); } regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i"); } }(window.document); var Input = function() { "use strict"; var specialKeyCodeMap; specialKeyCodeMap = { 9: "tab", 27: "esc", 37: "left", 39: "right", 13: "enter", 38: "up", 40: "down" }; function Input(o, www) { o = o || {}; if (!o.input) { $.error("input is missing"); } www.mixin(this); this.$hint = $(o.hint); this.$input = $(o.input); this.query = this.$input.val(); this.queryWhenFocused = this.hasFocus() ? this.query : null; this.$overflowHelper = buildOverflowHelper(this.$input); this._checkLanguageDirection(); if (this.$hint.length === 0) { this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop; } } Input.normalizeQuery = function(str) { return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " "); }; _.mixin(Input.prototype, EventEmitter, { _onBlur: function onBlur() { this.resetInputValue(); this.trigger("blurred"); }, _onFocus: function onFocus() { this.queryWhenFocused = this.query; this.trigger("focused"); }, _onKeydown: function onKeydown($e) { var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; this._managePreventDefault(keyName, $e); if (keyName && this._shouldTrigger(keyName, $e)) { this.trigger(keyName + "Keyed", $e); } }, _onInput: function onInput() { this._setQuery(this.getInputValue()); this.clearHintIfInvalid(); this._checkLanguageDirection(); }, _managePreventDefault: function managePreventDefault(keyName, $e) { var preventDefault; switch (keyName) { case "up": case "down": preventDefault = !withModifier($e); break; default: preventDefault = false; } preventDefault && $e.preventDefault(); }, _shouldTrigger: function shouldTrigger(keyName, $e) { var trigger; switch (keyName) { case "tab": trigger = !withModifier($e); break; default: trigger = true; } return trigger; }, _checkLanguageDirection: function checkLanguageDirection() { var dir = (this.$input.css("direction") || "ltr").toLowerCase(); if (this.dir !== dir) { this.dir = dir; this.$hint.attr("dir", dir); this.trigger("langDirChanged", dir); } }, _setQuery: function setQuery(val, silent) { var areEquivalent, hasDifferentWhitespace; areEquivalent = areQueriesEquivalent(val, this.query); hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false; this.query = val; if (!silent && !areEquivalent) { this.trigger("queryChanged", this.query); } else if (!silent && hasDifferentWhitespace) { this.trigger("whitespaceChanged", this.query); } }, bind: function() { var that = this, onBlur, onFocus, onKeydown, onInput; onBlur = _.bind(this._onBlur, this); onFocus = _.bind(this._onFocus, this); onKeydown = _.bind(this._onKeydown, this); onInput = _.bind(this._onInput, this); this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown); if (!_.isMsie() || _.isMsie() > 9) { this.$input.on("input.tt", onInput); } else { this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) { if (specialKeyCodeMap[$e.which || $e.keyCode]) { return; } _.defer(_.bind(that._onInput, that, $e)); }); } return this; }, focus: function focus() { this.$input.focus(); }, blur: function blur() { this.$input.blur(); }, getLangDir: function getLangDir() { return this.dir; }, getQuery: function getQuery() { return this.query || ""; }, setQuery: function setQuery(val, silent) { this.setInputValue(val); this._setQuery(val, silent); }, hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() { return this.query !== this.queryWhenFocused; }, getInputValue: function getInputValue() { return this.$input.val(); }, setInputValue: function setInputValue(value) { this.$input.val(value); this.clearHintIfInvalid(); this._checkLanguageDirection(); }, resetInputValue: function resetInputValue() { this.setInputValue(this.query); }, getHint: function getHint() { return this.$hint.val(); }, setHint: function setHint(value) { this.$hint.val(value); }, clearHint: function clearHint() { this.setHint(""); }, clearHintIfInvalid: function clearHintIfInvalid() { var val, hint, valIsPrefixOfHint, isValid; val = this.getInputValue(); hint = this.getHint(); valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0; isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow(); !isValid && this.clearHint(); }, hasFocus: function hasFocus() { return this.$input.is(":focus"); }, hasOverflow: function hasOverflow() { var constraint = this.$input.width() - 2; this.$overflowHelper.text(this.getInputValue()); return this.$overflowHelper.width() >= constraint; }, isCursorAtEnd: function() { var valueLength, selectionStart, range; valueLength = this.$input.val().length; selectionStart = this.$input[0].selectionStart; if (_.isNumber(selectionStart)) { return selectionStart === valueLength; } else if (document.selection) { range = document.selection.createRange(); range.moveStart("character", -valueLength); return valueLength === range.text.length; } return true; }, destroy: function destroy() { this.$hint.off(".tt"); this.$input.off(".tt"); this.$overflowHelper.remove(); this.$hint = this.$input = this.$overflowHelper = $("<div>"); } }); return Input; function buildOverflowHelper($input) { return $('<pre aria-hidden="true"></pre>').css({ position: "absolute", visibility: "hidden", whiteSpace: "pre", fontFamily: $input.css("font-family"), fontSize: $input.css("font-size"), fontStyle: $input.css("font-style"), fontVariant: $input.css("font-variant"), fontWeight: $input.css("font-weight"), wordSpacing: $input.css("word-spacing"), letterSpacing: $input.css("letter-spacing"), textIndent: $input.css("text-indent"), textRendering: $input.css("text-rendering"), textTransform: $input.css("text-transform") }).insertAfter($input); } function areQueriesEquivalent(a, b) { return Input.normalizeQuery(a) === Input.normalizeQuery(b); } function withModifier($e) { return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; } }(); var Dataset = function() { "use strict"; var keys, nameGenerator; keys = { val: "tt-selectable-display", obj: "tt-selectable-object" }; nameGenerator = _.getIdGenerator(); function Dataset(o, www) { o = o || {}; o.templates = o.templates || {}; o.templates.notFound = o.templates.notFound || o.templates.empty; if (!o.source) { $.error("missing source"); } if (!o.node) { $.error("missing node"); } if (o.name && !isValidName(o.name)) { $.error("invalid dataset name: " + o.name); } www.mixin(this); this.highlight = !!o.highlight; this.name = o.name || nameGenerator(); this.limit = o.limit || 5; this.displayFn = getDisplayFn(o.display || o.displayKey); this.templates = getTemplates(o.templates, this.displayFn); this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source; this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async; this._resetLastSuggestion(); this.$el = $(o.node).addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name); } Dataset.extractData = function extractData(el) { var $el = $(el); if ($el.data(keys.obj)) { return { val: $el.data(keys.val) || "", obj: $el.data(keys.obj) || null }; } return null; }; _.mixin(Dataset.prototype, EventEmitter, { _overwrite: function overwrite(query, suggestions) { suggestions = suggestions || []; if (suggestions.length) { this._renderSuggestions(query, suggestions); } else if (this.async && this.templates.pending) { this._renderPending(query); } else if (!this.async && this.templates.notFound) { this._renderNotFound(query); } else { this._empty(); } this.trigger("rendered", this.name, suggestions, false); }, _append: function append(query, suggestions) { suggestions = suggestions || []; if (suggestions.length && this.$lastSuggestion.length) { this._appendSuggestions(query, suggestions); } else if (suggestions.length) { this._renderSuggestions(query, suggestions); } else if (!this.$lastSuggestion.length && this.templates.notFound) { this._renderNotFound(query); } this.trigger("rendered", this.name, suggestions, true); }, _renderSuggestions: function renderSuggestions(query, suggestions) { var $fragment; $fragment = this._getSuggestionsFragment(query, suggestions); this.$lastSuggestion = $fragment.children().last(); this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions)); }, _appendSuggestions: function appendSuggestions(query, suggestions) { var $fragment, $lastSuggestion; $fragment = this._getSuggestionsFragment(query, suggestions); $lastSuggestion = $fragment.children().last(); this.$lastSuggestion.after($fragment); this.$lastSuggestion = $lastSuggestion; }, _renderPending: function renderPending(query) { var template = this.templates.pending; this._resetLastSuggestion(); template && this.$el.html(template({ query: query, dataset: this.name })); }, _renderNotFound: function renderNotFound(query) { var template = this.templates.notFound; this._resetLastSuggestion(); template && this.$el.html(template({ query: query, dataset: this.name })); }, _empty: function empty() { this.$el.empty(); this._resetLastSuggestion(); }, _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) { var that = this, fragment; fragment = document.createDocumentFragment(); _.each(suggestions, function getSuggestionNode(suggestion) { var $el, context; context = that._injectQuery(query, suggestion); $el = $(that.templates.suggestion(context)).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable); fragment.appendChild($el[0]); }); this.highlight && highlight({ className: this.classes.highlight, node: fragment, pattern: query }); return $(fragment); }, _getFooter: function getFooter(query, suggestions) { return this.templates.footer ? this.templates.footer({ query: query, suggestions: suggestions, dataset: this.name }) : null; }, _getHeader: function getHeader(query, suggestions) { return this.templates.header ? this.templates.header({ query: query, suggestions: suggestions, dataset: this.name }) : null; }, _resetLastSuggestion: function resetLastSuggestion() { this.$lastSuggestion = $(); }, _injectQuery: function injectQuery(query, obj) { return _.isObject(obj) ? _.mixin({ _query: query }, obj) : obj; }, update: function update(query) { var that = this, canceled = false, syncCalled = false, rendered = 0; this.cancel(); this.cancel = function cancel() { canceled = true; that.cancel = $.noop; that.async && that.trigger("asyncCanceled", query); }; this.source(query, sync, async); !syncCalled && sync([]); function sync(suggestions) { if (syncCalled) { return; } syncCalled = true; suggestions = (suggestions || []).slice(0, that.limit); rendered = suggestions.length; that._overwrite(query, suggestions); if (rendered < that.limit && that.async) { that.trigger("asyncRequested", query); } } function async(suggestions) { suggestions = suggestions || []; if (!canceled && rendered < that.limit) { that.cancel = $.noop; that._append(query, suggestions.slice(0, that.limit - rendered)); rendered += suggestions.length; that.async && that.trigger("asyncReceived", query); } } }, cancel: $.noop, clear: function clear() { this._empty(); this.cancel(); this.trigger("cleared"); }, isEmpty: function isEmpty() { return this.$el.is(":empty"); }, destroy: function destroy() { this.$el = $("<div>"); } }); return Dataset; function getDisplayFn(display) { display = display || _.stringify; return _.isFunction(display) ? display : displayFn; function displayFn(obj) { return obj[display]; } } function getTemplates(templates, displayFn) { return { notFound: templates.notFound && _.templatify(templates.notFound), pending: templates.pending && _.templatify(templates.pending), header: templates.header && _.templatify(templates.header), footer: templates.footer && _.templatify(templates.footer), suggestion: templates.suggestion || suggestionTemplate }; function suggestionTemplate(context) { return $("<div>").text(displayFn(context)); } } function isValidName(str) { return /^[_a-zA-Z0-9-]+$/.test(str); } }(); var Menu = function() { "use strict"; function Menu(o, www) { var that = this; o = o || {}; if (!o.node) { $.error("node is required"); } www.mixin(this); this.$node = $(o.node); this.query = null; this.datasets = _.map(o.datasets, initializeDataset); function initializeDataset(oDataset) { var node = that.$node.find(oDataset.node).first(); oDataset.node = node.length ? node : $("<div>").appendTo(that.$node); return new Dataset(oDataset, www); } } _.mixin(Menu.prototype, EventEmitter, { _onSelectableClick: function onSelectableClick($e) { this.trigger("selectableClicked", $($e.currentTarget)); }, _onRendered: function onRendered(type, dataset, suggestions, async) { this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); this.trigger("datasetRendered", dataset, suggestions, async); }, _onCleared: function onCleared() { this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); this.trigger("datasetCleared"); }, _propagate: function propagate() { this.trigger.apply(this, arguments); }, _allDatasetsEmpty: function allDatasetsEmpty() { return _.every(this.datasets, isDatasetEmpty); function isDatasetEmpty(dataset) { return dataset.isEmpty(); } }, _getSelectables: function getSelectables() { return this.$node.find(this.selectors.selectable); }, _removeCursor: function _removeCursor() { var $selectable = this.getActiveSelectable(); $selectable && $selectable.removeClass(this.classes.cursor); }, _ensureVisible: function ensureVisible($el) { var elTop, elBottom, nodeScrollTop, nodeHeight; elTop = $el.position().top; elBottom = elTop + $el.outerHeight(true); nodeScrollTop = this.$node.scrollTop(); nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10); if (elTop < 0) { this.$node.scrollTop(nodeScrollTop + elTop); } else if (nodeHeight < elBottom) { this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight)); } }, bind: function() { var that = this, onSelectableClick; onSelectableClick = _.bind(this._onSelectableClick, this); this.$node.on("click.tt", this.selectors.selectable, onSelectableClick); _.each(this.datasets, function(dataset) { dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that); }); return this; }, isOpen: function isOpen() { return this.$node.hasClass(this.classes.open); }, open: function open() { this.$node.addClass(this.classes.open); }, close: function close() { this.$node.removeClass(this.classes.open); this._removeCursor(); }, setLanguageDirection: function setLanguageDirection(dir) { this.$node.attr("dir", dir); }, selectableRelativeToCursor: function selectableRelativeToCursor(delta) { var $selectables, $oldCursor, oldIndex, newIndex; $oldCursor = this.getActiveSelectable(); $selectables = this._getSelectables(); oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1; newIndex = oldIndex + delta; newIndex = (newIndex + 1) % ($selectables.length + 1) - 1; newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex; return newIndex === -1 ? null : $selectables.eq(newIndex); }, setCursor: function setCursor($selectable) { this._removeCursor(); if ($selectable = $selectable && $selectable.first()) { $selectable.addClass(this.classes.cursor); this._ensureVisible($selectable); } }, getSelectableData: function getSelectableData($el) { return $el && $el.length ? Dataset.extractData($el) : null; }, getActiveSelectable: function getActiveSelectable() { var $selectable = this._getSelectables().filter(this.selectors.cursor).first(); return $selectable.length ? $selectable : null; }, getTopSelectable: function getTopSelectable() { var $selectable = this._getSelectables().first(); return $selectable.length ? $selectable : null; }, update: function update(query) { var isValidUpdate = query !== this.query; if (isValidUpdate) { this.query = query; _.each(this.datasets, updateDataset); } return isValidUpdate; function updateDataset(dataset) { dataset.update(query); } }, empty: function empty() { _.each(this.datasets, clearDataset); this.query = null; this.$node.addClass(this.classes.empty); function clearDataset(dataset) { dataset.clear(); } }, destroy: function destroy() { this.$node.off(".tt"); this.$node = $("<div>"); _.each(this.datasets, destroyDataset); function destroyDataset(dataset) { dataset.destroy(); } } }); return Menu; }(); var DefaultMenu = function() { "use strict"; var s = Menu.prototype; function DefaultMenu() { Menu.apply(this, [].slice.call(arguments, 0)); } _.mixin(DefaultMenu.prototype, Menu.prototype, { open: function open() { !this._allDatasetsEmpty() && this._show(); return s.open.apply(this, [].slice.call(arguments, 0)); }, close: function close() { this._hide(); return s.close.apply(this, [].slice.call(arguments, 0)); }, _onRendered: function onRendered() { if (this._allDatasetsEmpty()) { this._hide(); } else { this.isOpen() && this._show(); } return s._onRendered.apply(this, [].slice.call(arguments, 0)); }, _onCleared: function onCleared() { if (this._allDatasetsEmpty()) { this._hide(); } else { this.isOpen() && this._show(); } return s._onCleared.apply(this, [].slice.call(arguments, 0)); }, setLanguageDirection: function setLanguageDirection(dir) { this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl); return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0)); }, _hide: function hide() { this.$node.hide(); }, _show: function show() { this.$node.css("display", "block"); } }); return DefaultMenu; }(); var Typeahead = function() { "use strict"; function Typeahead(o, www) { var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged; o = o || {}; if (!o.input) { $.error("missing input"); } if (!o.menu) { $.error("missing menu"); } if (!o.eventBus) { $.error("missing event bus"); } www.mixin(this); this.eventBus = o.eventBus; this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; this.input = o.input; this.menu = o.menu; this.enabled = true; this.active = false; this.input.hasFocus() && this.activate(); this.dir = this.input.getLangDir(); this._hacks(); this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this); onFocused = c(this, "activate", "open", "_onFocused"); onBlurred = c(this, "deactivate", "_onBlurred"); onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed"); onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed"); onEscKeyed = c(this, "isActive", "_onEscKeyed"); onUpKeyed = c(this, "isActive", "open", "_onUpKeyed"); onDownKeyed = c(this, "isActive", "open", "_onDownKeyed"); onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed"); onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed"); onQueryChanged = c(this, "_openIfActive", "_onQueryChanged"); onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged"); this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this); } _.mixin(Typeahead.prototype, { _hacks: function hacks() { var $input, $menu; $input = this.input.$input || $("<div>"); $menu = this.menu.$node || $("<div>"); $input.on("blur.tt", function($e) { var active, isActive, hasActive; active = document.activeElement; isActive = $menu.is(active); hasActive = $menu.has(active).length > 0; if (_.isMsie() && (isActive || hasActive)) { $e.preventDefault(); $e.stopImmediatePropagation(); _.defer(function() { $input.focus(); }); } }); $menu.on("mousedown.tt", function($e) { $e.preventDefault(); }); }, _onSelectableClicked: function onSelectableClicked(type, $el) { this.select($el); }, _onDatasetCleared: function onDatasetCleared() { this._updateHint(); }, _onDatasetRendered: function onDatasetRendered(type, dataset, suggestions, async) { this._updateHint(); this.eventBus.trigger("render", suggestions, async, dataset); }, _onAsyncRequested: function onAsyncRequested(type, dataset, query) { this.eventBus.trigger("asyncrequest", query, dataset); }, _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) { this.eventBus.trigger("asynccancel", query, dataset); }, _onAsyncReceived: function onAsyncReceived(type, dataset, query) { this.eventBus.trigger("asyncreceive", query, dataset); }, _onFocused: function onFocused() { this._minLengthMet() && this.menu.update(this.input.getQuery()); }, _onBlurred: function onBlurred() { if (this.input.hasQueryChangedSinceLastFocus()) { this.eventBus.trigger("change", this.input.getQuery()); } }, _onEnterKeyed: function onEnterKeyed(type, $e) { var $selectable; if ($selectable = this.menu.getActiveSelectable()) { this.select($selectable) && $e.preventDefault(); } }, _onTabKeyed: function onTabKeyed(type, $e) { var $selectable; if ($selectable = this.menu.getActiveSelectable()) { this.select($selectable) && $e.preventDefault(); } else if ($selectable = this.menu.getTopSelectable()) { this.autocomplete($selectable) && $e.preventDefault(); } }, _onEscKeyed: function onEscKeyed() { this.close(); }, _onUpKeyed: function onUpKeyed() { this.moveCursor(-1); }, _onDownKeyed: function onDownKeyed() { this.moveCursor(+1); }, _onLeftKeyed: function onLeftKeyed() { if (this.dir === "rtl" && this.input.isCursorAtEnd()) { this.autocomplete(this.menu.getTopSelectable()); } }, _onRightKeyed: function onRightKeyed() { if (this.dir === "ltr" && this.input.isCursorAtEnd()) { this.autocomplete(this.menu.getTopSelectable()); } }, _onQueryChanged: function onQueryChanged(e, query) { this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty(); }, _onWhitespaceChanged: function onWhitespaceChanged() { this._updateHint(); }, _onLangDirChanged: function onLangDirChanged(e, dir) { if (this.dir !== dir) { this.dir = dir; this.menu.setLanguageDirection(dir); } }, _openIfActive: function openIfActive() { this.isActive() && this.open(); }, _minLengthMet: function minLengthMet(query) { query = _.isString(query) ? query : this.input.getQuery() || ""; return query.length >= this.minLength; }, _updateHint: function updateHint() { var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match; $selectable = this.menu.getTopSelectable(); data = this.menu.getSelectableData($selectable); val = this.input.getInputValue(); if (data && !_.isBlankString(val) && !this.input.hasOverflow()) { query = Input.normalizeQuery(val); escapedQuery = _.escapeRegExChars(query); frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i"); match = frontMatchRegEx.exec(data.val); match && this.input.setHint(val + match[1]); } else { this.input.clearHint(); } }, isEnabled: function isEnabled() { return this.enabled; }, enable: function enable() { this.enabled = true; }, disable: function disable() { this.enabled = false; }, isActive: function isActive() { return this.active; }, activate: function activate() { if (this.isActive()) { return true; } else if (!this.isEnabled() || this.eventBus.before("active")) { return false; } else { this.active = true; this.eventBus.trigger("active"); return true; } }, deactivate: function deactivate() { if (!this.isActive()) { return true; } else if (this.eventBus.before("idle")) { return false; } else { this.active = false; this.close(); this.eventBus.trigger("idle"); return true; } }, isOpen: function isOpen() { return this.menu.isOpen(); }, open: function open() { if (!this.isOpen() && !this.eventBus.before("open")) { this.menu.open(); this._updateHint(); this.eventBus.trigger("open"); } return this.isOpen(); }, close: function close() { if (this.isOpen() && !this.eventBus.before("close")) { this.menu.close(); this.input.clearHint(); this.input.resetInputValue(); this.eventBus.trigger("close"); } return !this.isOpen(); }, setVal: function setVal(val) { this.input.setQuery(_.toStr(val)); }, getVal: function getVal() { return this.input.getQuery(); }, select: function select($selectable) { var data = this.menu.getSelectableData($selectable); if (data && !this.eventBus.before("select", data.obj)) { this.input.setQuery(data.val, true); this.eventBus.trigger("select", data.obj); this.close(); return true; } return false; }, autocomplete: function autocomplete($selectable) { var query, data, isValid; query = this.input.getQuery(); data = this.menu.getSelectableData($selectable); isValid = data && query !== data.val; if (isValid && !this.eventBus.before("autocomplete", data.obj)) { this.input.setQuery(data.val); this.eventBus.trigger("autocomplete", data.obj); return true; } return false; }, moveCursor: function moveCursor(delta) { var query, $candidate, data, payload, cancelMove; query = this.input.getQuery(); $candidate = this.menu.selectableRelativeToCursor(delta); data = this.menu.getSelectableData($candidate); payload = data ? data.obj : null; cancelMove = this._minLengthMet() && this.menu.update(query); if (!cancelMove && !this.eventBus.before("cursorchange", payload)) { this.menu.setCursor($candidate); if (data) { this.input.setInputValue(data.val); } else { this.input.resetInputValue(); this._updateHint(); } this.eventBus.trigger("cursorchange", payload); return true; } return false; }, destroy: function destroy() { this.input.destroy(); this.menu.destroy(); } }); return Typeahead; function c(ctx) { var methods = [].slice.call(arguments, 1); return function() { var args = [].slice.call(arguments); _.each(methods, function(method) { return ctx[method].apply(ctx, args); }); }; } }(); (function() { "use strict"; var old, keys, methods; old = $.fn.typeahead; keys = { www: "tt-www", attrs: "tt-attrs", typeahead: "tt-typeahead" }; methods = { initialize: function initialize(o, datasets) { var www; datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1); o = o || {}; www = WWW(o.classNames); return this.each(attach); function attach() { var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, typeahead, MenuConstructor; _.each(datasets, function(d) { d.highlight = !!o.highlight; }); $input = $(this); $wrapper = $(www.html.wrapper); $hint = $elOrNull(o.hint); $menu = $elOrNull(o.menu); defaultHint = o.hint !== false && !$hint; defaultMenu = o.menu !== false && !$menu; defaultHint && ($hint = buildHintFromInput($input, www)); defaultMenu && ($menu = $(www.html.menu).css(www.css.menu)); $hint && $hint.val(""); $input = prepInput($input, www); if (defaultHint || defaultMenu) { $wrapper.css(www.css.wrapper); $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint); $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null); } MenuConstructor = defaultMenu ? DefaultMenu : Menu; eventBus = new EventBus({ el: $input }); input = new Input({ hint: $hint, input: $input }, www); menu = new MenuConstructor({ node: $menu, datasets: datasets }, www); typeahead = new Typeahead({ input: input, menu: menu, eventBus: eventBus, minLength: o.minLength }, www); $input.data(keys.www, www); $input.data(keys.typeahead, typeahead); } }, isEnabled: function isEnabled() { var enabled; ttEach(this.first(), function(t) { enabled = t.isEnabled(); }); return enabled; }, enable: function enable() { ttEach(this, function(t) { t.enable(); }); return this; }, disable: function disable() { ttEach(this, function(t) { t.disable(); }); return this; }, isActive: function isActive() { var active; ttEach(this.first(), function(t) { active = t.isActive(); }); return active; }, activate: function activate() { ttEach(this, function(t) { t.activate(); }); return this; }, deactivate: function deactivate() { ttEach(this, function(t) { t.deactivate(); }); return this; }, isOpen: function isOpen() { var open; ttEach(this.first(), function(t) { open = t.isOpen(); }); return open; }, open: function open() { ttEach(this, function(t) { t.open(); }); return this; }, close: function close() { ttEach(this, function(t) { t.close(); }); return this; }, select: function select(el) { var success = false, $el = $(el); ttEach(this.first(), function(t) { success = t.select($el); }); return success; }, autocomplete: function autocomplete(el) { var success = false, $el = $(el); ttEach(this.first(), function(t) { success = t.autocomplete($el); }); return success; }, moveCursor: function moveCursoe(delta) { var success = false; ttEach(this.first(), function(t) { success = t.moveCursor(delta); }); return success; }, val: function val(newVal) { var query; if (!arguments.length) { ttEach(this.first(), function(t) { query = t.getVal(); }); return query; } else { ttEach(this, function(t) { t.setVal(newVal); }); return this; } }, destroy: function destroy() { ttEach(this, function(typeahead, $input) { revert($input); typeahead.destroy(); }); return this; } }; $.fn.typeahead = function(method) { if (methods[method]) { return methods[method].apply(this, [].slice.call(arguments, 1)); } else { return methods.initialize.apply(this, arguments); } }; $.fn.typeahead.noConflict = function noConflict() { $.fn.typeahead = old; return this; }; function ttEach($els, fn) { $els.each(function() { var $input = $(this), typeahead; (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input); }); } function buildHintFromInput($input, www) { return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop("readonly", true).removeAttr("id name placeholder required").attr({ autocomplete: "off", spellcheck: "false", tabindex: -1 }); } function prepInput($input, www) { $input.data(keys.attrs, { dir: $input.attr("dir"), autocomplete: $input.attr("autocomplete"), spellcheck: $input.attr("spellcheck"), style: $input.attr("style") }); $input.addClass(www.classes.input).attr({ autocomplete: "off", spellcheck: false }); try { !$input.attr("dir") && $input.attr("dir", "auto"); } catch (e) {} return $input; } function getBackgroundStyles($el) { return { backgroundAttachment: $el.css("background-attachment"), backgroundClip: $el.css("background-clip"), backgroundColor: $el.css("background-color"), backgroundImage: $el.css("background-image"), backgroundOrigin: $el.css("background-origin"), backgroundPosition: $el.css("background-position"), backgroundRepeat: $el.css("background-repeat"), backgroundSize: $el.css("background-size") }; } function revert($input) { var www, $wrapper; www = $input.data(keys.www); $wrapper = $input.parent().filter(www.selectors.wrapper); _.each($input.data(keys.attrs), function(val, key) { _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val); }); $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input); if ($wrapper.length) { $input.detach().insertAfter($wrapper); $wrapper.remove(); } } function $elOrNull(obj) { var isValid, $el; isValid = _.isJQuery(obj) || _.isElement(obj); $el = isValid ? $(obj).first() : []; return $el.length ? $el : null; } })(); }); ; /*! RESOURCE: /scripts/sn.angularstrap/js_includes_angular_strap_aside.js */ /*! RESOURCE: /scripts/thirdparty/angular.strap.2.2.2/modules/dimensions.js */ angular.module('mgcrea.ngStrap.helpers.dimensions', []).factory('dimensions', [ '$document', '$window', function($document, $window) { var jqLite = angular.element; var fn = {}; var nodeName = fn.nodeName = function(element, name) { return element.nodeName && element.nodeName.toLowerCase() === name.toLowerCase(); }; fn.css = function(element, prop, extra) { var value; if (element.currentStyle) { value = element.currentStyle[prop]; } else if (window.getComputedStyle) { value = window.getComputedStyle(element)[prop]; } else { value = element.style[prop]; } return extra === true ? parseFloat(value) || 0 : value; }; fn.offset = function(element) { var boxRect = element.getBoundingClientRect(); var docElement = element.ownerDocument; return { width: boxRect.width || element.offsetWidth, height: boxRect.height || element.offsetHeight, top: boxRect.top + (window.pageYOffset || docElement.documentElement.scrollTop) - (docElement.documentElement.clientTop || 0), left: boxRect.left + (window.pageXOffset || docElement.documentElement.scrollLeft) - (docElement.documentElement.clientLeft || 0) }; }; fn.setOffset = function(element, options, i) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = fn.css(element, 'position'), curElem = angular.element(element), props = {}; if (position === 'static') { element.style.position = 'relative'; } curOffset = fn.offset(element); curCSSTop = fn.css(element, 'top'); curCSSLeft = fn.css(element, 'left'); calculatePosition = (position === 'absolute' || position === 'fixed') && (curCSSTop + curCSSLeft).indexOf('auto') > -1; if (calculatePosition) { curPosition = fn.position(element); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat(curCSSTop) || 0; curLeft = parseFloat(curCSSLeft) || 0; } if (angular.isFunction(options)) { options = options.call(element, i, curOffset); } if (options.top !== null) { props.top = options.top - curOffset.top + curTop; } if (options.left !== null) { props.left = options.left - curOffset.left + curLeft; } if ('using' in options) { options.using.call(curElem, props); } else { curElem.css({ top: props.top + 'px', left: props.left + 'px' }); } }; fn.position = function(element) { var offsetParentRect = { top: 0, left: 0 }, offsetParentElement, offset; if (fn.css(element, 'position') === 'fixed') { offset = element.getBoundingClientRect(); } else { offsetParentElement = offsetParent(element); offset = fn.offset(element); if (!nodeName(offsetParentElement, 'html')) { offsetParentRect = fn.offset(offsetParentElement); } offsetParentRect.top += fn.css(offsetParentElement, 'borderTopWidth', true); offsetParentRect.left += fn.css(offsetParentElement, 'borderLeftWidth', true); } return { width: element.offsetWidth, height: element.offsetHeight, top: offset.top - offsetParentRect.top - fn.css(element, 'marginTop', true), left: offset.left - offsetParentRect.left - fn.css(element, 'marginLeft', true) }; }; var offsetParent = function offsetParentElement(element) { var docElement = element.ownerDocument; var offsetParent = element.offsetParent || docElement; if (nodeName(offsetParent, '#document')) return docElement.documentElement; while (offsetParent && !nodeName(offsetParent, 'html') && fn.css(offsetParent, 'position') === 'static') { offsetParent = offsetParent.offsetParent; } return offsetParent || docElement.documentElement; }; fn.height = function(element, outer) { var value = element.offsetHeight; if (outer) { value += fn.css(element, 'marginTop', true) + fn.css(element, 'marginBottom', true); } else { value -= fn.css(element, 'paddingTop', true) + fn.css(element, 'paddingBottom', true) + fn.css(element, 'borderTopWidth', true) + fn.css(element, 'borderBottomWidth', true); } return value; }; fn.width = function(element, outer) { var value = element.offsetWidth; if (outer) { value += fn.css(element, 'marginLeft', true) + fn.css(element, 'marginRight', true); } else { value -= fn.css(element, 'paddingLeft', true) + fn.css(element, 'paddingRight', true) + fn.css(element, 'borderLeftWidth', true) + fn.css(element, 'borderRightWidth', true); } return value; }; return fn; } ]); ; /*! RESOURCE: /scripts/thirdparty/angular.strap.2.2.2/modules/modal.js */ angular.module('mgcrea.ngStrap.modal', [ 'mgcrea.ngStrap.helpers.dimensions' ]).provider('$modal', function() { var defaults = this.defaults = { animation: 'am-fade', backdropAnimation: 'am-fade', prefixClass: 'modal', prefixEvent: 'modal', placement: 'top', template: 'modal/modal.tpl.html', contentTemplate: false, container: false, element: null, backdrop: true, keyboard: true, html: false, show: true }; this.$get = [ '$window', '$rootScope', '$compile', '$q', '$templateCache', '$http', '$animate', '$timeout', '$sce', 'dimensions', function($window, $rootScope, $compile, $q, $templateCache, $http, $animate, $timeout, $sce, dimensions) { var forEach = angular.forEach; var trim = String.prototype.trim; var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; var bodyElement = angular.element($window.document.body); var htmlReplaceRegExp = /ng-bind="/gi; function ModalFactory(config) { var $modal = {}; var options = $modal.$options = angular.extend({}, defaults, config); $modal.$promise = fetchTemplate(options.template); var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new(); if (!options.element && !options.container) { options.container = 'body'; } $modal.$id = options.id || options.element && options.element.attr('id') || ''; forEach([ 'title', 'content' ], function(key) { if (options[key]) scope[key] = $sce.trustAsHtml(options[key]); }); scope.$hide = function() { scope.$$postDigest(function() { $modal.hide(); }); }; scope.$show = function() { scope.$$postDigest(function() { $modal.show(); }); }; scope.$toggle = function() { scope.$$postDigest(function() { $modal.toggle(); }); }; $modal.$isShown = scope.$isShown = false; if (options.contentTemplate) { $modal.$promise = $modal.$promise.then(function(template) { var templateEl = angular.element(template); return fetchTemplate(options.contentTemplate).then(function(contentTemplate) { var contentEl = findElement('[ng-bind="content"]', templateEl[0]).removeAttr('ng-bind').html(contentTemplate); if (!config.template) contentEl.next().remove(); return templateEl[0].outerHTML; }); }); } var modalLinker, modalElement; var backdropElement = angular.element('<div class="' + options.prefixClass + '-backdrop"/>'); backdropElement.css({ position: 'fixed', top: '0px', left: '0px', bottom: '0px', right: '0px', 'z-index': 1038 }); $modal.$promise.then(function(template) { if (angular.isObject(template)) template = template.data; if (options.html) template = template.replace(htmlReplaceRegExp, 'ng-bind-html="'); template = trim.apply(template); modalLinker = $compile(template); $modal.init(); }); $modal.init = function() { if (options.show) { scope.$$postDigest(function() { $modal.show(); }); } }; $modal.destroy = function() { if (modalElement) { modalElement.remove(); modalElement = null; } if (backdropElement) { backdropElement.remove(); backdropElement = null; } scope.$destroy(); }; $modal.show = function() { if ($modal.$isShown) return; var parent, after; if (angular.isElement(options.container)) { parent = options.container; after = options.container[0].lastChild ? angular.element(options.container[0].lastChild) : null; } else { if (options.container) { parent = findElement(options.container); after = parent[0] && parent[0].lastChild ? angular.element(parent[0].lastChild) : null; } else { parent = null; after = options.element; } } modalElement = $modal.$element = modalLinker(scope, function(clonedElement, scope) {}); if (scope.$emit(options.prefixEvent + '.show.before', $modal).defaultPrevented) { return; } modalElement.css({ display: 'block' }).addClass(options.placement); if (options.animation) { if (options.backdrop) { backdropElement.addClass(options.backdropAnimation); } modalElement.addClass(options.animation); } if (options.backdrop) { $animate.enter(backdropElement, bodyElement, null); } var promise = $animate.enter(modalElement, parent, after, enterAnimateCallback); if (promise && promise.then) promise.then(enterAnimateCallback); $modal.$isShown = scope.$isShown = true; safeDigest(scope); var el = modalElement[0]; requestAnimationFrame(function() { el.focus(); }); bodyElement.addClass(options.prefixClass + '-open'); if (options.animation) { bodyElement.addClass(options.prefixClass + '-with-' + options.animation); } if (options.backdrop) { modalElement.on('click', hideOnBackdropClick); backdropElement.on('click', hideOnBackdropClick); backdropElement.on('wheel', preventEventDefault); } if (options.keyboard) { modalElement.on('keyup', $modal.$onKeyUp); } }; function enterAnimateCallback() { scope.$emit(options.prefixEvent + '.show', $modal); } $modal.hide = function() { if (!$modal.$isShown) return; if (scope.$emit(options.prefixEvent + '.hide.before', $modal).defaultPrevented) { return; } var promise = $animate.leave(modalElement, leaveAnimateCallback); if (promise && promise.then) promise.then(leaveAnimateCallback); if (options.backdrop) { $animate.leave(backdropElement); } $modal.$isShown = scope.$isShown = false; safeDigest(scope); if (options.backdrop) { modalElement.off('click', hideOnBackdropClick); backdropElement.off('click', hideOnBackdropClick); backdropElement.off('wheel', preventEventDefault); } if (options.keyboard) { modalElement.off('keyup', $modal.$onKeyUp); } }; function leaveAnimateCallback() { scope.$emit(options.prefixEvent + '.hide', $modal); bodyElement.removeClass(options.prefixClass + '-open'); if (options.animation) { bodyElement.removeClass(options.prefixClass + '-with-' + options.animation); } } $modal.toggle = function() { $modal.$isShown ? $modal.hide() : $modal.show(); }; $modal.focus = function() { modalElement[0].focus(); }; $modal.$onKeyUp = function(evt) { if (evt.which === 27 && $modal.$isShown) { $modal.hide(); evt.stopPropagation(); } }; function hideOnBackdropClick(evt) { if (evt.target !== evt.currentTarget) return; options.backdrop === 'static' ? $modal.focus() : $modal.hide(); } function preventEventDefault(evt) { evt.preventDefault(); } return $modal; } function safeDigest(scope) { scope.$$phase || scope.$root && scope.$root.$$phase || scope.$digest(); } function findElement(query, element) { return angular.element((element || document).querySelectorAll(query)); } var fetchPromises = {}; function fetchTemplate(template) { if (fetchPromises[template]) return fetchPromises[template]; return fetchPromises[template] = $http.get(template, { cache: $templateCache }).then(function(res) { return res.data; }); } return ModalFactory; } ]; }).directive('bsModal', [ '$window', '$sce', '$modal', function($window, $sce, $modal) { return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope, element: element, show: false }; angular.forEach([ 'template', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation', 'id', 'prefixEvent', 'prefixClass' ], function(key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); var falseValueRegExp = /^(false|0|)$/i; angular.forEach([ 'backdrop', 'keyboard', 'html', 'container' ], function(key) { if (angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false; }); angular.forEach([ 'title', 'content' ], function(key) { attr[key] && attr.$observe(key, function(newValue, oldValue) { scope[key] = $sce.trustAsHtml(newValue); }); }); attr.bsModal && scope.$watch(attr.bsModal, function(newValue, oldValue) { if (angular.isObject(newValue)) { angular.extend(scope, newValue); } else { scope.content = newValue; } }, true); var modal = $modal(options); element.on(attr.trigger || 'click', modal.toggle); scope.$on('$destroy', function() { if (modal) modal.destroy(); options = null; modal = null; }); } }; } ]); ; /*! RESOURCE: /scripts/thirdparty/angular.strap.2.2.2/modules/aside.js */ angular.module('mgcrea.ngStrap.aside', [ 'mgcrea.ngStrap.modal' ]).provider('$aside', function() { var defaults = this.defaults = { animation: 'am-fade-and-slide-right', prefixClass: 'aside', prefixEvent: 'aside', placement: 'right', template: 'aside/aside.tpl.html', contentTemplate: false, container: false, element: null, backdrop: true, keyboard: true, html: false, show: true }; this.$get = [ '$modal', function($modal) { function AsideFactory(config) { var $aside = {}; var options = angular.extend({}, defaults, config); $aside = $modal(options); return $aside; } return AsideFactory; } ]; }).directive('bsAside', [ '$window', '$sce', '$aside', function($window, $sce, $aside) { var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; return { restrict: 'EAC', scope: true, link: function postLink(scope, element, attr, transclusion) { var options = { scope: scope, element: element, show: false }; angular.forEach([ 'template', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation' ], function(key) { if (angular.isDefined(attr[key])) options[key] = attr[key]; }); var falseValueRegExp = /^(false|0|)$/i; angular.forEach([ 'backdrop', 'keyboard', 'html', 'container' ], function(key) { if (angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false; }); angular.forEach([ 'title', 'content' ], function(key) { attr[key] && attr.$observe(key, function(newValue, oldValue) { scope[key] = $sce.trustAsHtml(newValue); }); }); attr.bsAside && scope.$watch(attr.bsAside, function(newValue, oldValue) { if (angular.isObject(newValue)) { angular.extend(scope, newValue); } else { scope.content = newValue; } }, true); var aside = $aside(options); element.on(attr.trigger || 'click', aside.toggle); scope.$on('$destroy', function() { if (aside) aside.destroy(); options = null; aside = null; }); } }; } ]); ; ; /*! RESOURCE: /scripts/sn.angularstrap/js_includes_angular_strap_components.js */ /*! RESOURCE: /scripts/sn.angularstrap/_module.js */ angular.module('sn.angularstrap', [ 'mgcrea.ngStrap.aside' ]); ; /*! RESOURCE: /scripts/sn.angularstrap/directive.snAside.js */ angular.module('sn.angularstrap').directive('snAside', function(getTemplateUrl, $aside, $animate, $timeout) { 'use strict'; return { replace: true, restrict: 'E', template: '<div />', scope: { name: '@', role: '@' }, link: function(scope, element, attrs) { var broadcastPrefix = 'sn.aside' + (attrs.name ? '.' + attrs.name : ''); scope.options = { title: '', content: '', placement: 'right', backdrop: false, keyboard: false, element: element, scope: scope, show: false, template: getTemplateUrl('sn_aside.xml') }; scope.aside = $aside(scope.options); scope.$on(broadcastPrefix + '.open', _openAside); scope.$on(broadcastPrefix + '.deferred.open', function(e, view, widthOverride) { scope.aside.$promise.then(function() { _openAside(e, view, widthOverride); }); }); scope.role = scope.role || 'dialog'; function _openAside(e, view, widthOverride) { if (!scope.$isShown) { scope.aside.show(); scope.$isShown = true; scope.aside.$element.addClass('sn-aside_open'); scope.aside.$element.addClass('sn-aside-hide'); $timeout(function() { scope.aside.$element.removeClass('sn-aside-hide'); }, 0, false); } applyManualWidth(widthOverride); if (view) scope.$broadcast(broadcastPrefix + '.load', view); } scope.$on(broadcastPrefix + '.resize', function(e, width) { applyManualWidth(width); }); scope.$on(broadcastPrefix + '.close', function(e, killAnimation) { if (!scope.$isShown) return; scope.$isShown = false; var element = scope.aside.$element; if (killAnimation === true) { element.addClass('disableAnimations'); scope.$broadcast(broadcastPrefix + '.unload'); } else { $animate.addClass(element, 'sn-aside-hide', function() { scope.$broadcast(broadcastPrefix + '.unload'); }); } element.removeClass('disableAnimations'); }); scope.$on('aside.hide.before', function() { scope.aside.$element.removeClass('sn-aside_open'); }); scope.$on('aside.hide', function() { scope.$isShown = false; scope.aside.$element.addClass('sn-aside-hide'); }); function applyManualWidth(width) { if(angular.isString(width)) return scope.aside.$element.css('width', width).find('.aside-dialog').css('min-width', width); if(angular.isNumber) { var newWidth = Math.max(320, width); return scope.aside.$element.innerWidth(newWidth).find('.aside-dialog').css('min-width', newWidth); } } } }; }); ; /*! RESOURCE: /scripts/sn.angularstrap/directive.snAsideContent.js */ angular.module('sn.angularstrap').directive('snAsideContent', function (getTemplateUrl, $compile, $templateCache, $timeout, $window) { 'use strict'; return { replace: true, restrict: 'E', template: '<div class="aside-content" />', link: function (scope, element, attrs) { var broadcastPrefix = 'sn.aside' + (attrs.name ? '.' + attrs.name : ''); scope.history = []; var findPrefix = '#snAsideContent_', viewPrefix = findPrefix.slice(1), cachedViews = {}, cachedViewScopes = {}, cachedViewKeys = [], asideContainer = element.parent().parent(); var asideTransitionDuration = parseFloat(asideContainer.css('transition-duration'), 10) * 1000 || 500; function stringFunction (stringOrFunction) { if (angular.isFunction(stringOrFunction)) return stringOrFunction(); return stringOrFunction; } scope.loadView = function (view) { var container; if (!view) return; if (view.cacheKey && cachedViewKeys.indexOf(stringFunction(view.cacheKey)) >= 0) { if (!view.isChild) unloadView(true); var escapedKey = stringFunction(view.cacheKey).replace(/\./g, '\\.'); container = element.find(findPrefix + escapedKey); container.show().siblings().hide(); focusOnFirstChild(container); return; } var subScope = scope.$new(); var historyObj = {view: view, cacheKey: stringFunction(view.cacheKey), subScope: subScope}; if (view.scope) { if (view.scope.constructor === scope.constructor) { subScope.$destroy(); delete historyObj.subScope; subScope = view.scope.$new(); historyObj.subScope = subScope; } else { for (var prop in view.scope) { if (view.scope.hasOwnProperty(prop) && !subScope.hasOwnProperty(prop)) subScope[prop] = view.scope[prop]; } } } var template = view.templateUrl ? $templateCache.get(view.templateUrl) : stringFunction(view.template); var compiledTemplate = $compile(template)(subScope); if (!view.isChild) unloadView(true); scope.history.push(historyObj); if (view.cacheKey) cachedViewKeys.push(stringFunction(view.cacheKey)); var containerID = viewPrefix; containerID += view.cacheKey ? stringFunction(view.cacheKey) : scope.history.length; element.append('<div id="' + containerID + '" />'); containerID = containerID.replace(/\./g, '\\.'); container = element.find('#' + containerID); container.html(compiledTemplate).siblings().hide(); if(asideContainer.hasClass("sn-aside-hide")) { $timeout(function() { focusOnFirstChild(container); }, asideTransitionDuration, false); } else { focusOnFirstChild(container); } }; scope.$on(broadcastPrefix + '.historyBack', function () { scope.historyBack(); }); scope.historyBack = function (evt) { if (scope.history.length <= 1 || (evt && evt.keyCode === 9)) return; unloadView(); var previousView = scope.history[scope.history.length - 1]; var previousElement; if (previousView.cacheKey) previousElement = element.find(findPrefix + previousView.cacheKey); else previousElement = element.find(findPrefix + scope.history.length); if (previousElement.length > 0) { previousElement.show(); if (findPrefix.indexOf('snAsideContent') > -1) { var previousCloseButton = previousElement.find('.icon-cross'); if (previousCloseButton.length > 0) previousCloseButton.focus(); } } scope.$emit(broadcastPrefix + '.historyBack.completed', previousView.view); }; function unloadView (unloadAll) { if (!scope.history.length) return; var numViews = scope.history.length, historyView = scope.history.pop(), escapedKey = '', contentDiv; if (historyView.cacheKey) { escapedKey = historyView.cacheKey.replace(/\./g, "\\."); contentDiv = element.find(findPrefix + escapedKey); contentDiv.hide(); cachedViews[historyView.cacheKey] = historyView.view; if (historyView.subScope) cachedViewScopes[historyView.cacheKey] = historyView.subScope; } else { contentDiv = element.find(findPrefix + numViews); contentDiv.remove(); if (historyView.subScope) historyView.subScope.$destroy(); } if (unloadAll) unloadView(unloadAll); } function clearCache (key) { var keys = cachedViewKeys.slice(); for (var i = 0, len = keys.length; i < len; i++) { if (keys[i].indexOf(key) !== 0) continue; if (cachedViews[keys[i]]) delete cachedViews[keys[i]]; if (cachedViewScopes[keys[i]]) { cachedViewScopes[keys[i]].$destroy(); delete cachedViewScopes[keys[i]]; } var escapedKey = keys[i].replace(/\./g, '\\.'); element.find(findPrefix + escapedKey).remove(); cachedViewKeys.splice(cachedViewKeys.indexOf(keys[i]), 1); } } function focusOnFirstChild(container) { if(!$window.tabbable) return; $timeout(function() { var firstFocusable = $window.tabbable(container[0])[0]; if(firstFocusable) firstFocusable.focus(); }, 0, false); } scope.close = function (evt) { if (evt.keyCode === 9) return; scope.$emit(broadcastPrefix + '.close'); }; scope.$on(broadcastPrefix + '.unload', function () { unloadView(true); }); scope.$on(broadcastPrefix + '.load', function (e, view) { if (!view) return; if (scope.history.length) { var currentView = scope.history[scope.history.length - 1]; if (angular.equals(currentView.view, view) && currentView.key === stringFunction(view.cacheKey)) return; } scope.loadView(view); }); scope.$on(broadcastPrefix + '.clearCache', function (e, cacheKey) { clearCache(cacheKey); }) } } }); ; ; /*! RESOURCE: /scripts/sn/common/accessibility/js_includes_common_accessibility.js */ /*! RESOURCE: /scripts/sn/common/accessibility/_module.js */ angular.module('sn.common.accessibility', []); ; /*! RESOURCE: /scripts/sn/common/accessibility/service.screenReaderStatus.js */ angular.module('sn.common.accessibility').service('screenReaderStatus', function($document) { function getAnnouncer() { var el = $document[0].getElementById('ngStatus'); if (el) return el; el = $document[0].createElement('span') el.id = 'ngStatus'; el.setAttribute('role', 'status'); el.setAttribute('aria-live', 'polite'); el.classList.add('sr-only'); $document[0].body.appendChild(el); } function cleanOldMessages(el) { var nodes = el.childNodes; for (var i = 0; i < nodes.length; i++) { el.removeChild(nodes[i]); } } function announce(text) { var statusEl = getAnnouncer(); cleanOldMessages(statusEl); var textNode = $document[0].createTextNode(text); statusEl.appendChild(textNode); statusEl.style.display = 'none'; statusEl.style.display = 'inline'; } getAnnouncer(); return { announce: announce } }); ; ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/js_includes_attachments.js */ /*! RESOURCE: /scripts/angularjs-1.4/thirdparty/angular-file-upload/angular-file-upload-all.js */ (function() { function patchXHR(fnName, newFn) { window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]); } if (window.XMLHttpRequest && !window.XMLHttpRequest.__isFileAPIShim) { patchXHR('setRequestHeader', function(orig) { return function(header, value) { if (header === '__setXHR_') { var val = value(this); if (val instanceof Function) { val(this); } } else { orig.apply(this, arguments); } } }); } var angularFileUpload = angular.module('angularFileUpload', []); angularFileUpload.version = '3.1.2'; angularFileUpload.service('$upload', ['$http', '$q', '$timeout', function($http, $q, $timeout) { function sendHttp(config) { config.method = config.method || 'POST'; config.headers = config.headers || {}; config.transformRequest = config.transformRequest || function(data, headersGetter) { if (window.ArrayBuffer && data instanceof window.ArrayBuffer) { return data; } return $http.defaults.transformRequest[0](data, headersGetter); }; var deferred = $q.defer(); var promise = deferred.promise; config.headers['__setXHR_'] = function() { return function(xhr) { if (!xhr) return; config.__XHR = xhr; config.xhrFn && config.xhrFn(xhr); xhr.upload.addEventListener('progress', function(e) { e.config = config; deferred.notify ? deferred.notify(e) : promise.progress_fn && $timeout(function(){promise.progress_fn(e)}); }, false); xhr.upload.addEventListener('load', function(e) { if (e.lengthComputable) { e.config = config; deferred.notify ? deferred.notify(e) : promise.progress_fn && $timeout(function(){promise.progress_fn(e)}); } }, false); }; }; $http(config).then(function(r){deferred.resolve(r)}, function(e){deferred.reject(e)}, function(n){deferred.notify(n)}); promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.progress = function(fn) { promise.progress_fn = fn; promise.then(null, null, function(update) { fn(update); }); return promise; }; promise.abort = function() { if (config.__XHR) { $timeout(function() { config.__XHR.abort(); }); } return promise; }; promise.xhr = function(fn) { config.xhrFn = (function(origXhrFn) { return function() { origXhrFn && origXhrFn.apply(promise, arguments); fn.apply(promise, arguments); } })(config.xhrFn); return promise; }; return promise; } this.upload = function(config) { config.headers = config.headers || {}; config.headers['Content-Type'] = undefined; var origTransformRequest = config.transformRequest; config.transformRequest = config.transformRequest ? (Object.prototype.toString.call(config.transformRequest) === '[object Array]' ? config.transformRequest : [config.transformRequest]) : []; config.transformRequest.push(function(data, headerGetter) { var formData = new FormData(); var allFields = {}; for (var key in config.fields) allFields[key] = config.fields[key]; if (data) allFields['data'] = data; if (config.formDataAppender) { for (var key in allFields) { config.formDataAppender(formData, key, allFields[key]); } } else { for (var key in allFields) { var val = allFields[key]; if (val !== undefined) { if (Object.prototype.toString.call(val) === '[object String]') { formData.append(key, val); } else { if (config.sendObjectsAsJsonBlob && typeof val === 'object') { formData.append(key, new Blob([val], { type: 'application/json' })); } else { formData.append(key, JSON.stringify(val)); } } } } } if (config.file != null) { var fileFormName = config.fileFormDataName || 'file'; if (Object.prototype.toString.call(config.file) === '[object Array]') { var isFileFormNameString = Object.prototype.toString.call(fileFormName) === '[object String]'; for (var i = 0; i < config.file.length; i++) { formData.append(isFileFormNameString ? fileFormName : fileFormName[i], config.file[i], (config.fileName && config.fileName[i]) || config.file[i].name); } } else { formData.append(fileFormName, config.file, config.fileName || config.file.name); } } return formData; }); return sendHttp(config); }; this.http = function(config) { return sendHttp(config); }; }]); angularFileUpload.directive('ngFileSelect', [ '$parse', '$timeout', '$compile', function($parse, $timeout, $compile) { return { restrict: 'AEC', require:'?ngModel', link: function(scope, elem, attr, ngModel) { handleFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile); } }}]); function handleFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile) { function isInputTypeFile() { return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file'; } var watchers = []; function watchForRecompile(attrVal) { $timeout(function() { if (elem.parent().length) { watchers.push(scope.$watch(attrVal, function(val, oldVal) { if (val != oldVal) { recompileElem(); } })); } }); } function recompileElem() { var clone = elem.clone(); if (elem.attr('__afu_gen__')) { angular.element(document.getElementById(elem.attr('id').substring(1))).remove(); } if (elem.parent().length) { for (var i = 0; i < watchers.length; i++) { watchers[i](); } elem.replaceWith(clone); $compile(clone)(scope); } return clone; } function bindAttr(bindAttr, attrName) { if (bindAttr) { watchForRecompile(bindAttr); var val = $parse(bindAttr)(scope); if (val) { elem.attr(attrName, val); attr[attrName] = val; } else { elem.attr(attrName, null); delete attr[attrName]; } } } bindAttr(attr.ngMultiple, 'multiple'); bindAttr(attr.ngAccept, 'ng-accept'); bindAttr(attr.ngCapture, 'capture'); if (attr['ngFileSelect'] != '') { attr.ngFileChange = attr.ngFileSelect; } function onChangeFn(evt) { var files = [], fileList, i; fileList = evt.__files_ || (evt.target && evt.target.files); updateModel(fileList, attr, ngModel, scope, evt); }; var fileElem = elem; if (!isInputTypeFile()) { fileElem = angular.element('<input type="file">') if (elem.attr('multiple')) fileElem.attr('multiple', elem.attr('multiple')); if (elem.attr('accept')) fileElem.attr('accept', elem.attr('accept')); if (elem.attr('capture')) fileElem.attr('capture', elem.attr('capture')); for (var key in attr) { if (key.indexOf('inputFile') == 0) { var name = key.substring('inputFile'.length); name = name[0].toLowerCase() + name.substring(1); fileElem.attr(name, attr[key]); } } fileElem.css('width', '0px').css('height', '0px').css('position', 'absolute').css('padding', 0).css('margin', 0) .css('overflow', 'hidden').attr('tabindex', '-1').css('opacity', 0).attr('__afu_gen__', true); elem.attr('__refElem__', true); fileElem[0].__refElem__ = elem[0]; elem.parent()[0].insertBefore(fileElem[0], elem[0]) elem.css('overflow', 'hidden'); elem.bind('click', function(e) { if (!resetAndClick(e)) { fileElem[0].click(); } }); } else { elem.bind('click', resetAndClick); } function resetAndClick(evt) { if (fileElem[0].value != null && fileElem[0].value != '') { fileElem[0].value = null; if (navigator.userAgent.indexOf("Trident/7") === -1) { onChangeFn({target: {files: []}}); } } if (!elem.attr('__afu_clone__')) { if (navigator.appVersion.indexOf("MSIE 10") !== -1 || navigator.userAgent.indexOf("Trident/7") !== -1) { var clone = recompileElem(); clone.attr('__afu_clone__', true); clone[0].click(); evt.preventDefault(); evt.stopPropagation(); return true; } } else { elem.attr('__afu_clone__', null); } } fileElem.bind('change', onChangeFn); elem.on('$destroy', function() { for (var i = 0; i < watchers.length; i++) { watchers[i](); } if (elem[0] != fileElem[0]) fileElem.remove(); }); watchers.push(scope.$watch(attr.ngModel, function(val, oldVal) { if (val != oldVal && (val == null || !val.length)) { if (navigator.appVersion.indexOf("MSIE 10") !== -1) { recompileElem(); } else { fileElem[0].value = null; } } })); function updateModel(fileList, attr, ngModel, scope, evt) { var files = [], rejFiles = []; var accept = $parse(attr.ngAccept)(scope); var regexp = angular.isString(accept) && accept ? new RegExp(globStringToRegex(accept), 'gi') : null; var acceptFn = regexp ? null : attr.ngAccept; for (var i = 0; i < fileList.length; i++) { var file = fileList.item(i); if ((!regexp || file.type.match(regexp) || (file.name != null && file.name.match(regexp))) && (!acceptFn || $parse(acceptFn)(scope, {$file: file, $event: evt}))) { files.push(file); } else { rejFiles.push(file); } } $timeout(function() { if (ngModel) { $parse(attr.ngModel).assign(scope, files); ngModel && ngModel.$setViewValue(files != null && files.length == 0 ? '' : files); if (attr.ngModelRejected) { $parse(attr.ngModelRejected).assign(scope, rejFiles); } } if (attr.ngFileChange && attr.ngFileChange != "") { $parse(attr.ngFileChange)(scope, { $files: files, $rejectedFiles: rejFiles, $event: evt }); } }); } } angularFileUpload.directive('ngFileDrop', [ '$parse', '$timeout', '$location', function($parse, $timeout, $location) { return { restrict: 'AEC', require:'?ngModel', link: function(scope, elem, attr, ngModel) { handleDrop(scope, elem, attr, ngModel, $parse, $timeout, $location); } }}]); angularFileUpload.directive('ngNoFileDrop', function() { return function(scope, elem, attr) { if (dropAvailable()) elem.css('display', 'none') } }); angularFileUpload.directive('ngFileDropAvailable', [ '$parse', '$timeout', function($parse, $timeout) { return function(scope, elem, attr) { if (dropAvailable()) { var fn = $parse(attr['ngFileDropAvailable']); $timeout(function() { fn(scope); }); } } }]); function handleDrop(scope, elem, attr, ngModel, $parse, $timeout, $location) { var available = dropAvailable(); if (attr['dropAvailable']) { $timeout(function() { scope.dropAvailable ? scope.dropAvailable.value = available : scope.dropAvailable = available; }); } if (!available) { if ($parse(attr.hideOnDropNotAvailable)(scope) != false) { elem.css('display', 'none'); } return; } var leaveTimeout = null; var stopPropagation = $parse(attr.stopPropagation)(scope); var dragOverDelay = 1; var accept = $parse(attr.ngAccept)(scope) || attr.accept; var regexp = angular.isString(accept) && accept ? new RegExp(globStringToRegex(accept), 'gi') : null; var acceptFn = regexp ? null : attr.ngAccept; var actualDragOverClass; elem[0].addEventListener('dragover', function(evt) { evt.preventDefault(); if (stopPropagation) evt.stopPropagation(); if (navigator.userAgent.indexOf("Chrome") > -1) { var b = evt.dataTransfer.effectAllowed; evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy'; } $timeout.cancel(leaveTimeout); if (!scope.actualDragOverClass) { actualDragOverClass = calculateDragOverClass(scope, attr, evt); } elem.addClass(actualDragOverClass); }, false); elem[0].addEventListener('dragenter', function(evt) { evt.preventDefault(); if (stopPropagation) evt.stopPropagation(); }, false); elem[0].addEventListener('dragleave', function(evt) { leaveTimeout = $timeout(function() { elem.removeClass(actualDragOverClass); actualDragOverClass = null; }, dragOverDelay || 1); }, false); if (attr['ngFileDrop'] != '') { attr.ngFileChange = attr['ngFileDrop']; } elem[0].addEventListener('drop', function(evt) { evt.preventDefault(); if (stopPropagation) evt.stopPropagation(); elem.removeClass(actualDragOverClass); actualDragOverClass = null; extractFiles(evt, function(files, rejFiles) { $timeout(function() { if (ngModel) { $parse(attr.ngModel).assign(scope, files); ngModel && ngModel.$setViewValue(files != null && files.length == 0 ? '' : files); } if (attr['ngModelRejected']) { if (scope[attr.ngModelRejected]) { $parse(attr.ngModelRejected).assign(scope, rejFiles); } } }); $timeout(function() { $parse(attr.ngFileChange)(scope, { $files: files, $rejectedFiles: rejFiles, $event: evt }); }); }, $parse(attr.allowDir)(scope) != false, attr.multiple || $parse(attr.ngMultiple)(scope)); }, false); function calculateDragOverClass(scope, attr, evt) { var valid = true; if (regexp || acceptFn) { var items = evt.dataTransfer.items; if (items != null) { for (var i = 0 ; i < items.length && valid; i++) { valid = valid && (items[i].kind == 'file' || items[i].kind == '') && ((acceptFn && $parse(acceptFn)(scope, {$file: items[i], $event: evt})) || (regexp && (items[i].type != null && items[i].type.match(regexp)) || (items[i].name != null && items[i].name.match(regexp)))); } } } var clazz = $parse(attr.dragOverClass)(scope, {$event : evt}); if (clazz) { if (clazz.delay) dragOverDelay = clazz.delay; if (clazz.accept) clazz = valid ? clazz.accept : clazz.reject; } return clazz || attr['dragOverClass'] || 'dragover'; } function extractFiles(evt, callback, allowDir, multiple) { var files = [], rejFiles = [], items = evt.dataTransfer.items, processing = 0; function addFile(file) { if ((!regexp || file.type.match(regexp) || (file.name != null && file.name.match(regexp))) && (!acceptFn || $parse(acceptFn)(scope, {$file: file, $event: evt}))) { files.push(file); } else { rejFiles.push(file); } } if (items && items.length > 0 && $location.protocol() != 'file') { for (var i = 0; i < items.length; i++) { if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) { var entry = items[i].webkitGetAsEntry(); if (entry.isDirectory && !allowDir) { continue; } if (entry != null) { traverseFileTree(files, entry); } } else { var f = items[i].getAsFile(); if (f != null) addFile(f); } if (!multiple && files.length > 0) break; } } else { var fileList = evt.dataTransfer.files; if (fileList != null) { for (var i = 0; i < fileList.length; i++) { addFile(fileList.item(i)); if (!multiple && files.length > 0) break; } } } var delays = 0; (function waitForProcess(delay) { $timeout(function() { if (!processing) { if (!multiple && files.length > 1) { var i = 0; while (files[i].type == 'directory') i++; files = [files[i]]; } callback(files, rejFiles); } else { if (delays++ * 10 < 20 * 1000) { waitForProcess(10); } } }, delay || 0) })(); function traverseFileTree(files, entry, path) { if (entry != null) { if (entry.isDirectory) { var filePath = (path || '') + entry.name; addFile({name: entry.name, type: 'directory', path: filePath}); var dirReader = entry.createReader(); var entries = []; processing++; var readEntries = function() { dirReader.readEntries(function(results) { try { if (!results.length) { for (var i = 0; i < entries.length; i++) { traverseFileTree(files, entries[i], (path ? path : '') + entry.name + '/'); } processing--; } else { entries = entries.concat(Array.prototype.slice.call(results || [], 0)); readEntries(); } } catch (e) { processing--; console.error(e); } }, function() { processing--; }); }; readEntries(); } else { processing++; entry.file(function(file) { try { processing--; file.path = (path ? path : '') + file.name; addFile(file); } catch (e) { processing--; console.error(e); } }, function(e) { processing--; }); } } } } } function dropAvailable() { var div = document.createElement('div'); return ('draggable' in div) && ('ondrop' in div); } function globStringToRegex(str) { if (str.length > 2 && str[0] === '/' && str[str.length -1] === '/') { return str.substring(1, str.length - 1); } var split = str.split(','), result = ''; if (split.length > 1) { for (var i = 0; i < split.length; i++) { result += '(' + globStringToRegex(split[i]) + ')'; if (i < split.length - 1) { result += '|' } } } else { if (str.indexOf('.') == 0) { str= '*' + str; } result = '^' + str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + '-]', 'g'), '\\$&') + '$'; result = result.replace(/\\\*/g, '.*').replace(/\\\?/g, '.'); } return result; } var ngFileUpload = angular.module('ngFileUpload', []); for (var key in angularFileUpload) { ngFileUpload[key] = angularFileUpload[key]; } })(); (function() { var hasFlash = function() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch(e) { if (navigator.mimeTypes['application/x-shockwave-flash'] != undefined) return true; } return false; } function patchXHR(fnName, newFn) { window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]); }; if ((window.XMLHttpRequest && !window.FormData) || (window.FileAPI && FileAPI.forceLoad)) { var initializeUploadListener = function(xhr) { if (!xhr.__listeners) { if (!xhr.upload) xhr.upload = {}; xhr.__listeners = []; var origAddEventListener = xhr.upload.addEventListener; xhr.upload.addEventListener = function(t, fn, b) { xhr.__listeners[t] = fn; origAddEventListener && origAddEventListener.apply(this, arguments); }; } } patchXHR('open', function(orig) { return function(m, url, b) { initializeUploadListener(this); this.__url = url; try { orig.apply(this, [m, url, b]); } catch (e) { if (e.message.indexOf('Access is denied') > -1) { this.__origError = e; orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]); } } } }); patchXHR('getResponseHeader', function(orig) { return function(h) { return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h])); }; }); patchXHR('getAllResponseHeaders', function(orig) { return function() { return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this)); } }); patchXHR('abort', function(orig) { return function() { return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this)); } }); patchXHR('setRequestHeader', function(orig) { return function(header, value) { if (header === '__setXHR_') { initializeUploadListener(this); var val = value(this); if (val instanceof Function) { val(this); } } else { this.__requestHeaders = this.__requestHeaders || {}; this.__requestHeaders[header] = value; orig.apply(this, arguments); } } }); function redefineProp(xhr, prop, fn) { try { Object.defineProperty(xhr, prop, {get: fn}); } catch (e) {} } patchXHR('send', function(orig) { return function() { var xhr = this; if (arguments[0] && arguments[0].__isFileAPIShim) { var formData = arguments[0]; var config = { url: xhr.__url, jsonp: false, cache: true, complete: function(err, fileApiXHR) { xhr.__completed = true; if (!err && xhr.__listeners['load']) xhr.__listeners['load']({type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true}); if (!err && xhr.__listeners['loadend']) xhr.__listeners['loadend']({type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true}); if (err === 'abort' && xhr.__listeners['abort']) xhr.__listeners['abort']({type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true}); if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function() {return (fileApiXHR.status == 0 && err && err !== 'abort') ? 500 : fileApiXHR.status}); if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function() {return fileApiXHR.statusText}); redefineProp(xhr, 'readyState', function() {return 4}); if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function() {return fileApiXHR.response}); var resp = fileApiXHR.responseText || (err && fileApiXHR.status == 0 && err !== 'abort' ? err : undefined); redefineProp(xhr, 'responseText', function() {return resp}); redefineProp(xhr, 'response', function() {return resp}); if (err) redefineProp(xhr, 'err', function() {return err}); xhr.__fileApiXHR = fileApiXHR; if (xhr.onreadystatechange) xhr.onreadystatechange(); if (xhr.onload) xhr.onload(); }, fileprogress: function(e) { e.target = xhr; xhr.__listeners['progress'] && xhr.__listeners['progress'](e); xhr.__total = e.total; xhr.__loaded = e.loaded; if (e.total === e.loaded) { var _this = this setTimeout(function() { if (!xhr.__completed) { xhr.getAllResponseHeaders = function(){}; _this.complete(null, {status: 204, statusText: 'No Content'}); } }, FileAPI.noContentTimeout || 10000); } }, headers: xhr.__requestHeaders } config.data = {}; config.files = {} for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function() { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { if (this.__origError) { throw this.__origError; } orig.apply(xhr, arguments); } } }); window.XMLHttpRequest.__isFileAPIShim = true; var addFlash = function(elem) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } var el = angular.element(elem); if (!el.attr('disabled')) { var hasFileSelect = false; for (var i = 0; i < el[0].attributes.length; i++) { var attrib = el[0].attributes[i]; if (attrib.name.indexOf('file-select') !== -1) { hasFileSelect = true; break; } } if (!el.hasClass('js-fileapi-wrapper') && (hasFileSelect || el.attr('__afu_gen__') != null)) { el.addClass('js-fileapi-wrapper'); if (el.attr('__afu_gen__') != null) { var ref = (el[0].__refElem__ && angular.element(el[0].__refElem__)) || el; while (ref && !ref.attr('__refElem__')) { ref = angular.element(ref[0].nextSibling); } ref.bind('mouseover', function() { if (el.parent().css('position') === '' || el.parent().css('position') === 'static') { el.parent().css('position', 'relative'); } el.css('position', 'absolute').css('top', ref[0].offsetTop + 'px').css('left', ref[0].offsetLeft + 'px') .css('width', ref[0].offsetWidth + 'px').css('height', ref[0].offsetHeight + 'px') .css('padding', ref.css('padding')).css('margin', ref.css('margin')).css('filter', 'alpha(opacity=0)'); ref.attr('onclick', ''); el.css('z-index', '1000'); }); } } } }; var changeFnWrapper = function(fn) { return function(evt) { var files = FileAPI.getFiles(evt); for (var i = 0; i < files.length; i++) { if (files[i].size === undefined) files[i].size = 0; if (files[i].name === undefined) files[i].name = 'file'; if (files[i].type === undefined) files[i].type = 'undefined'; } if (!evt.target) { evt.target = {}; } evt.target.files = files; if (evt.target.files != files) { evt.__files_ = files; } (evt.__files_ || evt.target.files).item = function(i) { return (evt.__files_ || evt.target.files)[i] || null; } if (fn) fn.apply(this, [evt]); }; }; var isFileChange = function(elem, e) { return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file'; } if (HTMLInputElement.prototype.addEventListener) { HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) { return function(e, fn, b, d) { if (isFileChange(this, e)) { addFlash(this); origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]); } else { origAddEventListener.apply(this, [e, fn, b, d]); } } })(HTMLInputElement.prototype.addEventListener); } if (HTMLInputElement.prototype.attachEvent) { HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) { return function(e, fn) { if (isFileChange(this, e)) { addFlash(this); if (window.jQuery) { angular.element(this).bind('change', changeFnWrapper(null)); } else { origAttachEvent.apply(this, [e, changeFnWrapper(fn)]); } } else { origAttachEvent.apply(this, [e, fn]); } } })(HTMLInputElement.prototype.attachEvent); } window.FormData = FormData = function() { return { append: function(key, val, name) { if (val.__isFileAPIBlobShim) { val = val.data[0]; } this.data.push({ key: key, val: val, name: name }); }, data: [], __isFileAPIShim: true }; }; window.Blob = Blob = function(b) { return { data: b, __isFileAPIBlobShim: true }; }; (function () { if (!window.FileAPI) { window.FileAPI = {}; } if (FileAPI.forceLoad) { FileAPI.html5 = false; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.search(/\/angular\-file\-upload[\-a-zA-z0-9\.]*\.js/) if (index > -1) { basePath = src.substring(0, index + 1); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js'); document.getElementsByTagName('head')[0].appendChild(script); FileAPI.hasFlash = hasFlash(); } })(); FileAPI.disableFileInput = function(elem, disable) { if (disable) { elem.removeClass('js-fileapi-wrapper') } else { elem.addClass('js-fileapi-wrapper'); } } } if (!window.FileReader) { window.FileReader = function() { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function(type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function(type, fn) { _this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function(evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; var constructEvent = function(type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function(evt) { if (!loadStarted) { loadStarted = true; _this.onloadstart && _this.onloadstart(constructEvent('loadstart', evt)); } if (evt.type === 'load') { _this.onloadend && _this.onloadend(constructEvent('loadend', evt)); var e = constructEvent('load', evt); _this.onload && _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { var e = constructEvent('progress', evt); _this.onprogress && _this.onprogress(e); _this.dispatchEvent(e); } else { var e = constructEvent('error', evt); _this.onerror && _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsArrayBuffer = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsBinaryString = function(file) { FileAPI.readAsBinaryString(file, listener); } this.readAsDataURL = function(file) { FileAPI.readAsDataURL(file, listener); } this.readAsText = function(file) { FileAPI.readAsText(file, listener); } } } })(); ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/_module.js */ angular.module('sn.common.attachments', [ 'angularFileUpload', 'sn.common.util' ]); ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/factory.nowAttachmentHandler.js */ angular.module("sn.common.attachments").factory("nowAttachmentHandler", function($http, nowServer, $upload, $q, $rootScope, $timeout, snNotification, snAttachmentHandler, i18n) { "use strict"; $rootScope.$on('attachment.updated', function(evt,options) { if (options.operation === 'update' && options.state === 'not_available') snAttachmentHandler.showMessage('error',i18n.getMessage('Upload file scan failed').withValues([options.filename])); }); return function(setAttachments, appendError) { var self = this; self.cardUploading = ''; self.setAttachments = setAttachments; self.appendError = appendError; self.encryptionContext = ''; self.ADDED = 'added'; self.DELETED = 'deleted'; self.RENAMED = 'renamed'; self.getAttachmentList = function(action) { var url = nowServer.getURL('ngk_attachments', { action: 'list', sys_id: self.tableId, table: self.tableName }); var worker = $http.get; if (!self.tableId) { worker = function() { return $q(function(resolve) { resolve({data:{files:[]}}); }); }; } worker(url).then(function(response) { var attachments = response.data.files || []; attachments = self.canViewImage(attachments); self.setAttachments(attachments, action); if (self.startedUploadingTimeout || self.errorTimeout) { self.stopAllUploading(); $rootScope.$broadcast('board.uploading.end'); } }); }; self.canViewImage = function(attachments) { if (typeof g_attachment_force_download_all_mime_types != "undefined" && typeof g_attachment_force_download_mime_type != "undefined") { var contentTypes = g_attachment_force_download_mime_type.split(','); for (var i = 0; i < attachments.length; i++) { var attachmentFile = attachments[i]; var canDownloadAttachmentFromThumbSrc = g_attachment_force_download_all_mime_types; if (!canDownloadAttachmentFromThumbSrc) { if (contentTypes.indexOf(attachmentFile.content_type) != -1) canDownloadAttachmentFromThumbSrc = true; } attachmentFile.viewImage = (attachmentFile.thumbSrc || attachmentFile.thumbnail_path) && !canDownloadAttachmentFromThumbSrc; } } return attachments; }; self.stopAllUploading = function() { $timeout.cancel(self.errorTimeout); $timeout.cancel(self.startedUploadingTimeout); hideProgressBar(); $rootScope.$broadcast("attachment.upload.stop"); }; self.setEncryptionContext = function(context) { self.encryptionContext = context; } self.manageFocus = function() { if (self.attachmentAction === self.RENAMED && self.updatedAttachmentSysId) { $timeout(function() { var editButton = $('#'+ self.updatedAttachmentSysId + ' button')[0]; if (editButton) editButton.focus(); delete self.attachmentAction; delete self.updatedAttachmentSysId; delete self.editButton; }); } } self.onFileSelect = function($files) { if(!$files.length) return; var url = nowServer.getURL('ngk_attachments', { sys_id: self.tableId, table: self.tableName, action: 'add' }); self.cardUploading = self.tableId; self.maxfiles = $files.length; self.fileCount = 1; self.filesUploaded = self.maxfiles; self.startedUploadingTimeout = $timeout(showUploaderDialog, 1500); for (var i = 0; i < self.maxfiles; i++) { if (parseInt($files[i].size) > parseInt(self.fileUploadSizeLimit)) { self.stopAllUploading(); $rootScope.$broadcast('dialog.upload_too_large.show'); return; } } var fields = { attachments_modified: 'true', sysparm_table: self.tableName, sysparm_sys_id: self.tableId, sysparm_nostack: 'yes', sysparm_encryption_context: self.encryptionContext, sysparm_ck: window.g_ck }; var idx = 0; var fileNames = []; var processFile = function() { $rootScope.$broadcast("attachment.upload.start"); var ff = $files[idx]; self.upload = $upload.upload({ url: url, fields: fields, fileFormDataName: 'attachFile', file: ff }).progress(function(evt) { var percent = parseInt(100.0 * evt.loaded / evt.total, 10); updateProgress(percent); }).success(function(data, status, headers, config) { processError(data); if (!data.error) fileNames.push(data.file_name); if (self.filesUploaded <= 0) self.cardUploading = ''; idx++; if (idx < $files.length) processFile(); else { self.stopAllUploading(); self.getAttachmentList(self.ADDED); if (fileNames.length) $rootScope.$broadcast("attachment.upload.success", {names: fileNames.join(",")}); } }); } processFile(); }; self.downloadAttachment = function(attachment) { var url = '/sys_attachment.do?sys_id=' + attachment.sys_id; window.open(url, '_blank'); }; self.viewAttachment = function($event, attachment) { var url = window.location.protocol + '//' + window.location.host; url += '/sys_attachment.do?sysparm_referring_url=tear_off&view=true&sys_id=' + attachment.sys_id; window.open(url, attachment.sys_id, "toolbar=no,menubar=no,personalbar=no,width=800,height=600,scrollbars=yes,resizable=yes"); }; self.editAttachment = function($event, attachment) { self.editButton = $event.currentTarget; var parent = $(self.editButton).closest('.file-attachment'); var thumbnail = parent.find('.thumbnail'); var input = parent.find('input'); var tools = parent.find('.tools'); var fileName = attachment.file_name; if (attachment.file_name.indexOf('.') !== -1) { attachment.ext = fileName.match(/(\.[^\.]+)$/i)[0]; fileName = attachment.file_name.replace(/(\.[^\.]+)$/i, ''); } input.val(fileName); var w = input.prev().width(); input.width(w); input.prev().hide(); input.css('display', 'block'); thumbnail.addClass('state-locked'); tools.find('.delete-edit').hide(); tools.find('.rename-cancel').css('display', 'inline-block'); input.focus(); } self.onKeyDown = function($event, attachment) { var keyCode = $event.keyCode; if (keyCode === 13) { $event.stopPropagation(); $event.preventDefault(); self.updateAttachment($event, attachment); }else if (keyCode === 27) { $event.stopPropagation(); $event.preventDefault(); self.updateAttachment($event); } }; self.updateAttachment = function($event, attachment) { if (self.renameInProgress) return; var el = $($event.currentTarget); var parent = el.closest('.file-attachment'); var thumbnail = parent.find('.thumbnail'); var input = parent.find('input'); var link = parent.find('a'); var tools = parent.find('.tools'); if (attachment) { var fileName = input.val(); if (fileName.length) { fileName += attachment.ext; if (fileName !== attachment.file_name) { link.text(fileName); self.renameAttachment(attachment, fileName); } else setFocus(); } } input.hide(); input.prev().show(); tools.find('.rename-cancel').hide(); thumbnail.removeClass('state-locked'); tools.find('.delete-edit').css('display', 'inline-block'); self.editButton && self.editButton.focus(); }; self.dismissMsg = function($event, $index, errorMessages) { var msg = $($event.currentTarget); msg.addClass('remove'); setTimeout(function() { msg.remove(); errorMessages.splice($index, 1); }, 500); }; $rootScope.$on("dialog.comment_form.close", function() { hideProgressBar(); }); self.openSelector = function($event) { $event.stopPropagation(); $event.preventDefault(); var target = $($event.currentTarget); var input = target.parent().find('input[type=file]'); $timeout(function() { input.click(); }); } self.deleteAttachment = function (attachment) { if (attachment && attachment.sys_id) { $('#' + attachment.sys_id).hide(); var url = nowServer.getURL('ngk_attachments', { action: 'delete', sys_id: attachment.sys_id }); $http.get(url).then(function (response) { processError(response.data); self.getAttachmentList(self.DELETED); if (!response.data.error) $rootScope.$broadcast("attachment.delete.success"); }); } }; function setFocus() { if (self.editButton) { $(self.editButton).focus(); delete self.editButton; } } self.renameAttachment = function (attachment, newName) { self.renameInProgress = true; $http({ url: nowServer.getURL('ngk_attachments'), method: 'POST', params: { action: 'rename', sys_id: attachment.sys_id, new_name: newName } }).then(function (response) { processError(response.data); self.attachmentAction = self.RENAMED; self.updatedAttachmentSysId = attachment.sys_id; self.getAttachmentList(self.RENAMED); self.renameInProgress = false; if (!response.data.error) $rootScope.$broadcast("attachment.rename.success"); }); }; self.scanAttachment = function (attachment) { snAttachmentHandler.scanAttachment(attachment); }; function showUploaderDialog() { $rootScope.$broadcast('board.uploading.start', self.tableId); } function updateProgress(percent) { if (self.prevPercent === percent && self.fileCount <= self.maxfiles) return; if (self.fileCount <= self.maxfiles) { if (percent > 99) self.fileCount++; if (self.fileCount <= self.maxfiles) { $timeout.cancel(self.errorTimeout); self.errorTimeout = $timeout(broadcastError, 15000); $('.progress-label').text('Uploading file ' + self.fileCount + ' of ' + self.maxfiles); $('.upload-progress').val(percent); $('.progress-wrapper').show(); } } self.prevPercent = percent; } function hideProgressBar() { try { $('.progress-wrapper').hide(); } catch(e) {} } self.setParams = function(tableName, tableId, fileUploadSizeLimit) { self.tableName = tableName; self.tableId = tableId; self.fileUploadSizeLimit = fileUploadSizeLimit; }; function broadcastError() { $rootScope.$broadcast('board.uploading.end'); snNotification.show('error', 'An error occured when trying to upload your file. Please try again.'); self.stopAllUploading(); } function processError(data) { if (!data.error) return; self.appendError({ msg: data.error, fileName: '' }); } }; }); ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/directive.nowAttachmentsList.js */ angular.module('sn.common.attachments').directive('nowAttachmentsList', function(getTemplateUrl) { 'use strict'; function updateTrackByKey(scope) { if (scope.attachments && scope.attachments.length > 0) { scope.hasTrackByKey = scope.hasTrackByKey || scope.attachments[0].hasOwnProperty('trackByKey'); if (!scope.hasTrackByKey) { scope.attachments.forEach(function(attachment) { attachment.trackByKey = attachment.sys_id + attachment.state + attachment.file_name.replace(/\s/g, '') + attachment.viewImage; }); } } } return { restrict: 'E', replace: true, templateUrl: getTemplateUrl("attachments_list.xml"), link: function(scope, elem, attrs, $parse) { scope.icons = { preview: attrs.previewIcon, edit: attrs.editIcon, delete: attrs.deleteIcon, ok: attrs.okIcon, cancel: attrs.cancelIcon }; scope.hasTrackByKey = false; updateTrackByKey(scope); scope.$watch('attachments', function() { updateTrackByKey(scope); }); scope.listClass = "list-group"; var inline = scope.$eval(attrs.inline); if (inline) scope.listClass = "list-inline"; scope.entryTemplate = getTemplateUrl(attrs.template || "attachment"); } }; }); ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/factory.snAttachmentHandler.js */ angular.module('sn.common.attachments').factory('snAttachmentHandler', function(urlTools, $http, $upload, $window, $q, $rootScope, i18n) { "use strict"; return { getViewUrl: getViewUrl, create: createAttachmentHandler, deleteAttachment: deleteAttachmentBySysID, renameAttachment: renameAttachmentBySysID, showMessage : showMessage, scanAttachment : scanAttachment }; function getViewUrl(sysId) { return '/sys_attachment.do?sys_id=' + sysId; } function showMessage(type, message) { $rootScope.$broadcast("$$uiNotification", {type: type, message: message}); } function deleteAttachmentBySysID(sysID) { var url = urlTools.getURL('ngk_attachments', { action: 'delete', sys_id: sysID }); return $http.get(url); } function renameAttachmentBySysID(sysID, newName) { var url = urlTools.getURL('ngk_attachments', { action: 'rename', sys_id: sysID, new_name: newName }); return $http.post(url); } var isAjaxInProgress = false; function updateState(options) { this.state = options.state; $rootScope.$broadcast("sn.attachment.scanned"); if (options.msg) showMessage(options.type, options.msg); } function scanAttachment(attachment) { if (isAjaxInProgress) return; isAjaxInProgress = true; var updateAttachmentState = updateState.bind(attachment); var url = '/sys_attachment.do?sys_id=' + attachment.sys_id; $http({ url: '/xmlhttp.do', method: 'POST', params: { sysparm_processor: 'AntiVirusAttachmentDescriptor', sysparm_name: 'getAttachmentState', sysparm_sysid: attachment.sys_id }, dataType: 'xml' }).then(function (response) { var element = (new DOMParser().parseFromString(response.data, 'text/xml')).getElementsByTagName('xml')[0]; var answer = element.getAttribute('answer'); var options = {}; options.state = answer; if (answer === 'available') { window.open(url, '_blank'); } else if (answer === 'not_available') { options.type = 'error'; options.msg = i18n.getMessage('File not available'); } else if (answer === 'pending') { options.type = 'error'; options.msg = i18n.getMessage('File pending'); } updateAttachmentState(options); isAjaxInProgress = false; }); } function createAttachmentHandler(tableName, sysID, options) { var _tableName = tableName; var _sysID = sysID; var _files = []; function getTableName() { return _tableName; } function getSysID() { return _sysID; } function getAttachments() { var url = urlTools.getURL('ngk_attachments', { action: 'list', sys_id: _sysID, table: _tableName }); var worker = $http.get; if (!_sysID) { worker = function() { return $q(function(resolve) { resolve({data:{files:[]}}); }); }; } return worker(url).then(function(response) { var files = response.data.files; if (_files.length == 0) { files.forEach(function(file) { if (file && file.sys_id) { _transformFileResponse(file); _files.push(file); } }) } else { _files = files; } return _files; }); } function addAttachment(attachment) { _files.unshift(attachment); } function deleteAttachment(attachment) { var index = _files.indexOf(attachment); if (index !== -1) { return deleteAttachmentBySysID(attachment.sys_id).then(function() { _files.splice(index, 1); }); } } function uploadAttachments(files, uploadFields) { var defer = $q.defer(); var promises = []; var fileData = []; angular.forEach(files, function(file) { promises.push(uploadAttachment(file, uploadFields).then(function(response) { fileData.push(response); })); }); $q.all(promises).then(function() { defer.resolve(fileData); }); return defer.promise; } function uploadAttachment(file, uploadFields, uploadMethods) { var url = urlTools.getURL('ngk_attachments', { action: 'add', sys_id: _sysID, table: _tableName, load_attachment_record: 'true' }); var fields = { attachments_modified: 'true', sysparm_table: _tableName, sysparm_sys_id: _sysID, sysparm_nostack: 'yes', sysparm_encryption_context: '' }; if (typeof $window.g_ck !== 'undefined') { fields['sysparm_ck'] = $window.g_ck; } if (uploadFields) { angular.extend(fields, uploadFields); } var upload = $upload.upload({ url: url, fields: fields, fileFormDataName: 'attachFile', file: file, fileName : file.file_name || file.name }); if (uploadMethods !== undefined) { if (uploadMethods.hasOwnProperty('progress')) { upload.progress(uploadMethods.progress); } if (uploadMethods.hasOwnProperty('success')) { upload.success(uploadMethods.success); } if (uploadMethods.hasOwnProperty('error')) { upload.error(uploadMethods.error); } } return upload.then(function(response) { var sysFile = response.data; if (sysFile.error) { return $q.reject("Exception when adding attachment: " + sysFile.error); } if (typeof sysFile === "object" && sysFile.hasOwnProperty('sys_id')) { _transformFileResponse(sysFile); addAttachment(sysFile); } if (options && options.onUploadComplete) { options.onUploadComplete(sysFile); } return sysFile; }); } function _transformFileResponse(file) { file.isImage = false; file.canPreview = false; if (file.content_type.indexOf('image') !== -1) { file.isImage = true; if (!file.thumbSrc) { } else if (file.thumbSrc[0] !== '/') { file.thumbSrc = '/' + file.thumbSrc; } file.canPreview = file.content_type.indexOf('tiff') === -1; } file.viewUrl = getViewUrl(file.sys_id); } return { getSysID: getSysID, getTableName: getTableName, getAttachments: getAttachments, addAttachment: addAttachment, deleteAttachment: deleteAttachment, uploadAttachment: uploadAttachment, uploadAttachments: uploadAttachments }; } }); ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/directive.snFileUploadInput.js */ angular.module('sn.common.attachments').directive('snFileUploadInput', function(cabrillo, $document) { 'use strict'; return { restrict: 'E', scope: { attachmentHandler: '=', customClassNames: '@classNames' }, template: function() { var inputTemplate; if (cabrillo.isNative()) { inputTemplate = '<button class="{{classNames}}" ng-click="showAttachOptions($event)" aria-labelledby="attach-label-{{ ::$id }}"><span class="upload-label" id="attach-label-{{ ::$id }}"><translate key="Add Attachment" /></span></button>'; } else { inputTemplate = '<button class="{{classNames}}" ng-file-select="onFileSelect($files)" aria-labelledby="attach-label-{{ ::$id }}"><span class="upload-label" id="attach-label-{{ ::$id }}"><translate key="Add Attachment" /></span></button>'; } return [ '<div class="file-upload-input" role="button" aria-labelledby="attach-label-{{ ::$id }}">', '<div role="group" class="injected-contents-break-accessibility" aria-hidden="true">', inputTemplate, '</div>', '</div>' ].join(''); }, controller: function($element, $scope) { var classNames = 'btn btn-icon attachment-btn icon-paperclip'; if ($scope.customClassNames) { classNames += ' ' + $scope.customClassNames; } $scope.classNames = classNames; $scope.showAttachOptions = function($event) { var handler = $scope.attachmentHandler; var target = angular.element($event.currentTarget); var elRect = target[0].getBoundingClientRect(); var body = $document[0].body; var rect = { x: elRect.left + body.scrollLeft, y: elRect.top + body.scrollTop, width: elRect.width, height: elRect.height }; var options = {sourceRect: rect}; cabrillo.attachments.addFile( handler.getTableName(), handler.getSysID(), null, options ).then(function(data) { console.log('Attached new file', data); handler.addAttachment(data); }, function() { console.log('Failed to attach new file'); }); }; $scope.onFileSelect = function($files) { $scope.attachmentHandler.uploadAttachments($files); }; $scope.showFileSelector = function($event) { $event.stopPropagation(); var target = angular.element($event.currentTarget); var input = target.parent().find('input'); input.triggerHandler('click'); }; } } }); ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/directive.snPasteFileHandler.js */ angular.module('sn.common.attachments').directive('snPasteFileHandler', function($parse) { 'use strict'; return { restrict: 'A', link: function(scope, element, attrs) { var snPasteFileHandler = $parse(attrs.snPasteFileHandler); element.bind("paste", function(event) { event = event.originalEvent || event; var item = event.clipboardData.items[0]; if (!item) return; var file = item.getAsFile(); if (!file) return; snPasteFileHandler(scope, {file: file}); event.preventDefault(); event.stopPropagation(); }); } }; }); ; /*! RESOURCE: /scripts/angularjs-1.4/sn/common/attachments/directive.snAttachmentList.js */ angular.module('sn.common.attachments').directive('snAttachmentList', function(getTemplateUrl, snAttachmentHandler, $rootScope, $window, $timeout, $q) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl("sn_attachment_list.xml"), scope: { tableName: "=?", sysID: "=?sysId", attachmentList: "=?", uploadFileFn: "&", deleteFileFn: "=?", canEdit: "=?", canRemove: "=?", canAdd: "=?", canDownload: "=?", showHeader: "=?", clickImageFn: "&?", confirmDelete: "=?" }, controller: function($scope) { $scope.canEdit = $scope.canEdit || false; $scope.canDownload = $scope.canDownload || false; $scope.canRemove = $scope.canRemove || false; $scope.canAdd = $scope.canAdd || false; $scope.showHeader = $scope.showHeader || false; $scope.clickImageFn = $scope.clickImageFn || function() {}; $scope.confirmDelete = $scope.confirmDelete || false; $scope.filesInProgress = {}; $scope.attachmentToDelete = null; function refreshResources() { var handler = snAttachmentHandler.create($scope.tableName, $scope.sysID); handler.getAttachments().then(function(files) { $scope.attachmentList = files; }); } if (!$scope.attachmentList) { $scope.attachmentList = []; refreshResources(); } $scope.$on('attachments_list.update', function(e, tableName, sysID) { if (tableName === $scope.tableName && sysID === $scope.sysID) { refreshResources(); } }); function removeFromFileProgress (fileName) { delete $scope.filesInProgress[fileName]; } function updateFileProgress (file) { if (!$scope.filesInProgress[file.name]) $scope.filesInProgress[file.name] = file; } $scope.$on('attachments_list.upload.progress', function (e, file) { updateFileProgress(file); }); $scope.$on('attachments_list.upload.success', function (e, file) { removeFromFileProgress(file.name); }); $scope.attachFiles = function(files) { if ($scope.tableName && $scope.sysID) { var handler = snAttachmentHandler.create($scope.tableName, $scope.sysID); var promises = []; files.forEach(function (file) { var promise = handler.uploadAttachment(file, null , { progress: function (e) { var file = e.config.file; file.progress = 100.0 * event.loaded / event.total; updateFileProgress(file); }, success: function (data) { removeFromFileProgress(data.file_name); } }); promises.push(promise); }); $q.all(promises).then(function() { refreshResources(); }); } else { if ($scope.uploadFileFn) $scope.uploadFileFn({files: files}); } }; $scope.getProgressStyle = function (fileName) { return { 'width': $scope.filesInProgress[fileName].progress + '%' }; }; $scope.openSelector = function($event) { $event.stopPropagation(); var target = angular.element($event.currentTarget); $timeout(function() { target.parent().find('input').click(); }); }; $scope.confirmDeleteAttachment = function (attachment) { $scope.attachmentToDelete = attachment; $scope.$broadcast('dialog.confirm-delete.show'); }; $scope.deleteAttachment = function () { snAttachmentHandler.deleteAttachment($scope.attachmentToDelete.sys_id).then(function () { var index = $scope.attachmentList.indexOf($scope.attachmentToDelete); $scope.attachmentList.splice(index, 1); }); }; } }; }) .directive('snAttachmentListItem', function(getTemplateUrl, snAttachmentHandler, $rootScope, $window, $timeout, $parse) { 'use strict'; return { restrict: "E", replace: true, templateUrl: getTemplateUrl("sn_attachment_list_item.xml"), link: function (scope, element, attrs) { function translateAttachment(att) { return { content_type: att.content_type, file_name: att.file_name, image: (att.thumbSrc !== undefined), size_bytes: att.size, sys_created_by: "", sys_created_on: "", sys_id: att.sys_id, thumb_src: att.thumbSrc }; } scope.attachment = ($parse(attrs.attachment.size_bytes)) ? scope.$eval(attrs.attachment) : translateAttachment(attrs.attachment); var fileNameView = element.find('.sn-widget-list-title_view'); var fileNameEdit = element.find('.sn-widget-list-title_edit'); function editFileName() { fileNameView.hide(); fileNameEdit.show(); element.find('.edit-text-input').focus(); } function viewFileName() { fileNameView.show(); fileNameEdit.hide(); } viewFileName(); scope.editModeToggle = function ($event) { $event.preventDefault(); $event.stopPropagation(); scope.editMode = !scope.editMode; if (scope.editMode) editFileName(); else viewFileName(); }; scope.updateName = function () { scope.editMode = false; viewFileName(); snAttachmentHandler.renameAttachment(scope.attachment.sys_id, scope.attachment.file_name); }; }, controller: function ($scope, snCustomEvent, i18n, $http) { $scope.editMode = false; $scope.buttonFocus = false; $scope.removeAttachment = function (attachment, index) { if ($scope.deleteFileFn !== undefined && $scope.deleteFileFn instanceof Function) { $scope.deleteFileFn.apply(null, arguments); return; } if ($scope.confirmDelete) { $scope.confirmDeleteAttachment($scope.attachment); return; } snAttachmentHandler.deleteAttachment($scope.attachment.sys_id).then(function () { $scope.attachmentList.splice($scope.$index, 1); }); }; var contentTypeMap = { "application/pdf": "icon-document-pdf", "text/plain": "icon-document-txt", "application/zip": "icon-document-zip", "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "icon-document-doc", "application/vnd.openxmlformats-officedocument.presentationml.presentation": "icon-document-ppt", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "icon-document-xls", "application/vnd.ms-powerpoint": "icon-document-ppt" }; $scope.getDocumentType = function (contentType) { return contentTypeMap[contentType] || "icon-document"; }; function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } $scope.handleAttachmentClick = function (event) { if (event.keyCode === 9) return; if ($scope.editMode || !$scope.attachment) return; switch ($scope.attachment.state) { case "available": previewOrDownloadAttachment(true, event); break; case "not_available": var escapedFileName = escapeHtml($scope.attachment.file_name); var msg = i18n.getMessage('The file {0} did not pass security scan and cannot be downloaded').withValues([escapedFileName]); attachmentUnavailableMsg(msg); break; default: getAttachmentAvailability(true, event); } }; $scope.handleAttachmentDownload = function ($event) { $event.stopPropagation(); if ($scope.attachment.state !== "available") { $event.preventDefault(); getAttachmentAvailability(false); } }; function getAttachmentAvailability(isPreview, event) { $http.get('/api/now/as_attachment/getAvailability/' + $scope.attachment.sys_id) .then(function(response) { var _res = response.data.result; if (_res && _res.availability) { if (_res.availability === 'available') previewOrDownloadAttachment(isPreview, event); else attachmentUnavailableMsg(_res.message); } else { previewOrDownloadAttachment(isPreview, event); } }, function() { previewOrDownloadAttachment(isPreview, event); }); } function previewOrDownloadAttachment(isPreview, event) { if (isPreview && $scope.attachment.image) { if (!$scope.attachment.size) $scope.attachment.size = $scope.getSize($scope.attachment.size_bytes, 2); $scope.clickImageFn({file: $scope.attachment}); snCustomEvent.fire('sn.attachment.preview', event, $scope.attachment); } else { if (!$scope.attachment.sys_id) return; $window.location.href = 'sys_attachment.do?sys_id=' + $scope.attachment.sys_id; } } function attachmentUnavailableMsg(msg) { if (window.NOW && window.NOW.CustomEvent) window.NOW.CustomEvent.fire('stream.attachment.unavailable', msg); } $scope.getSize = function (bytes, precision) { if ($scope.attachment.state === "not_available") return '[unavailable]'; if (typeof bytes === 'string' && bytes.slice(-1) === 'B') return bytes; var kb = 1024; var mb = kb * 1024; var gb = mb * 1024; if ((bytes >= 0) && (bytes < kb)) return bytes + ' B'; else if ((bytes >= kb) && (bytes < mb)) return (bytes / kb).toFixed(precision) + ' KB'; else if ((bytes >= mb) && (bytes < gb)) return (bytes / mb).toFixed(precision) + ' MB'; else if (bytes >= gb) return (bytes / gb).toFixed(precision) + ' GB'; else return bytes + ' B'; }; $scope.onButtonFocus = function() { $scope.buttonFocus = true; }; $scope.onButtonBlur = function() { $scope.buttonFocus = false; }; } }; }); ; ; /*! RESOURCE: /scripts/app.ng_chat/_ng_chat.js */ (function() { 'use strict'; var dependencies = [ 'sn.connect.profile', 'sn.connect.presence', 'sn.connect.conversation', 'sn.connect.document', 'sn.connect.queue', 'ng.amb', 'sn.angularstrap', 'mentio', 'sn.dragdrop']; if (window.concoursePluginInstalled) { dependencies.unshift('sn.concourse'); dependencies.push('sn.overviewhelp'); } if (window.notificationPluginInstalled) { dependencies.push('sn.notification_preference'); } angular.module('sn.connect', dependencies) .run(function(i18n) { i18n.preloadMessages(); }); })(); ; /*! RESOURCE: /scripts/app.ng_chat/controller.chat.js */ angular.module('sn.connect').controller('chat', function( $scope, $rootScope, $location, $window, $q, $element, $timeout, conversations, userPreferences, profiles, queues, liveProfileID, snTabActivity, snPresence, snConversationAsideHistory, activeConversation, snNotification, screenWidth, messageNotifier, snCustomEvent, audioNotifier, connectDropTargetService) { 'use strict'; $scope.dropTargetService = connectDropTargetService; snTabActivity.setAppName("sn.connect"); messageNotifier.registerMessageServiceWatch(shouldSendNotification); audioNotifier.registerMessageServiceWatch(activeConversation, shouldSendNotification); function shouldSendNotification(message) { if(snTabActivity.isVisible && activeConversation.sysID !== message.conversationID) { return true; } return !snTabActivity.isVisible; } $scope.activeConversation = activeConversation; $scope.isTopWindow = true; $scope.hasQueues = queues.hasQueues; $timeout(function() { conversations.loaded.then(function() { $element.removeClass("loading"); }) }, 1000, false); try { $scope.isTopWindow = window.top == window.self; if(!$scope.isTopWindow) { $timeout(function() { window.top.location = "/$c.do" }, 3000) } } catch(IGNORED) { $scope.isTopWindow = false; } $scope.redirectFrame = function() { window.location = "/home.do"; }; $rootScope.$on('http-error.retry', function () { location.reload(); }); $scope.$on("connect.conversation.attachment_errors", function(evt, data) { if(!activeConversation.isActive(data.conversation)) return; $scope.attachmentErrors = data.errors; angular.forEach(data.errors, function(error) { snNotification.show("error", error) }) }); var loadPromises = []; loadPromises.push(conversations.refreshAll()); var pageLoadPromise = $q.all(loadPromises).then(function () { profiles.getAsync(liveProfileID).then(function(profile) { $scope.currentUser = profile; snPresence.init(); }); $scope.resourcesWidth = 285; $scope.resourcesWidthHelpDesk = '49%'; }); $scope.$on('pane.collapsed', function (event, position, collapsed) { userPreferences.setPreference('collaboration.' + position + '.collapsed', collapsed.toString()); }); var initialLocationHandled = false; $scope.$on('$locationChangeSuccess', function () { pageLoadPromise.then(function() { initialLocationHandled = true; var location = activeConversation.location; activeConversation.tab = location.tab || activeConversation.tab; $rootScope.$broadcast("connect.conversation.select", activeConversation.tab, location.conversationID); if (activeConversation.isEmpty) $scope.$broadcast("sn.aside.close", true); else $scope.$broadcast('connect.pane.close'); if (location.profileID) { profiles.openConversation(location.profileID); changeLocation(); } }); }); $scope.$watch(function() {return activeConversation.sysID;}, function(sysID, old) { if (sysID === old) return; if (!initialLocationHandled) return; changeLocation(); }); function changeLocation() { var path = activeConversation.tab; if (!activeConversation.isEmpty) path += '/' + activeConversation.sysID; $location.path(path); } $scope.$watch(function() {return activeConversation.tab;}, function(tab, old) { if (tab === old) return; if (!initialLocationHandled) return; if (!activeConversation.isEmpty) return; $location.path(activeConversation.tab); }); CustomEvent.observe("glide:nav_open_url", function(data) { $window.open(data.url, "_blank"); }); CustomEvent.observe("connect:open_group", function(data) { conversations.followDocumentConversation(data).then(function(conversation) { activeConversation.conversation = conversation; }) }); CustomEvent.observe("connect:follow_document", conversations.followDocumentConversation); CustomEvent.observe("connect:unfollow_document", conversations.unfollowDocumentConversation); function passAlongAsideEventInfo(e, view, widthOverride) { if (angular.equals(e.targetScope, $scope)) return; $scope.$broadcast(e.name, view, widthOverride); if(view && !view.isChild && e.name === "sn.aside.open") { snConversationAsideHistory.saveHistory(activeConversation.sysID, view); } else if (e.name === "sn.aside.close") snConversationAsideHistory.clearHistory(activeConversation.sysID); } $scope.$on("sn.aside.open", passAlongAsideEventInfo); $scope.$on("sn.aside.close", passAlongAsideEventInfo); $scope.$on("sn.aside.resize", passAlongAsideEventInfo); $scope.$on("sn.aside.historyBack", passAlongAsideEventInfo); $scope.$on("sn.aside.controls.active", function(e, data) { if(!angular.equals(e.targetScope, $scope)) $scope.$broadcast("sn.aside.controls.active", data); }); $scope.isWideEnough = function() { return screenWidth.isAbove(800); }; screenWidth.threshold(800, function(above){ if (above) $scope.$broadcast('connect.pane.close'); }); }); ; /*! RESOURCE: /scripts/app.ng_chat/controller.chatFloating.js */ angular.module('sn.connect').controller('chatFloating', function( $scope, $rootScope, userPreferences, snTabActivity, snConnectAsideManager, messageNotifier, conversations, audioNotifier, isRTL, activeConversation, paneManager, $timeout) { 'use strict'; paneManager.registerPane('connect:conversation_list'); $scope.conversationListCollapsed = true; snTabActivity.setAppName("sn.connect"); messageNotifier.registerMessageServiceWatch(shouldSendNotification); audioNotifier.registerMessageServiceWatch(activeConversation, shouldSendNotification); userPreferences.getPreference('glide.ui.accessibility', false).then(function(val) { if (!!window.MSInputMethodContext && !!document.documentMode) { $scope.useIE11AccessibilitySpecialCase = val === "true" ? true : false; } }); function shouldSendNotification(message) { if(!snTabActivity.isVisible) return true; var conversation = conversations.indexed[message.conversationID]; if(snTabActivity.isIdle) return (conversation && conversation.isFrameStateOpen) ? false : true; if(conversation && conversation.isFrameStateOpen) return false; return $scope.conversationListCollapsed; } $scope.$watch("conversationListCollapsed", function(listCollapsed) { CustomEvent.fireTop("connect:conversation_list:state", (listCollapsed) ? "closed" : "open"); }); CustomEvent.observe("connect:conversation_list.toggle", function(manualSave, autoFocusPane) { $scope.conversationListCollapsed = !$scope.conversationListCollapsed; $rootScope.$broadcast("pane.collapsed", 'right', $scope.conversationListCollapsed, autoFocusPane); if(manualSave) userPreferences.setPreference("connect:conversation_list.opened", !$scope.conversationListCollapsed); }); snConnectAsideManager.setup(); $scope.$on('pane.collapsed', function (event, position, collapsed, autoFocusPane) { var UI15Layout = angular.element(document.body).data().layout, $snConnect = angular.element('.sn-connect-content'), $layout = angular.element('.navpage-layout'), $pageRight = angular.element('.navpage-right'); var pane = isRTL ? 'west' : 'east'; function focusInput() { if (activeConversation.isSupport) { var supportTab = angular.element("#connectSupportTab"); supportTab.focus(); } if ($snConnect.hasClass('sn-pane-visible')) { var el = $snConnect.find('input').filter(':first'); el.focus(); } } if(collapsed) { if(UI15Layout) { UI15Layout.hide(pane); } else { $layout.addClass('navpage-right-hidden'); $pageRight.css('visibility', 'hidden'); } $snConnect.addClass('sn-pane-hidden'); $snConnect.removeClass('sn-pane-visible'); } else { if(UI15Layout) { UI15Layout.show(pane); UI15Layout.sizePane(pane, 285); } else { $layout.removeClass('navpage-right-hidden'); $pageRight.css('visibility', 'visible'); } $snConnect.removeClass('sn-pane-hidden'); $snConnect.addClass('sn-pane-visible'); if (autoFocusPane) { if ($scope.useIE11AccessibilitySpecialCase) { $timeout(function() { focusInput(); }, 425); } else { $snConnect.one('transitionend', function() { focusInput(); }); } } } }); }); ; /*! RESOURCE: /scripts/app.ng_chat/message/js_includes_connect_message.js */ /*! RESOURCE: /scripts/app.ng_chat/message/_module.js */ angular.module("sn.connect.message", ["ng.common", "sn.connect.util", "sn.connect.profile"]); ; /*! RESOURCE: /scripts/app.ng_chat/message/directive.snAriaChatMessage.js */ angular.module('sn.connect.message').directive('snAriaChatMessage', function(getTemplateUrl, $templateCache, $interpolate, $sanitize) { 'use strict'; var ariaTemplate = $templateCache.get(getTemplateUrl('snAriaChatMessage.xml')); return { restrict: 'E', replace: true, template: "<div></div>", scope: { message: '=' }, link: function(scope, element) { var node = $interpolate(ariaTemplate)(scope); element.html($sanitize(node)); }, controller: function($scope) { $scope.displayedText = function() { if (!$scope.message.isMessageShowing) { return ""; } return $scope.message.displayText; }; $scope.attachmentMessage = function() { if (!$scope.message.attachments || !$scope.message.attachments.length) { return ""; } var output = ""; for ( var i = 0, len = $scope.message.attachments.length; i < len; i++ ) { var attachment = $scope.message.attachments[i]; output += i > 0 ? ' . ' : ''; output += attachment.fileName + ', ' + attachment.byteDisplay; } return output; } } } }); ; /*! RESOURCE: /scripts/app.ng_chat/message/directive.snCreateMessage.js */ angular.module('sn.connect.message').directive('snCreateMessage', function( $timeout, $rootScope, getTemplateUrl, i18n, messageFactory, messageService, activeConversation, conversations, snTypingTracker, snNotification, inFrameSet, isLoggedIn) { "use strict"; var i18nText; i18n.getMessages([ 'Worknote', 'Comment (customer visible)', 'Message', 'Attachments cannot be uploaded', 'Upload attachment' ], function (results) { i18nText = results; }); return { restrict: 'E', templateUrl: getTemplateUrl("snCreateMessage.xml"), replace: true, scope: { conversation: "=", autofocusOnInput: "=?" }, link: function(scope, element) { var lastTypeaheadSuggestion; var preventSubmitAfterMentioSelection; var input = element.find('.new-message'); if( navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i)) { scope.autofocusOnInput = false; } if (scope.autofocusOnInput === undefined) scope.autofocusOnInput = true; input.typeahead({ hint: true, highlight: false, minLength: 1 }, { name: 'commands', displayKey: 'hint', source: function (q, cb) { if(scope.conversation.pendingMessage && scope.conversation.pendingMessage.indexOf("/") === 0) cb(scope.conversation.chatActions.getCommands(q)); else cb([]); }, templates: { suggestion: function(command) { return '<div class="command-row"><div class="col-sm-4 command-key">' + command.shortcut + '</div><div class="col-sm-8 command-description">' + command.description + '</div></div>'; } } } ); input[0].spellcheck = true; var ttTypeahead = input.data("ttTypeahead"); ttTypeahead.input.off("blurred"); ttTypeahead.input.$hint.css('display', 'none'); input.on("typeahead:render", function(event, suggestion) { lastTypeaheadSuggestion = suggestion; }); input.on("typeahead:cursorchange", function(event, suggestion) { lastTypeaheadSuggestion = suggestion; }); ttTypeahead.input._managePreventDefault = function managePreventDefaultModified(keyName, $e) { var preventDefault = false; if(keyName === "up" || keyName === "down") preventDefault = !ttTypeahead.menu._allDatasetsEmpty(); if(preventDefault) $e.preventDefault(); }; input.on("keydown", function(event) { if(event.keyCode === 13 && !event.shiftKey) event.preventDefault(); var openMenus = angular.element("mentio-menu").filter(function(index, element) { return element.style.display === "block"; }); preventSubmitAfterMentioSelection = openMenus.length > 0; if (event.keyCode === 27 && !preventSubmitAfterMentioSelection) { if (!scope.conversation.isPending) scope.$emit("connect.floatingConversationEscape"); else scope.$emit("connect.message_control_key", "escape"); } if(event.keyCode === 13 && !event.shiftKey && !preventSubmitAfterMentioSelection) { input.trigger("enterkey-pressed"); if(!scope.conversation.pendingMessage) return; if (!handleSlashCommand()) { addMessage(); if (activeConversation.pendingConversation && activeConversation.pendingConversation.sysID === scope.conversation.sysID) { conversations.get(activeConversation.pendingConversation.sysID).then(function(conversation) { if((inFrameSet && conversation.isFrameStateOpen) || (!inFrameSet && conversation.visible)) { $rootScope.$broadcast("connect.new_conversation.cancelled"); } }); } } closeTypeahead(); } else { snTypingTracker.typing() } }); function handleSlashCommand() { var pendingMessage = scope.conversation.pendingMessage; if(pendingMessage[0] !== "/") return false; if(lastTypeaheadSuggestion) { var lastSuggestionIsValid = lastTypeaheadSuggestion.canRun(pendingMessage); $timeout(function () { if(lastSuggestionIsValid) { scope.conversation.pendingMessage = lastTypeaheadSuggestion.shortcut + " "; input.triggerHandler("blur") } lastTypeaheadSuggestion = void(0); }); return true; } if (scope.conversation.chatActions.hasMatchingAction(pendingMessage)) { if (scope.conversation.chatActions.hasRequiredArguments(pendingMessage)) { scope.conversation.chatActions.run(pendingMessage); scope.conversation.pendingMessage = ""; scope.$apply(); } else { scope.$emit("connect.chat_action.require_options", scope.conversation); } return true; } return false; } function closeTypeahead() { ttTypeahead.input.query = ""; ttTypeahead.menu.empty(); ttTypeahead.input.resetInputValue(); ttTypeahead.input.trigger("blurred"); input.typeahead('close'); } function addMessage() { $rootScope.$broadcast("connect.auto_scroll.jump_to_bottom"); snTypingTracker.cancelTyping(); var newMessageText = scope.conversation.pendingMessage; if (!newMessageText) return; var message = messageFactory.newPendingMessage(scope.conversation, newMessageText, scope.messageType); scope.sendMessage(message); scope.conversation.pendingMessage = ""; } var waitForConversationCreation = false; scope.sendMessage = function(message) { if(!message) { return; } message.text = expandMentions(message.text, scope.mentionMap); if (!activeConversation.pendingConversation || (message.conversationID === activeConversation.sysID)) { messageService.send(message, activeConversation.conversation); return; } var conversation = activeConversation.pendingConversation; if (!conversation.isPending) { message.conversationID = conversation.sysID; messageService.send(message); done(conversation, false); return; } if (waitForConversationCreation) return; waitForConversationCreation = true; var newConversation = conversations.newConversation; if (newConversation.pendingRecipients.length === 0) return; var recipients = newConversation.pendingRecipients; var groupName = newConversation.getGroupName(); conversations.beginNewConversation(groupName, recipients, message) .then(function(conversation) { waitForConversationCreation = false; done(conversation, true); }); }; function expandMentions(entryText, mentionIDMap) { var text = entryText; Object.getOwnPropertyNames(mentionIDMap).forEach(function(element) { var atMention = element.replace(/[.*+\-?^()|[\]\\]/g, '\\$&'); var search = new RegExp("@\\[" + atMention + "\\]", "gi"); var sysId = mentionIDMap[element]; text = text.replace(search, "@[" + sysId + ":" + element + "]"); }); return text; } function done(conversation, isNew) { activeConversation.conversation = conversation; $rootScope.$broadcast("connect.new_conversation.complete", conversation, isNew); $rootScope.$broadcast("connect.focus", conversation); } input.on("blur", function() { input.val(scope.conversation.pendingMessage); }); scope.$on("connect.message.focus", function(event, conversation) { if (inFrameSet) { if (!conversation) return; if (!scope.conversation) return; if (conversation.sysID !== scope.conversation.sysID) return; if (conversation !== scope.conversation && scope.conversation.isPending) { return; } } focus(); }); scope.$on("connect.message.focus.type", function(event, newInputType) { if (newInputType !== "chat") return; focus(); }); function focus() { if(window.getSelection().toString()) return; $timeout(function () { input.focus(); }, 0, false); } scope.focus = focus; scope.$on("connect.attachment_dialog.open", function(e, sysID) { if(sysID !== scope.conversation.sysID) return; $timeout(function() { element.find('.message-attach-file').click(); }, 0, false); }); if (element.find(".document-message-type .dropup").hideFix) element.find(".document-message-type .dropup").hideFix(); $timeout(focus, 0, false); }, controller: function($scope, liveProfileID, messageService, messageFactory, uploadAttachmentService, snConnectMention, inSupportClient) { $scope.members = []; $scope.members.loading = false; $scope.mentionMap = {}; $scope.searchMembers = function(term) { if ($scope.conversation.isDirectMessage) { $scope.members = []; } else { if(!$scope.conversation.document || !$scope.conversation.table) return snConnectMention.retrieveMembers($scope.conversation, term).then(function (members) { $scope.members = members; }); $scope.members.loading = true; if(term.length === 0) { $scope.members = [{ termLengthIsZero: true }]; $scope.members.loading = false; } else { snConnectMention.retrieveMembers($scope.conversation, term).then(function (members) { $scope.members = members; $scope.members.loading = false; }); } } }; $scope.selectAtMention = function(item) { if(item.termLengthIsZero) return item.name; $scope.mentionMap[item.name] = item.sys_id; return "@[" + item.name + "]"; }; $scope.openAttachFileDialog = function($event) { if($scope.isAttachmentDisabled()) return; if($scope.conversation.amMember || $scope.conversation.isPending) uploadAttachmentService.openFileSelector.apply(this, arguments); }; $scope.$on("connect.drop.files", function(event, files, conversationID) { var isDropable = $scope.conversation.isPending ? !$scope.conversation.isPendingNoRecipients : conversationID === $scope.conversation.sysID; if (isDropable) $scope.sendFiles(files); }); $scope.sendFiles = function(files) { if ($scope.conversation.isHelpDesk && $scope.conversation.queueEntry.isTransferringToMe) { $scope.$broadcast('dialog.attachment-transfer.show'); return; } if ($scope.isWorknote()) { $scope.okAttachmentsAsComment = function() { attachFiles(files); }; $scope.$broadcast('dialog.attachment-work-notes.show'); return; } attachFiles(files); }; function attachFiles(files) { $rootScope.$broadcast("connect.auto_scroll.scroll_to_bottom"); messageService.uploadAttachments($scope.conversation, files).then(function (message) { return $scope.sendMessage(message); }).then(function() { $timeout(function() { if(activeConversation.conversation.sysID === $scope.conversation.sysID) $scope.focus(); }, 0, false); }); } $scope.isAttachmentDisabled = function() { return $scope.isWorknote() || ($scope.conversation.isHelpDesk && $scope.conversation.queueEntry.isTransferringToMe) || !isLoggedIn; }; $scope.getAttachmentTitle = function() { return $scope.isAttachmentDisabled() ? i18nText['Attachments cannot be uploaded'] : i18nText['Upload attachment']; }; $scope.$watch("conversation.sysID", function() { initializeMessageType(); }); $scope.$watch('conversation.queueEntry.sysID', function() { initializeMessageType(); }); $scope.$watch('conversation.queueEntry.isTransferAccepted', function() { initializeMessageType(); }); $scope.setAsWorkNote = function() { $scope.messageType = "work_notes"; }; $scope.setAsComment = function() { $scope.messageType = "comments"; }; $scope.isWorknote = function() { return $scope.messageType === "work_notes"; }; function isComment() { return $scope.messageType === 'comments'; } $scope.isDocumentGroup = function() { return $scope.conversation.isDocumentGroup && !inSupportClient; }; $scope.isMessageTypeVisible = function() { return $scope.isDocumentGroup() && !hasPendingTransferToMe() && $scope.conversation.canSaveWorkNotes && $scope.conversation.canSaveComments; }; $scope.isEndChatVisible = function() { return $scope.conversation.isHelpDesk && $scope.conversation.queueEntry.isAssignedToMe; }; function hasPendingTransferToMe() { return $scope.conversation.isHelpDesk && $scope.conversation.queueEntry.isTransferringToMe && $scope.conversation.queueEntry.isTransferPending; } $scope.placeholderText = function() { if ($scope.isDocumentGroup() && $scope.conversation.canSaveWorkNotes && $scope.conversation.canSaveComments) { if (isComment()) return i18nText['Comment (customer visible)']; if ($scope.isWorknote()) return i18nText['Worknote']; } return i18nText['Message']; }; function initializeMessageType() { if (hasPendingTransferToMe()) { $scope.setAsWorkNote(); return; } if ($scope.isDocumentGroup() && !$scope.conversation.isHelpDesk && $scope.conversation.table !== "vtb_board" && $scope.conversation.canSaveWorkNotes) { $scope.setAsWorkNote(); return; } if ($scope.isDocumentGroup() && !$scope.conversation.isHelpDesk && $scope.conversation.table !== "vtb_board" && $scope.conversation.canSaveComments) { $scope.setAsComment(); return; } if($scope.conversation.isDirectMessage || $scope.conversation.isGroup) { $scope.messageType = undefined; return; } } $scope.closeSupportConversation = function () { conversations.closeSupport($scope.conversation.sysID, false); }; function addLinkMessage(link) { $scope.sendMessage(messageFactory.newPendingMessage($scope.conversation, link)); } $scope.$on("conversation.resource.add", function(event, data) { addLinkMessage(data.link); }); $scope.$on("connect.drop", function(event, data, conversationID) { if (conversationID !== $scope.conversation.sysID && !$scope.conversation.isPending) return; var link; if (data.type === "document") { link = data.href; } else if (data.type === "record") { link = data.payload.url; } else if (data.type === "link") { link = data.payload; } else if (data.icon && data.icon === "form" && data.url) { link = data.url; } else { return; } addLinkMessage(link); }); $scope.openDropup = function($event) { $event.stopPropagation(); var actionButton = $event.target; var dropdownMenuEl = angular.element(actionButton) .siblings(".dropdown-menu"); if (dropdownMenuEl.length > 0) { dropdownMenuEl.dropdown("toggle"); if (dropdownMenuEl.parent().hasClass('open')) { actionButton.setAttribute('aria-expanded', true ); } else { actionButton.setAttribute('aria-expanded', false ); } } }; $scope.setMessageType = function($event, msgType) { $event.stopPropagation(); if (msgType === 'comments') { $scope.setAsComment(); } else if (msgType === 'work_notes') { $scope.setAsWorkNote(); } var dropdownMenuEl = angular.element($event.target) .parents(".dropdown-menu"); if (dropdownMenuEl.length > 0) { dropdownMenuEl.dropdown("toggle"); } $scope.focus(); }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/message/directive.snMessageBatch.js */ angular.module('sn.connect.message').directive('snMessageBatch', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snMessageBatch.xml'), scope: { batch: '=', isGroupConversation: '=', disableAvatarPopovers: '=?' }, controller: function($scope, showAgentAvatar, inSupportClient) { $scope.isSystemMessage = function() { return $scope.batch.isSystemMessage; }; $scope.inSupportClient = inSupportClient; $scope.isQueueAvatarShowing = function() { return (inSupportClient && !showAgentAvatar && $scope.batch.isFromPeer) || $scope.isFromQueue(); }; $scope.isFromQueue = function() { return $scope.batch.profileData && $scope.batch.profileData.table === 'chat_queue_entry'; }; $scope.isTextShowing = function(message) { return message.isMessageShowing && !message.uploadingFiles; }; if (!$scope.batch.profileData) { var unwatch = $scope.$watch('batch.profileData', function (newVal) { if (newVal) { $scope.profileData = newVal; unwatch(); } }) } else { $scope.profileData = $scope.batch.profileData; } } } }); ; /*! RESOURCE: /scripts/app.ng_chat/message/directive.snUploadAttachmentList.js */ angular.module('sn.connect.message').directive('snUploadAttachmentList', function(getTemplateUrl) { "use strict"; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl("snUploadAttachmentList.xml"), scope: { uploadingFiles: "=" }, controller: function($scope) { $scope.isFileNameShowing = function (file) { return file.state !== 'error'; }; $scope.isProgressBarShowing = function (file) { return file.state === 'progress'; }; $scope.getProgressStyle = function (file) { return { 'width': file.progress + '%' }; }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/message/factory.Message.js */ angular.module('sn.connect.message').factory("messageFactory", function( liveProfileID, profiles, liveLinkFactory, attachmentFactory, resourcePersister) { "use strict"; var AT_MENTIONS = /(?:@|@)M\[([^|]+?)\|([^\]]+?)]/gi; var AT_MENTION_OLD = /(?:@|@)\[([^:\]]+?):([^\]]+)]/g; var LINKS = /(?:@|@)L\[([^|]+?)\|([^\]]*)]/gi; var SYS_ID = /^[0-9A-F]{32}$/i; var CARRIAGE_RETURN = /\r/g; var LINE_FEED = /\n/g; var TIMESTAMP = /([^T]*)T([^.]*)[.].*/g; var REUSE_DIV = document.createElement('div'); function buildMessageFromJSONObject(jsonObject) { jsonObject = jsonObject || {}; var mentions = jsonObject.mentions || []; var links = []; var attachments = []; var isSystem = jsonObject.created_by === "system"; angular.forEach((jsonObject.links || []), function (rawLink) { var link = liveLinkFactory.fromObject(rawLink, !isSystem); resourcePersister.addLink(jsonObject.group, link); this.push(link); }, links); angular.forEach((jsonObject.attachments || []), function (rawAttachment) { var attachment = attachmentFactory.fromObject(rawAttachment); resourcePersister.addAttachment(jsonObject.group, attachment); this.push(attachment) }, attachments); var text = jsonObject.formatted_message; var displayText = createDisplayText(text, links); var cleanText = createCleanText(text, jsonObject.pending); return { sysID: jsonObject.sys_id, text: text, createdOn: jsonObject.created_on, conversationID: jsonObject.group, profile: jsonObject.profile, timestamp: jsonObject.timestamp, reflectedField: jsonObject.reflected_field, hasLinks: links.length > 0, id: jsonObject.id, pending: false, get cleanText() { return cleanText; }, get profileData() { if (this.profile) return profiles.get(this.profile); }, get isSystemMessage() { return isSystem; }, get isFromPeer() { return this.profile !== liveProfileID; }, get attachments() { return attachments; }, get links() { return links; }, get mentions() { return mentions; }, get isMessageShowing() { if (!this._isMessageShowing) this._isMessageShowing = !shouldHide(this); return this._isMessageShowing; }, get hasSystemLink() { return this.isSystemMessage && links[0]; }, get displayText() { return displayText; } } } function shouldHide(message) { if (onlyAttachmentMessage(message)) return true; var links = message.links; return (links.length === 1) && links[0].isHideable && (replaceText(message.text, "X", "X").trim().length === 1); } function onlyAttachmentMessage(message) { var attachments = message.attachments; if (attachments.length === 0) return false; var text = message.text; message.attachments.forEach(function(attachment){ text = text.replace("File: " + attachment.fileName,""); }); return text.trim().length === 0; } function createDisplayText(text, links) { function linkFormatter(wholeMatch, urlOrSysID, linkText) { var isSysID = urlOrSysID.match(SYS_ID); var fn = isSysID ? function(link) { return link.sysID === urlOrSysID; } : function(link) { var url = urlOrSysID; var escapedLinkUrl = removeHtml(link.url); var escapedLinkUrl2 = removeHtml(escapedLinkUrl); return link.url === url || escapedLinkUrl === url || escapedLinkUrl2 === url; }; var matchedLink = links.filter(fn)[0]; if (matchedLink) { try { return matchedLink.aTag(linkText); } catch (unused) {} } return linkText; } return replaceText(text, "<a class='at-mention at-mention-user-$1'>@$2</a>", linkFormatter) .replace(CARRIAGE_RETURN, '') .replace(LINE_FEED, '<br/>'); } function replaceText(text, mentions, links) { if(!text) return ""; return text .replace(AT_MENTIONS, mentions) .replace(AT_MENTION_OLD, mentions) .replace(LINKS, links); } function newPendingAttachmentMessage(conversation, files) { var message = newPendingMessage(conversation, ""); message.uploadingFiles = files; return message; } function newPendingMessage(conversation, text, journalType) { var timestamp = new Date().getTime(); var message = buildMessageFromJSONObject({ sys_id: timestamp + Math.random(), profile: liveProfileID, group: conversation.sysID, created_on: getLocalCreatedOn(timestamp), formatted_message: text, reflected_field: journalType || "comments", timestamp: timestamp, pending: true }); message.pending = true; return message; } function getLocalCreatedOn(timestamp) { return new Date(timestamp) .toISOString() .replace(TIMESTAMP,"$1 $2"); } function removeHtml(html, unsanitized) { if (unsanitized) return html; REUSE_DIV.innerText = html; return REUSE_DIV.textContent || REUSE_DIV.innerHTML || ''; } function createCleanText(html, pending) { var text = removeHtml(html, pending); return replaceText(text, '@$2', '$2'); } return { fromObject: buildMessageFromJSONObject, newPendingMessage: newPendingMessage, newPendingAttachmentMessage: newPendingAttachmentMessage } }); ; /*! RESOURCE: /scripts/app.ng_chat/message/service.messageBatcher.js */ angular.module('sn.connect.message').service("messageBatcherService", function(i18n, $filter, liveProfileID, nextBatchDelay) { "use strict"; var yesterday = "Yesterday"; var today = "Today"; i18n.getMessages([yesterday, today], function(results) { yesterday = results[yesterday]; today = results[today]; }); var MINIMUM_TIME = nextBatchDelay; function getMonthCount(date) { return (date.getFullYear() * 12 + date.getMonth()); } function getDayCount(date) { return (date.getFullYear() * 365 + date.getMonth() * 30 + date.getDate()); } function MessageBatch (messages, isLastBatchFn) { return { messages: messages, get firstMessage() { return this.messages[0]; }, get lastMessage() { return this.messages[this.messages.length - 1] }, get batchID() { return this.firstMessage.sysID + "" + this.lastMessage.sysID; }, get isFromPeer() { return !!this.firstMessage.isFromPeer; }, get isSystemMessage() { return !!this.firstMessage.isSystemMessage; }, get profileData() { return this.firstMessage.profileData; }, get createdOn() { return this.lastMessage.createdOn; }, get timestamp() { return this.lastMessage.timestamp; }, get isLastBatch() { return isLastBatchFn(this); }, get systemMessageLink() { if (this.lastMessage.hasSystemLink) return this.lastMessage.links[0]; }, getSeparator: function() { var timestamp = new Date(this.lastMessage.timestamp); var now = new Date(); var hasYear = now.getFullYear() - timestamp.getFullYear() > 0; if (hasYear && getMonthCount(now) - getMonthCount(timestamp) > 12) return $filter('date')(timestamp, 'yyyy'); var hasMonth = now.getMonth() - timestamp.getMonth() > 0; if ((hasMonth || hasYear) && getDayCount(now) - getDayCount(timestamp) > 30) return $filter('date')(timestamp, 'MMMM yyyy'); var hasDay = now.getDate() - timestamp.getDate() > 0; if (hasMonth || hasYear || hasDay) { if (now.getDate() - timestamp.getDate() === 1) return yesterday; return $filter('date')(timestamp, 'longDate'); } return today; } } } var messageBatchers = {}; var ariaMessages = {}; function compare(message1, message2) { if(message1.id && message2.id) return message1.id < message2.id ? -1 : 1; return message1.timestamp - message2.timestamp; } function MessageBatcher() { var messageBatchMap = {}; var batches = []; var lastMessageUnloaded; function isLastBatchFn(batch) { return lastBatch() === batch; } function lastBatch() { return batches[batches.length - 1]; } function removeBatchesBefore(idx) { if (idx >= batches.length) { return; } for (var i = 0; i < idx; i++) { var batch = batches.shift(); for (var j = 0; j < batch.messages.length; j++) { var message = batch.messages[j]; delete messageBatchMap[message.sysID]; lastMessageUnloaded = message; } } } function add(message) { if (batches.length == 0) { insertNewBatch(0, [message]); return true; } var batch = messageBatchMap[message.sysID]; if (batch) { update(batch, message); return false; } for(var i = 0; i < batches.length; ++i) { batch = batches[i]; var insert = insertAt(batch, message); if (insert === "after") continue; if (insert === "before") { insertNewBatch(i, [message]); return true; } var isLast = (insert === batch.messages.length); if (isBatchable(batch, message)) { if (isLast) { var next = batches[i + 1]; if (next && compare(message, next.firstMessage) > 0) continue; } batch.messages.splice(insert, 0, message); messageBatchMap[message.sysID] = batch; coalesce(i); return true; } if (insert === 0) { insertNewBatch(i, [message]); return true; } if (!isLast) { split(i, insert); insertNewBatch(i +1, [message]); return true; } } insertNewBatch(batches.length, [message]); return true; } function update(batch, message){ if (message.isPlaceholder) return; for (var i = 0; i < batch.messages.length; ++i) { if (batch.messages[i].sysID === message.sysID) { batch.messages[i] = message; break; } } } function insertAt(batch, message) { if (!isInRange(message, batch.firstMessage)) return "before"; if (!isInRange(batch.lastMessage, message)) return "after"; var messages = batch.messages; for (var i = 0; i < messages.length; ++i) { if (compare(message, messages[i]) < 0) return i; } return messages.length; } function isBatchable(batch, message) { if (message.isSystemMessage) return false; var first = batch.firstMessage; return !first.isSystemMessage && (message.profile === first.profile); } function mapMessageToBatch(batch, messages) { messages.forEach(function (message) { messageBatchMap[message.sysID] = batch; }); } function coalesce(batchIndex) { var curr = batches[batchIndex]; var remove = batchIndex + 1; var next = batches[remove]; if (!next) return; if (!isBatchable(curr, next.firstMessage)) return; if (!isInRange(curr.lastMessage, next.firstMessage)) return; batches.splice(remove, 1); curr.messages = curr.messages.concat(next.messages); mapMessageToBatch(curr, next.messages); } function split(batchIndex, messageIndex) { var batch = batches[batchIndex]; insertNewBatch(batchIndex + 1, batch.messages.slice(messageIndex)); batch.messages = batch.messages.slice(0, messageIndex); } function insertNewBatch(batchIndex, messages) { var batch = new MessageBatch(messages, isLastBatchFn); batches.splice(batchIndex, 0, batch); mapMessageToBatch(batch, messages); } function isInRange(message1, message2) { return message1.timestamp + MINIMUM_TIME >= message2.timestamp; } function removeFromBatch(batch, messageIndex) { var messages = batch.messages; messages.splice(messageIndex, 1); var batchIndex = batches.indexOf(batch); var length = messages.length; if (length === 0){ batches.splice(batchIndex, 1); return; } if (messageIndex === length) return; var prev = messages[messageIndex-1]; if (!prev) return; var curr = messages[messageIndex]; if (isInRange(prev, curr)) return; split(batchIndex, messageIndex); } function remove(message) { var batch = messageBatchMap[message.sysID]; if (!batch) return false; for (var i = 0; i < batch.messages.length; ++i) { if (batch.messages[i].sysID === message.sysID) { removeFromBatch(batch, i); break; } } delete messageBatchMap[message.sysID]; return true; } function isInBounds(message) { if (typeof lastMessageUnloaded === "undefined") { return true; } return compare(message, lastMessageUnloaded); } function isSeparator(index) { var currTimestamp = new Date(batches[index].timestamp); if (index === 0) { var now = new Date(); return getDayCount(now) - getDayCount(currTimestamp) > 0; } var prevTimestamp = new Date(batches[index - 1].timestamp); var hasYear = currTimestamp.getFullYear() - prevTimestamp.getFullYear() > 0; var hasMonth = currTimestamp.getMonth() - prevTimestamp.getMonth() > 0; var hasDay = currTimestamp.getDate() - prevTimestamp.getDate() > 0; return hasYear || hasMonth || hasDay; } return { get batches() { return batches; }, get lastBatch() { return lastBatch(); }, isInBounds: isInBounds, isSeparator: isSeparator, addMessage: add, removeMessage: remove, removeBatchesBefore: removeBatchesBefore } } function add(message, results) { if (!message.conversationID) return results; var batcher = messageBatchers[message.conversationID]; if (!batcher) batcher = messageBatchers[message.conversationID] = new MessageBatcher(); var added = batcher.addMessage(message); if (added) { results.added.push(message); if(message.profile !== liveProfileID || message.isSystemMessage) { ariaMessages[message.conversationID] = ariaMessages[message.conversationID] || []; ariaMessages[message.conversationID].push(message); ariaMessages[message.conversationID].sort(compare); } } else { results.existing.push(message); } return results; } function remove(message, results){ var batcher = messageBatchers[message.conversationID]; if (!batcher) return results; var removed = batcher.removeMessage(message); if (removed) results.push(message); return results; } function callActionFn(messages, isPlaceholder, results, fn) { if (angular.isArray(messages)) { messages .sort(compare) .forEach(function (message) { message.isPlaceholder = isPlaceholder; fn(message, results); }); return results; } messages.isPlaceholder = isPlaceholder; return fn(messages, results); } return { addMessages: function(messages, doNotUpdate) { return callActionFn(messages, doNotUpdate, {added: [], existing: []}, add); }, isInBounds: function(message) { var batcher = messageBatchers[message.conversationID]; if (!batcher) { return true; } return batcher.isInBounds(message); }, removeMessages: function(messages) { return callActionFn(messages, undefined, [], remove); }, getBatcher: function(conversationID) { var batcher = messageBatchers[conversationID]; if (!batcher) batcher = messageBatchers[conversationID] = new MessageBatcher(); return batcher; }, removeMessageBatcher: function(conversationID) { delete messageBatchers[conversationID]; delete ariaMessages[conversationID]; }, clearAriaMessages: function(conversationID) { ariaMessages[conversationID] = []; }, getAriaMessages: function(conversationID, count) { if(angular.isUndefined(count)) count = 1; count = -Math.abs(count); ariaMessages[conversationID] = ariaMessages[conversationID] || []; return ariaMessages[conversationID].slice(count); }, getLastMessage: function(conversationID) { var batcher = this.getBatcher(conversationID); var lastBatch = batcher.lastBatch; return lastBatch && lastBatch.lastMessage; }, getFirstMessage: function(conversationID) { var batcher = this.getBatcher(conversationID); var firstBatch = batcher.batches[0]; return firstBatch && firstBatch.firstMessage; }, _wipeOut_: function(){ messageBatchers = {}; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/message/service.unreadCount.js */ angular.module('sn.connect.message').service('unreadCountService', function(conversationPersister, messageBatcherService) { 'use strict'; var unreadCountObjects = {}; function setCount(conversationID, lastViewed, count) { if (!conversationID) return; if (angular.isUndefined(lastViewed)) return; unreadCountObjects[conversationID] = { timestamp : lastViewed, count : count } } function resetCount(conversationID, doNotPersist) { var batches = messageBatcherService.getBatcher(conversationID).batches; var lastMessageTime = (batches.length > 0) ? batches[batches.length - 1].lastMessage.timestamp : new Date().getTime(); var old = unreadCountObjects[conversationID]; unreadCountObjects[conversationID] = { timestamp : lastMessageTime }; if (doNotPersist) return; if (old && (old.timestamp === lastMessageTime)) return; conversationPersister.lastViewed(conversationID, lastMessageTime); } function getCount(conversationID) { var unreadCountObject = unreadCountObjects[conversationID]; if (!unreadCountObject) return 0; var batches = messageBatcherService.getBatcher(conversationID).batches; var count = 0; batches.forEach(function (batch){ if (count > 0) { count += batch.messages.length; return; } if(unreadCountObject.timestamp < batch.lastMessage.timestamp) { var messages = batch.messages; for (var i = 0; i < messages.length; ++i) { if (unreadCountObject.timestamp < messages[i].timestamp) { count = messages.length - i; break; } } } }); return unreadCountObject.count ? Math.max(count, unreadCountObject.count) : count; } function getTimestamp(conversationID) { var unreadCounts = unreadCountObjects[conversationID]; return unreadCounts ? unreadCounts.timestamp : 0; } return { set: setCount, get: getCount, reset: resetCount, getLastTimestamp: getTimestamp }; }); ; /*! RESOURCE: /scripts/app.ng_chat/message/service.messages.js */ angular.module('sn.connect.message').value('CONNECT_CONTEXT', Date.now() + "" + Math.random() * Math.pow(10, 19)); angular.module('sn.connect.message').service("messageService", function( $q, $rootScope, snHttp, amb, userID, liveProfileID, messageFactory, unreadCountService, messageBatcherService, uploadAttachmentService, CONNECT_CONTEXT, snNotification, $timeout, isLoggedIn, sessionID) { "use strict"; var CONVERSATIONS_URL = isLoggedIn ? "/api/now/connect/conversations/" : "/api/now/connect/support/anonymous/conversations/"; var context = CONNECT_CONTEXT; var allHistoryLoaded = {}; var watches = []; var channelId = isLoggedIn ? userID : sessionID; amb.getChannel("/connect/message/" + channelId).subscribe(function(response) { addRawMessage(response.data); }); amb.connect(); function retrieveMessages(conversation, time) { if (!conversation) return $q.when([]); if (!conversation.sysID) return $q.when([]); if (conversation.isPending) return $q.when([]); if (time && allHistoryLoaded[conversation.sysID]) return $q.when([]); var conversationID = conversation.sysID; var url = CONVERSATIONS_URL + conversationID + "/messages"; if (time) url += "?before=" + time; return snHttp.get(url).then(function(response) { var processedMessages = []; angular.forEach(response.data.result, function (messageData) { processedMessages.push(messageFactory.fromObject(messageData)); }); if (time && processedMessages.length === 0) allHistoryLoaded[conversationID] = true; conversation.restricted = conversation.restricted || false; var added = messageBatcherService.addMessages(processedMessages).added; $rootScope.$broadcast('sn.TimeAgo.tick'); return added; }, function(response) { if(response.status === 403) conversation.restricted = true; return $q.reject(response) }); } function addRawMessage(messageData) { var message = messageFactory.fromObject(messageData); if (!messageBatcherService.isInBounds(message)) { return message; } var isOldMessage = unreadCountService.getLastTimestamp(message.conversationID) > message.timestamp; $rootScope.$apply(function () { messageBatcherService.addMessages(message); $timeout(function () { $rootScope.$broadcast('sn.TimeAgo.tick'); }, 0, false); }); if (isOldMessage) return message; if (message.profileID === liveProfileID) return message; angular.forEach(watches, function(watch) { watch(message); }); return message; } function send(message, conversation) { messageBatcherService.addMessages(message); unreadCountService.reset(message.conversationID, true); return snHttp.post(CONVERSATIONS_URL + message.conversationID + "/messages", { group: message.conversationID, message: message.text, reflected_field: message.reflectedField || "comments" , attachments: message.attachmentSysIDs, context: context, document_table: conversation && conversation.table ? conversation.table : "" }).then(function(response) { var newMessage = messageFactory.fromObject(response.data.result); $rootScope.$evalAsync(function() { messageBatcherService.removeMessages(message); messageBatcherService.addMessages(newMessage); unreadCountService.reset(message.conversationID); }); return newMessage; }, function(response) { if(response.status === 403) snNotification.show("error", response.data.result); return $q.reject(response) }); } function uploadAttachments(conversation, fileList) { if (fileList.length === 0) return $q.when({}); var files = []; for (var i = 0; i < fileList.length; ++i) files.push(fileList[i]); var message = messageFactory.newPendingAttachmentMessage(conversation, files); messageBatcherService.addMessages(message); unreadCountService.reset(message.conversationID, true); return uploadAttachmentService.attachFiles(conversation, files, { error: function(file) { $rootScope.$broadcast("connect.conversation.attachment_errors", { conversation: conversation, errors: [file.name + ": " + file.error] }); } }).then(function (files){ var array = files.filter(function(file){ return !file.error; }); if (array.length === 0) { messageBatcherService.removeMessages(message); return; } message.attachmentSysIDs = array.map(function(file){ return file.sysID; }); var text = ""; array.forEach(function(file){ text += "File: " + file.name + "\n"; }); message.text = text.trim(); return message; }); } function historyUnloaded(conversationID) { allHistoryLoaded[conversationID] = false; } return { retrieveMessages: retrieveMessages, uploadAttachments: uploadAttachments, send: send, historyUnloaded: historyUnloaded, watch: function(callback) { watches.push(callback) } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/message/directive.virtualScroll.js */ angular.module("sn.connect.message").directive("snVirtualScroll", function($interval, $timeout, $rootScope, messageService, virtualScrollInterval) { "use strict"; var BUFFER_PX = 150; var BATCH_SELECTOR = ".sn-feed-message-holder"; function VirtualScroll($element, conversation) { var scrolling = false; var el = $element.get(0); var debouncedScrollReset = _.debounce(function() { scrolling = false; }, virtualScrollInterval); this.onScroll = function() { scrolling = true; debouncedScrollReset(); }; el.addEventListener("scroll", this.onScroll); this.remove = function() { if (el) { el.removeEventListener("scroll", this.onScroll); } }; this.update = function() { if (scrolling) { return; } var cumulative = 0; var scrollTop = $element.scrollTop(); var cullIndex = -1; $element.find(BATCH_SELECTOR).each(function(index) { cumulative += this.clientHeight; if (index === 0) { return true; } if (scrollTop > cumulative + BUFFER_PX) { cullIndex = index; } else { return false; } }); if (cullIndex === -1) { return; } var scrollHeightBefore = el.scrollHeight; var scrollTopBefore = el.scrollTop; $element.scope().$apply(function() { conversation.messageBatcher.removeBatchesBefore(cullIndex + 1); messageService.historyUnloaded(conversation.sysID); }); var diff = scrollHeightBefore - el.scrollHeight; var newScrollTop = scrollTopBefore - diff; $element.scrollTop(newScrollTop); }; } function loop() { for (var key in conversations) { if (!conversations.hasOwnProperty(key)) { continue; } var vs = conversations[key]; vs.update(); } } function register(conversation, element) { if (!conversation || !conversation.sysID) { return; } var sysID = conversation.sysID; conversations[sysID] = new VirtualScroll( element, conversation ); } function unregister(conversation) { var vs = conversations[conversation.sysID]; if (!vs) { return; } vs.remove(); delete conversations[conversation.sysID]; } var conversations = {}; setInterval(loop, virtualScrollInterval); return { restrict: "A", link: function(scope, element) { register(scope.conversation, element); scope.$watch("conversation", function(newVal, oldVal) { if (!oldVal || !newVal) { return; } if (oldVal.sysID !== newVal.sysID) { unregister(oldVal); register(newVal, element); } }); scope.$on("$destroy", function() { unregister(scope.conversation); }) } }; }); ; ; /*! RESOURCE: /scripts/app.ng_chat/document/js_includes_connect_document.js */ /*! RESOURCE: /scripts/app.ng_chat/document/_module.js */ angular.module("sn.connect.document", []); ; /*! RESOURCE: /scripts/app.ng_chat/document/directive.snLinkCardList.js */ angular.module('sn.connect.document').directive('snLinkCardList', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snLinkCardList.xml'), scope: { links: '=' }, controller: function($scope) { } } }); ; /*! RESOURCE: /scripts/app.ng_chat/document/service.documentLinkMatcher.js */ angular.module('sn.connect.document').service('documentLinkMatcher', function() { "use strict"; function match(str) { if (str.match) { return str.match(/([\w_]+).do\?sys_id=(\w{32})/); } return null; } return { isLink: function(href) { return match(href) !== null; }, getRecordData: function(href) { var linkMatch = match(href); if(!linkMatch) return {} return { table: linkMatch[1], sysID: linkMatch[2] } } } }) ; /*! RESOURCE: /scripts/app.ng_chat/document/service.documents.js */ angular.module('sn.connect.document').service('documentsService', function( $rootScope, $q, nowServer, snHttp, snCustomEvent, documentFactory, snConversationAsideHistory, inFrameSet) { 'use strict'; var documents = {}; function getDocument (documentsSysID) { return documents[documentsSysID]; } function retrieve (table, sysId) { if (!table || !sysId) { var deferred = $q.defer(); deferred.reject("Invalid document parameters -- table: " + table + " sysId: " + sysId); return deferred.promise } var src = nowServer.getURL('record_data', 'table=' + table + '&sys_id=' + sysId); return snHttp.get(src).then(function (response) { var data = response.data; if (!data.sys_id) return; return documents[data.sys_id] = documentFactory.fromObject(data); }); } function show (table, sysID) { if (!inFrameSet) { $rootScope.$broadcast("sn.aside.trigger_control", "record"); } else { var url = (table === 'vtb_board') ? '/$vtb.do?sysparm_board=' + sysID : '/' + table + '.do?sys_id=' + sysID; snCustomEvent.fire('glide:nav_open_url', {url: url, openInForm: true}); } } function create (conversation, data) { conversation.pendingRecord = true; var redirectUrl = encodeURIComponent('/$connect_record_created.do?sysparm_conversation=' + conversation.sysID + '&sysparm_table=' + data.table + '&sysparm_sys_id=$sys_id' + '&sysparm_nostack=yes'); var url = data.table + '.do?sys_id=-1'; if(data.view) url += ('&sysparm_view=' + data.view); url += ('&sysparm_goto_url=' + redirectUrl + '&sysparm_query=' + data.query + "&sysparm_clear_stack=true"); if (inFrameSet) { snCustomEvent.fire('glide:nav_open_url', {url: url, openInForm: true}) } else { var view = { template: '<sn-aside-frame name="pending_record" url="/' + url + '" title="New Record"></sn-aside-frame>', width: '50%', cacheKey: conversation.sysID + '.pending_record.' + data.table + data.actionId }; $rootScope.$broadcast('sn.aside.open', view, "50%"); snConversationAsideHistory.saveHistory(conversation.sysID, view); } } return { getDocument: getDocument, retrieve: retrieve, show: show, create: create }; }); ; /*! RESOURCE: /scripts/app.ng_chat/document/factory.Document.js */ angular.module('sn.connect.document').factory('documentFactory', function (liveLinkFactory) { "use strict"; function getFieldByName(fields, name) { for (var i = 0; i < fields.length; i++) if (fields[i].name == name) return fields[i]; return {}; } function fromObject(data) { var fields = data.fields || []; var sysID = data.sys_id; var table = data.table; var number = getFieldByName(fields, 'number').displayValue; var active = data.active; var url = (data.table === "vtb_board") ? '/' + "$vtb" + '.do?sysparm_board=' + data.sys_id : '/' + data.table + '.do?sys_id=' + data.sys_id + '&sysparm_nameofstack=' + data.sys_id; var link = liveLinkFactory.linkObject(url); return { get table() { return table; }, get sysID() { return sysID; }, get fields() { return fields; }, get number() { return number; }, get link () { return link; }, get active () { return active; } }; } return { fromObject: fromObject } }); ; ; /*! RESOURCE: /scripts/app.ng_chat/util/js_includes_connect_util.js */ /*! RESOURCE: /scripts/app.ng_chat/util/_module.js */ angular.module("sn.connect.util", ["sn.connect.resource", "sn.common.attachments", "sn.common.accessibility"]); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.connectConversationBarToggle.js */ angular.module('sn.connect').directive('connectConversationBarToggle', [ 'getTemplateUrl', function(getTemplateUrl) { "use strict"; return { templateUrl : getTemplateUrl('connectConversationBarToggle.xml'), restrict : 'E', replace : true, controller : ['$scope', 'paneManager', function($scope, paneManager) { $scope.unreadMessages = 0; $scope.state = "closed"; $scope.toggleConversationList = function() { paneManager.togglePane('connect:conversation_list', true); }; CustomEvent.observe("connect:conversation_list:state", function(state) { $scope.state = state; }); CustomEvent.observe('connect:message_notification.update', function(val) { $scope.unreadMessages = val; }); $scope.formattedUnreadCount = function(count) { return (count <= 99) ? count : "99+"; } }], link: function(scope, element) { scope.$on('pane.collapsed', function($event, position, isCollapsed, autoFocus) { if (isCollapsed && autoFocus) { element.focus(); } }); } } }]); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snConnectHeader.js */ angular.module('sn.connect').directive('snConnectHeader', function (getTemplateUrl, activeConversation) { 'use strict'; return { templateUrl : getTemplateUrl('snConnectHeader.xml'), restrict : 'E', replace : true, controller : function($scope) { var asideTab = 'members'; $scope.toggleAside = function (side) { $scope.$root.$broadcast('connect.pane.toggle.' + side); if (side === 'right') { $scope.$root.$broadcast('sn.aside.trigger_control', asideTab); } }; $scope.$on('sn.aside.trigger_control', function (event, newAsideTab) { asideTab = newAsideTab; }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snConnectContent.js */ angular.module('sn.connect').directive('snConnectContent', function (getTemplateUrl) { 'use strict'; return { templateUrl : getTemplateUrl('snConnectContent.xml'), restrict : 'E', replace : true, transclude: true, link: function (scope) { function togglePane (pane) { return function () { if (scope.activePane !== pane) scope.activePane = pane; else delete scope.activePane; }; } function closePane () { delete scope.activePane; } scope.$on('connect.pane.toggle.left', togglePane('left')); scope.$on('connect.pane.toggle.right', togglePane('right')); scope.$on('connect.pane.close', closePane); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snActions.js */ angular.module('sn.connect.util').directive('snActions', function(getTemplateUrl) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl("snActions.xml"), replace: true }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snActionsMenu.js */ angular.module("sn.connect.util").directive("snActionsMenu", function(getTemplateUrl) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl("snActionsMenu.xml"), scope: { conversation: "=" }, replace: true, link: function(scope, elem) { if(elem.hideFix) elem.hideFix(); }, controller: function($scope, $timeout, $rootScope) { $scope.runAction = function($event, chatAction) { if(chatAction.isActive) { $event.preventDefault(); $event.stopPropagation(); return; } if(chatAction.requiresArgs) { $timeout(function() { $scope.conversation.chatActions.currentAction = chatAction; $scope.$emit("connect.chat_action.require_options", $scope.conversation); }, 0, false) } else { chatAction.trigger($scope.conversation); } }; $scope.addAttachment = function() { $rootScope.$broadcast("connect.attachment_dialog.open", $scope.conversation.sysID); }; $scope.openDropup = function($event) { $event.stopPropagation(); angular.element($event.target) .siblings(".dropdown-menu") .dropdown("toggle"); }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snDropTargetPopup.js */ angular.module("sn.connect.util").directive("snDropTargetPopup", function(getTemplateUrl, $window) { "use strict"; return { restrict: "E", templateUrl: getTemplateUrl('snDropTargetPopup.xml'), replace: true, scope: { conversation: "=" }, link: function(scope, element) { var messageElement = element.find(".drop-target-message"); scope.showDropTarget = false; scope.$on("connect.drop_target_popup.show", function(e, conversationID) { if ($window.navigator.userAgent.indexOf("Firefox") > -1) return; if (conversationID !== scope.conversation.sysID) return; scope.showDropTarget = true; element.css({"z-index": 10}); element.velocity({ opacity: 1 }, { duration: 300, easing: "easeOutCubic" }); messageElement.velocity({ "padding-top": "0px" }, { duration: 300, easing: "easeOutCubic" }); }); scope.$on("connect.drop_target_popup.hide", function(e, conversationID) { if ($window.navigator.userAgent.indexOf("Firefox") > -1) return; if (conversationID !== scope.conversation.sysID) return; element.velocity({ opacity: 0 }, { duration: 300, easing: "easeOutCubic", complete: function() { scope.showDropTarget = false; element.css({"z-index": -1}) } }); messageElement.velocity({ paddingTop: "40px" }, { duration: 300, easing: "easeOutCubic" }); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snLoadingBar.js */ angular.module('sn.connect.util').directive('snLoadingBar', function() { "use strict"; return { restrict: 'E', template: "<div class='sn-loading-bar'></div>", replace: true, link: function(scope, element) { scope.$on("connect.loading-bar.start", function() { element.velocity({ width: 90 + "%" }, { easing: "linear", duration: 450 }); }); scope.$on("connect.loading-bar.finish", function() { element.velocity({ width: 100 + "%" }, { easing: "linear", duration: 50 }).velocity({ opacity: 0 }, { easing: "linear", duration: 300 }).velocity({ width: 0, opacity: 1 }, { duration: 0 }) }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snPulse.js */ angular.module('sn.connect.util').directive('snPulse', function($timeout) { "use strict"; return { restrict : 'A', link: function (scope, element, attrs) { var timeouts = scope.pulseTimeouts ? angular.fromJson(attrs.pulseTimeouts) : [10000, 10000, 10000, 10000]; var classes = ['pulse-off', 'pulse-positive', 'pulse-warning', 'pulse-danger']; var index = 0; var timeout; var enabled = true; scope.$watch(function () { return attrs.pulseEnabled; }, function () { enabled = attrs.pulseEnabled === 'true'; if (!enabled) { $timeout.cancel(timeout); element.removeClass(classes.join(' ')); } }); scope.$watch(function () { return attrs.pulseTimestamp; }, function () { index = 0; $timeout.cancel(timeout); if (attrs.pulseTimestamp && enabled) { var start = parseInt(attrs.pulseTimestamp, 10); var now = Date.now(); var diff = now - start; var elapsedTime = 0; for (var i = 0; i < timeouts.length; i++) { if (diff >= elapsedTime) { index = i; elapsedTime += timeouts[i]; } } updateClass(); } }); function updateClass () { element.removeClass(classes.join(' ')); if (index > 0) { element.addClass(classes[index]); } if (index < timeouts.length - 1) { timeout = $timeout(updateClass, timeouts[index + 1]); index++; } } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.liveIntroduction.js */ angular.module('sn.connect').directive('liveIntroduction', function(getTemplateUrl) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('liveIntroduction.xml'), replace: true, scope : {}, controller: function ($scope, activeConversation) { $scope.activeConversation = activeConversation; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.messageNotifier.js */ angular.module('sn.connect.util').service('messageNotifier', function( $window, $q, snNotifier, i18n, profiles, pageLoadTimestamp, liveProfileID, snTabActivity, conversations, userPreferences, notificationPreferences, activeConversation, messageService, titleFlasher) { "use strict"; var lastMessageTime = pageLoadTimestamp || 0; var glideNotificationText; var securedLinkNotificationText; i18n.getMessages(["New Message From {0}: {1}", "You don't have permission to access this document/content"], function (results) { glideNotificationText = results["New Message From {0}: {1}"]; securedLinkNotificationText = results["You don't have permission to access this document/content"]; }); function notify(message) { var shouldExit = !(message.isFromPeer || message.isSystemMessage) || messageIsOlderThanMostRecentNotification(message); if(shouldExit) return; if (!notificationPreferences.globalPreferences.desktop) return; lastMessageTime = message.timestamp + 1; if(!snTabActivity.isPrimary) return; var promises = []; var allowWebNotifications = false; var conversationID = message.conversationID; promises.push(userPreferences.getPreference("connect.notifications.desktop").then(function(value) { allowWebNotifications = angular.isString(value) ? value === "true" : value; })); $q.all(promises).then(function() { if(!allowWebNotifications) return; var preferences = notificationPreferences.get(message.conversationID); if (preferences.desktop === "off") return; if (preferences.desktop === "mention") { if (!message.mentions || message.mentions.length === 0) return; var mentioned = message.mentions.some(function(mention) { return mention.mention === liveProfileID; }); if (!mentioned) return; } if (message.isSystemMessage && !preferences.systemMessage) return; titleFlasher.flash(); var notifyAvatar = null; conversations.get(conversationID).then(function(conversation) { var promise; if (message.conversationID && message.isSystemMessage) { var profile = (conversation.profileData || conversation.profile); if(profile) promise = $q.when(profile.name); else { promise = profiles.getAsync(message.profile).then(function(profile) { return (profile && profile.name) ? profile.name : "Unknown User"; }); } } else { promise = profiles.getAsync(message.profile).then(function(profile) { if (conversation.isGroup) { notifyAvatar = conversation.avatar || null; return (profile && profile.name) ? profile.name + " in " + conversation.name : "Unknown User" + " in " + conversation.name; } else { notifyAvatar = profile.avatar || null; return (profile && profile.name) ? profile.name : "Unknown User"; } }); } promise.then(function(title) { var body; if (snNotifier().canUseNativeNotifications()) { body = message.cleanText; } else { body = glideNotificationText.replace(/\{0\}/, title).replace(/\{1\}/, message.cleanText); } snNotifier().notify(title, { body: body, lifespan: 7000, icon: notifyAvatar || '/native_notification_icon.png', tag: message.sysID, onClick: function () { activeConversation.conversation = conversation; } }); }); }); }); } function messageIsOlderThanMostRecentNotification(message) { return message.timestamp < lastMessageTime; } return { notify: notify, registerMessageServiceWatch: function(additionalRequirements) { messageService.watch(function(message) { if (activeConversation.sysID === message.conversationID && snTabActivity.idleTime < snTabActivity.defaultIdleTime && snTabActivity.isVisible) return; if(angular.isFunction(additionalRequirements) && !additionalRequirements(message)) return; notify(message); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.audioNotifier.js */ angular.module('sn.connect.util').service('audioNotifier', function( notifySound, $timeout, messageService, snTabActivity, pageLoadTimestamp, notificationPreferences, userPreferences, $q, liveProfileID) { "use strict"; var audio = new Audio(notifySound), AUDIO_COOLDOWN = Math.max(1000, (audio.duration * 1000 + 100)), cdTimer, notifyQueued = false, notifyAvailable = true, lastMessageTime = pageLoadTimestamp || 0; function notify(message) { if(angular.isString(message)) message = {conversationID: message, timestamp: lastMessageTime + 1}; if(message.timestamp < lastMessageTime) return; if('isFromPeer' in message && !message.isFromPeer) return; if(!notifyAvailable) return notifyQueued = true; lastMessageTime = message.timestamp + 1; if(!snTabActivity.isPrimary) return; notifyAvailable = false; notifyQueued = false; function reset() { notifyAvailable = true; } var promises = [], allowAudioNotifications = false; promises.push(userPreferences.getPreference("connect.notifications.audio").then(function(value) { allowAudioNotifications = angular.isString(value) ? value === "true" : value; })); $q.all(promises).then(function() { if (!allowAudioNotifications) return reset(); if (message.conversationID) { var preferences = notificationPreferences.get(message.conversationID); if (preferences.audio === "off") return reset(); if (preferences.audio === "mention") { if(!message.mentions || message.mentions.length === 0) return reset(); var mentioned = message.mentions.some(function (mention) { return mention.mention = liveProfileID; }); if (!mentioned) return reset(); } } audio.play(); cdTimer = $timeout(function() { reset(); if (notifyQueued) notify(message); }, AUDIO_COOLDOWN, false); }); } return { notify: notify, registerMessageServiceWatch: function(activeConversation, additionalRequirements) { messageService.watch(function(message) { if ((!activeConversation.sysID || activeConversation.sysID === message.conversationID) && snTabActivity.idleTime < snTabActivity.defaultIdleTime && snTabActivity.isVisible) return; if (angular.isFunction(additionalRequirements) && !additionalRequirements(message)) return; notify(message); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.uploadAttachment.js */ angular.module('sn.connect.util').service('uploadAttachmentService', function( $q, $rootScope, $timeout, snAttachmentHandler, maxAttachmentSize, liveProfileID, i18n, screenReaderStatus) { "use strict"; var MAX_SIZE = maxAttachmentSize * 1024 * 1024; var attachmentHandlers = []; var filesInProgress = []; var uploadSuccess = "{0} successfully uploaded"; var uploadFailure = "Failed to upload {0}: {1}"; i18n.getMessages([uploadSuccess, uploadFailure], function(results) { uploadSuccess = results[uploadSuccess]; uploadFailure = results[uploadFailure]; }); function remove(file) { var index = filesInProgress.indexOf(file); if (index < 0) return; return filesInProgress.splice(index, 1)[0]; } function apply(fileFns, fnType, file) { var fn = fileFns[fnType]; if (fn) fn(file); file.state = fnType; $rootScope.$broadcast('attachments_list.upload.' + fnType, file); } function progress(fileFns, file, loaded, total) { total = total || file.size; if (angular.isDefined(loaded)) { file.loaded = loaded; file.progress = Math.min(100.0 * loaded / total, 100.0); } else { file.loaded = total; file.progress = 100.0; } apply(fileFns, "progress", file); } function getAttachmentHandler(conversation) { var sysID = conversation.sysID; var attachmentHandler = attachmentHandlers[sysID]; if (!attachmentHandler) attachmentHandler = attachmentHandlers[sysID] = conversation.isPending ? snAttachmentHandler.create("live_profile", liveProfileID) : snAttachmentHandler.create("live_group_profile", sysID); return attachmentHandler; } function attachFile (conversation, file, fileFns) { if(file.size > MAX_SIZE) { file.error = file.name + ' size exceeds the limit of ' + maxAttachmentSize + ' MB'; apply(fileFns, "error", file); return $q.when(file); } filesInProgress.push(file); apply(fileFns, "start", file); progress(fileFns, file, 0); return getAttachmentHandler(conversation).uploadAttachment(file, null, { progress: function (event) { progress(fileFns, event.config.file, event.loaded, event.total); } }).then(function(response) { remove(file); file.sysID = response.sys_id; progress(fileFns, file); apply(fileFns, "success", file); screenReaderStatus.announce(i18n.format(uploadSuccess, file.name)); return file; }, function(errorMessage) { remove(file); file.error = errorMessage; apply(fileFns, "error", file); screenReaderStatus.announce(i18n.format(uploadFailure, file.name, errorMessage)); return file; }); } function openFileSelector($event) { $event.stopPropagation(); var target = angular.element($event.currentTarget); $timeout(function() { target.parent().find('input').click(); }); } return { get filesInProgress() { return Object.keys(filesInProgress).map(function (key) { return filesInProgress[key]; }); }, attachFiles: function(conversation, files, fileFns) { fileFns = fileFns || {}; var promises = []; angular.forEach(files, function(file) { promises.push(attachFile(conversation, file, fileFns)); }); return $q.all(promises); }, openFileSelector: openFileSelector }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.fileSizeConverter.js */ angular.module("sn.connect.util").service("fileSizeConverter", function() { "use strict"; return { getByteCount: function(bytes, precision) { if (bytes.slice(-1) === 'B') return bytes; var kb = 1024; var mb = kb * 1024; var gb = mb * 1024; if ((bytes >= 0) && (bytes < kb)) return bytes + ' B'; else if ((bytes >= kb) && (bytes < mb)) return (bytes / kb).toFixed(precision) + ' KB'; else if ((bytes >= mb) && (bytes < gb)) return (bytes / mb).toFixed(precision) + ' MB'; else if (bytes >= gb) return (bytes / gb).toFixed(precision) + ' GB'; else return bytes + ' B'; } }; }) ; /*! RESOURCE: /scripts/app.ng_chat/util/service.notificationPreferences.js */ angular.module('sn.common.glide').factory("notificationPreferences", function ( snHttp, $q, amb, unwrappedHTTPPromise, snNotifier, initGlobalNotificationPreferences, urlTools, snCustomEvent, isLoggedIn) { "use strict"; var BASE_URL = isLoggedIn? "/api/now/connect/conversations/" : "/api/now/connect/support/anonymous/conversations/"; var preferencesCache = {}; function fromGlobalObject(rawGlobalPreference) { function update(field, preferenceValue) { rawGlobalPreference[field] = preferenceValue; var eventName = 'connect.notifications.' + field; var targetURL = urlTools.getURL('user_preference', { "sysparm_pref_name": eventName, "sysparm_action": "set", "sysparm_pref_value": "" + !!preferenceValue }); snHttp.get(targetURL).then(function() { snCustomEvent.fireAll(eventName + '.update', preferenceValue); }); } snCustomEvent.on('connect.notifications.mobile.update', function(newVal) { rawGlobalPreference.mobile = newVal; }); snCustomEvent.on('connect.notifications.desktop.update', function(newVal) { rawGlobalPreference.desktop = newVal; updateDesktopNotificationPermission(); }); snCustomEvent.on('connect.notifications.email.update', function(newVal) { rawGlobalPreference.email = newVal; }); snCustomEvent.on('connect.notifications.audio.update', function(newVal) { rawGlobalPreference.audio = newVal; }); function updateDesktopNotificationPermission() { if (!rawGlobalPreference.desktop) return; if (snNotifier().canUseNativeNotifications()) return; snNotifier().requestNotificationPermission(); } updateDesktopNotificationPermission(); return { get mobile() { return rawGlobalPreference.mobile }, get desktop() { return rawGlobalPreference.desktop; }, get email() { return rawGlobalPreference.email; }, get audio() { return rawGlobalPreference.audio; }, set mobile(value) { return update('mobile', value); }, set desktop(value) { return update('desktop', value); }, set email(value) { return update('email', value); }, set audio(value) { return update('audio', value); } } } var globalPreferences = fromGlobalObject(initGlobalNotificationPreferences); function fromObject(rawPreferences) { function update(field, value) { rawPreferences[field] = value; if (rawPreferences.loading) return; snHttp.post(BASE_URL + rawPreferences.sys_id + "/notifications", rawPreferences).then(function (response) { addRaw(response.data.result); }); } return { get loading() { return rawPreferences.loading; }, get mobile() { return rawPreferences.push_notification_preference; }, get desktop() { return rawPreferences.browser_notification_preference; }, get email() { return rawPreferences.email_notification_preference; }, get audio() { return rawPreferences.audio_notification_preference; }, get canEmail() { return rawPreferences.can_email; }, get systemMessage() { return rawPreferences.system_message_notification_preference; }, set mobile(value){ update('push_notification_preference', value); }, set desktop(value){ update('browser_notification_preference', value); }, set email(value){ update('email_notification_preference', value); }, set audio(value){ update('audio_notification_preference', value); }, set canEmail(value){ update('can_email', value); }, set systemMessage(value){ update('system_message_notification_preference', value); } } } function getPreferences(conversationID) { if (!preferencesCache[conversationID]) { addRaw({ sys_id: conversationID, push_notification_preference: 'all', browser_notification_preference: 'all', email_notification_preference: 'all', audio_notification_preference: 'all', can_email: true, system_message_notification_preference: true, loading: true }); snHttp.get(BASE_URL + conversationID + "/notifications").then(function (response) { addRaw(response.data.result); }); } return preferencesCache[conversationID]; } function addRaw(preference){ preferencesCache[preference.sys_id] = fromObject(preference); } return { get: getPreferences, addRaw: addRaw, globalPreferences: globalPreferences }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snAutoScroll.js */ angular.module("sn.connect.util").directive('snAutoScroll', function($timeout, $window, $q, inFrameSet, activeConversation) { "use strict"; function throttle(func, wait) { var initialCall = true, deferred = $q.defer(), timerId; if (typeof func != 'function') { return; } function throttled() { if(timerId) { return; } if(initialCall) { initialCall = false; deferred.resolve(func()); return deferred.promise; } timerId = $timeout(function() { timerId = undefined; deferred.resolve(func()); }, wait, false); return deferred.promise; } return throttled; } return { restrict : 'A', scope: { onScrollToTop: "&" }, link: function(scope, element) { var HISTORY_THROTTLE_MS = 100; var SCROLL_THROTTLE_MS = 500; var RESIZE_THROTTLE_MS = 500; var STICKY_ZONE_HEIGHT = 32; var shouldStick = true; var activeTopRequest = false; var resizeTrigger = false; var el = element[0]; var prevScrollPos = el.scrollTop; var lastScrollHeight = el.scrollHeight; var onScrollTop, heightAdjustUnwatch; function enforceSticky() { if (shouldStick) { el.scrollTop = el.scrollHeight; } } function forceScroll() { shouldStick = true; enforceSticky(); } var scrollHandler = throttle(function() { if (resizeTrigger) { resizeTrigger = false; return; } var scrollPos = el.scrollTop; var scrollHeight = el.scrollHeight; var scrollUp = prevScrollPos > scrollPos; prevScrollPos = scrollPos; if (scrollUp) { shouldStick = false; if(angular.isFunction(scope.onScrollToTop) && !onScrollTop) { onScrollTop = throttle(scope.onScrollToTop, HISTORY_THROTTLE_MS); } if (scrollPos === 0) { var oldScrollHeight = scrollHeight; if (!activeTopRequest) { activeTopRequest = true; var topBatch = element.find(".sn-feed-message-holder:first-child"); var topBatchLastMessage = topBatch.scope().batch.lastMessage; onScrollTop().finally(function(result) { activeTopRequest = false; if(!heightAdjustUnwatch) { heightAdjustUnwatch = scope.$on("ngRepeat.complete", function() { var heightAdjust = 0; var potentialConflict = topBatch.prev(); var newTopBatch = element.find(".sn-feed-message-holder:first-child"); if (potentialConflict.length && potentialConflict.scope().batch.lastMessage.sysID === topBatchLastMessage.sysID) { heightAdjust = topBatch[0].clientHeight; } else if(topBatch[0] !== newTopBatch[0]) { heightAdjust = topBatch.find('.sn-feed-message_date').outerHeight(true); } el.scrollTop = el.scrollHeight - oldScrollHeight - heightAdjust; heightAdjustUnwatch(); heightAdjustUnwatch = void(0); }); } return result; }); } } return; } if (scrollPos + el.clientHeight + STICKY_ZONE_HEIGHT >= scrollHeight) { shouldStick = true; enforceSticky(); } lastScrollHeight = scrollHeight; }, SCROLL_THROTTLE_MS); var resizeHandler = throttle(function() { resizeTrigger = true; if (el.scrollTop <= STICKY_ZONE_HEIGHT) { shouldStick = true; } enforceSticky(); }, RESIZE_THROTTLE_MS); el.scrollTop = el.scrollHeight; $timeout(function() { el.scrollTop = el.scrollHeight; prevScrollPos = el.scrollTop; }, 0, false); angular.element(el).on('scroll', scrollHandler); angular.element($window).on('resize', resizeHandler); scope.$on('connect.auto_scroll.scroll_to_bottom', forceScroll); scope.$on('connect.auto_scroll.jump_to_bottom', forceScroll); scope.$watch(enforceSticky); if(!inFrameSet) scope.$watch(function() { return activeConversation.sysID; }, function(newVal, oldVal) { if(newVal === oldVal) return; forceScroll(); }); scope.$on("$destroy", function() { angular.element(el).off('scroll', scrollHandler); angular.element($window).off('resize', resizeHandler); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snClickToEdit.js */ angular.module('sn.connect.util').directive('snClickToEdit', function($timeout, getTemplateUrl) { "use strict"; return { restrict : 'E', scope : { currText: "=text", onSaveText: "&onsavetext", canEdit: "=condition" }, transclude: true, templateUrl: getTemplateUrl("snClickToEdit.xml"), replace: true, controller: function($scope) { $scope.editingText = false; $scope.inputClick = function($event) { $event.stopPropagation(); if (!$scope.canEdit) return; $scope.editingText = true; $scope.prevText = $scope.currText; } $scope.saveText = function() { if (!$scope.editingText || ($scope.prevText === $scope.currText) || !$scope.canEdit) { $scope.editingText = false return; } $scope.editingText = false; if ($scope.onSaveText) $scope.onSaveText({text: $scope.currText}); } $scope.cancelEdit = function() { $scope.editingText = false; $scope.currText = $scope.prevText; } } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snEscape.js */ angular.module('sn.connect.util').directive('snEscape', function() { 'use strict'; return function(scope, element, attrs) { element.bind("keyup", function(event) { if (event.which !== 27) return; scope.$apply(function() { scope.$eval(attrs.snEscape); }); event.preventDefault(); }); }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snFocusOnConversation.js */ angular.module('sn.connect.util').directive('snFocusOnConversation', function($timeout, $parse, $window, activeConversation) { 'use strict'; return { restrict: "A", link: function(scope, element, attr) { if (attr.disableAutofocus) return; scope.snFocusOnConversation = $parse(attr.snFocusOnConversation)(scope); scope.$watch(function(){ return activeConversation.conversation; }, function (conversation) { if(window.getSelection().toString() !== "") return; if (!scope.snFocusOnConversation) return; if (!conversation) return; if (conversation.sysID !== scope.snFocusOnConversation.sysID) return; $timeout(function () { focusOnMessageInput(); }); }); function focusOnMessageInput() { if ($window.ontouchstart) return; $timeout(function () { element.focus(); }); } focusOnMessageInput(); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snLoadingIndicator.js */ angular.module('sn.connect.util').directive('snLoadingIndicator', function(getTemplateUrl) { "use strict"; return { restrict : 'E', scope: { active: "=" }, transclude: true, templateUrl: getTemplateUrl("snLoadingIndicator.xml"), replace: true } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snOnload.js */ angular.module('sn.connect.util').directive('snOnload', function() { return { scope: { callBack: '&snOnload' }, link: function(scope, element){ element.on('load', function(){ scope.callBack(); scope.$apply(); }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snOptions.js */ angular.module('sn.connect.util').directive('snOptions', function(getTemplateUrl) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl("snOptions.xml"), replace: true }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snPane.js */ angular.module('sn.connect.util').directive('snPane', function($timeout, getTemplateUrl, paneManager) { 'use strict'; return { restrict: 'E', replace: true, transclude: true, templateUrl: getTemplateUrl('snPane.xml'), scope: { paneCollapsed: '=', panePosition: '@', paneResizeable: '@', paneWidth: '=', paneToggle: '@' }, link: function(scope, element) { var scrollPromise; var mouseHeldDown = false; var mouseClicked = true; scope.toggleConversationList = function($event) { if($event && $event.keyCode === 9) return; paneManager.togglePane('connect:conversation_list', true); }; scope.$watch('paneWidth', function () { if (scope.paneWidth) { element.width(scope.paneWidth); } }); scope.isMobile = function () { return angular.element('html').width() <= 800; }; scope.scrollMousedown = function (moveBy) { scrollPromise = $timeout(function () { mouseHeldDown = true; mouseClicked = false; updateScrollPosition(moveBy); }, 300); }; scope.scrollMouseup = function () { $timeout.cancel(scrollPromise); scrollPromise = void(0); if (!mouseClicked) { mouseHeldDown = false; } }; scope.scrollUpCick = function () { if (mouseClicked) { var scrollContainer = element.find('.pane-scroll-container'); updateScrollPosition(-scrollContainer.height()); } mouseClicked = true; mouseHeldDown = false; }; scope.scrollDownCick = function () { if (mouseClicked) { var scrollContainer = element.find('.pane-scroll-container'); updateScrollPosition(scrollContainer.height()); } mouseClicked = true; mouseHeldDown = false; }; scope.openConnect = function($event) { $event.stopPropagation(); if($event && $event.keyCode === 9) return; window.open("$c.do", "_blank"); }; function updateScrollPosition (moveBy) { var scrollContainer = element.find('.pane-scroll-container'); scrollContainer.animate({scrollTop: scrollContainer[0].scrollTop + moveBy}, 300, 'linear', function () { if (mouseHeldDown) { updateScrollPosition(moveBy); } }); } function updateScrollButtons () { var scrollContainer = element.find('.pane-scroll-container'); if (scope.paneCollapsed && !scope.isMobile() && scrollContainer.get(0)) { if (scrollContainer.outerHeight() < scrollContainer.get(0).scrollHeight) { } else { } } else { } } scope.togglePane = function() { scope.paneCollapsed = !scope.paneCollapsed; scope.$root.$broadcast('pane.collapsed', scope.panePosition, scope.paneCollapsed); updateScrollButtons(); } angular.element(window).on('resize', function() { updateScrollButtons(); }); $timeout(updateScrollButtons); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snPaneManager.js */ angular.module('sn.connect.util').directive('snPaneManager', function() { 'use strict'; return { restrict : 'A', link: function(scope, element, attrs) { scope.resourcePaneClass = attrs.snPaneManager; scope.resourcePaneClasses = { 'closed': 'pane-closed', 'large': 'pane-large large-resource-pane', 'compact': 'pane-compact compact-resource-pane' }; scope.$on('conversation.resource.open', function($evt, data) { scope.$broadcast('conversation.resource.show', data); scope.resizePane(data.type); }); scope.$on('conversation.resource.close', function() { scope.resizePane('closed'); }); scope.resizePane = function (type) { angular.forEach(scope.resourcePaneClasses, function (resourcePaneClass) { element.removeClass(resourcePaneClass); }); scope.resourcePaneClass = scope.resourcePaneClasses[type || 'closed']; element.addClass(scope.resourcePaneClass); }; scope.resizePane(attrs.snPaneManager); } } }) ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snPod.js */ angular.module('sn.connect.util').directive('snPod', function (getTemplateUrl) { 'use strict'; return { restrict: 'E', templateUrl: getTemplateUrl("snPod.xml"), replace: true, scope: { user: '=', label: '=label', showLabel: '=showLabel', removeTitle: '@removeTitle', removeClick: '&removeClick' }, controller: function ($scope) { $scope.onRemove = function ($event) { if ($scope.removeClick) { $event.stopPropagation(); $scope.removeClick({$event: $event}); } }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snPopOver.js */ angular.module('sn.connect.util').directive('snPopover', function($window, $rootScope) { 'use strict'; if($window.jQuery) $window.jQuery('html').on('click', function(e) { $rootScope.$broadcast("popover-html-click", e); }); return { restrict : 'A', scope: { options: '=snPopover', enabled: '=snPopoverEnabled' }, link: function(scope, element) { scope.popoverID = scope.$id; function getContent () { if (!$content) { if(angular.isObject(scope.options) && scope.options.target) { $content = angular.element(scope.options.target).detach().show(); } else if(typeof scope.options == "string") { $content = angular.element(scope.options).detach().show(); } else { $content = element.siblings('.popover-body').eq(0).detach().show(); } } return $content; } var $content = getContent(); if (!angular.element('html').hasClass('touch')) { if(scope.options && scope.options.popoverID) scope.popoverID = scope.options.popoverID; var options = { placement: 'left', html: true, content: getContent, container: 'body', template: '<div scope-id="' + scope.popoverID + '" class="popover" role="tooltip" onClick="event.stopPropagation();"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>', trigger: 'hover', hideOnBlur: true, onShow: function(){}, onHide: function(){} }; angular.extend(options, scope.options); var oldHide = element[0].hide; if (oldHide) { element[0].prototypeHide = oldHide; element[0].hide = function() { if (!jQuery.event.triggered && this.prototypeHide){ this.prototypeHide(); } } } if(!element.popover) return; scope.$popover = element.popover(options); scope.$popover.on("hidden.bs.popover", function(e) { options.onHide(e); }); scope.$popover.on("shown.bs.popover", function(e) { options.onShow(e); }); scope.$watch('enabled', function () { element.popover(scope.enabled || scope.enabled == undefined ? 'enable' : 'disable'); }); scope.$on('$destroy', function () { angular.element('[scope-id=' + scope.popoverID + ']').remove(); }); scope.$on('popover-html-click', function($evt, e) { if(element.find(e.target).length > 0 || options.hideOnBlur === false) return; element.popover('hide'); }); } } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snAriaUnreadNotifications.js */ angular.module('sn.connect.util').directive('snAriaUnreadNotifications', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snAriaUnreadNotifications.xml'), controller: function($scope, $timeout) { $scope.messages = []; $scope.$on("connect.aria.new_unread_message", function(evt, message) { $scope.messages.push(message); $timeout(function() { $scope.messages.shift(); }, 5000, false); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snRepeatEventEmitter.js */ angular.module('sn.connect.util').directive('snRepeatEventEmitter', function() { 'use strict'; return { restrict: 'A', link: function (scope) { if (scope.$first === true) { scope.$evalAsync(function() { scope.$emit("ngRepeat.complete"); }); } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/filter.truncate.js */ angular.module('sn.connect.util').filter('truncate', function() { "use strict"; var MAX_LENGTH = 75; return function(text) { if (text) { if (text.length <= MAX_LENGTH) { return text; } return text.substring(0,MAX_LENGTH).trim() + "..."; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.snHttp.js */ angular.module('sn.connect.util').factory('snHttp', function ($http, $q, $rootScope, $timeout) { $http.defaults.headers.common["Cache-Control"] = "no-cache"; $http.defaults.headers.common["Pragma"] = "no-cache"; var http = function () { if (arguments.length) { var deferred = $q.defer(); $http.apply($http, arguments).then(success(deferred), error(deferred)); return deferred.promise; } }; var retryCodes = [0]; var errorCount = 0; var responseWithError; var retryPromise; var pollPeriods = [10,20,30,60,90,120]; var retryListener; function success (deferred) { return function (response) { if (errorCount > 0) { errorCount = 0; responseWithError = void(0); $rootScope.$broadcast('http-error.hide'); pollPeriods = [10,20,30,60,90,120]; if(retryListener) retryListener(); } deferred.resolve(response); }; } function error (deferred) { return function (response) { if (retryCodes.indexOf(response.status) < 0) { deferred.reject(response); return; } errorCount++; if (errorCount === 2 || (response.config && response.config.retry)) { responseWithError = response; var pollTime = pollPeriods.shift() || 120; $rootScope.$broadcast('http-error.show', pollTime); retryPromise = $timeout(function () { response.config.retry = true; http(response.config); }, pollTime * 1000); retryListener = $rootScope.$on('http-error.retry', function () { $timeout.cancel(retryPromise); retryPromise = void(0); responseWithError.config.retry = true; http(responseWithError.config); retryListener(); }); } deferred.reject(response); }; } var methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'jsonp', 'trace']; angular.forEach(methods, function (method) { http[method] = function() { var deferred = $q.defer(); $http[method].apply($http, arguments).then(success(deferred), error(deferred)); return deferred.promise; }; }); return http; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.sysNumberData.js */ angular.module("sn.connect.util").factory("sysNumberData", function(snHttp, nowServer) { "use strict"; return { getListPrefixes: function() { var url = nowServer.getURL("number_data"); return snHttp.get(url).then(function(result) { return result.data }); } } }) ; /*! RESOURCE: /scripts/app.ng_chat/util/factory.commandFactory.js */ angular.module('sn.connect.util').factory('commandFactory', function($http, $rootScope) { var service = {}; var SN_Commands = { "commands": { 'key': 'commands', 'args': 0, 'value': function() { angular.element("#commandPopupModal").detach().appendTo("body").modal()}, 'description': "Displays a list of all available commands. If unknown command is entered, defaults to this." }, "snip": { 'key': 'snip', 'args': 0, 'value': function () { $rootScope.$broadcast("conversation.enable_snippet_search", true); }, 'description': "Opens snippet search window" } }; var Customer_Commands = {}; var commands = angular.extend(SN_Commands, Customer_Commands); service.commands = commands; service.commandNames = []; service.arr = Object.keys(commands); for (var i = 0; i < service.arr.length; i++) service.arr[i] = "/" + service.arr[i]; service.commandNames = Object.keys(commands); service.setMessageFilter = function (m) { service.messageFilter = m; }; service.getMessageFilter = function() { return service.messageFilter; } service.addSNCommand = function (key, args, value, description) { if (commands[key]) return false; commands[key] = { 'key': key, 'args': args, 'value': value, 'official': true, 'description': description }; return true; }; service.getCommand = function(entry) { var tokens = entry.split(" "); tokens[0] = tokens[0].slice(1); var key = tokens[0] || "commands"; var comm = commands[key] || commands["commands"]; var f = comm['value']; return f(entry); }; return service; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/factory.snHotKey.js */ angular.module("sn.connect.util").factory("snHotKey", function() { "use strict"; var commonKeys = { "ENTER": 13, "TAB": 9, "ESC": 27, "ESCAPE": 27, "SPACE": 32, "LEFT": 37, "UP": 38, "RIGHT": 39, "DOWN": 40 }; var modKeys = { "SHIFT": "shiftKey", "CTRL": "ctrlKey", "CONTROL": "ctrlKey", "ALT": "altKey", "OPT": "altKey", "OPTION": "altKey", "CMD": "metaKey", "COMMAND": "metaKey", "APPLE": "metaKey", "META": "metaKey" }; function HotKey(options) { options = options || {}; this.callback = angular.isFunction(options.callback) ? options.callback : void(0); this.modifiers = { shiftKey: false, ctrlKey: false, altKey: false, metaKey: false }; if(typeof options.key === "number") this.key = options.key; else if(typeof options.key === "string") { if (options.key.length === 1) this.key = options.key.toUpperCase().charCodeAt(0); else this.key = commonKeys[options.key.toUpperCase()]; } if(options.modifiers) { var modifier; if(typeof options.modifiers === "string") { modifier = modKeys[options.modifiers.toUpperCase()]; this.modifiers[modifier] = true; } else if(angular.isArray(options.modifiers)) { for (var i = 0, len = options.modifiers.length; i < len; i++) { modifier = modKeys[options.modifiers[i].toUpperCase()]; this.modifiers[modifier] = true; } } } } HotKey.prototype.trigger = function(e) { for(var key in this.modifiers) if(this.modifiers.hasOwnProperty(key)) if(this.modifiers[key] !== e[key]) return; this.callback(e); }; return HotKey; }) ; /*! RESOURCE: /scripts/app.ng_chat/util/service.hotKeyHandler.js */ angular.module("sn.connect.util").factory("hotKeyHandler", function(snHotKey) { "use strict"; var activeHotKeys = {}; var html = angular.element('html')[0]; var oldKeyDown = html.onkeydown; function addHotKey(hotKey) { if(!arguments.length) return false; if(!hotKey instanceof snHotKey) hotKey = new snHotKey(hotKey); activeHotKeys[hotKey.key] = activeHotKeys[hotKey.key] || []; activeHotKeys[hotKey.key].push(hotKey); return hotKey; } function removeHotKey(hotKey) { if(!hotKey instanceof snHotKey || !activeHotKeys[hotKey.key].length) return false; var loc = activeHotKeys[hotKey.key].indexOf(hotKey); if(loc !== -1) return activeHotKeys[hotKey.key].splice(loc, 1); return false; } html.onkeydown = function(e) { if (typeof oldKeyDown === "function") oldKeyDown(); angular.forEach(activeHotKeys[e.keyCode], function(handler) { handler.trigger(e) }) }; return { add: addHotKey, remove: removeHotKey } }) ; /*! RESOURCE: /scripts/app.ng_chat/util/factory.snChatAction.js */ angular.module("sn.connect.util").factory("snChatAction", function(snHotKey) { "use strict"; var order = 100; function defaultOrder() { return order += 10; } function ChatAction(config) { this.name = config.name || ""; this.id = config.id || this.name; this.icon = config.icon || ""; if(config.order && typeof config.order === "string") config.order = parseInt(config.order); this.$order = typeof config.order === "number" ? config.order : defaultOrder(); this.numArgs = config.numArgs || 0; this.requiresArgs = !!config.requiresArgs; this.description = config.description || ""; this.isActive = config.isActive || false; this.showInMenu = angular.isUndefined(config.showInMenu) ? true : !!config.showInMenu; if (angular.isFunction(config.isVisible)) this.isVisible = config.isVisible; else { var isVisibleValue = angular.isUndefined(config.isVisible) ? true : config.isVisible; this.isVisible = function() {return isVisibleValue;}; } this.shortcut = "/" + config.shortcut; this.hint = config.hint || this.shortcut; this.argumentHint = config.argumentHint || ''; if(this.requiresArgs) this.hint += " " + this.argumentHint; this.action = angular.isFunction(config.action) ? config.action : void(0); if(config.hotKey) { if (config.hotKey instanceof snHotKey) this.hotKey = config.hotKey; else this.hotKey = new snHotKey(config.hotKey); this.hotKey.callback = this.trigger; } } ChatAction.prototype.trigger = function() { if(this.isValid() && this.isVisible(arguments[0])) this.action.apply(this, arguments); }; ChatAction.prototype.isValid = function() { return this.action && this.id; }; ChatAction.prototype.canRun = function(commandText) { return this.shortcut.toLowerCase().indexOf(commandText.trim().toLowerCase()) === 0; }; return ChatAction; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.ChatActionHandler.js */ angular.module("sn.connect.util").factory("ChatActionHandler", function( $http, $q, $rootScope, i18n, snChatAction, hotKeyHandler, isLoggedIn) { "use strict"; var i18nDeferred = $q.defer(); i18n.getMessages([ 'Transfer', 'Transfer the support conversation to another agent or queue', 'Escalate', 'Escalate the support conversation to another queue', 'End Session', 'End the support conversation session', 'Create VTB Task', 'Creates a VTB Task on the conversations VTB' ], function (i18nNames) { var actions = [ new snChatAction({ id: 'transfer', name: i18nNames['Transfer'], shortcut: "transfer", description: i18nNames['Transfer the support conversation to another agent or queue'], icon: 'icon-arrow-right', order: 70, isVisible: function(conversation) { return conversation.isHelpDesk && conversation.queueEntry.isAssignedToMe && !conversation.queueEntry.isTransferPending; }, action: function (conversation) { $rootScope.$broadcast('connect.support.conversation.transfer', conversation); } }), new snChatAction({ id: 'escalate', name: i18nNames['Escalate'], shortcut: "escalate", description: i18nNames['Escalate the support conversation to another queue'], icon: 'icon-my-feed', order: 60, isVisible: function(conversation) { if (!conversation.isHelpDesk) return false; var queueEntry = conversation.queueEntry; if (!queueEntry.isAssignedToMe) return false; if (queueEntry.isTransferPending) return false; var queue = queueEntry.queue; return queue && queue.escalateTo && queue.escalationQueue.available; }, action: function () { $rootScope.$broadcast('dialog.escalation-confirm.show'); } }), new snChatAction({ id: 'End Session', name: i18nNames['End Session'], shortcut: "end", description: i18nNames['End the support conversation session'], icon: 'icon-cross', order: 9999, isVisible: function(conversation) { return conversation.isHelpDesk && conversation.queueEntry.isAssignedToMe && !conversation.queueEntry.isClosedByClient; }, action: function (conversation) { $rootScope.$broadcast('connect.support_conversation.close_prompt', conversation, false); } }) ]; i18nDeferred.resolve(actions); }); var actionHandlers = {}; function createHandler(conversation) { var actionHandler = actionHandlers[conversation.sysID]; if (!actionHandler) actionHandler = actionHandlers[conversation.sysID] = new Handler(conversation); actionHandler.reload(); return actionHandler; } function Handler(conversation) { if (!conversation) throw "conversation object must be set"; var shortcutMap = {}; var idMap = {}; var actions = []; var currentAction; var loading; i18nDeferred.promise.then(function (actions) { angular.forEach(actions, function(action){ add(action); }); }); function reload() { if (!conversation.sysID) return; if (loading) return; loading = true; var url = isLoggedIn ? 'api/now/connect/conversations/' + conversation.sysID + '/actions' : 'api/now/connect/support/anonymous/conversations/' + conversation.sysID + '/actions'; $http.get(url).then(function (response) { loading = false; shortcutMap = {}; idMap = {}; actions = []; currentAction = undefined; i18nDeferred.promise.then(function (actions) { angular.forEach(actions, function(action){ add(action); }); }); angular.forEach(response.data.result, function (actionData) { actionData.action = function (conversation, argString) { $http.post(url, { action: actionData.sys_id, text: argString }).then(function (resp) { if (!resp.data) return; if (!resp.data.result) return; var result = resp.data.result; $rootScope.$emit(result.event, result.data, conversation); }); }; actionData.name = actionData.name || actionData.title; add(new snChatAction(actionData)); }); }); } function add(action) { if (!arguments.length) return false; if (!action instanceof snChatAction) action = new snChatAction(action); actions.push(action); idMap[action.id] = action; if (action.shortcut) { shortcutMap[action.shortcut] = shortcutMap[action.shortcut] || []; shortcutMap[action.shortcut].push(action); } if (action.hotKey) hotKeyHandler.add(action.hotKey); return action; } function clearAction() { currentAction = undefined; } function getVisible() { return actions .filter(function(chatAction){ return chatAction.isVisible(conversation); }); } return { reload: reload, get: function (id) { return idMap[id]; }, run: function(cmdString) { cmdString = cmdString.toLowerCase(); var cmdArray = cmdString.split(" "); var possibleActions = shortcutMap[cmdArray[0]]; var args = cmdArray.slice(1); var argString = args.join(" "); if (currentAction) { currentAction.trigger.call(currentAction, conversation, argString); currentAction = void(0); return true; } if (possibleActions && possibleActions.length) { var selectedAction = possibleActions[0]; selectedAction.trigger.call(selectedAction, conversation, argString); clearAction(); return true; } return false; }, hasRequiredArguments: function(cmdString) { cmdString = cmdString.toLowerCase(); var cmdArray = cmdString.split(" "); var possibleActions = shortcutMap[cmdArray[0]]; var args = cmdArray.slice(1); if (!possibleActions || !possibleActions.length) return false; currentAction = possibleActions[0]; if (currentAction.requiresArgs) return args.length > 0; return true; }, hasMatchingAction: function(text) { if(!text) return false; text = text.trim().toLowerCase(); return getVisible().some(function(action) { var shortcut = action.shortcut.toLowerCase(); return text === shortcut || text.indexOf(shortcut + " ") === 0; }) }, getCommands: function(filterText) { if(filterText) filterText = filterText.toLowerCase(); return getVisible() .filter(function(command) { return filterText ? command.shortcut.toLowerCase().indexOf(filterText) === 0 : true; }) .sort(function (a, b) { return a.shortcut > b.shortcut; }); }, getMenuActions: function() { return getVisible() .filter(function(chatAction) { return chatAction.showInMenu; }) .sort(function (a, b) { return a.$order - b.$order; }); } } } return { create: createHandler } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.connectDropTarget.js */ angular.module('sn.connect.util').service('connectDropTargetService', function($rootScope, activeConversation) { 'use strict'; function isMobile() { if( 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)) { return true; } else { return false; } } function isIgnoreDrop(conversation) { if (isMobile()) return true; if (!conversation.amMember) return false; if (conversation.isPending && !conversation.isPendingNoRecipients) return false; return (conversation.isHelpDesk && conversation.queueEntry.isPermanentlyClosed) } return { activateDropTarget: function(conversation) { conversation = conversation || activeConversation.conversation; if (isIgnoreDrop(conversation)) return; $rootScope.$broadcast("connect.drop_target_popup.show", conversation.sysID); }, deactivateDropTarget: function(conversation) { conversation = conversation || activeConversation.conversation; if (isIgnoreDrop(conversation)) return; $rootScope.$broadcast("connect.drop_target_popup.hide", conversation.sysID); }, onFileDrop: function(files, conversation) { conversation = conversation || activeConversation.conversation; if (isIgnoreDrop(conversation)) return; this.deactivateDropTarget(conversation); $rootScope.$broadcast("connect.drop.files", files, conversation.sysID); }, handleDropEvent: function(data, conversation) { conversation = conversation || activeConversation.conversation; if (isIgnoreDrop(conversation)) return; this.deactivateDropTarget(conversation); $rootScope.$broadcast("connect.drop", data, conversation.sysID); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.durationFormatter.js */ angular.module('sn.connect.util').service('durationFormatter', function($filter, i18n) { 'use strict'; var units = { years: 365 * 24 * 60 * 60 * 1000, months: 30 * 24 * 60 * 60 * 1000, weeks: 7 * 24 * 60 * 60 * 1000, days: 24 * 60 * 60 * 1000, hours: 60 * 60 * 1000, minutes: 60 * 1000, seconds: 1000 }; var names; i18n.getMessages([ 'month', 'months', 'week', 'weeks', 'day', 'days', 'hour', 'hours'], function (results) { names = results; }); function durationYearFn(duration, startTimestamp, endTimestamp) { return function() { if (duration.years > 0) { var start = Math.abs(Date.now() - startTimestamp); var end = Math.abs(Date.now() - endTimestamp); var date = new Date((start > end) ? startTimestamp : endTimestamp); return $filter('date')(date, 'mediumDate'); } }; } function durationGeneralFn(duration, single, plural, format) { return function () { if (duration) return stringFormat(duration + ' ' + ((duration === 1) ? single : plural), format); } } function stringFormat(value, format) { return format.replace(/\{0}/, value); } return { format: function (timestamp, format) { return this.formatWithRange(Date.now(), timestamp, format); }, formatWithRange: function (startTimestamp, endTimestamp, format) { format = format || "{0}"; var duration = {}; var remaining = Math.abs(startTimestamp - endTimestamp); angular.forEach(units, function (value, key) { duration[key] = Math.floor(remaining / value); remaining -= duration[key] * value; }); var durationFunction = [ durationYearFn(duration.years, startTimestamp, endTimestamp), durationGeneralFn(duration.months, names['month'], names['months'], format), durationGeneralFn(duration.weeks, names['week'], names['weeks'], format), durationGeneralFn(duration.days, names['day'], names['days'], format), durationGeneralFn(duration.hours, names['hour'], names['hours'], format) ]; for(var i = 0; i < durationFunction.length; ++i) { var value = durationFunction[i](); if (value) return value; } return stringFormat(duration.minutes + ':' + (duration.seconds < 10 ? '0' + duration.seconds : duration.seconds), format); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snConnectDuration.js */ angular.module('sn.connect.util').directive('snConnectDuration', function ($interval, $sanitize, durationFormatter) { 'use strict'; var listenerCount = 0; var listeners = {}; $interval(tick, 1000, 0, false); function tick() { angular.forEach(listeners, function(listenerFn) { if (typeof listenerFn !== "function") return; listenerFn(); }) } function onTick(fn) { listenerCount++; listeners[listenerCount] = fn; return listenerCount; } function remove(listenerCount) { delete listeners[listenerCount]; } return { template : '<span></span>', restrict : 'E', replace : true, scope: { startTimestamp: '=?', endTimestamp: '=?', placeholder: '@' }, link : function(scope, element, attrs) { var listenerIndex; function calculate() { var duration = attrs.placeholder || ''; if (scope.startTimestamp && scope.endTimestamp) { duration = durationFormatter.formatWithRange(scope.startTimestamp, scope.endTimestamp); } else if (scope.startTimestamp) { duration = durationFormatter.format(scope.startTimestamp); } else if (scope.endTimestamp) { duration = durationFormatter.format(scope.endTimestamp); } element.html($sanitize(duration)); } listenerIndex = onTick(calculate); scope.$on('$destroy', function() { remove(listenerIndex); }); calculate(); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.snConversationAsideHistory.js */ angular.module("sn.connect.util").service("snConversationAsideHistory", function() { "use strict"; var conversationAsides = {}; function getHistory(conversation) { if(conversationAsides.hasOwnProperty(conversation)) return conversationAsides[conversation]; return false; } function saveAsideHistory(conversation, view) { conversationAsides[conversation] = view; } function clearAsideHistory(conversation) { delete conversationAsides[conversation]; } return { getHistory: getHistory, saveHistory: saveAsideHistory, clearHistory: clearAsideHistory } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.snConnectAsideManager.js */ angular.module("sn.connect.util").service("snConnectAsideManager", function(paneManager) { "use strict"; return { setup: function() { if(angular.element('body').data().layout) paneManager.registerPane('connect:conversation_list'); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.snTypingTracker.js */ angular.module('sn.connect.util').service("snTypingTracker", function($rootScope, $timeout) { "use strict"; var typingTimeout; var newKeystroke = false; function notifyTyping() { newKeystroke = true; if(!typingTimeout) { $rootScope.$broadcast("record.typing", {status: "typing"}); waitForTypingToStop(); } } function cancelTypingTimer() { $rootScope.$broadcast("record.typing", {status: "viewing"}); newKeystroke = false; if(!typingTimeout) return; $timeout.cancel(typingTimeout); typingTimeout = void(0); } function waitForTypingToStop() { newKeystroke = false; typingTimeout = $timeout(function() { if(newKeystroke) { waitForTypingToStop() } else { cancelTypingTimer(); } }, 3000) } return { typing: notifyTyping, cancelTyping: cancelTypingTimer } }) ; /*! RESOURCE: /scripts/app.ng_chat/util/service.screenWidth.js */ angular.module("sn.connect.util").service("screenWidth", function($window, $timeout) { "use strict"; var window = angular.element($window); var thresholdTimeout; return { get width() { return window.width(); }, onResize: function(fn) { var self = this; window.on('resize', function() { fn(self.width); }); }, isAbove: function (width) { return this.width > width; }, threshold: function(threshold, fn, debounce) { var lastState; this.onResize(function (curr) { $timeout.cancel(thresholdTimeout); thresholdTimeout = $timeout(function () { var state = curr >= threshold; if (state === lastState) return; fn(state, curr); lastState = state; }, debounce); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.titleFlasher.js */ angular.module('sn.connect.util').service('titleFlasher', function($document, $window, i18n, snTabActivity) { "use strict"; var singleMessage = "1 New Message", manyMessages = "{0} New Messages"; i18n.getMessages(["1 New Message", "{0} New Messages"], function(results) { singleMessage = results[singleMessage]; manyMessages = results[manyMessages]; }); var initialTitle, FLASH_DELAY = 500, numMessages = 0, changedTitle = false, flashTimer; function flash(doNotIncrement) { if(snTabActivity.isVisible || !snTabActivity.isPrimary) return reset(); if(!doNotIncrement) numMessages++; if(doNotIncrement && changedTitle) setTitle(initialTitle); else if(numMessages - 1) setTitle(manyMessages); else setTitle(singleMessage); if(flashTimer) $window.clearTimeout(flashTimer); flashTimer = $window.setTimeout(function() { flash(true); }, FLASH_DELAY); } function reset() { if (!flashTimer) { return; } numMessages = 0; setTitle(initialTitle); $window.clearTimeout(flashTimer); flashTimer = void(0); } function setTitle(newTitle) { if(newTitle.indexOf("{0}") >= 0) newTitle = newTitle.replace("{0}", numMessages); changedTitle = newTitle !== initialTitle; $document[0].title = newTitle; } snTabActivity.on("tab.primary", reset); snTabActivity.on("tab.secondary", reset); return { flash: function() { if (!flashTimer) { initialTitle = $document[0].title; } flash(false); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.snConnectMention.js */ angular.module("sn.connect.util").factory("snConnectMention", function(liveProfileID, $q, snMention) { "use strict"; function retrieveMembers(conversation, term) { if(!conversation.table || !conversation.document) { var deferred = $q.defer(); deferred.resolve(conversation.members.filter(function(mem) { return (mem.name.toUpperCase().indexOf(term.toUpperCase()) >= 0 && liveProfileID !== mem.sysID); }).slice(0,5)); return deferred.promise; } return snMention.retrieveMembers(conversation.table, conversation.document, term); } return { retrieveMembers: retrieveMembers } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snInfiniteScroll.js */ angular.module("sn.connect.util").directive('snInfiniteScroll', function($q, $interval, $window, $timeout, infiniteScrollFactory) { var SCROLL_THROTTLE_MS = 50; var LOOK_AHEAD = 0.15; var snInfiniteScrollService; function throttle(func, wait) { var initialCall = true, deferred = $q.defer(), timerId; if (typeof func != 'function') { return; } function throttled() { if(timerId) { return; } if(initialCall) { initialCall = false; deferred.resolve(func()); return deferred.promise; } timerId = $timeout(function() { timerId = undefined; deferred.resolve(func()); }, wait, false); return deferred.promise; } return throttled; } return { restrict: 'A', scope: { scrollConfig: '=' }, bindToController: true, controllerAs: '$ctrl', link: function(scope, element) { var el = element[0]; var scrollHandler = function() { snInfiniteScrollService.onScroll(el.scrollTop, el.scrollHeight, el.clientHeight); }; el.onscroll = scrollHandler; angular.element($window).on('resize', scrollHandler); }, controller: function() { this.scrollConfig = this.scrollConfig || {}; this.scrollConfig.lookAhead = LOOK_AHEAD; this.scrollConfig.throttleFunc = throttle; this.scrollConfig.scrollThrottleInMs = SCROLL_THROTTLE_MS; snInfiniteScrollService = infiniteScrollFactory.get(this.scrollConfig); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/util/service.infiniteScrollFactory.js */ "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var InfiniteScrollService = function () { function InfiniteScrollService(_ref) { var onScrollUp = _ref.onScrollUp, onScrollDown = _ref.onScrollDown, onScrollMissing = _ref.onScrollMissing, throttleFunc = _ref.throttleFunc, scrollThrottleInMs = _ref.scrollThrottleInMs, lookAhead = _ref.lookAhead; _classCallCheck(this, InfiniteScrollService); this.onScrollUp = onScrollUp; this.onScrollDown = onScrollDown; this.onScrollMissing = onScrollMissing; this.lookAhead = lookAhead; this.throttleFunc = throttleFunc; this.scrollThrottleInMs = scrollThrottleInMs; this.prevScrollPos = 0; } _createClass(InfiniteScrollService, [{ key: "onScroll", value: function onScroll(scrollPos, scrollHeight, clientHeight) { var _this = this; this.throttleFunc(function () { if (_this.isScrollBarMissing(scrollHeight, clientHeight)) { _this.onScrollMissing(); return; } var scrollUp = _this.prevScrollPos > scrollPos; var scrollDown = _this.prevScrollPos < scrollPos; _this.prevScrollPos = scrollPos; var upperBoundary = Math.ceil(scrollHeight * _this.lookAhead); var lowerBoundary = Math.ceil(scrollHeight * (1 - _this.lookAhead)); if (scrollPos + clientHeight >= lowerBoundary && scrollDown) { _this.onScrollDown(); } else if (scrollPos <= upperBoundary && scrollUp) { _this.onScrollUp(); } }, this.scrollThrottleInMs)(); } }, { key: "isScrollBarMissing", value: function isScrollBarMissing(scrollHeight, clientHeight) { if (scrollHeight > clientHeight) { return false; } else { return true; } } }]); return InfiniteScrollService; }(); angular.module('sn.connect.util').factory('infiniteScrollFactory', function() { return { get: function(options) { return new InfiniteScrollService(options); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/util/directive.snChatPaneScroll.js */ angular.module("sn.connect.util").directive('snChatPaneScroll', function($timeout, $window, $q) { "use strict"; function throttle(func, wait) { var initialCall = true, deferred = $q.defer(), timerId; if (typeof func != 'function') { return; } function throttled() { if (timerId) { return; } if (initialCall) { initialCall = false; deferred.resolve(func()); return deferred.promise; } timerId = $timeout(function() { timerId = undefined; deferred.resolve(func()); }, wait, false); return deferred.promise; } return throttled; } return { restrict : 'A', link: function(scope, element, attrs) { var SCROLL_THROTTLE_MS = 500; var TRIGGER_HEIGHT = 5; var resizeTrigger = false; var el = element[0]; var prevScrollPos = el.scrollTop; var lastScrollHeight = el.scrollHeight; var scrollHandler = throttle(function() { if (resizeTrigger) { resizeTrigger = false; return; } var scrollPos = el.scrollTop; var scrollHeight = el.scrollHeight; if (scrollPos + el.offsetHeight + TRIGGER_HEIGHT >= scrollHeight) { scope.$apply(attrs.snChatPaneScroll); } lastScrollHeight = scrollHeight; }, SCROLL_THROTTLE_MS); el.scrollTop = el.scrollHeight; $timeout(function() { el.scrollTop = el.scrollHeight; prevScrollPos = el.scrollTop; }, 0, false); angular.element(el).on('scroll', scrollHandler); scope.$on("$destroy", function() { angular.element(el).off('scroll', scrollHandler); }); } } }); ; ; /*! RESOURCE: /scripts/app.ng_chat/profile/js_includes_connect_profile.js */ /*! RESOURCE: /scripts/app.ng_chat/profile/_module.js */ angular.module("sn.connect.profile", []); ; /*! RESOURCE: /scripts/app.ng_chat/profile/service.profiles.js */ angular.module('sn.connect.profile').service('profiles', function(snHttp, $q, i18n, snCustomEvent, snNotification, isLoggedIn) { "use strict"; var errorText = "User profile was not found"; i18n.getMessages([errorText], function (array) { errorText = array[errorText]; }); var PROFILES_URL = isLoggedIn ? '/api/now/live/profiles/' : '/api/now/connect/support/anonymous/live/profiles/'; var activeRequests = {}; var profiles = {}; function fromObject (config) { if (!config) return; if (!profiles[config.sys_id]) { config.name = config.name || ''; config.sysID = config.sys_id; config.avatar = config.avatar || ''; config.userID = config.document; profiles[config.sys_id] = config; } profiles[config.sys_id].supportConversationCount = config.supportConversationCount; return profiles[config.sys_id]; } function getAsync(id) { if (!id) return $q.when(null); if (angular.isObject(id)) id = id.sysID || id.userID; if (profiles[id]) return $q.when(profiles[id]); var url = PROFILES_URL + id; if (!activeRequests[url]) { activeRequests[url] = snHttp.get(url).then(function (response) { delete activeRequests[url]; return fromObject(response.data.result); }); } return activeRequests[url]; } function openConversation(profileID) { getAsync(profileID).then(function(profile) { snCustomEvent.fireTop('chat:open_conversation', profile); }, function (response) { if(response.status === 404) snNotification.show("error", errorText); }); } return { fromObject:fromObject, get: function(id) { if (!profiles[id]) this.getAsync(id); return profiles[id]; }, getAsync: getAsync, addMembers: function(members) { angular.forEach(members, fromObject); }, openConversation : openConversation }; }); ; ; /*! RESOURCE: /scripts/app.ng_chat/presence/js_includes_connect_presence.js */ /*! RESOURCE: /scripts/app.ng_chat/presence/_module.js */ angular.module("sn.connect.presence", []); ; ; /*! RESOURCE: /scripts/app.ng_chat/conversation/js_includes_connect_conversation.js */ /*! RESOURCE: /scripts/sn/common/ui/popover/js_includes_ui_popover.js */ /*! RESOURCE: /scripts/sn/common/ui/popover/_module.js */ angular.module('sn.common.ui.popover', []); ; /*! RESOURCE: /scripts/sn/common/ui/popover/directive.snBindPopoverSelection.js */ angular.module('sn.common.ui.popover').directive('snBindPopoverSelection', function(snCustomEvent) { "use strict"; return { restrict: "A", controller: function($scope, $element, $attrs , snCustomEvent) { snCustomEvent.observe('list.record_select', recordSelectDataHandler); function recordSelectDataHandler(data, event) { if (!data || !event) return; event.stopPropagation(); var ref = ($scope.field) ? $scope.field.ref : $attrs.ref; if (data.ref === ref) { if (window.g_form) { if ($attrs.addOption) { addGlideListChoice('select_0' + $attrs.ref, data.value, data.displayValue); } else { var fieldValue = typeof $attrs.ref === 'undefined' ? data.ref : $attrs.ref; window.g_form._setValue(fieldValue, data.value, data.displayValue); clearDerivedFields(data.value); } } if ($scope.field) { $scope.field.value = data.value; $scope.field.displayValue = data.displayValue; } } } function clearDerivedFields(value) { if (window.DerivedFields) { var df = new DerivedFields($scope.field ? $scope.field.ref : $attrs.ref); df.clearRelated(); df.updateRelated(value); } } } }; }); ; /*! RESOURCE: /scripts/sn/common/ui/popover/directive.snComplexPopover.js */ angular.module('sn.common.ui.popover').directive('snComplexPopover', function(getTemplateUrl, $q, $http, $templateCache, $compile, $timeout){ "use strict"; return { restrict: 'E', replace:true, templateUrl: function(elem, attrs){ return getTemplateUrl(attrs.buttonTemplate); }, controller: function($scope, $element, $attrs, $q, $document, snCustomEvent, snComplexPopoverService){ $scope.type = $attrs.complexPopoverType || "complex_popover"; if ($scope.closeEvent){ snCustomEvent.observe($scope.closeEvent, destroyPopover); $scope.$on($scope.closeEvent, destroyPopover); } $scope.$parent.$on('$destroy', destroyPopover); $scope.$on('$destroy', function() { snCustomEvent.un($scope.closeEvent, destroyPopover); }); var newScope; var open; var popover; var content; var popoverDefaults = { container: 'body', html: true, placement: 'auto', trigger: 'manual', template: '<div class="complex_popover popover" role="dialog"><div class="arrow"></div><div class="popover-content"></div></div>' }; var popoverConfig = angular.extend(popoverDefaults, $scope.popoverConfig); $scope.loading = false; $scope.initialized = false; $scope.popOverDisplaying = false; $scope.togglePopover = function(event) { if (!open){ showPopover(event); } else { destroyPopover(); } $scope.popOverDisplaying = !$scope.popOverDisplaying; }; function showPopover(e) { if ($scope.loading) return; $scope.$toggleButton = angular.element(e.target); $scope.loading = true; $scope.$emit('list.toggleLoadingState', true); _getTemplate() .then(_insertTemplate) .then(_createPopover) .then(_bindHtml) .then(function(){ $scope.initialized = true; if (!$scope.loadEvent) _openPopover(); }); } function destroyPopover() { if (!newScope) return; $scope.$toggleButton.on('hidden.bs.popover', function(){ open = false; $scope.$toggleButton.data('bs.popover').$element.removeData('bs.popover').off('.popover'); $scope.$toggleButton = null; snCustomEvent.fire('hidden.complexpopover.' + $scope.ref); }); $scope.$toggleButton.popover('hide'); snCustomEvent.fire('hide.complexpopover.' + $scope.ref, $scope.$toggleButton); newScope.$broadcast('$destroy'); newScope.$destroy(); newScope = null; $scope.initialized = false; angular.element(popoverConfig.container).off({ 'keydown': keyDownHandler }); angular.element(window).off({ 'click': complexHtmlHandler }); } function _getTemplate() { return snComplexPopoverService.getTemplate(getTemplateUrl($attrs.template)); } function _createPopover() { $scope.$toggleButton.popover(popoverConfig); return $q.when(true); } function _insertTemplate(response) { newScope = $scope.$new(); if ($scope.loadEvent) newScope.$on($scope.loadEvent, _openPopover); content = $compile(response.data)(newScope); popoverConfig.content = content; newScope.open = true; snCustomEvent.fire('inserted.complexpopover.' + $scope.ref, $scope.$toggleButton); return $q.when(true); } function _bindHtml() { angular.element(popoverConfig.container).on({ 'keydown': keyDownHandler }); angular.element(window).on({ 'click': complexHtmlHandler }); return $q.when(true); } function complexHtmlHandler(e) { var parentComplexPopoverScope = angular.element(e.target).parents('.popover-content').children().scope(); if (parentComplexPopoverScope && (parentComplexPopoverScope.type = "complex_popover") && $scope.type === "complex_popover") return; if (!open || angular.element(e.target).parents('html').length === 0) return; if ($scope.initialized && !$scope.loading && !$scope.$toggleButton.is(e.target) && content.parents('.popover').has(angular.element(e.target)).length === 0) { _eventClosePopover(e); destroyPopover(e); } } function keyDownHandler(e) { if (e.keyCode != 27) return; if (!open || angular.element(e.target).parents('html').length === 0) return; if ($scope.initialized && !$scope.loading && !$scope.$toggleButton.is(e.target) && content.parents('.popover').has(angular.element(e.target)).length > 0) { _eventClosePopover(e); destroyPopover(); } } function _eventClosePopover(e) { e.preventDefault(); e.stopPropagation(); } function createAndActivateFocusTrap(popover) { var deferred = $q.defer(); if (!window.focusTrap) { deferred.reject('Focus trap not found'); } else { if (!$scope.focusTrap) { $scope.focusTrap = window.focusTrap(popover, { clickOutsideDeactivates: true }); } try { $scope.focusTrap.activate({ onActivate: function() { deferred.resolve(); } }); } catch(e) { console.warn("Unable to activate focus trap", e); } } return deferred.promise; } function deactivateAndDestroyFocusTrap() { var deferred = $q.defer(); if (!$scope.focusTrap) { deferred.reject("Focus trap not found"); } else { try { $scope.focusTrap.deactivate({ returnFocus: false, onDeactivate: function () { deferred.resolve(); } }); } catch (e) { console.warn("Unable to deactivate focus trap", e); } $scope.focusTrap = null; } return deferred.promise; } function _openPopover() { if (open) { return; } open = true; $timeout(function() { $scope.$toggleButton.popover('show'); $scope.loading = false; snCustomEvent.fire('show.complexpopover.' + $scope.ref, $scope.$toggleButton); $scope.$toggleButton.on('shown.bs.popover', function(evt) { var popoverObject = angular.element(evt.target).data('bs.popover'), $tooltip, popover; $tooltip = popoverObject && popoverObject.$tip; popover = $tooltip && $tooltip[0]; if (popover) { createAndActivateFocusTrap(popover); } snCustomEvent.fire('shown.complexpopover.' + $scope.ref, $scope.$toggleButton); }); $scope.$toggleButton.on('hide.bs.popover', function () { deactivateAndDestroyFocusTrap().finally(function() { $scope.$toggleButton.focus(); }); }); }, 0 ); } } }; }); ; /*! RESOURCE: /scripts/sn/common/ui/popover/service.snComplexPopoverService.js */ angular.module('sn.common.ui.popover').service('snComplexPopoverService', function($http, $q, $templateCache){ "use strict"; return { getTemplate: getTemplate }; function getTemplate(template){ return $http.get(template, {cache: $templateCache}); } }); ; ; /*! RESOURCE: /scripts/app.ng_chat/conversation/_module.js */ angular.module("sn.connect.conversation", ["ng.common", "sn.connect.util", "sn.connect.profile", "sn.connect.message", "sn.connect.resource", 'sn.connect.presence', 'sn.common.ui.popover']); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/factory.Conversation.js */ angular.module('sn.connect.conversation').factory('conversationFactory', function( conversationPersister, unreadCountService, profiles, messageFactory, ChatActionHandler, liveProfileID, notificationPreferences, queueEntries, documentsService, resourcePersister, messageBatcherService, inSupportClient, isLoggedIn) { 'use strict'; function formatUnreadCount(count) { return count > 99 ? "99+" : count; } function fromObject(data) { var frameState = data.frame_state || 'open'; var frameOrder = data.frame_order || 0; var amMember = true; var visible = data.visible; var pendingMessage = ""; try { pendingMessage = sessionStorage.getItem("messagePersist." + data.sys_id) || ""; } catch (ignored) {} unreadCountService.set(data.sys_id, data.last_viewed, data.unread_messages); messageBatcherService.addMessages(messageFactory.fromObject(data.last_message), true); function getMemberIndexByID(id) { for(var i = 0, len = data.members.length; i < len; i++) if(data.members[i].sys_id === id) return i; return -1; } function setFrameState(value) { if (frameState === value) return; frameState = value; conversationPersister.frameState(data.sys_id, value); } if (!data.members) { data.members = []; } var memberProfiles = []; profiles.addMembers(data.members); if (data.queueEntry) queueEntries.addRaw(data.queueEntry); return { get name() { return (!data.group && this.peer) ? this.peer.name : data.name; }, set name(newName) { if(!data.group) return; data.name = newName; }, get access() { return data.access || "unlisted"; }, set access(newAccess) { data.access = newAccess; }, get peer () { if(data.group || !this.members || this.members.length < 2) { return null; } return (this.members[0].sysID === liveProfileID) ? this.members[1] : this.members[0]; }, get members () { if (memberProfiles.length !== data.members.length) { memberProfiles.length = 0; angular.forEach(data.members, function (member) { if (member.table !== 'sys_user') return; var memberProfile = isLoggedIn ? profiles.get(member.sys_id || member) : profiles.fromObject(member); if (!memberProfile) return; if(memberProfiles.indexOf(memberProfile) >= 0) return; memberProfiles.push(memberProfile); }); } return memberProfiles; }, get avatarMembers() { if (!data.isHelpDesk) return this.members; return this.members.filter(function(member){ return member.sys_id !== liveProfileID; }); }, get pendingMessage() { return pendingMessage }, set pendingMessage(message) { pendingMessage = message; try { sessionStorage.setItem("messagePersist." + this.sysID, message); } catch (ignored) {} }, get description() { return data.description; }, set description(newDescription) { data.description = newDescription; }, resetUnreadCount: function () { if (this.sysID) unreadCountService.reset(this.sysID); }, get messageBatcher() { return messageBatcherService.getBatcher(this.sysID); }, get ariaMessages() { var messages = messageBatcherService.getAriaMessages(this.sysID, 5); return messages.filter(function(message) { return message.timestamp >= data.last_viewed; }); }, get lastMessage() { return messageBatcherService.getLastMessage(this.sysID) || {}; }, get firstMessage() { return messageBatcherService.getFirstMessage(this.sysID) || {}; }, get hasUnreadMessages() { return this.unreadCount > 0; }, get unreadCount() { return unreadCountService.get(this.sysID); }, get lastReadMessageTime() { return unreadCountService.getLastTimestamp(this.sysID); }, get formattedUnreadCount() { return formatUnreadCount(this.unreadCount); }, get isDirectMessage() { return !(this.isGroup || this.isDocumentGroup || this.isHelpDesk); }, get isGroup() { return data.group; }, get isHelpDesk() { return !!this.queueEntry && !!this.queueEntry.sysID; }, get queueEntry () { return queueEntries.get(this.sysID); }, get isDocumentGroup() { return !!data.document || this.isHelpDesk; }, restricted: data.restricted, avatar: data.avatar, get sysID() { return data.sys_id; }, get href() { return '/$c.do#/' + (this.isHelpDesk ? 'support' : 'chat') + '/' + this.sysID; }, get document() { return data.document; }, get table() { return data.table; }, get type() { return data.type; }, get hasRecord() { var documentDetails = this.documentDetails; return documentDetails && !!documentDetails.sysID; }, get documentDetails() { if (data.table === 'chat_queue_entry') return; if (!this._documentsServiceRetrieve) { this._documentsServiceRetrieve = true; documentsService.retrieve(data.table, data.document); } return documentsService.getDocument(data.document); }, get documentActive() { var documentDetails = this.documentDetails; return documentDetails && documentDetails.active; }, get resources() { return resourcePersister.get(this.sysID); }, get preferences() { return notificationPreferences.get(this.sysID); }, get chatActions() { if (!this.chatActionHandler) this.chatActionHandler = ChatActionHandler.create(this); return this.chatActionHandler; }, frameOrder: frameOrder, openFrameState: function() { setFrameState('open'); }, get isFrameStateOpen() { return frameState === 'open'; }, minimizeFrameState: function() { setFrameState('minimized'); }, get isFrameStateMinimize() { return frameState === 'minimized'; }, closeFrameState: function() { setFrameState('closed'); }, get isFrameStateClosed() { return frameState === 'closed'; }, get amMember() { return amMember || getMemberIndexByID(liveProfileID) !== -1; }, get visible() { return visible; }, set visible(value) { if (visible === value) return; visible = value; conversationPersister.visible(this.sysID, visible); }, get sortIndex() { if (inSupportClient && this.isHelpDesk) { var queueEntry = this.queueEntry; if (queueEntry.workEnd) return queueEntry.workEnd; if (queueEntry.workStart) return queueEntry.workStart; } return this.lastMessage.timestamp || 0; }, get canSaveWorkNotes() { return data.can_save_work_notes; }, addMember: function (member) { if(getMemberIndexByID(member.sys_id) < 0) { data.members.push(member); if(member.sys_id === liveProfileID) amMember = true; } }, removeMember: function (member) { var memberIndex = getMemberIndexByID(member.sys_id); if(memberIndex < 0) return; data.members.splice(memberIndex, 1); memberProfiles.splice(memberIndex, 1); if(member.sys_id === liveProfileID) amMember = false; }, get canSaveComments() { return data.can_save_comments; }, }; } return { fromObject: fromObject, fromRawConversation: function (data) { data.memberData = data.members; var preference = data.notification_preference; preference.sys_id = data.sys_id; notificationPreferences.addRaw(preference); return fromObject(data); }, formatUnreadCount: formatUnreadCount }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/service.activeConversation.js */ angular.module('sn.connect.conversation').service('activeConversation', function( $rootScope, $filter, $location, $q, i18n, userPreferences, conversations, documentsService, messageService, snTabActivity, startingTab, inFrameSet, inSupportClient, supportEnabled, chatEnabled, supportAddMembers, messageBatcherService, snNotification) { "use strict"; var WINDOW_TYPE = inFrameSet ? 'frameSet' : 'standAlone'; var PREFERENCE_ROOT = 'connect.conversation_list.active_list.' + WINDOW_TYPE; var restrictedConversationText = 'The conversation you requested could not be found'; i18n.getMessages([restrictedConversationText], function (array) { restrictedConversationText = array[restrictedConversationText]; }); function ConversationHandler(preferenceName, isSupport) { var conversationID; function contains(conversation) { if (!conversation) return false; if (!conversation.sysID) return false; if (conversation.isPending) return false; var isSupportConv = (supportEnabled || !supportAddMembers) ? isSupport : undefined; var conversationList = $filter('conversation')(conversations.all, true, isSupportConv); return conversations.find(conversation, conversationList).index >= 0; } return { get sysID() { return conversationID; }, set sysID(newSysID) { if (conversationID === newSysID) { return; } conversationID = newSysID; setPreference(preferenceName, conversationID); }, get conversation() { return conversations.indexed[this.sysID] || conversations.emptyConversation; }, set conversation(newConversation) { this.sysID = contains(newConversation) ? newConversation.sysID : undefined; } }; } var inFrameSetConversationHandler; if (inFrameSet) inFrameSetConversationHandler = new ConversationHandler(PREFERENCE_ROOT + ".id"); function TabData(isSupport) { var tab = isSupport ? "support" : "chat"; var preferenceName = PREFERENCE_ROOT + '.' + tab + '.id'; var conversationHandler = inFrameSetConversationHandler || new ConversationHandler(preferenceName, isSupport); if (!inSupportClient) { var startingLocation = location(); if (!inFrameSet && (startingLocation.tab === tab) && startingLocation.conversationID) { initialize(startingLocation.conversationID, true).catch(function(){ snNotification.show('error', restrictedConversationText); setPreference(preferenceName); }); } else { userPreferences.getPreference(preferenceName).then(initialize).catch(function() { setPreference(preferenceName); }); } } function initialize(id, makeVisible) { if (!id || id === "null") return $q.when(); return conversations.get(id).then(function (conversation) { if (!conversation) return; if (!conversation.visible && !makeVisible) return; conversationHandler.sysID = conversation.sysID; }); } return { get tab() { return tab; }, get isSupport() { return isSupport; }, get sysID() { return conversationHandler.sysID; }, get conversation() { return conversationHandler.conversation; }, set conversation(conv) { conversationHandler.conversation = conv; } }; } var tabDataList = { chat: new TabData(false), support: new TabData(true) }; var tab = checkedLocation().tab || (inSupportClient ? tabDataList.support.tab : startingTab[WINDOW_TYPE]); if(tab == "chat" && !chatEnabled) tab = "support"; else if(tab == "support" && !supportEnabled) tab = "chat"; var activeTabData = tabDataList[tab]; $rootScope.$on("connect.action.create_record", function(evt, data, conversation) { if(conversation) { API.conversation = conversation; } documentsService.create(activeTabData.conversation, data); }); function setPreference(name, value) { if (inSupportClient) return; userPreferences.setPreference(name, value || ''); } messageService.watch(function(message) { if (activeTabData.sysID !== message.conversationID) $rootScope.$broadcast("connect.aria.new_unread_message", message); conversations.get(message.conversationID).then(function(conversation) { if (!conversation) return; if (conversation.isGroup) message.groupName = conversation.name; if(!message.isSystemMessage && (message.timestamp > conversation.lastReadMessageTime)) conversation.visible = true; if (conversation.sysID !== activeTabData.sysID) return; if (snTabActivity.idleTime >= snTabActivity.defaultIdleTime) return; if (!snTabActivity.isVisible) return; conversation.resetUnreadCount(); }); }); snTabActivity.on("tab.primary", function() { if (snTabActivity.isActive()) activeTabData.conversation.resetUnreadCount(); }); function location() { var path = $location.path().split('/'); return {tab: path[1], conversationID: path[2]}; } function checkedLocation() { var path = location(); if (path.tab === 'with') return {profileID: path.conversationID}; return isValidTab(path.tab) ? path : {}; } function isValidTab(tab) { return angular.isDefined(tabDataList[tab]) } var pendingConversation; var API = { get tab() { return activeTabData.tab; }, get sysID() { return activeTabData.sysID; }, get conversation() { return activeTabData.conversation; }, get isEmpty() { return !this.sysID || this.conversation.isEmpty; }, get isSupport() { return activeTabData.isSupport; }, get location() { return checkedLocation(); }, getTab: function(tab){ if (!isValidTab(tab)) throw "Not a valid tab name"; return tabDataList[tab]; }, set conversation(conv) { if (conv) conv.visible = true; else conv = conversations.emptyConversation; var old = activeTabData.conversation; if (!old.isEmpty) { old.resetUnreadCount(); if(conv.sysID !== old.sysID) messageBatcherService.clearAriaMessages(old.sysID); } activeTabData.conversation = conv; if (this.isEmpty) return; if (inFrameSet) conv.openFrameState(); this.conversation.resetUnreadCount(); $rootScope.$broadcast("connect.message.focus", this.conversation); }, set tab(newTab) { if (this.tab === newTab) return; activeTabData = this.getTab(newTab); if (!this.isEmpty) this.conversation.resetUnreadCount(); setPreference(PREFERENCE_ROOT, newTab); }, clear: function(check) { if (!check || check.sysID === this.sysID) this.conversation = undefined; }, isActive: function(conversation) { return !this.pendingConversation && !this.isEmpty && conversation && conversation.sysID === this.sysID; }, get pendingConversation() { return pendingConversation; }, set pendingConversation(pending) { pendingConversation = pending; } }; return API; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/service.conversationPersister.js */ angular.module('sn.connect.conversation').service('conversationPersister', function( snHttp, CONNECT_CONTEXT, isLoggedIn) { "use strict"; var REST_API_PATH = isLoggedIn?'/api/now/connect/conversations':'/api/now/connect/support/anonymous/conversations'; function createGroup(optionalParams) { optionalParams = optionalParams || {}; return snHttp.post(REST_API_PATH, optionalParams).then(extractResult); } function addUser(conversationID, profileID) { return snHttp.post(REST_API_PATH + '/' + conversationID + '/members', { "member_id" : profileID }).then(extractResult); } function removeUser(conversationID, profileID) { return snHttp.delete(REST_API_PATH + '/' + conversationID + '/members/' + profileID).then(extractResult); } function update(conversationID, data) { return snHttp.put(REST_API_PATH + '/' + conversationID, data).then(extractResult); } function extractResult(response) { return response.data.result; } function getEncodedURL(conversationURL, params) { var paramsList = []; Object.keys(params).forEach(function(key){ paramsList.push(key + "=" + encodeURIComponent(params[key])); }); return conversationURL + "?" + paramsList.join('&'); } var conversationURL = REST_API_PATH; return { createGroup: createGroup, addUser: addUser, removeUser: removeUser, update: update, loadConversations: function(offset, limit, isSupport) { return snHttp.get(getEncodedURL(conversationURL, {offset:offset, limit:limit, isSupport:isSupport})).then(extractResult); }, getConversations: function(queueID) { var limit = 25; var offset = 0; if (queueID) { conversationURL = isLoggedIn ? '/api/now/connect/support/queues/' + queueID + '/sessions' : '/api/now/connect/support/anonymous/queues/' + queueID + '/sessions' ; return snHttp.get(conversationURL).then(extractResult); } return snHttp.get(getEncodedURL(conversationURL, {offset:offset, limit:limit, initialLoad:true})).then(extractResult); }, searchConversations: function(keyword) { var searchURL = '/api/now/connect/search/conversations'; return snHttp.get(getEncodedURL(searchURL, {keywords:keyword, visible:true, includeSupport:false})).then(extractResult); }, getConversation: function(conversationID) { return snHttp.get(REST_API_PATH + '/' + conversationID) .then(extractResult) }, lastViewed: function(conversationID, timestamp) { return update(conversationID, { last_viewed: timestamp }) }, visible: function(conversationID, visible) { return update(conversationID, { visible: visible }); }, frameState: function(conversationID, state) { var data = { frame_state: state }; if (state === 'closed') data.frame_order = -1; return update(conversationID, data); }, changeFrameOrder: function(conversations) { var data = { frame_order: conversations.join(',') }; return snHttp.post(REST_API_PATH + '/order', data).then(extractResult); }, createConversation: function(groupName, recipients, message) { var recipientJIDs = recipients.map(function (recipient){ return recipient.jid; }); var data = { group_name: groupName, recipients: recipientJIDs, message: message.text, reflected_field: message.reflectedField || "comments", attachments: message.attachmentSysIDs, context: CONNECT_CONTEXT }; return snHttp.post(REST_API_PATH, data).then(extractResult); }, createDocumentConversation: function(table, sysID) { var data = { table: table, sys_id: sysID }; return snHttp.post(REST_API_PATH + '/records', data).then(extractResult); }, setDocument: function(profileID, table, document) { var data = { table: table, document: document }; return snHttp.put(REST_API_PATH + '/' + profileID + '/records', data); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/service.conversations.js */ angular.module('sn.connect.conversation').service('conversations', function( $rootScope, $q, $timeout, amb, i18n, conversationFactory, conversationPersister, documentsService, liveProfileID, userID, snHttp, queueEntries, snComposingPresence, snCustomEvent, snTabActivity, snNotification, profiles, snNotifier, userPreferences, messageBatcherService, isLoggedIn, sessionID, supportEnabled) { "use strict"; var i18nText; i18n.getMessages(['and', 'more', 'You have been mentioned', "New Conversation"], function (i18nNames) { i18nText = i18nNames; }); var currentLiveProfile; profiles.getAsync(liveProfileID).then(function(liveProfile) { currentLiveProfile = liveProfile; }); var conversationsIndex = {}; var onNextUpdate = function(){}; var lastRefresh = $q.when(); var firstRefresh = $q.defer(); var loaded = false; var isLoading = false; var channelId = isLoggedIn ? userID : sessionID; amb.getChannel("/connect/" + channelId).subscribe(function(response) { var event = response.data; var type = event.event_type; var data = event.event_data; var conversationID = event.event_target || event.group || data.conversation_id; var conversation = conversationsIndex[conversationID]; if (!conversation) return; if(type === "conversation_member_removed") { conversation.removeMember(data); if (data.sys_id !== liveProfileID) return; if (conversation.isPending) return; snComposingPresence.set(conversation.sysID, [], []); delete conversationsIndex[conversation.sysID]; return; } if(type === "conversation_member_added") { conversation.addMember(data); if(data.sys_id === liveProfileID) { $rootScope.$broadcast("conversation.refresh_messages", conversation); } return; } if (type === "conversation_deauthorized") { conversation.restricted = true; return; } if (type === "conversation_updated") refreshConversation(conversationID).then(onNextUpdate).then(function() { onNextUpdate = function(){}; }); }); amb.getChannel("/notifications/" + liveProfileID).subscribe(function(message) { userPreferences.getPreference("connect.notifications.desktop").then(function(value) { var allowWebNotifications = angular.isString(value) ? value === "true" : value; if(allowWebNotifications && snTabActivity.isPrimary) { var body = i18nText[message.data.message] || message.data.message; snNotifier().notify(message.data.title, { body: body, lifespan: 7000, onClick: function () { window.open("/nav_to.do?uri=/" + message.data.table + ".do?sys_id=" + message.data.document, "_blank"); } }); } }); }); amb.connect(); snCustomEvent.observe('connect:set_document', function(data) { conversationPersister.setDocument(data.conversation, data.table, data.document) .then(function () { onNextUpdate = function(conversation) { documentsService.show(conversation.table, conversation.document); }; }); }); $rootScope.$on("amb.connection.recovered", function() {refreshAll();}); $rootScope.$on("amb.session.logged.in", function() {refreshAll();}); $rootScope.$on("amb.session.reestablished", function() {refreshAll();}); snTabActivity.on("tab.primary", function() {refreshAll();}); function refreshAll(queueID) { var deferred = $q.defer(); lastRefresh = deferred.promise; conversationPersister.getConversations(queueID).then(function(conversations) { if(!loaded) { loaded = true; firstRefresh.resolve(); } conversationsIndex = {}; angular.forEach(conversations, addRawConversation); deferred.resolve(); }); return lastRefresh; } function refreshConversation(id) { return conversationPersister.getConversation(id).then(addRawConversation, function(response) { if(response.status === 403) snNotification.show("error", response.data.result); return $q.reject(response) }); } function addRawConversation(conversationData) { if (!conversationData) return; var conversation = new conversationFactory.fromRawConversation(conversationData); return conversationsIndex[conversation.sysID] = conversation; } function _get(conversationID) { if(conversationsIndex[conversationID]) return $q.when(conversationsIndex[conversationID]); return refreshConversation(conversationID).then(function() { if (conversationID === 'pending') return NewConversation(); if(!conversationsIndex[conversationID]) throw "Conversation " + conversationID + " does not exist"; return conversationsIndex[conversationID]; }) } function get(conversationID) { return lastRefresh.then(function() { return _get(conversationID); }, function() { return _get(conversationID); }) } function getCachedPeerConversations(userSysID) { return allConversations().filter(function(conversation) { return conversation.isDirectMessage && conversation.members.some(function(member) { return member.userID === userSysID; }); }); } function allConversations() { return Object.keys(conversationsIndex).map(function (key) { return conversationsIndex[key]; }); } function find(conversation, conversationList) { conversationList = conversationList || allConversations(); var sysID = conversation.sysID || conversation; for (var i = 0; i < conversationList.length; ++i) { var conv = conversationList[i]; if (conv.sysID === sysID) return {conversation: conv, index: i}; } return {index: -1}; } function close(conversationID) { var conversation = conversationsIndex[conversationID]; if (!conversation) return false; if (!conversation.isHelpDesk) { remove(conversation); return true; } var queueEntry = conversation.queueEntry; if (queueEntry.isTransferCancelled && (queueEntry.isClosedByAgent || queueEntry.isClosedByClient)) { closeSupport(conversationID, true); return true; } if (queueEntry.isWaiting || queueEntry.isEscalated || queueEntry.isTransferRejected || queueEntry.isTransferCancelled) { removeSupport(conversation.sysID); return true; } if (queueEntry.isClosedByAgent || queueEntry.isClosedByClient || !queueEntry.isAssignedToMe) { if (!supportEnabled && !conversation.restricted) { $rootScope.$broadcast('connect.non_agent_conversation.close_prompt', conversation); return false; } closeSupport(conversationID, true); return true; } $rootScope.$broadcast('connect.support_conversation.close_prompt', conversation, true); return false; } function remove(conversation) { conversation.closeFrameState(); conversation.resetUnreadCount(); conversation.visible = false; } function closeSupport(conversationID, agentLeave){ queueEntries.close(conversationID, agentLeave); if (agentLeave) removeSupport(conversationID); } function removeSupport(conversationID) { queueEntries.remove(conversationID); delete conversationsIndex[conversationID]; } function removeUser(conversationID, userID) { var conversation = conversationsIndex[conversationID]; if (userID === liveProfileID) { remove(conversation); if (conversation.isHelpDesk) removeSupport(conversation.sysID); } conversationPersister.removeUser(conversationID, userID); } function exists(conversationID) { return conversationID in conversationsIndex; } var NewConversation = function() { messageBatcherService.removeMessageBatcher("pending"); function listRecipients(recipients, shorten) { var names = recipients.map(function (recipient){ return shorten ? recipient.name.split(" ")[0] : recipient.name; }); var and = shorten ? " & " : (" " + i18nText["and"] + " "); var more = shorten ? (" +" + (recipients.length - 3)) : (and + (recipients.length - 3)); more += " " + i18nText["more"]; switch (recipients.length) { case 0: return ""; case 1: return names[0]; case 2: return names[0] + and + names[1]; case 3: return names[0] + ", " + names[1] + ", " + and + names[2]; case 4: return names[0] + ", " + names[1] + ", " + names[2] + ", " + and + names[3]; default: return names[0] + ", " + names[1] + ", " + names[2] + ", " + more; } } return { sysID: "pending", isPending: true, pendingRecipients: [], name: i18nText["New Conversation"], frameState: 'open', frameOrder: 0, get messageBatcher() { return messageBatcherService.getBatcher(this.sysID); }, get firstMessage() { return messageBatcherService.getFirstMessage(this.sysID); }, get isPendingNoRecipients() { return this.pendingRecipients.length === 0; }, getGroupName: function () { var nameArray = this.pendingRecipients.slice(); nameArray.unshift(currentLiveProfile); return listRecipients(nameArray, true); }, get displayRecipients() { return listRecipients(this.pendingRecipients, false); }, closeFrameState: function () {}, openFrameState: function () {}, $reset: function () { return newConversation = new NewConversation(); } }; }; var newConversation = new NewConversation(); var emptyConversation = conversationFactory.fromObject({}); emptyConversation.isEmpty = true; return { get all() { return allConversations(); }, get indexed() { return conversationsIndex; }, get isLoading() { return isLoading; }, loaded: firstRefresh.promise, get: get, getCachedPeerConversations: getCachedPeerConversations, refreshAll: refreshAll, refreshConversation: refreshConversation, exists: exists, find: find, addUser: function (conversationID, userID) { return conversationPersister.addUser(conversationID, userID).then(get, function(response) { if(response.status === 403) snNotification.show("error", response.data.result); return $q.reject(response) }); }, removeUser: removeUser, loadConversations: function(offset, limit, isSupport) { offset = offset || 0; limit = limit || 25; conversationPersister.loadConversations(offset, limit, isSupport).then(function(conversations) { angular.forEach(conversations, addRawConversation); }); }, updateConversations: function(keyword) { isLoading = true; conversationPersister.searchConversations(keyword).then(function(conversations) { angular.forEach(conversations, addRawConversation); isLoading = false; }); }, followDocumentConversation: function(data) { return conversationPersister.createDocumentConversation(data.table, data.sysID).then(addRawConversation); }, unfollowDocumentConversation: function(data) { var conversationID = data.conversationID; if (conversationID === "undefined") conversationID = undefined; if (!conversationID) { for (var id in conversationsIndex) { if (!conversationsIndex.hasOwnProperty(id)) continue; var conversation = conversationsIndex[id]; if (conversation.document === data.sysID) { conversationID = conversation.sysID; break; } } } return removeUser(conversationID, liveProfileID); }, close: close, closeSupport: closeSupport, update: function(conversationID, data) { var conversation = conversationsIndex[conversationID]; data.name = data.name.trim(); if (data.name.length === 0) data.name = conversation.name; data.description = data.description.trim(); if (data.description.length === 0) data.description = conversation.description; if((data.name === conversation.name) && (data.description === conversation.description) && (data.access === conversation.access)) return; conversation.name = data.name; conversation.description = data.description; conversation.access = data.access; var element = { name : data.name, short_description: data.description, access: data.access }; return conversationPersister.update(conversationID, element).then(addRawConversation); }, beginNewConversation: function(groupName, recipients, message) { messageBatcherService.addMessages(message); return conversationPersister.createConversation(groupName, recipients, message).then(addRawConversation); }, get newConversation() { return newConversation; }, get emptyConversation() { return emptyConversation; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversation.js */ angular.module('sn.connect.conversation').directive('snConversation', function( getTemplateUrl, $rootScope, $timeout, messageService, activeConversation, profiles) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl("snConversation.xml"), replace: true, scope: { conversation: "=", shouldAnnounce: "=readmessages", showSenderPresence: "@" }, link: function(scope, element) { scope.loading = false; scope.$watch("messagesLoadedOnce", function() { var isConversationActive = !activeConversation.pendingConversation; if(isConversationActive) $timeout(function () { var el = element.find('.new-message'); el.focus() }, 0, false); $timeout(function () { scope.loading = !scope.messagesLoadedOnce && isConversationActive; }, 0, true); }); scope.checkForUnloadedMessages = function() { $timeout(function() { var scrollHeight = element.find(".sn-feed-messages")[0].scrollHeight; var containerHeight = element.find(".sn-feed-messages").height(); if (scrollHeight < containerHeight) { scope.retrieveMessageHistory().then(function (retrievedMessages) { if (retrievedMessages.length === 30) scope.checkForUnloadedMessages(); else $timeout(function () { scope.$broadcast('connect.auto_scroll.jump_to_bottom'); }, 0, false); }); } }); }; function onClick(evt) { $timeout(function() { var profileID = angular.element(evt.target).attr('class').substring("at-mention at-mention-user-".length); profiles.getAsync(profileID).then(function(profile) { scope.showPopover = true; scope.mentionPopoverProfile = profile; scope.clickEvent = evt; }); }, 0, false); } element.on("click", ".at-mention", function(evt) { if (scope.showPopover) { var off = scope.$on("snMentionPopover.showPopoverIsFalse", function () { onClick(evt); off(); }); } else { onClick(evt); } }); element.on("click", function(evt) { scope.focusOnConversation(); }); }, controller: function($scope, $element, $q, snRecordPresence, queueEntries, hotKeyHandler, snHotKey, snComposingPresence, userID, inFrameSet) { $scope.messagesLoadedOnce = false; $scope.showLoading = true; $scope.rawMessages = []; $scope.asideOpen = false; $scope.$on("sn.aside.open", function() { $scope.asideOpen = true; }); $scope.$on("sn.aside.close", function() { $scope.asideOpen = false; }); $scope.isComposingHidden = function() { return $scope.conversation.isHelpDesk && !$scope.conversation.queueEntry.isActive; }; var closeHotKey = new snHotKey({ key: "ESC", callback: function() { $scope.$broadcast("snippets.hide", $scope.conversation); hotKeyHandler.remove(closeHotKey); } }); $scope.escalateOk = function() { queueEntries.escalate($scope.conversation); }; $rootScope.$on('http-error.hide', function () { messageService.retrieveMessages($scope.conversation); }); $scope.isNoRecipientsMessageShowing = function() { return hasNoMessage() && $scope.conversation.pendingRecipients.length === 0; }; $scope.isOneRecipientsMessageShowing = function() { return hasNoMessage() && $scope.conversation.pendingRecipients.length === 1; }; $scope.isGroupMessageShowing = function() { return hasNoMessage() && $scope.conversation.pendingRecipients.length > 1; }; function hasNoMessage() { return !$scope.conversation.firstMessage; } function isVisible() { return ($element[0].offsetWidth !== 0) && ($element[0].offsetHeight !== 0); } $scope.$watch(isVisible, function(visible) { if (!visible || $scope.conversation.isPending) return; if (inFrameSet && $scope.conversation.isFrameStateMinimize) return; $scope.conversation.resetUnreadCount(); }); $scope.$watch("conversation.sysID", function(newSysID) { if (!newSysID) return; if ($scope.conversation.isPending) return; $scope.messagesLoadedOnce = false; $scope.conversationAlreadyViewed = $scope.conversation.unreadCount > 0; $scope.rawMessages = []; $scope.previousProfileID = void(0); if (!$scope.conversation) return; if ($scope.conversation.sysID) { snComposingPresence.set($scope.conversation.sysID, {viewing: [], typing: []}); snRecordPresence.initPresence("live_group_profile", $scope.conversation.sysID); } refreshMessages().then(function(loadedMessages) { if (loadedMessages.length === 30) $scope.checkForUnloadedMessages(); }); }); $scope.$root.$on("sn.sessions", function(name, data) { if (!$scope.conversation || !$scope.conversation.members) return; var viewing = {}; var typing = {}; angular.forEach(data, function(value){ if (value.user_id === userID) return; var conversationID = $scope.conversation.sysID; if (value.sys_id === conversationID) { if (value.status === "typing") { typing[value.user_id] = true; delete viewing[value.user_id]; } else if ((value.status === "viewing" || value.status === "entered") && !typing[value.user_id]) { viewing[value.user_id] = true; } } }); var conversationViewing = []; var conversationTyping = []; if($scope.conversation.amMember) { angular.forEach($scope.conversation.members, function(member) { if (viewing[member.document]) conversationViewing.push(member); if (typing[member.document]) conversationTyping.push(member); }); snComposingPresence.set($scope.conversation.sysID, {viewing: conversationViewing, typing: conversationTyping}); } }); $rootScope.$on("sn.presence", function(event, presenceArray) { if (!$scope.conversation || !$scope.conversation.members) return; if (!presenceArray || presenceArray.length < 2) return; var conversationID = $scope.conversation.sysID; var currentComposingPresence = snComposingPresence.get(conversationID); var viewing = currentComposingPresence.viewing; var typing = currentComposingPresence.typing; var conversationViewing = viewing.filter(function(member){ return checkPresence(member, presenceArray); }); var conversationTyping = typing.filter(function(member){ return checkPresence(member, presenceArray); }); snComposingPresence.set(conversationID, {viewing: conversationViewing, typing: conversationTyping}); }); function checkPresence(user, presenceArray) { return presenceArray .find(function(presence){ return (user.userID == presence.user && presence.status == "online") }); } $scope.$on("conversation.refresh_messages", function(e, data) { if($scope.conversation.sysID !== data.sysID) return; refreshMessages(); }); $scope.$on("amb.connection.recovered", refreshMessages); $scope.$on("amb.session.logged.in", refreshMessages); $scope.$on("amb.session.reestablished", refreshMessages); function refreshMessages() { return messageService.retrieveMessages($scope.conversation) .then(function(loadedMessages) { $timeout(function() { $scope.$broadcast('connect.auto_scroll.jump_to_bottom'); }, 500); $scope.messagesLoadedOnce = true; return loadedMessages; }) .catch(function() { $scope.messagesLoadedOnce = true; return []; }); } $scope.focusOnConversation = function() { if (activeConversation.pendingConversation) $rootScope.$broadcast("connect.message.focus", this.conversation); else activeConversation.conversation = $scope.conversation; }; $scope.retrieveMessageHistory = function() { if ($scope.conversation.isPending || $scope.conversation.restricted || !$scope.conversation.messageBatcher.batches.length) return $q.when([]); var earliestReceivedTime = $scope.conversation.firstMessage.timestamp; var promise = messageService.retrieveMessages($scope.conversation, earliestReceivedTime); if (!promise) return $q.when([]); var deferred = $q.defer(); promise.then(function (retrievedMessages) { $scope.messagesLoadedOnce = false; $scope.rawMessages = []; $scope.messagesLoadedOnce = true; deferred.resolve(retrievedMessages); }); return deferred.promise; }; $scope.$on("ngRepeat.complete", function(e) { if (angular.equals(e.targetScope, $scope)) return; $scope.$broadcast("ngRepeat.complete"); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationFooter.js */ angular.module('sn.connect.conversation').directive('snConversationFooter', function(getTemplateUrl) { "use strict"; return { restrict: 'E', templateUrl: getTemplateUrl("snConversationFooter.xml"), replace: true, scope: { conversation: "=" }, controller: function($scope, $rootScope, amb, uploadAttachmentService, queueEntries, inSupportClient, showActionsForClosedCases) { $scope.amb = amb; var snHttpError = false; $scope.$on('http-error.show', function () { snHttpError = true; }); $scope.$on('http-error.hide', function () { snHttpError = false; }); function getNoticeType () { if (isQueueEntry("isClosedByAgent") || isQueueEntry("isClosedByClient")) return "closed session"; if ($scope.conversation.restricted) return "restricted"; if (amb.interrupted || snHttpError) return "connection error"; if (inSupportClient && isQueueEntry("isReOpenable")) return "rejoin"; if (!inSupportClient && isQueueEntry("isWaiting")) return "agent waiting"; if ($scope.conversation.isPendingNoRecipients) return "no recipients"; if (uploadAttachmentService.filesInProgress.length > 0) return "upload in progress"; if ($scope.conversation.documentActive === "false") return "inactive document"; } $scope.isDocumentActive = function () { return !(getNoticeType() === "inactive document"); } $scope.isNoticeShowing = function() { return !!getNoticeType(); }; $scope.isClosedSessionShowing = function() { return getNoticeType() === "closed session"; }; $scope.isConnectionErrorShowing = function() { return getNoticeType() === "connection error"; }; $scope.isRestrictedShowing = function() { return getNoticeType() === "restricted"; }; $scope.isRejoinShowing = function() { return getNoticeType() === "rejoin"; }; $scope.isAgentWaitingShowing = function() { return getNoticeType() === "agent waiting"; }; $scope.isNewConversationNoRecipientsShowing = function() { return getNoticeType() === "no recipients"; }; $scope.isUploadInProgressShowing = function() { return getNoticeType() === "upload in progress"; }; $scope.isError = function() { return $scope.isRestrictedShowing() || $scope.isConnectionErrorShowing(); }; $scope.isQueueNameShowing = function() { return isQueueEntry("queue"); }; $scope.isQueueNumberShowing = function () { return $scope.conversation.table == 'chat_queue_entry'; }; $scope.isDocumentNumberShowing = function () { return $scope.conversation.hasRecord; }; function isQueueEntry(field) { return $scope.conversation.isHelpDesk && $scope.conversation.queueEntry[field]; } $scope.selectSnippet = function(snippet) { $scope.$broadcast("connect.conversation.insert_snippet", snippet); }; $scope.rejoin = function() { queueEntries.rejoin($scope.conversation.sysID); }; $scope.isMenuVisible = function() { return !inSupportClient && !$scope.conversation.isEmpty && $scope.conversation.chatActions && $scope.conversation.chatActions.getMenuActions().length > 0 && (!isQueueEntry("isClosedByAgent") || showActionsForClosedCases); }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationAddUserButton.js */ angular.module('sn.connect.conversation').directive('snConversationAddUserButton', function(getTemplateUrl) { "use strict"; return { restrict : 'E', scope: { conversation: "=" }, templateUrl: getTemplateUrl("snConversationAddUserButton.xml"), controller: function($scope, $rootScope, conversations, activeConversation) { $scope.userSelected = function(user) { conversations.addUser($scope.conversation.sysID, user) .then(function (conversation) { activeConversation.conversation = conversation; }) }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationContainer.js */ angular.module('sn.connect.conversation').directive('snConversationContainer', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', templateUrl: getTemplateUrl('snConversationContainer.xml'), replace: true, scope: {}, controller: function ($scope, $timeout, conversations, activeConversation, screenWidth) { $scope.activeConversation = activeConversation; var loading = true; conversations.loaded.then(function() { loading = false; }); $scope.$on("connect.new_conversation.cancelled", function() { activeConversation.pendingConversation = undefined; }); $scope.$on("connect.new_conversation.complete", function() { activeConversation.pendingConversation = undefined; }); $scope.$on("connect.show_create_conversation_screen", function(unused, preloadedMember) { activeConversation.pendingConversation = conversations.newConversation.$reset(); activeConversation.tab = 'chat'; if (preloadedMember) $timeout(function () { $scope.$emit("connect.member_profile.direct_message", preloadedMember); }); }); $scope.showLoading = function() { return loading; }; $scope.showIntroduction = function() { return !loading && activeConversation.isEmpty; }; $scope.showConversation = function() { return !loading && !activeConversation.isEmpty; }; $scope.showSidePanel = function() { return $scope.showConversation() && screenWidth.isAbove(800); }; $scope.isCloseNewConversationShowing = function() { return !conversations.newConversation.firstMessage; }; $scope.closeNewConversation = function() { $scope.$emit("connect.new_conversation.cancelled"); }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationHeader.js */ angular.module('sn.connect').directive('snConversationHeader', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', templateUrl: getTemplateUrl('snConversationHeader.xml'), replace: true, scope: { conversation: '=' }, controller: function($scope, $element, $timeout, conversations, snAttachmentHandler, userID) { $scope.conversationTemp = {}; $scope.middleAlignName = false; $scope.userID = userID; $scope.canEdit = function() { return $scope.conversation && $scope.conversation.isGroup; }; $scope.getPrimaryUser = function() { return $scope.conversation.isGroup ? $scope.conversation.lastMessage.profileData : $scope.conversation.peer; }; $scope.onlyShowName = function () { if ($scope.conversation.isHelpDesk) return false; if ($scope.conversation.isGroup) return !$scope.showDescription(); if (!$scope.conversation.peer) return true; var detail = $scope.conversation.peer.detail; return !detail || !(detail.department || detail.city); }; $scope.showDescription = function () { return $scope.conversation.isGroup && !(!$scope.conversation.description || $scope.conversation.description === "") && !($scope.conversation.isHelpDesk && $scope.conversation.queueEntry.isTransferPending); }; $scope.isEditable = function() { return $scope.conversation.isGroup && !$scope.conversation.isHelpDesk && $scope.conversation.amMember; }; $scope.saveGroupEdit = function() { conversations.update($scope.conversation.sysID, $scope.conversationTemp); }; $scope.openModal = function(evt) { if(evt.keyCode === 9 || !$scope.isEditable()) return; $scope.conversationTemp = { name: $scope.conversation.name, description: $scope.conversation.description, access: $scope.conversation.access }; angular.element("#chatGroupPopupModal").modal('show').find("#groupName").focus(); }; $scope.stopProp = function(event) { event.stopPropagation(); }; $scope.uploadNewGroupImage = function() { if($scope.conversation.amMember) $timeout(function() { $element.find(".message-attach-file").click(); }, 0, false); }; $scope.getImageBackground = function() { return {'background-image': "url('" + $scope.conversation.avatar + "')"} }; $scope.attachFiles = function(files) { $scope.uploading = true; snAttachmentHandler.create("live_group_profile", $scope.conversation.sysID).uploadAttachment(files.files[0], { sysparm_fieldname: "photo" }).then(function(response) { conversations.refreshConversation($scope.conversation.sysID); $scope.conversation.avatar = response.sys_id + ".iix"; $scope.uploading = false; }); } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationHeaderControls.js */ angular.module('sn.connect').directive('snConversationHeaderControls', function(getTemplateUrl, i18n) { 'use strict'; var knowledgeBaseTitle = ""; var documentTitle = ""; i18n.getMessages(["Knowledge Base", "Document"], function(results) { knowledgeBaseTitle = results["Knowledge Base"]; documentTitle = results["Document"]; }); return { restrict: 'E', templateUrl: getTemplateUrl('snConversationHeaderControls.xml'), replace: true, scope: { conversation: '=', collapsible: '@' }, link: function (scope, element, attrs) { attrs.$observe('collapsible', function (value) { scope.collapsible = scope.$eval(value || 'true'); }); }, controller: function($scope, $element, $animate, snConversationAsideHistory, $timeout) { $scope.expandDirection = "left"; $scope.activeAside = ""; $scope.buttons = $element.find('#conversationAsideButtons'); var activeAsideButton; var helpDeskAsides = ["knowledge", "record", "pending_record"]; var pendingRecordKeys = {}; var defaultAsideScope = $scope.$new(); var asideViews = { members: { template: "<sn-aside-member-list></sn-aside-member-list>", scope: defaultAsideScope }, info: { template: "<sn-aside-info></sn-aside-info>", scope: defaultAsideScope }, attachments: { template: "<sn-aside-attachments></sn-aside-attachments>", scope: defaultAsideScope }, notifications: { template: "<sn-aside-notifications></sn-aside-notifications>", scope: defaultAsideScope }, knowledge: { template: function() { return "<sn-aside-frame name='knowledge' url=\"/$knowledge.do\" title='" + knowledgeBaseTitle + "'></sn-aside-frame>"; }, width: "50%", cacheKey: function() { return $scope.conversation.sysID + ".knowledgeBase"; } }, record: { template: function() { return "<sn-aside-frame name='record' url=\"/" + $scope.conversation.table + ".do?sys_id=" + $scope.conversation.document + "\" title=\"" + documentTitle + "\"></sn-aside-frame>"; }, width: "50%", cacheKey: function() { return $scope.conversation.sysID + ".record"; } }, pending_record: { template: "", width: "50%", cacheKey: function() { return pendingRecordKeys[$scope.conversation.sysID] ? pendingRecordKeys[$scope.conversation.sysID] : $scope.conversation.sysID + ".pending_record"; } } }; $scope.isShowInfo = function() { return !$scope.conversation.isHelpDesk && ($scope.conversation.document || $scope.conversation.resources.links.length > 0 || $scope.conversation.resources.records.length > 0); }; $scope.isShowRecord = function() { return $scope.conversation.isHelpDesk && $scope.conversation.document && $scope.conversation.table != 'chat_queue_entry' }; function stringFunction(stringOrFunction) { if(angular.isFunction(stringOrFunction)) return stringOrFunction(); return stringOrFunction; } $scope.$on("sn.aside.open", function(e, view) { var cacheKey = stringFunction(view.cacheKey); if(cacheKey && cacheKey.indexOf("pending_record") > -1) { pendingRecordKeys[$scope.conversation.sysID] = cacheKey; } }); $scope.$watch("conversation.sysID", function() { var historicalAside = snConversationAsideHistory.getHistory($scope.conversation.sysID); if ($scope.conversation.restricted) { $scope.$emit("sn.aside.close"); return; } var historicalAsideScopeValid = (historicalAside && historicalAside.scope && historicalAside.scope.$parent && !historicalAside.scope.$parent["$$destroyed"]); if(historicalAside && historicalAsideScopeValid) { $scope.$evalAsync(function() { $scope.$emit("sn.aside.open", historicalAside); }); return; } if (!$scope.activeAside) return; if (!$scope.showInfo && $scope.activeAside === "info") { $scope.$emit("sn.aside.close"); return; } if (helpDeskAsides.indexOf($scope.activeAside) >= 0 && !$scope.conversation.isHelpDesk) { $scope.$emit("sn.aside.close"); return; } if ($scope.activeAside === "record" && $scope.conversation.table === "chat_queue_entry") { $scope.$emit("sn.aside.close"); return; } if ($scope.activeAside === "pending_record" && !$scope.conversation.pendingRecord) { $scope.$emit("sn.aside.close"); return; } $scope.$emit("sn.aside.open", asideViews[$scope.activeAside], asideWidth($scope.activeAside)); }); function asideWidth(view) { return asideViews[view].width || $scope.buttons.width(); } $scope.$on("sn.aside.trigger_control", function(e, view) { if (!asideViews.hasOwnProperty(view)) return; if ($scope.activeAside === view) { if ($scope.collapsible) $scope.$emit("sn.aside.close"); return; } $scope.activeAside = view; $timeout(function() { $scope.$emit("sn.aside.open", asideViews[view], asideWidth(view)); }, 0, false); }); $scope.openAside = function(view) { $scope.$emit("sn.aside.trigger_control", view); }; $scope.$on("sn.aside.controls.active", function(e, data) { activeAsideButton = $element.find('[aside-view-name="' + data + '"]'); $scope.activeAside = data; }); $scope.$on("sn.aside.close", function() { if(activeAsideButton) { activeAsideButton.focus(); } $scope.activeAside = void(0); activeAsideButton = void(0); }); function resizeAside(unused, phase) { if(phase === "close" && $scope.activeAside && asideViews[$scope.activeAside]) { $scope.$emit("sn.aside.resize", asideWidth($scope.activeAside)); } } $animate.on('addClass', $scope.buttons, resizeAside); $animate.on('removeClass', $scope.buttons, resizeAside); $scope.close = function(evt) { if(evt.keyCode === 9) return; $scope.$emit("sn.aside.close"); } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationItem.js */ angular.module('sn.connect.conversation').directive('snConversationItem', function( getTemplateUrl, inSupportClient, conversations, activeConversation) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl(inSupportClient ? 'snConversationItem-SupportClient.xml' : 'snConversationItem.xml'), replace: true, scope: { conversation: '=' }, controller: function($scope, $rootScope) { $scope.isBadgeVisible = function() { return ($scope.conversation.unreadCount > 0) && !$scope.isTransferPending(); }; $scope.getUserFromProfile = function (conversation) { return conversation.isGroup ? conversation.lastMessage.profileData : conversation.peer; }; $scope.remove = function($event) { if($event && $event.keyCode === 9) return; $rootScope.$broadcast("conversation.removed_from_sidebar"); $event.stopPropagation(); closeConversation(); }; function closeConversation() { if (conversations.close($scope.conversation.sysID)) { $rootScope.$broadcast("sn.aside.clearCache", $scope.conversation.sysID); activeConversation.clear($scope.conversation); } } return { closeConversation: closeConversation } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snSupportConversationItem.js */ angular.module('sn.connect.conversation').directive('snSupportConversationItem', function(getTemplateUrl, inSupportClient) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl(inSupportClient ? 'snConversationItem-SupportClient.xml' : 'snSupportConversationItem.xml'), replace: true, require: 'snConversationItem', scope: { conversation: '=' }, controller: function($scope, $rootScope, activeConversation, queueEntries, queueEntryNotifier, supportEnabled, inFrameSet, snConversationItemDirective) { var parent = snConversationItemDirective[0].controller.apply(this, arguments); $scope.supportEnabled = supportEnabled || false; for (var i = 0; i < $scope.conversation.members.length; i++) if ($scope.conversation.members[i].document === $scope.conversation.queueEntry.openedBy) $scope.openedBy = $scope.conversation.members[i]; $scope.acceptTransfer = function ($event) { $event.stopPropagation(); $scope.conversation.queueEntry.clearTransferState(); queueEntries.accept($scope.conversation.sysID); activeConversation.conversation = $scope.conversation; }; $scope.rejectTransfer = function ($event) { $event.stopPropagation(); $scope.conversation.queueEntry.clearTransferState(); queueEntries.reject($scope.conversation.sysID); if ($scope.conversation.queueEntry.transferShouldClose) parent.closeConversation(); }; $scope.cancelTransfer = function ($event) { $event.stopPropagation(); $scope.conversation.queueEntry.clearTransferState(); queueEntries.cancel($scope.conversation.sysID); }; $scope.isTransferPending = function() { return !!$scope.conversation.isHelpDesk && $scope.conversation.queueEntry.isTransferPending; }; $scope.isSendingTransfer = function() { return $scope.isTransferPending() && $scope.conversation.queueEntry.isTransferringFromMe; }; $scope.isReceivingTransfer = function() { return $scope.isTransferPending() && $scope.conversation.queueEntry.isTransferringToMe; }; $rootScope.$on("connect.queueEntry.updated", queueEntryUpdated); queueEntryUpdated(undefined, $scope.conversation.queueEntry); function queueEntryUpdated(event, queueEntry, old) { if (queueEntry.conversationID !== $scope.conversation.sysID) return; if (!queueEntry) return; var initial = angular.isUndefined(old); if (!queueEntry.isTransferStateChanged && !initial) return; if ((inFrameSet || activeConversation.isEmpty) && queueEntry.isTransferringToMe && queueEntry.isTransferPending) activeConversation.conversation = $scope.conversation; var isTransferNegative = queueEntry.isTransferCancelled || queueEntry.isTransferRejected; if (queueEntry.isTransferringToMe && queueEntry.transferShouldClose && isTransferNegative) parent.closeConversation(); queueEntryNotifier.notify($scope.conversation); } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snChatTab.js */ angular.module('sn.connect.conversation').directive('snChatTab', function(getTemplateUrl) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('snChatTab.xml'), replace: true, scope : {}, controller: function ($scope, $rootScope, $filter, conversations, activeConversation, inFrameSet, supportEnabled, supportAddMembers) { $scope.isSupportListEnabled = !supportEnabled && supportAddMembers; if (!inFrameSet) { var index = 0; var cachedConversationsIndex; $scope.$watch(function() { return activeConversation.sysID; }, function(sysID){ if (!sysID) return; index = conversations.find(activeConversation.conversation, filterConversations(true)).index; if (index < 0) index = 0; }); $scope.$watchCollection(function () { return filterConversations(true); }, function (conversationList) { if (activeConversation.isSupport) return; if (conversationList.length === 0) return; if (!activeConversation.isEmpty) return; activeConversation.conversation = getIndexConversation(conversationList); } ); $scope.$on('connect.conversation.select', function(unused, tab, conversationID) { if (activeConversation.getTab(tab).isSupport) return; conversationID = conversationID || activeConversation.sysID; var conversationList = filterConversations(!conversationID); var conversation; if (conversationID) conversation = conversations.find(conversationID, conversationList).conversation; activeConversation.conversation = conversation || getIndexConversation(conversationList); }); var getIndexConversation = function(conversationList) { if (index >= conversationList.length) index = conversationList.length -1; if (index < 0) index = 0; return conversationList[index]; } } $scope.$watch('searchTerm', function(newVal, oldVal) { $scope.$emit("connect.search_text",$scope.searchTerm); if (newVal === oldVal) return; if (!newVal) { conversations.loadConversations(); return; } conversations.updateConversations(newVal); }); $scope.supportConversationsFilter = function(conversations) { return supportEnabled ? [] : getConversations(conversations, true, true, $scope.searchTerm); }; $scope.openConversationsFilter = function(conversations) { return getConversations(conversations, true, false, $scope.searchTerm); }; $scope.closedConversationsFilter = function(conversations) { return getConversations(conversations, false, false, $scope.searchTerm); }; function getConversations(conversations, visible, support, searchTerm) { var searchFiltered = $filter('searchTerm')(conversations, searchTerm); if (searchFiltered.length === 0) return []; return $filter('conversation')(searchFiltered, visible, support); } function filterConversations(visible) { if (!visible) return getConversations(conversations.all); return $scope.supportConversationsFilter(conversations.all) .concat($scope.openConversationsFilter(conversations.all)); } $scope.triggerCreateConversation = function(evt) { if(evt && evt.keyCode === 9) return; $rootScope.$broadcast("connect.show_create_conversation_screen"); $rootScope.$broadcast('connect.pane.close'); }; $scope.clearFilterText = function() { $scope.searchTerm = ""; }; $scope.hasSearchText = function() { return $scope.searchTerm && $scope.searchTerm.length > 0; }; $scope.showOpenHeader = function() { return ($scope.hasSearchText() || hasSupportConversations()) && hasOpenConversations(); }; $scope.showClosedHeader = function() { return $scope.hasSearchText() && hasClosedConversations(); }; $scope.showMessageBlock = function() { return ($scope.showNoChatConversations() || $scope.showNoSearchResults() || $scope.isLoading()); }; $scope.showNoChatConversations = function() { return !$scope.hasSearchText() && filterConversations(true).length === 0; }; $scope.isLoading = function() { return conversations.isLoading; }; $scope.showNoSearchResults = function() { return $scope.hasSearchText() && !$scope.isLoading() && !hasSupportConversations() && !hasOpenConversations() && !hasClosedConversations(); }; function hasSupportConversations() { return $scope.supportConversationsFilter(conversations.all).length > 0; } function hasOpenConversations() { return $scope.openConversationsFilter(conversations.all).length > 0; } function hasClosedConversations() { return $scope.closedConversationsFilter(conversations.all).length > 0; } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snSupportTab.js */ angular.module('sn.connect.conversation').directive('snSupportTab', function(getTemplateUrl) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('snSupportTab.xml'), replace: true, scope : {}, controller: function ($scope, $filter, conversations, activeConversation, inFrameSet) { if (!inFrameSet) { $scope.$watchCollection(function () { return filterConversations(); }, function (conversationList) { if (!activeConversation.isSupport) return; if (conversationList.length === 0) return; if (activeConversation.isEmpty) activeConversation.conversation = conversationList[0]; } ); } $scope.primarySupportConversationsFilter = function(conversations) { return supportConversationsFilter(conversations, true); }; $scope.secondarySupportConversationsFilter = function(conversations) { return supportConversationsFilter(conversations, false); }; function supportConversationsFilter(conversations, primary) { return $filter('conversation')(conversations, true, true).filter(function(conversation){ var queueEntry = conversation.queueEntry; return primary === (queueEntry.isAssignedToMe || queueEntry.isTransferringToMe); }); }; function filterConversations() { return $scope.primarySupportConversationsFilter(conversations.all) .concat($scope.secondarySupportConversationsFilter(conversations.all)); } $scope.$on('connect.conversation.select', function(unused, tab, conversationID) { if (!activeConversation.getTab(tab).isSupport) return; if (!activeConversation.isEmpty && activeConversation.sysID === conversationID) return; conversationID = conversationID || activeConversation.sysID; var conversationList = filterConversations(); var conversation; if (conversationID) conversation = conversations.find(conversationID, conversationList).conversation; activeConversation.conversation = conversation || conversationList[0]; }); $scope.showNoSupportSession = function() { return filterConversations().length === 0; }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationList.js */ angular.module('sn.connect.conversation').directive('snConversationList', function(getTemplateUrl, i18n) { 'use strict'; var unreadMessage = 'Unread Messages'; i18n.getMessages([unreadMessage], function (i18nNames) { unreadMessage = i18nNames[unreadMessage]; }); return { restrict : 'E', templateUrl: getTemplateUrl('snConversationList.xml'), scope : { headerText: '@', isHelpDesk: '=?', filter: '&?', isHeaderVisible: '&?' }, controller: function ($scope, $rootScope, conversations, activeConversation, inSupportClient, inFrameSet) { var focusedConversation; $scope.isHelpDesk = $scope.isHelpDesk || false; $scope.conversations = []; $scope.inFrameSet = inFrameSet; if (angular.isUndefined($scope.isHeaderVisible)) { $scope.isHeaderVisible = function() { return function() { return $scope.conversations.length > 0; }; } } else { var value = $scope.isHeaderVisible(); if (!angular.isFunction(value)) { $scope.isHeaderVisible = function () { return function () { return value; }; } } } $scope.$watchCollection(function () { if ($scope.filter) return $scope.filter()(conversations.all); return conversations.all; }, function (conversations) { $scope.conversations = conversations || []; }); $scope.isActive = function(conversation) { return activeConversation.isActive(conversation) || conversation === focusedConversation; }; $scope.selectConversation = function(conversation) { $rootScope.$broadcast('connect.open.floating', conversation); $rootScope.$broadcast("connect.new_conversation.cancelled"); activeConversation.conversation = conversation; }; $scope.focusConversation = function(conversation, reverse) { if ( reverse && focusedConversation === conversation ) { focusedConversation = undefined; } else { focusedConversation = conversation; } }; $scope.getAriaText = function(conversation) { var text = inSupportClient ? conversation.description : conversation.name; text += conversation.unreadCount ? ' ' + conversation.formattedUnreadCount + ' ' + unreadMessage : ''; return text; } $scope.conversationDelta = function (conversation) { return conversation.sysID + conversation.avatar + conversation.name; } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationListContainer.js */ angular.module('sn.connect.conversation').directive('snConversationListContainer', function( getTemplateUrl, conversations, i18n) { 'use strict'; var supportTabAriaLabel = "Support Conversations - {0} Unread Messages"; i18n.getMessages([supportTabAriaLabel], function(results) { supportTabAriaLabel = results[supportTabAriaLabel]; }); return { restrict : 'E', templateUrl: getTemplateUrl('snConversationListContainer.xml'), replace: true, scope : { }, link: function(scope, element) { conversations.loaded.then(function() { element.removeClass("loading"); }) }, controller: function ($scope, $rootScope, $filter, snCustomEvent, conversationFactory, queues, activeConversation, supportEnabled, inFrameSet, chatEnabled) { $scope.inFrameSet = inFrameSet; $scope.supportEnabled = supportEnabled; $scope.chatEnabled = chatEnabled; $scope.hasSearchText = false; $scope.connectOffset = 0; $scope.supportOffset = 0; $scope.limit = 25; $scope.connectConversationsRemoved = 0; $scope.supportConversationsRemoved = 0; $scope.loadConversations = function() { if ($scope.hasSearchText) return; var offset; if (!$scope.isSupport()) { $scope.connectOffset = $scope.connectOffset + $scope.limit - $scope.connectConversationsRemoved; offset = $scope.connectOffset; } else { $scope.supportOffset = $scope.supportOffset + $scope.limit - $scope.supportConversationsRemoved; offset = $scope.supportOffset; } return conversations.loadConversations(offset, $scope.limit, $scope.isSupport()); }; $scope.showTabs = function() { return supportEnabled && chatEnabled; }; $scope.getSupportTabAriaLabel = function() { return i18n.format(supportTabAriaLabel, $scope.getSupportUnreadCount()); }; $scope.isUsersWaitingIndicatorShowing = function() { return (queues.getAllWaitingCount() > 0) && !$scope.isSupport(); }; snCustomEvent.observe('chat:open_conversation', function (profile) { var cachedPeerConversations = conversations.getCachedPeerConversations(profile.userID || profile.sys_id); if (cachedPeerConversations[0]) { activeConversation.tab = 'chat'; activeConversation.conversation = cachedPeerConversations[0]; } else { $rootScope.$broadcast("connect.show_create_conversation_screen", profile); } }); $scope.isSupport = function() { return activeConversation.isSupport; }; $scope.openChat = openTab('chat'); $scope.openSupport = openTab('support'); function openTab(tab) { return function () { activeConversation.tab = tab; } } $scope.getChatUnreadCount = getUnreadCount(false); $scope.getSupportUnreadCount = getUnreadCount(true); function getUnreadCount(isSupport) { return function () { var unreadCount = 0; $filter('conversation')(conversations.all, true, isSupport) .forEach(function (conversation) { if (isSupport && conversation.queueEntry && conversation.queueEntry.isTransferringToMe) return; unreadCount += conversation.unreadCount; }); return conversationFactory.formatUnreadCount(unreadCount); } } $scope.$watch(function() { return $scope.getChatUnreadCount() + $scope.getSupportUnreadCount(); }, function(unreadCount) { CustomEvent.fireTop('connect:message_notification.update', unreadCount); }); $scope.$on("connect.search_text",function(event,searchTerm) { if (searchTerm && searchTerm.length > 0) $scope.hasSearchText = true; else $scope.hasSearchText = false; }); $scope.$on("conversation.removed_from_sidebar", function() { ($scope.isSupport()) ? $scope.supportConversationsRemoved++ : $scope.connectConversationsRemoved++; if ($scope.connectConversationsRemoved >= 10) { $scope.loadConversations(); $scope.connectConversationsRemoved = 0; } if ($scope.supportConversationsRemoved >= 10) { $scope.loadConversations(); $scope.supportConversationsRemoved = 0; } }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snConversationSearch.js */ angular.module('sn.connect.conversation').directive('snConversationSearch', function(getTemplateUrl, $timeout) { "use strict"; return { restrict : 'E', scope: { title: "@", table: "=", name: "=", icon: "@", qualifier: "=?", searchField: "=?", onSelect: "&" }, templateUrl: getTemplateUrl('snConversationSearch.xml'), replace: true, link: function(scope, element) { scope.search = function(evt) { $timeout(function() { element.find(".select2-choice").triggerHandler("mousedown"); evt.preventDefault(); }, 0, false); return false; } }, controller: function($scope) { $scope.descriptor = { reference: $scope.table, attributes: '', name: $scope.name, searchField: $scope.searchField, qualifier: $scope.qualifier }; $scope.valueSelected = function() { $scope.onSelect({ value: "live_profile." + $scope.field.value }) }; $scope.field = {}; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snCreateNewConversationHeader.js */ angular.module('sn.connect.conversation').directive('snCreateNewConversationHeader', function(getTemplateUrl, $timeout) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('snCreateNewConversationHeader.xml'), replace: true, link: function(scope, elem) { var input; scope.focusOnInput = function() { if(!input) input = elem.find("input"); input.focus(); }; scope.scrollRecipientListToBottom = function() { $timeout(function() { var recipientListElem = document.getElementById("create-conversation-recipient-list"); recipientListElem.scrollTop = recipientListElem.scrollHeight; }, 0, false); }; var unWatch = scope.$on("live.search.control.ready", function(evt, control) { if(control) input = control; $timeout(scope.focusOnInput, 0, false); unWatch(); }); }, controller: function ($scope, $rootScope, activeConversation, conversations, snCustomEvent) { snCustomEvent.observe('connect:member_profile.direct_message', function (suggestion) { $scope.selectedMember(null, suggestion); if (suggestion) $scope.$broadcast("connect.message.focus", $scope.newConversation); }); $rootScope.$on("connect.member_profile.direct_message", function (evt, suggestion) { $scope.selectedMember(null, suggestion); if (suggestion) $scope.$broadcast("connect.message.focus", $scope.newConversation); }); function updatePendingConversation() { var conversation = conversations.newConversation; var pendingRecipients = conversation.pendingRecipients; if (pendingRecipients.length === 1) { var userSysID = pendingRecipients[0].sysID; var cachedPeerConversation = conversations.getCachedPeerConversations(userSysID)[0]; if (cachedPeerConversation) { conversation = angular.copy(cachedPeerConversation); conversation.isPending = true; } } activeConversation.pendingConversation = conversation; } $scope.pendingRecipients = function() { return conversations.newConversation.pendingRecipients; }; $scope.isAddUserShowing = function() { return !conversations.newConversation.firstMessage; }; $scope.ignoreList = function() { return conversations.newConversation.pendingRecipients.map(function(recipient){ return recipient.sysID; }).join(','); }; $scope.selectedMember = function(id, suggestion) { var sys_id = suggestion.sys_id || suggestion.userID || suggestion.jid.split(".")[1]; var recipient = { name: suggestion.name, jid: suggestion.jid || (suggestion.table + "." + sys_id), sysID: sys_id }; var alreadyAdded = conversations.newConversation.pendingRecipients .some(function(obj) { return angular.equals(obj, recipient); }); if(!alreadyAdded) { conversations.newConversation.pendingRecipients.push(recipient); updatePendingConversation(); } $scope.scrollRecipientListToBottom(); }; $scope.removeRecipient = function(event, index) { if(event && event.keyCode === 9) return; conversations.newConversation.pendingRecipients.splice(index, 1); updatePendingConversation(); $scope.focusOnInput(); }; $scope.$on("connect.search_control_key", function(evt, key) { $scope.$evalAsync(function() { if (key === "backspace") { conversations.newConversation.pendingRecipients.pop(); updatePendingConversation(); } else if (key === "enter") $rootScope.$broadcast("connect.message.focus", activeConversation.pendingConversation); else if (key === "escape") $scope.$emit("connect.new_conversation.cancelled"); }); }); $scope.$on("connect.message_control_key", function(evt, key) { if (key === "escape") $scope.$emit("connect.new_conversation.cancelled"); }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snFloatingConversation.js */ angular.module('sn.connect.conversation').directive('snFloatingConversation', function(getTemplateUrl, $timeout, $animate, isRTL) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('snFloatingConversation.xml'), replace: true, scope: { position: '=', conversation: '=' }, link: function(scope, element) { scope.$watch('position', function() { $timeout(function() { var property = isRTL ? 'left' : 'right'; element.css(property, scope.position); element.addClass('loaded'); }, 0 , false); }); scope.animateClose = function() { return $animate.addClass(element, "state-closing"); }; scope.$watch('conversation.isFrameStateOpen', function(value, old) { if (value === old) return; scope.$broadcast('connect.auto_scroll.scroll_to_bottom', scope.conversation); }); element.on("click", function(evt) { scope.focusOnConversation(); }); }, controller: function($scope, $rootScope, activeConversation, resourcePersister, profiles, queueEntries, documentsService, userID, $timeout, snCustomEvent, audioNotifier, supportAddMembers, connectDropTargetService) { $scope.activeConversation = activeConversation; $scope.userID = userID; $scope.popoverOpen = function (evt) { var el = angular.element(evt.target).closest(".sn-navhub-content").find(".sub-avatar"); $timeout(function () {angular.element(el).trigger('click')},0); }; CustomEvent.observe('glide:nav_sync_list_with_form', function(conversation) { $scope.$apply(function() { setSpotlighted(conversation); }) }); $scope.$on("connect.spotlight", function(evt, conversation) { setSpotlighted(conversation); }); function setSpotlighted(conversation) { $scope.isSpotlighted = conversation.table === $scope.conversation.table && conversation.sysID === $scope.conversation.document; } $scope.focusOnConversation = function(event) { activeConversation.conversation = $scope.conversation; if (!event) return; if (!$scope.conversation.isPending) return; if (angular.element(event.target).parents(".sn-add-users").length !== 0) return; $rootScope.$broadcast("connect.message.focus", $scope.conversation); }; $scope.isCurrentConversation = function() { return activeConversation.isActive($scope.conversation); }; $scope.isReadMessages = function() { return $scope.isCurrentConversation() && $scope.conversation.isFrameStateOpen; }; $scope.isTransferPending = function() { var queueEntry = $scope.conversation.queueEntry; return queueEntry && queueEntry.isTransferPending && queueEntry.isTransferringToMe; }; $scope.isCloseButtonShowing = function() { return !$scope.conversation.isPending || !$scope.conversation.firstMessage; }; if($scope.isTransferPending()) audioNotifier.notify($scope.conversation.sysID); $scope.$on("connect.floatingConversationEscape", function (evt) { $scope.removeConversation(evt); }); $scope.removeConversation = function($event) { if($event && $event.keyCode === 9) return; snCustomEvent.fireTop('snAvatar.closePopover'); $rootScope.$broadcast('mentio.closeMenu'); $scope.stopPropagation($event); $scope.animateClose().then(function() { if ($scope.conversation.isPending) { $rootScope.$broadcast("connect.new_conversation.cancelled"); return; } $scope.conversation.closeFrameState(); activeConversation.clear($scope.conversation); }) }; $scope.getWindowTarget = function () { return '_blank'; }; $scope.showDocument = function(table, sysID, $event) { $scope.stopPropagation($event); documentsService.show(table, sysID); }; $scope.showDocumentIfExists = function($event) { if ($scope.isDocumentConversation()) $scope.showDocument($scope.conversation.table, $scope.conversation.document, $event); }; $scope.stopPropagation = function($event) { if ($event) $event.stopPropagation(); }; var toggleOpenLock; $scope.toggleOpen = function($event) { $scope.stopPropagation($event); if (toggleOpenLock && $event.timeStamp === toggleOpenLock) { toggleOpenLock = null; return; } else toggleOpenLock = $event.timeStamp; if ($scope.conversation.isFrameStateOpen) { snCustomEvent.fireTop('snAvatar.closePopover'); $scope.conversation.minimizeFrameState(); if (activeConversation.isActive($scope.conversation)) activeConversation.clear(); } else { $scope.conversation.openFrameState(); $timeout(function() { activeConversation.conversation = $scope.conversation; }, 0, false); } }; $scope.isPendingVisible = function() { return $scope.isTransferPending() || $scope.conversation.isPending; }; $scope.isAddUserButtonVisible = function() { var conversation = $scope.conversation; if (!conversation.isHelpDesk) return conversation.isGroup && conversation.table !== 'vtb_board'; return supportAddMembers && conversation.queueEntry.isActive; }; $scope.activateDropTarget = function() { connectDropTargetService.activateDropTarget($scope.conversation); }; $scope.deactivateDropTarget = function() { connectDropTargetService.deactivateDropTarget($scope.conversation); }; $scope.onFileDrop = function(files) { connectDropTargetService.onFileDrop(files, $scope.conversation); }; $scope.handleDropEvent = function(data) { connectDropTargetService.handleDropEvent(data, $scope.conversation); }; $scope.getPrimary = function() { return $scope.conversation.isGroup ? $scope.conversation.lastMessage.profileData : $scope.conversation.peer; }; $scope.$watch('conversation', function (conversation) { if (activeConversation.isActive(conversation) && !conversation.isFrameStateOpen) activeConversation.clear(); }); $scope.$watch('conversation.queueEntry', function updateAssignedToProfile () { if (!$scope.conversation.isHelpDesk) return; profiles.getAsync('sys_user.' + $scope.conversation.queueEntry.assignedTo).then(function (profile) { $scope.assignedToProfile = profile; }); }); $scope.acceptTransfer = function ($event) { $scope.stopPropagation($event); queueEntries.accept($scope.conversation.sysID); }; $scope.rejectTransfer = function ($event) { $scope.stopPropagation($event); queueEntries.reject($scope.conversation.sysID); $scope.removeConversation(); }; $scope.isDocumentConversation = function( ) { return $scope.conversation.document !== ''; } } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snFloatingConversationCompressed.js */ angular.module('sn.connect.conversation').directive('snFloatingConversationCompressed', function(getTemplateUrl, $timeout, isRTL) { "use strict"; return { restrict : 'E', templateUrl: getTemplateUrl("snFloatingConversationCompressed.xml"), replace: true, scope: { start: '=', position: '=' }, link: function(scope, element) { var positionProperty = isRTL ? 'left' : 'right'; if (element.hideFix) { element.hideFix(); } scope.$watch("start", setRightCoordinate); function setRightCoordinate() { $timeout(function() { element.css(positionProperty, scope.position); }, 0, false); } setRightCoordinate(); }, controller: function($scope, $rootScope, $filter, conversations, activeConversation) { $scope.filterConversations = function() { return $filter('frameSet')(conversations.all); }; $scope.isVisible = function() { return $scope.compressConversations.length > 0; }; $scope.openConversation = function(conversation, $event) { if($event && $event.keyCode === 9) return; $rootScope.$broadcast('connect.open.floating', conversation); }; $scope.closeConversation = function(conversation, $event) { if($event && $event.keyCode === 9) return; conversation.closeFrameState(); activeConversation.clear(); }; $scope.toggleOpen = function() { $scope.open = !$scope.open; }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/directive.snFloatingConversationContainer.js */ angular.module('sn.connect.conversation').directive('snFloatingConversationContainer', function( getTemplateUrl, $rootScope, documentLinkMatcher, conversations, activeConversation) { "use strict"; return { restrict : 'E', templateUrl: getTemplateUrl('snFloatingConversationContainer.xml'), scope: {}, link: function(scope) { var mainFrame = angular.element("#gsft_main"); if(mainFrame.length > 0) { scope.$watch(function() { return mainFrame[0].contentDocument.location.href; }, checkForRecord); mainFrame.on("load", function() { scope.$digest(); }); mainFrame.on("click", function() { scope.$apply(function() { checkForRecord(mainFrame[0].contentDocument.location.href) }) }) } CustomEvent.observe("connect:open_group", function(data) { conversations.followDocumentConversation(data).then(function(conversation) { activeConversation.conversation = conversation; }) }); CustomEvent.observe("connect:follow_document", conversations.followDocumentConversation); CustomEvent.observe("connect:unfollow_document", conversations.unfollowDocumentConversation); function checkForRecord(newValue) { if (!documentLinkMatcher.isLink(newValue)) return; $rootScope.$broadcast("connect.spotlight", documentLinkMatcher.getRecordData(newValue)); } }, controller: function($scope, $element, $filter, $timeout, $window, snRecordPresence, conversationPersister, isRTL) { angular.element('document').append($element); var FRAME_SPACING = 350; var FRAME_COMPRESSED = 60; var FRAME_SEPARATOR = 10; var ASIDE_WIDTH = 285; $scope.activeConversation = activeConversation; conversations.refreshAll().then(function() { activeConversation.conversation = getFirstFocusConversation(); }); $scope.filterConversations = function() { return $filter('frameSet')(conversations.all); }; $scope.visibleFilterConversations = function() { var convs = $scope.filterConversations(); return convs.slice(0, $scope.getConversationDisplayCount()).reverse(); }; var isAsideOpen = false; CustomEvent.observe("connect:conversation_list:state", function(state) { isAsideOpen = state === "open"; resize(); }); angular.element($window).bind('resize', resize); var conversationDisplayCount = calculateConversationDisplayCount(); var resizeTimeout; function resize() { if (resizeTimeout) $timeout.cancel(resizeTimeout); resizeTimeout = $timeout(function() { conversationDisplayCount = calculateConversationDisplayCount(); }, 100); } function calculateConversationDisplayCount() { var frameWidth = $window.innerWidth; if (isAsideOpen) frameWidth -= ASIDE_WIDTH; var allWidth = $scope.filterConversations().length * FRAME_SPACING; frameWidth -= (allWidth > frameWidth) ? FRAME_COMPRESSED : FRAME_SEPARATOR; return Math.max(Math.floor(frameWidth / FRAME_SPACING), 1); } $scope.getConversationDisplayCount = function() { return conversationDisplayCount - (activeConversation.pendingConversation ? 1 : 0); }; $scope.getCompressPosition = function() { return $scope.getContainerPosition(conversationDisplayCount); }; $scope.getContainerPosition = function(index) { return index * FRAME_SPACING + FRAME_SEPARATOR; }; $scope.newConversation = function() { return conversations.newConversation; }; $scope.$watch(function(){ return activeConversation.sysID; }, function(sysID) { if (!sysID) { activeConversation.conversation = getFirstFocusConversation(); sysID = activeConversation.sysID; } if (sysID) snRecordPresence.initPresence("live_group_profile", sysID); }); function getFirstFocusConversation() { if (activeConversation.pendingConversation) return activeConversation.pendingConversation; var first = undefined; $scope.filterConversations() .some(function (conversation, index) { if (!conversation.isFrameStateOpen) return false; if (index > conversationDisplayCount) return false; first = conversation; return true; }); return first; } $scope.$on("connect.show_create_conversation_screen", function(evt, preloadedMember) { if (activeConversation.pendingConversation) return; activeConversation.pendingConversation = conversations.newConversation.$reset(); if (preloadedMember) $timeout(function () { $rootScope.$broadcast("connect.member_profile.direct_message", preloadedMember); $timeout(function () { $rootScope.$broadcast("connect.member_profile.direct_message", preloadedMember) }, 0, false); }); }); $scope.$on("connect.new_conversation.cancelled", function() { activeConversation.pendingConversation = undefined; if (activeConversation.isEmpty) activeConversation.conversation = getFirstFocusConversation(); }); $scope.$on("connect.new_conversation.complete", function(event, conversation) { activeConversation.pendingConversation = undefined; moveToTop(conversation); }); $scope.$on("connect.open.floating", function(event, conversation) { moveToTop(conversation); }); function moveToTop(conversation) { if (conversation.isPending) return; if (!conversation) return; conversation.openFrameState(); var conversationList = $scope.filterConversations(); var position = conversations.find(conversation, conversationList).index; if (position < 1) { activeConversation.conversation = conversation; $scope.$broadcast('connect.auto_scroll.jump_to_bottom'); return; } conversationList.splice(position, 1); conversationList.unshift(conversation); conversationPersister.changeFrameOrder(conversationList.map(function (conversation, index) { conversation.frameOrder = index; return conversation.sysID; })); activeConversation.conversation = conversation; $scope.$broadcast('connect.auto_scroll.jump_to_bottom'); } if(angular.element(document.body).data().layout) { var $connectFloating = $element.find('.sn-connect-floating'); var positionProperty = isRTL ? 'left' : 'right'; $connectFloating.css(positionProperty, "5px"); $scope.$on("pane.collapsed", function(evt, position, collapsed) { $connectFloating.css(positionProperty, collapsed ? "5px" : "290px"); }); } } } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/filter.searchTerm.js */ angular.module('sn.connect.conversation').filter('searchTerm', function() { 'use strict'; return function(input, searchTerm) { if (!searchTerm || searchTerm.length === 0) return input; var directMessages = [], groupMessages = []; input.filter(function(item) { if (item.isGroup) groupMessages.push(item); else directMessages.push(item); }); var tempA = [], tempB = []; directMessages.filter(function (item) { if (item.name.indexOf(searchTerm) === 0) { tempA.push(item); } else { tempB.push(item); } }); directMessages = tempA.concat(tempB); tempA = []; tempB = []; groupMessages.filter(function (item) { if (item.name.indexOf(searchTerm) === 0 || item.description.indexOf(searchTerm) === 0) { tempA.push(item); } else { tempB.push(item); } }); groupMessages = tempA.concat(tempB); var newInput = directMessages.concat(groupMessages); function contains(s, t) { var s2 = s.toUpperCase(); var t2 = t.toUpperCase(); return s2.indexOf(t2) > -1; } return newInput.filter(function(entry) { return contains(entry.name, searchTerm) || contains(entry.description, searchTerm) }); } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/filter.conversation.js */ angular.module('sn.connect.conversation').filter('conversation', function( inSupportClient, supportEnabled, supportAddMembers, closedConversationLimit) { 'use strict'; function isConversationDisplayable(conversation, isHelpDesk) { if (conversation.type == "interaction") { return false; } if (inSupportClient) return conversation.isHelpDesk && conversation.queueEntry.isOpenedByMe; if (isHelpDesk !== conversation.isHelpDesk) return false; if (!isHelpDesk) return true; return (supportEnabled || supportAddMembers) && !conversation.queueEntry.isOpenedByMe; } function isOpenSession(conversation, isOpenSession) { if (!conversation.isHelpDesk) return false; return !isOpenSession === (conversation.queueEntry.isClosedByAgent || conversation.queueEntry.isAbandoned || conversation.queueEntry.isClosedByClient); } function isVisible(conversation, visible) { return conversation.visible === visible; } function filter(input, filter, fn) { return angular.isUndefined(filter) ? input : input.filter(function (conversation) { return fn(conversation, filter); }); } return function(input, visible, helpDesk, openSession) { if (angular.isObject(visible)) { var object = visible; visible = object.visible; helpDesk = object.helpDesk; openSession = object.openSession; } input = filter(input, visible, isVisible); input = filter(input, helpDesk, isConversationDisplayable); input = filter(input, openSession, isOpenSession); input.sort(function(conv1, conv2){ return conv2.sortIndex - conv1.sortIndex; }); if (angular.isDefined(openSession) && !openSession && closedConversationLimit) input = input.slice(0, closedConversationLimit); return input; } }); ; /*! RESOURCE: /scripts/app.ng_chat/conversation/filter.frameSet.js */ angular.module('sn.connect.conversation').filter('frameSet', function() { 'use strict'; return function(input) { return input.filter(function(conversation){ return !conversation.isFrameStateClosed && conversation.visible; }).sort(function(conv1, conv2){ return conv1.frameOrder - conv2.frameOrder; }); } }); ; ; /*! RESOURCE: /scripts/app.ng_chat/resource/js_includes_connect_resource.js */ /*! RESOURCE: /scripts/app.ng_chat/resource/_module.js */ angular.module("sn.connect.resource", ["ng.common"]); ; /*! RESOURCE: /scripts/app.ng_chat/resource/factory.LiveLink.js */ angular.module("sn.connect.resource").factory("liveLinkFactory", function( $sce, $window, attachmentFactory, inFrameSet, enforceFrameSetLinking) { "use strict"; function linkObject(link, external, type) { var isConnectType = (type === 'connect'); external |= isConnectType; var url = (inFrameSet || external || !enforceFrameSetLinking) ? link : "/nav_to.do?uri=" + encodeURIComponent(link); var target = (!inFrameSet && isConnectType) ? "_self" : (inFrameSet && !external) ? 'gsft_main' : "_blank"; var classType = external ? "external-link" : "internal-link"; return { url: url, target: target, classType: classType } } function fromObject(data, visible) { if (angular.isUndefined(visible)) visible = true; var attachment = data.type_metadata && data.type_metadata.attachment; if (attachment) attachment = attachmentFactory.fromObject(attachment); return { sysID: data.sys_id, type: data.type, url: data.url, display: data.title || data.url, displayUrl: data.url.replace(/^(?:https?:\/)?\//, ''), title: data.title, shortDescription: data.short_description, siteName: data.site_name, timestamp: data.timestamp, external: data.external, displayFields: data.type_metadata && data.type_metadata.display_fields, embedLink: data.type_metadata && data.type_metadata.embed_link, imageLink: data.type_metadata && data.type_metadata.image_link, avatarID: data.type_metadata && data.type_metadata.avatar_id, avatarDisplay: data.type_metadata && data.type_metadata.avatar_display, createdOn: data.type_metadata && data.type_metadata.sys_created_on, updatedOn: data.type_metadata && data.type_metadata.sys_updated_on, isActive: data.state === "active", isPending: data.state === "pending", isError: data.state === "error", isUnauthorized: data.state === "unauthorized", isDeleted: data.state === "deleted", visible: visible, isRecord: data.type == "record", isImage: data.type === "image", attachment: attachment, get isHideable() { return ((attachment || this.isRecord) && this.isActive) || this.isImage; }, open: function(event) { if(event.keyCode === 9) return; var link = linkObject(this.url, this.external, this.type); var newWindow = $window.open(link.url, link.target); newWindow.opener = null; }, aTag: function(text) { var link = linkObject(this.url, this.external, this.type); var aTag = angular.element("<a />"); aTag.attr('class', link.classType); aTag.attr('rel', "noreferrer"); aTag.attr('target', link.target); aTag.attr('href', link.url); aTag[0].innerHTML = text; return $sce.getTrustedHtml(aTag[0].outerHTML); } }; } return { fromObject: fromObject, linkObject: linkObject } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/factory.attachment.js */ angular.module("sn.connect.resource").factory("attachmentFactory", function(fileSizeConverter, $window) { "use strict"; function fromObject(data) { data.size = fileSizeConverter.getByteCount("" + data.size_bytes, 2); var downloadSource = "/sys_attachment.do?sys_id=" + data.sys_id; var newTabSource = "/" + data.sys_id + ".iix"; return { rawData: data, sysID: data.sys_id, timestamp: data.sys_created_on, name: data.file_name || "Image", byteDisplay: data.size, canRead: data.can_read, fileName: data.file_name, sizeInBytes: data.size_bytes, compressSize: data.size_compressed, contentType: data.content_type, thumbSource: data.thumb_src, createdBy: data.sys_created_by, isImage: data.image, height: data.image_height, width: data.image_width, averageColor: data.average_image_color, newTabSource: newTabSource, downloadSource: downloadSource, open: function(event){ if(event.keyCode === 9) return; $window.open(newTabSource, "_blank"); }, download: function(event){ if(event.keyCode === 9) return; $window.open(downloadSource, "_self"); } } } return { fromObject: fromObject } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/service.resourcePersister.js */ angular.module('sn.connect.resource').service('resourcePersister', function( $q, snHttp, liveLinkFactory, attachmentFactory, $timeout, isLoggedIn) { "use strict"; var CONVERSATION_PATH = isLoggedIn?"/api/now/connect/conversations/":"/api/now/connect/support/anonymous/conversations/"; var FETCH_THRESHOLD = 25; var conversations = {}; var limit = FETCH_THRESHOLD; function addLink(conversationID, link) { var field = (link.isRecord) ? "records" : "links"; addToArray(conversationID, field, link, linkEquals); } function linkEquals(link1, link2){ return link1.url === link2.url; } function addAttachment(conversationID, attachment) { addToArray(conversationID, "attachments", attachment, attachmentEquals); } function attachmentEquals(attachment1, attachment2) { function cmp (field) { var field1 = attachment1[field]; var field2 = attachment2[field]; return !!field1 && field1 === field2; } return attachment1.isImage && cmp ("sizeInBytes") && cmp ("compressSize") && cmp ("contentType") && cmp ("height") && cmp ("width") && cmp ("averageColor"); } function addToArray(conversationID, field, element, equalsFn) { var resources = conversations[conversationID]; if (!resources) { conversations[conversationID] = newResource(); conversations[conversationID][field] = [element]; return; } var array = resources[field]; for (var i = 0; i < array.length; i += 1) { var item = array[i]; if (item.sysID === element.sysID) { array[i] = element; return; } if (equalsFn(item, element)) { if (item.timestamp > element.timestamp) return; array.splice(i, 1); break; } } for (i = 0; i < array.length; ++i) { if(array[i].timestamp <= element.timestamp) { array.splice(i, 0, element); return; } } array.push(element); } function newResource() { return { links: [], records: [], attachments: [] }; } function retrieve(conversationID) { var resources = conversations[conversationID]; if (resources && (resources.loading || resources.retrieved)) return; if(!resources) { resources = conversations[conversationID] = newResource(); } resources.loading = true; $timeout(function() { snHttp.get(CONVERSATION_PATH + conversationID + "/resources?sysparm_limit=" + limit).then(function(response) { delete conversations[conversationID].loading; conversations[conversationID].retrieved = true; limit = limit + FETCH_THRESHOLD; var result = response.data.result; result.links.forEach(function (rawLink) { addLink(conversationID, liveLinkFactory.fromObject(rawLink)); }); result.attachments.forEach(function (rawAttachment) { addAttachment(conversationID, attachmentFactory.fromObject(rawAttachment)); }); resources.retrieved = true; }); }) } return { get: function(conversationID) { retrieve(conversationID); return conversations[conversationID]; }, addLink: addLink, addAttachment: addAttachment }; }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/service.supportTabHandler.js */ angular.module('sn.connect.resource').service('supportTabHandler', function() { 'use strict'; var tabs = {}; var watches = {}; var globalWatches = []; function addTab(channelID, tab) { if(!channelID || !tab) return false; tabs[channelID] = tabs[channelID] || []; if(ngObjectIndexOf(tabs[channelID], tab) !== -1) return tab; tabs[channelID].push(tab); callWatches(channelID, tab); return tab; } function removeTab(channelID, tab) { if(!channelID || !tab || !tabs[channelID]) return false; var loc = ngObjectIndexOf(tabs[channelID], tab); if(loc !== -1) { var removedTab = tabs[channelID].splice(loc, 1)[0]; callWatches(channelID, removedTab); return removedTab; } return false; } function removeChannel(channelID) { if(!channelID || !tabs[channelID]) return false; tabs[channelID] = []; callWatches(channelID, []); return true; } function getTabs(channelID, sort) { if(!tabs[channelID]) return []; return sort? tabs[channelID].sort(function(a,b) { return a.$order - b.$order;}) : tabs[channelID]; } function ngObjectIndexOf(arr, obj) { for(var i = 0, len = arr.length; i < len; i++) if(angular.equals(arr[i], obj)) return i; return -1; } function watch(func, channelID) { if(channelID) { watches[channelID] = watches[channelID] || []; watches[channelID].push(func) } else { globalWatches.push(func); } return func; } function unwatch(func, channelID) { var i, len; if(channelID && watches[channelID]) { for(i = 0, len = watches[channelID].length; i < len; i++) { var watchLoc = watches[channelID].indexOf(func); if (watchLoc !== -1) watches[channelID].splice(watchLoc, 1); } } else { for(i = 0, len = globalWatches.length; i < len; i++) { var globalWatchLoc = globalWatches.indexOf(func); if(globalWatchLoc !== -1) globalWatches.splice(globalWatchLoc, 1); } } } function callWatches(channelID, response) { var i, len; if(channelID && watches[channelID] && watches[channelID].length) { for(i = 0, len = watches[channelID].length; i < len; i++) watches[channelID][i](response); } for(i = 0, len = globalWatches.length; i < len; i++) globalWatches[i](response); } return { add: addTab, remove: removeTab, get: getTabs, removeChannel: removeChannel, watch: watch, unwatch: unwatch }; }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideMemberList.js */ angular.module('sn.connect.resource').directive('snAsideMemberList', function( getTemplateUrl, $timeout, activeConversation) { 'use strict'; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideMemberList.xml'), link: function(scope, element) { scope.$on("sn.aside.open", function() { $timeout(function() { if(element.is(":visible")) scope.$emit("sn.aside.controls.active", "members"); }, 0, false); }); scope.changeMode = function (evt, mode) { if(!scope.conversation.amMember || (evt && evt.keyCode === 9)) return; scope.mode = mode; if (mode == 'add') { $timeout(function () { element.find('.form-control-search.tt-input').focus(); }, 200); } else if (mode == 'view') { $timeout(function () { element.find('.add-member-to-group').focus(); }, 200); } }; }, controller: function($scope, conversations, liveProfileID, supportAddMembers) { $scope.mode = 'view'; $scope.$emit("sn.aside.controls.active", "members"); $scope.viewProfile = function(evt, member) { if (evt.keyCode === 9) return; $scope.$emit("sn.aside.open", { templateUrl: getTemplateUrl("snAsideMemberList_profile.xml"), isChild: true, scope: { profile: member, showDirectMessage: !$scope.conversation.isDirectMessage && !$scope.conversation.isHelpDesk } }); }; $scope.isAddUserButtonVisible = function() { if ($scope.mode !== 'view') return false; return isButtonVisible(function() {return true;}); }; $scope.isLeaveButtonVisible = function() { var queueEntryCheckFn = function(queueEntry) { return !queueEntry.isAssignedToMe; }; return isButtonVisible(queueEntryCheckFn); }; $scope.isRemoveUserButtonVisible = function(userID) { var queueEntryCheckFn = function(queueEntry) { return queueEntry.openedBy !== userID && queueEntry.assignedTo !== userID; }; return isButtonVisible(queueEntryCheckFn); }; function isButtonVisible(queueEntryCheckFn) { var conversation = $scope.conversation; if (!conversation.isHelpDesk) return conversation.isGroup && conversation.table !== 'vtb_board'; var queueEntry = conversation.queueEntry; return supportAddMembers && queueEntryCheckFn(queueEntry) && queueEntry.isActive; } $scope.user = false; $scope.findUser = function () { for (var i = 0; i < $scope.conversation.members.length; i++) { if ($scope.conversation.members[i].sysID === liveProfileID) { $scope.user = $scope.conversation.members[i]; return; } } $scope.user = false; }; $scope.findUser(); $scope.$watch('conversation.sysID', function () { $scope.findUser(); }); $scope.addMember = function(memberID) { conversations.addUser($scope.conversation.sysID, memberID); $scope.changeMode(null, 'view'); if (!$scope.user) $scope.findUser(); }; $scope.showRemoveMember = function() { return $scope.conversation.amMember && $scope.conversation.isGroup; }; $scope.removeMember = function ($event, memberID) { if($event && $event.keyCode === 9) return; $event.stopPropagation(); conversations.removeUser($scope.conversation.sysID, memberID); if (memberID === liveProfileID) { activeConversation.clear($scope.conversation); $scope.user = null; } }; $scope.showAddMembers = function () { return !$scope.conversation.isHelpDesk && $scope.conversation.isGroup && $scope.mode == 'view' }; $scope.showUser = function () { return user && $scope.memberFilterText && user.name.indexOf($scope.memberFilterText) > -1; } } } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideInfo.js */ angular.module('sn.connect.resource').directive('snAsideInfo', function(getTemplateUrl, $timeout) { 'use strict'; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideInfo.xml'), link: function(scope, element) { scope.$on("sn.aside.open", function() { $timeout(function() { if(element.is(":visible")) scope.$emit("sn.aside.controls.active", "info"); }, 0, false); }); }, controller: function($scope) { $scope.$emit("sn.aside.controls.active", "info"); $scope.isFieldVisible = function(field) { return field.displayValue && field.type !== 'journal_input' && field.type !== 'journal_list'; }; $scope.historyBack = function(evt) { if(evt && evt.keyCode === 9) return; $scope.$emit("sn.aside.historyBack"); }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideInfoItem.js */ angular.module('sn.connect.resource').directive('snAsideInfoItem', function(getTemplateUrl) { 'use strict'; var iconMap = { record: "icon-article-document", link: "icon-link", connect: "icon-collaboration", uipage: "icon-document", search: "icon-search", list: "icon-list", chart: "icon-poll", update: "icon-form", image: "icon-image", video: "icon-video", unauthorized: "icon-locked sn-highlight_negative", error: "icon-alert-triangle", pending: "icon-loading" }; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideInfoItem.xml'), scope: { isLink: "=", title: "@", description: "@", link: "=" }, controller: function($scope) { $scope.isExternalIcon = function() { return !$scope.link.isPending && $scope.link.external; }; $scope.getExternalIcon = function() { return "https://www.google.com/s2/favicons?domain=" + $scope.link.url.toLowerCase(); }; $scope.getIcon = function() { if ($scope.link.isUnauthorized) return iconMap.unauthorized; if ($scope.link.isError) return iconMap.error; if ($scope.link.isPending) return iconMap.pending; return iconMap[$scope.link.type] || iconMap.link; }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideInfoViewAllItem.js */ angular.module('sn.connect.resource').directive('snAsideInfoViewAllItem', function(getTemplateUrl) { 'use strict'; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideInfoViewAllItem.xml'), scope: { title: "@", templateUrl: "@", minCount: "@", links: "=" }, controller: function($scope) { $scope.isShowing = function() { return $scope.links.length > $scope.minCount; }; $scope.openView = function(evt) { if (evt.keyCode === 9) return; $scope.$emit("sn.aside.open", { templateUrl: getTemplateUrl($scope.templateUrl), isChild: true, scope: $scope.$parent }); }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideAttachments.js */ angular.module('sn.connect.resource').directive('snAsideAttachments', function(getTemplateUrl, $timeout) { 'use strict'; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideAttachments.xml'), link: function(scope, element) { scope.$on("sn.aside.open", function() { $timeout(function() { if(element.is(":visible")) scope.$emit("sn.aside.controls.active", "attachments"); }, 0, false); }); }, controller: function($scope, $rootScope, resourcePersister) { $scope.$emit("sn.aside.controls.active", "attachments"); $scope.$watch("conversation.sysID", rawifyAttachments); $scope.$watchCollection("conversation.resources.attachments", rawifyAttachments); function rawifyAttachments() { $scope.attachments = $scope.conversation.resources.attachments.map(function(attachment){ return attachment.rawData; }); } rawifyAttachments(); $scope.attachFiles = function(evt) { if (evt.keyCode === 9) return; if($scope.conversation.amMember) $rootScope.$broadcast("connect.attachment_dialog.open", $scope.conversation.sysID); }; $scope.isAddButtonShowing = function() { return !$scope.conversation.isHelpDesk || !$scope.conversation.queueEntry.isClosedByAgent; } $scope.scrollConfig = { onScrollUp: function() { console.info("Up!"); }, onScrollDown:function () { console.info("Down!"); $scope.conversation.resources.retrieved = false; resourcePersister.get($scope.conversation.sysID); }, onScrollMissing: function () { console.info("Missing!"); } }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideNotifications.js */ angular.module('sn.connect.resource').directive('snAsideNotifications', function(getTemplateUrl, $timeout) { 'use strict'; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideNotifications.xml'), link: function(scope, element) { scope.$on("sn.aside.open", function() { $timeout(function() { if(element.is(":visible")) scope.$emit("sn.aside.controls.active", "notifications"); }, 0, false); }); }, controller: function($scope, notificationPreferences) { $scope.$emit("sn.aside.controls.active", "notifications"); $scope.showSystemMessage = function() { return !$scope.conversation.isDirectMessage && notificationPreferences.globalPreferences.mobile && $scope.conversation.preferences.mobile === "all"; }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideNotificationItem.js */ angular.module('sn.connect.resource').directive('snAsideNotificationItem', function(getTemplateUrl) { 'use strict'; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideNotificationItem.xml'), scope: { conversation: "=", section: "@", disableText: "@", disableLinkText: "@", description: "@", type: '@' }, controller: function($scope, notificationPreferences) { $scope.globalPreferences = notificationPreferences.globalPreferences; $scope.enable = function(event) { if(event.keyCode === 9) return; $scope.globalPreferences[$scope.type] = true; }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/resource/directive.snAsideFrame.js */ angular.module('sn.connect.resource').directive('snAsideFrame', function(getTemplateUrl, $timeout) { 'use strict'; return { replace : true, restrict : 'E', templateUrl: getTemplateUrl('snAsideFrame.xml'), link: function (scope, element, attrs) { scope.title = attrs.title; scope.url = attrs.url + (attrs.url.indexOf('?') < 0 ? '?' : '&') + "sysparm_clear_stack=true"; scope.name = attrs.name; scope.$on("sn.aside.open", function() { $timeout(function() { if(element.is(":visible")) scope.$emit("sn.aside.controls.active", scope.name); }, 0, false); }); }, controller: function($scope) { $timeout(function() { $scope.$emit('sn.aside.controls.active', $scope.name); }, 0, false); $scope.close = function(evt) { if(evt.keyCode === 9) return; $scope.$emit("sn.aside.close"); } } } }); ; ; /*! RESOURCE: /scripts/app.ng_chat/queue/js_includes_connect_queue.js */ /*! RESOURCE: /scripts/app.ng_chat/queue/_module.js */ angular.module("sn.connect.queue", ["sn.connect.profile", "sn.connect.conversation"]); ; /*! RESOURCE: /scripts/app.ng_chat/queue/directive.snQueueList.js */ angular.module('sn.connect.queue').directive('snQueueList', function(getTemplateUrl) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('snQueueList.xml'), replace: true, scope: { }, controller: function($scope, $filter, queues, conversations, supportConversationLimit) { $scope.agents = queues.agents; $scope.hasQueues = queues.hasQueues; $scope.isLimitReached = function () { if (supportConversationLimit === -1) return false; var supportConversations = $filter('conversation')(conversations.all, true, true) .filter(function(conversation){ var queueEntry = conversation.queueEntry; return queueEntry.isAssignedToMe && !queueEntry.isPermanentlyClosed; }); return supportConversationLimit <= supportConversations.length; }; $scope.$on('dialog.queue-error.show', function(evt, data) { $scope.queueErrorData = data; }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/directive.snQueueItem.js */ angular.module('sn.connect.queue').directive('snQueueItem', function(getTemplateUrl, $timeout, i18n) { 'use strict'; var acceptButtonLabel = "Accept Ticket From {0}"; i18n.getMessages([acceptButtonLabel], function(translations) { acceptButtonLabel = translations[acceptButtonLabel]; }); return { restrict: 'E', templateUrl: getTemplateUrl('snQueueItem.xml'), replace: true, scope: { queue: '=', canAnswer: '=' }, link: function(scope, element) { var flashCoolDown = 1000; var onCoolDown = false; var queueItem = element.find('.queue-item'); scope.flashQueue = function() { if(onCoolDown) return; onCoolDown = true; queueItem.addClass("highlight-flash"); $timeout(function() { queueItem.removeClass("highlight-flash"); }, 250); $timeout(function() { onCoolDown = false; }, flashCoolDown); } }, controller: function($scope, $rootScope, queueEntries, queueNotifier, conversations, activeConversation) { $scope.isEmpty = function() { return $scope.queue.waitingCount == 0; }; $scope.getAcceptAriaLabel = function() { return i18n.format(acceptButtonLabel, $scope.queue.name); }; $scope.answer = function() { $scope.isProcessingRequest = true; if ($scope.isEmpty()) return; if(!$scope.canAnswer) return; queueEntries.requestNext($scope.queue.id).then(function(queueEntry) { $scope.isProcessingRequest = false; conversations.get(queueEntry.conversationID).then(function(conversation) { activeConversation.conversation = conversation; }); }, function(response) { $scope.isProcessingRequest = false; if (response.status !== 404 || !response.data || !response.data.result || !response.data.result.error) return; $rootScope.$broadcast('dialog.queue-error.show', { queue: $scope.queue, message: response.data.result.error }); }) }; $scope.$watch('queue.waitingCount', function() { $scope.flashQueue(); queueNotifier.notify($scope.queue); }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/directive.snNonAgentClose.js */ angular.module('sn.connect.queue').directive('snNonAgentClose', function( getTemplateUrl, conversations, activeConversation) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snNonAgentClose.xml'), scope: {}, controller: function($scope) { $scope.$on('connect.non_agent_conversation.close_prompt', function (event, conversation) { $scope.conversation = conversation; $scope.$broadcast('dialog.queue-non-agent-modal.show'); }); $scope.close = function () { conversations.closeSupport($scope.conversation.sysID, true); activeConversation.clear($scope.conversation); }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/directive.snQueueEntryClose.js */ angular.module('sn.connect.queue').directive('snQueueEntryClose', function( getTemplateUrl, conversations, activeConversation) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snQueueEntryClose.xml'), scope: {}, controller: function($scope) { var hideConversation = true; $scope.$on('connect.support_conversation.close_prompt', function (event, conversation, shouldHide) { $scope.conversation = conversation; hideConversation = shouldHide; $scope.$broadcast('dialog.queue-entry-close-modal.show'); }); $scope.close = function () { conversations.closeSupport($scope.conversation.sysID, hideConversation); if (hideConversation) activeConversation.clear($scope.conversation); }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/directive.snQueueEntryTransfer.js */ angular.module('sn.connect.queue').directive('snQueueEntryTransfer', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snQueueEntryTransfer.xml'), scope: {}, controller: function($scope, queues, queueEntries, userID, supportConversationLimit) { $scope.queues = []; function reset () { $scope.queue = {}; $scope.agents = []; } $scope.$on('connect.support.conversation.transfer', function (event, conversation) { reset(); $scope.conversation = conversation; $scope.queues.length = 0; queueEntries.requestByConversation(conversation.sysID).then(function (queueEntry) { queues.getQueue(queueEntry.queueID).then(function(queue) { $scope.queue = queue; }); queues.getAgents(queueEntry.queueID).then(function (agents) { $scope.agents = agents.filter(function (agent) { return (agent.userID !== queueEntry.openedBy) && (agent.userID !== userID); }).sort(function (a, b) { return a.name.localeCompare(b.name); }); }); queues.refresh().then(function () { angular.forEach(queues.all, function (value, key) { if (key !== queueEntry.queueID) $scope.queues.push(value) }); }); $scope.$broadcast('dialog.transfer-modal.show'); }); }); $scope.close = reset; $scope.startsWith = function (actual, expected) { return actual.toLowerCase().indexOf(expected.toLowerCase()) > -1; }; $scope.canTransferToAgent = function (agent) { if (supportConversationLimit === -1) return true; if (!agent.supportConversationCount) return true; return agent.supportConversationCount < supportConversationLimit; }; $scope.transferToAgent = function (agent) { queueEntries.transfer($scope.conversation.sysID, agent.userID); $scope.$broadcast('dialog.transfer-modal.close'); reset(); }; $scope.transferToQueue = function (queue) { $scope.transferQueue = queue; $scope.$broadcast('dialog.transfer-modal.close'); reset(); $scope.$broadcast('dialog.queue-transfer-confirm.show'); }; $scope.transferQueueOk = function() { queueEntries.escalate($scope.conversation, $scope.transferQueue.id); }; $scope.cancelTransfer = function () { queueEntries.cancel($scope.conversation.sysID); }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/directive.snQueueEntryTransferAccepted.js */ angular.module('sn.connect.queue').directive('snQueueEntryTransferAccepted', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', replace: true, templateUrl: getTemplateUrl('snQueueEntryTransferAccepted.xml'), scope: {}, controller: function($scope, $rootScope, $timeout, $filter, activeConversation, conversations, queueEntries, profiles) { var transferOrder = []; $scope.$watchCollection(function() { return $filter('transferAccepted')(conversations.all).map(function(conversation){ return conversation.sysID; }); }, function(newCollection){ transferOrder = newCollection.sort(function(sysID1, sysID2){ return sortIndex(sysID1) - sortIndex(sysID2); }); if (transferOrder.length > 0) show(); else hide(); }); function sortIndex(sysID) { var index = transferOrder.indexOf(sysID); return (index < 0) ? 1000 : index; } $scope.leave = closeModal(true); $scope.stay = closeModal(false); function closeModal (removeConversation) { return function() { var conversation = conversations.indexed[currentSysID]; queueEntries.complete(currentSysID); conversation.queueEntry.clearTransferState(); if (removeConversation) { conversations.closeSupport(conversation.sysID, true); activeConversation.clear(conversation); } hide(); } } var currentSysID; function show() { var sysID = transferOrder[0]; if (currentSysID === sysID) return; currentSysID = sysID; var conversation = conversations.indexed[currentSysID]; var queueEntry = conversation.queueEntry; delete $scope.profileForSession; delete $scope.transferToProfile; profiles.getAsync('sys_user.' + queueEntry.openedBy).then(function (profile) { $scope.profileForSession = profile; profiles.getAsync('sys_user.' + queueEntry.transferTo).then(function (profile) { $scope.transferToProfile = profile; $scope.$broadcast('dialog.transfer-accepted-modal.show'); activeConversation.conversation = conversation; }); }); } function hide() { $scope.$broadcast('dialog.transfer-accepted-modal.close'); if (currentSysID === transferOrder[0]) transferOrder.shift(); currentSysID = undefined; if (transferOrder.length === 0) return; $timeout(function () { show(); }, 400); } } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/factory.queue.js */ angular.module('sn.connect.queue').factory('queueFactory', function() { 'use strict'; return { fromObject: function (data) { return { get id () { return data.sys_id; }, get name () { return data.name; }, get question () { return data.question; }, get waitTime () { return data.average_wait_time.replace(/ Minute(s?)/g, "m").replace(/ Hour(s?)/g, "h").replace(/ Second(s?)/g, "s"); }, get waitTimeLong () { return data.average_wait_time; }, get waitingCount () { return data.waiting_count; }, get available () { return angular.isUndefined(data.not_available); }, get unavailableMessage () { return data.not_available; }, get escalateTo () { return data.escalate_to; }, get isAgentsQueue() { return data.is_agent_for; }, __rawData: data }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/factory.queueEntry.js */ angular.module('sn.connect.queue').factory('queueEntryFactory', function(profiles, userID, queues) { 'use strict'; var WAITING = 1; var WORK_IN_PROGRESS = 2; var CLOSED_COMPLETE = 3; var CLOSED_ESCALATED = 4; var CLOSED_BY_CLIENT = 7; var CLOSED_ABANDONED = 8; var TRANSFER_PENDING = 'pending'; var TRANSFER_CANCELLED = 'cancelled'; var TRANSFER_ACCEPTED = 'accepted'; var TRANSFER_REJECTED = 'rejected'; return { fromObject: function (data) { return { equals: function (rawQueueEntry){ return angular.equals(data, rawQueueEntry); }, get averageWaitTime () { return data.average_wait_time; }, get sysID () { return data.sys_id; }, get queueID () { return data.queue; }, get queue () { return queues.all[data.queue]; }, get conversationID () { return data.group; }, get assignedTo () { return data.assigned_to; }, get isAssignedToMe () { return this.assignedTo === userID; }, get number () { return data.number; }, get position () { return data.position; }, get profile () { return profiles.get(data.sys_id); }, get shortDescription () { return data.short_description; }, get state () { return data.state; }, set state (value) { data.state = value; }, get waitTime () { return data.wait_time; }, get workStart () { return data.work_start; }, get workEnd () { return data.work_end; }, get workEndUserTZ() { return data.work_end_userTZ; }, get isTransferStateChanged () { return data.transfer_change; }, clearTransferState: function() { data.transfer_state = undefined; }, get hasTransfer () { return !!data.transfer_state; }, get isTransferPending () { return data.transfer_state === TRANSFER_PENDING; }, get isTransferCancelled () { return data.transfer_state === TRANSFER_CANCELLED; }, get isTransferAccepted () { return data.transfer_state === TRANSFER_ACCEPTED; }, get isTransferRejected () { return data.transfer_state === TRANSFER_REJECTED; }, get openedBy () { return data.opened_by; }, get isOpenedByMe () { return this.openedBy === userID; }, get transferTo () { return data.transfer_to; }, get isTransferringToMe () { return this.transferTo === userID; }, get isTransferringFromMe () { return data.transfer_from === userID; }, get transferShouldClose () { if (this.isAssignedToMe) return false; return data.transfer_should_close; }, get transferUpdatedOn () { return new Date(data.transfer_updated_on); }, get updatedOn () { return new Date(data.sys_updated_on); }, get isActive () { return this.isWaiting || this.isAccepted || (!this.isOpenedByMe && this.isClosedByClient); }, get isPermanentlyClosed() { return this.isClosedByAgent || this.isEscalated || this.isClosedByClient; }, get isReOpenable(){ return this.isAbandoned; }, get isWaiting () { return this.state === WAITING; }, get isAccepted () { return this.state === WORK_IN_PROGRESS; }, get isEscalated () { return this.state === CLOSED_ESCALATED; }, get isAbandoned () { return this.state === CLOSED_ABANDONED; }, get isClosedByAgent () { return this.state === CLOSED_COMPLETE; }, get isClosedByClient() { return this.state === CLOSED_BY_CLIENT; }, escalate: function(){ this.state = CLOSED_ESCALATED; } }; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/service.queues.js */ angular.module('sn.connect.queue').service('queues', function( $rootScope, $q, amb, snHttp, queueFactory, profiles, supportAddMembers, supportEnabled, inSupportClient, isLoggedIn, alertOnQueueEnter, audioNotifier) { 'use strict'; var AMB_CHANNEL = '/connect/support/queues'; var REST_API_PATH = isLoggedIn ? "/api/now/connect/support/queues" : "/api/now/connect/support/anonymous/queues"; var queues = {}; var agentsQueues = {}; var ambChannel; $rootScope.$on("amb.session.logged.in", function() {refresh();}); $rootScope.$on("amb.session.reestablished", function() {refresh();}); function refresh() { if ((supportAddMembers || supportEnabled) && !inSupportClient) { return snHttp.get(REST_API_PATH).then(function (response) { queues = {}; ambUnsubscribe(); if (response.data) { addRawQueues(response.data.result); ambSubscribe(); } return queues; }); } } function ambSubscribe() { if (!ambChannel) { ambChannel = amb.getChannel(AMB_CHANNEL).subscribe(function (response) { var queue = addRawQueue(response.data); addEscalationQueue(queue); return queue; }); amb.connect(); } return ambChannel; } function ambUnsubscribe() { if (ambChannel) { ambChannel.unsubscribe(); ambChannel = void(0); } } function addRawQueues(rawQueuesData) { angular.forEach(rawQueuesData, function (queueData) { addRawQueue(queueData); }); angular.forEach(queues, function (queue) { addEscalationQueue(queue); }); return queues; } function addRawQueue(rawQueueData) { if (!rawQueueData) return; if (queues[rawQueueData.sys_id]) { var existingItem = queues[rawQueueData.sys_id]; rawQueueData = angular.extend({}, existingItem.__rawData, rawQueueData); } var queue = queueFactory.fromObject(rawQueueData); if (queue.isAgentsQueue) { if (shouldAlertOnQueueEnter(queue)) { audioNotifier.notify({timestamp: Date.now()}); } agentsQueues[queue.id] = queue; } return queues[queue.id] = queue; } function shouldAlertOnQueueEnter(queue) { var staleQueue = agentsQueues[queue.id]; if (!staleQueue) { return false; } return alertOnQueueEnter && queue.waitingCount > staleQueue.waitingCount; } function addEscalationQueue(queue) { if (!queue.escalateTo) return; requestQueue(queue.escalateTo).then(function (escalationQueue) { queue.escalationQueue = escalationQueue; }); } function requestHttpQueue(queueID) { return snHttp.get(REST_API_PATH + '/' + queueID).then(function (response) { var queue = addRawQueue(response.data.result); addEscalationQueue(queue); return queue; }); } function requestQueue(queueID) { if (!queueID) return $q.when(); if (queues[queueID]) return $q.when(queues[queueID]); return requestHttpQueue(queueID); } refresh(); return { get all () { return queues; }, get agents () { return agentsQueues; }, hasQueues: function() { return Object.keys(agentsQueues).length > 0; }, refresh: refresh, getAgents: function (queueID) { return snHttp.get(REST_API_PATH + '/' + queueID + '/agents').then(function (response) { return response.data.result.map(profiles.fromObject); }); }, getQueue: requestQueue, getAllWaitingCount: function() { var waitingCount = 0; angular.forEach(agentsQueues, function(queue) { waitingCount = waitingCount + queue.waitingCount; }); return waitingCount; } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/service.queueNotifier.js */ angular.module('sn.connect.queue').service('queueNotifier', function($window, snNotifier, i18n, userPreferences, queues) { 'use strict'; var LOCAL_STORAGE_KEY = 'sn.connect.queueNotifier.lastUpdatedOn'; var queueWaitingCountUpdated; i18n.getMessages([ 'A new customer has joined your support queue' ], function (results) { queueWaitingCountUpdated = results['A new customer has joined your support queue']; }); var lastWaitingCounts = {}; angular.forEach(queues.all, function (queue) { updateWaitingCounts(queue); }); angular.element($window).on('storage', function(e) { if(e.originalEvent.key !== LOCAL_STORAGE_KEY) return; var lastWaitingCountsJson = $window.localStorage.getItem(LOCAL_STORAGE_KEY); if (lastWaitingCountsJson) { lastWaitingCounts = angular.fromJson(lastWaitingCountsJson); } }); function updateWaitingCounts (queue) { lastWaitingCounts[queue.id] = queue.waitingCount; $window.localStorage.setItem(LOCAL_STORAGE_KEY, angular.toJson(lastWaitingCounts)); } return { notify: function (queue) { userPreferences.getPreference('connect.notifications.desktop').then(function(value) { if(value === 'false') return; if (queue.waitingCount <= lastWaitingCounts[queue.id]) { updateWaitingCounts(queue); return; } updateWaitingCounts(queue); snNotifier().notify(queueWaitingCountUpdated); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/service.queueEntries.js */ angular.module('sn.connect.queue').service('queueEntries', function( $q, $rootScope, snHttp, amb, queueEntryFactory, queues, inSupportClient, isLoggedIn, snNotification, i18n, supportEnabled) { 'use strict'; var QUEUE_AMB = '/connect/support/queues'; var GROUP_AMB = '/connect/support/group/'; var queueEntries = {}; var ambWatchers = {}; if (inSupportClient || supportEnabled) { amb.getChannel(QUEUE_AMB).subscribe(function (response) { var queueID = response.data.sys_id; if (queues.agents[queueID]) { requestFiltered({'closed': !inSupportClient, 'queue_id': queueID}); } }); } amb.connect(); var messageUnknownError = "Unable to complete your request: An unknown error occurred"; i18n.getMessages([messageUnknownError], function (results) { messageUnknownError = results[messageUnknownError]; }); function requestFiltered(filter) { var url = '/api/now/connect/support/sessions'; if (filter) { url += '?'; for (var item in filter) if (filter.hasOwnProperty(item)) url += item + "=" + encodeURIComponent(filter[item]) + "&"; url = url.slice(0, -1); } return snHttp.get(url).then(function (response) { if (!response.data.result) return; angular.forEach(response.data.result, function (rawQueueEntry) { addRawQueueEntry(rawQueueEntry); }); }); } function addRawQueueEntry(rawQueueEntry) { var oldQueueEntry = queueEntries[rawQueueEntry.sys_id]; if (oldQueueEntry && oldQueueEntry.equals(rawQueueEntry)) return oldQueueEntry; var queueEntry = queueEntryFactory.fromObject(rawQueueEntry); queueEntries[queueEntry.conversationID] = queueEntries[queueEntry.sysID] = queueEntry; if(ambWatchers[queueEntry.conversationID]) { if (queueEntry.isPermanentlyClosed) removeAMBWatch(queueEntry.conversationID); } else if (!queueEntry.isPermanentlyClosed && (queueEntry.isOpenedByMe === inSupportClient)) { ambWatchers[queueEntry.conversationID] = amb.getChannel(GROUP_AMB + queueEntry.conversationID) .subscribe(function (response) { addRawQueueEntry(response.data); } ); } $rootScope.$broadcast("connect.queueEntry.updated", queueEntry, oldQueueEntry); return queueEntry; } function removeAMBWatch(conversationID) { if (ambWatchers[conversationID]) { ambWatchers[conversationID].unsubscribe(); delete ambWatchers[conversationID]; } } function remove(id) { var queueEntry = queueEntries[id]; if (!queueEntry) return; delete queueEntries[queueEntry.conversationID]; delete queueEntries[queueEntry.sysID]; removeAMBWatch(queueEntry.conversationID); } function postAction(conversationID, action, data) { data = data || {}; if (!conversationID) throw 'conversationID cannot be undefined'; var sessionsApiUri = isLoggedIn ? '/api/now/connect/support/sessions/' : '/api/now/connect/support/anonymous/sessions/'; return snHttp.post(sessionsApiUri + conversationID + action, data).then(function(response) { return addRawQueueEntry(response.data.result); }); } function requestByConversation(conversationID) { if (!conversationID) throw 'conversationID cannot be undefined'; var queueEntry = queueEntries[conversationID]; if (queueEntry) return $q.when(queueEntry); return requestFiltered({'group_id' :conversationID}).then(function (){ return queueEntries[conversationID]; }); } function requestNext(queueID) { return snHttp.post('/api/now/connect/support/queues/' + queueID + '/accept', {}).then(function (response) { return addRawQueueEntry(response.data.result); }); } return { addRaw: addRawQueueEntry, get: function (id) { return queueEntries[id]; }, requestByConversation: requestByConversation, create: function(queueID, message, fromRecord) { if (!queueID) throw 'queue ID cannot be undefined'; if (!message) throw 'message cannot be undefined'; var url = isLoggedIn? '/api/now/connect/support/queues/' + queueID + '/sessions' : '/api/now/connect/support/anonymous/queues/' + queueID + '/sessions'; var data = {message: message}; if(fromRecord && fromRecord.table && fromRecord.sysId) { data.from_table = fromRecord.table; data.from_sysid = fromRecord.sysId; } return snHttp.post(url, data).then(function (response) { return addRawQueueEntry(response.data.result); }, function(response) { if (response.status === 403 || response.status === 503) { snNotification.show("error", response.data.result); } else { snNotification.show("error", messageUnknownError); } return $q.reject(response) }); }, remove: remove, close: function (conversationID, agentLeave) { return postAction(conversationID, '/close', { agent_leave: !!agentLeave }); }, leave: function (conversationID) { return postAction(conversationID, '/leave'); }, rejoin: function (conversationID) { return postAction(conversationID, '/rejoin'); }, escalate: function (conversation, queueID) { queueID = queueID || conversation.queueEntry.queue.escalateTo; if (!queueID) throw "queueID must be set"; conversation.queueEntry.escalate(); return postAction(conversation.sysID, '/escalate/' + queueID); }, transfer: function (conversationID, agentID) { if (!agentID) throw 'agentID cannot be undefined'; return postAction(conversationID, '/transfer/' + agentID); }, accept: function (conversationID) { return postAction(conversationID, '/transfer/accept'); }, reject: function (conversationID) { var complete = this.complete; return postAction(conversationID, '/transfer/reject').then(function(){ return complete(conversationID); }); }, cancel: function (conversationID) { var complete = this.complete; return postAction(conversationID, '/transfer/cancel').then(function(){ return complete(conversationID); }); }, complete: function (conversationID) { return postAction(conversationID, '/transfer/complete'); }, requestNext: requestNext }; }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/service.queueEntryNotifier.js */ angular.module('sn.connect.queue').service('queueEntryNotifier', function( $window, snNotifier, i18n, profiles, userPreferences, activeConversation, snNotification, inFrameSet) { 'use strict'; var A_TAG = '<a href="/$c.do#/support" target="_self">{0}</a>'; var LOCAL_STORAGE_KEY = 'sn.connect.queueEntryNotifier.lastUpdatedOn'; var NOTIFICATION_TEMPLATE = ['You have an incoming case transfer from {0}.', 'To view the conversation, accept or decline the request,' ].join(' '); var transferPendingText, transferAcceptedText, transferRejectedText, transferCancelledText, transferPendingNotificationText; i18n.getMessages([ 'Incoming chat transfer', 'Accepted {0}', 'Rejected {0}', 'Cancelled transfer {0}', 'click here', NOTIFICATION_TEMPLATE ], function (results) { transferPendingText = results['Incoming chat transfer']; transferAcceptedText = results['Accepted {0}']; transferRejectedText = results['Rejected {0}']; transferCancelledText = results['Cancelled transfer {0}']; transferPendingNotificationText = results[NOTIFICATION_TEMPLATE] + " " + A_TAG.replace(/(\{0})/g, results['click here']); }); var lastUpdatedOn; angular.element($window).on('storage', function(e) { if(e.originalEvent.key !== LOCAL_STORAGE_KEY) return; lastUpdatedOn = $window.localStorage.getItem(LOCAL_STORAGE_KEY); if (lastUpdatedOn) { lastUpdatedOn = new Date(lastUpdatedOn) } }); return { notify: function (conversation) { var queueEntry = conversation.queueEntry; if (!inFrameSet && !activeConversation.isSupport && queueEntry.isTransferringToMe) { profiles.getAsync('sys_user.' + queueEntry.assignedTo).then(function(profile) { snNotification.show('info', i18n.format(transferPendingNotificationText, profile.name)) .then(function (element) { element.on('click', function () { snNotification.hide(element); activeConversation.conversation = conversation; }); }); }); } userPreferences.getPreference('connect.notifications.desktop').then(function(value) { if(value === 'false') return; if (!queueEntry.isTransferStateChanged) return; if (queueEntry.transferUpdatedOn <= lastUpdatedOn) return; var body, userID; if (queueEntry.isTransferringToMe) { if (queueEntry.isTransferPending) { userID = queueEntry.assignedTo; body = transferPendingText + "\n" + queueEntry.number + " - " + queueEntry.shortDescription; } if (queueEntry.isTransferCancelled) { userID = queueEntry.assignedTo; body = transferCancelledText.replace(/\{0\}/, queueEntry.number); } } else if (queueEntry.isTransferringFromMe) { if (queueEntry.isTransferAccepted) { userID = queueEntry.assignedTo; body = transferAcceptedText.replace(/\{0\}/, queueEntry.number); } if (queueEntry.isTransferRejected) { userID = queueEntry.transferTo; body = transferRejectedText.replace(/\{0\}/, queueEntry.number); } } if (!body) return; $window.localStorage.setItem(LOCAL_STORAGE_KEY, queueEntry.transferUpdatedOn); profiles.getAsync('sys_user.' + userID).then(function(profile) { snNotifier().notify(profile.name, { body: body, onClick: function () { activeConversation.conversation = conversation; } }); }); }); } } }); ; /*! RESOURCE: /scripts/app.ng_chat/queue/filter.transferAccepted.js */ angular.module('sn.connect.queue').filter('transferAccepted', function() { 'use strict'; return function (input) { return input.filter(function(conversation){ var queueEntry = conversation.queueEntry; return queueEntry && queueEntry.isTransferringFromMe && queueEntry.isTransferAccepted; }); } }); ; ; /*! RESOURCE: /scripts/app.ng_chat/search/directive.liveSearch.js */ angular.module('sn.connect').directive('liveSearch', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', templateUrl: getTemplateUrl('liveSearch.xml'), replace: true, scope: { type: '@', limit: '@', placeholder: '@', expandDirection: '@', onSelect: '&' }, link: function(scope) { scope.forwardOnSelect = function (id) { scope.onSelect({id: id}); }; } } }); ; /*! RESOURCE: /scripts/app.ng_chat/search/directive.liveSearchControl.js */ angular.module('sn.connect').directive('liveSearchControl', function( $compile, $timeout, getTemplateUrl, snHttp, userJID, $rootScope, i18n) { 'use strict'; var MINIMUM_TYPING_WAIT = 250; var CACHE_TIME_LIMIT = 15 * 60 * 1000; var liveSearchTranslatedStrings; i18n.getMessages([ 'People', 'No matching people', 'Groups', 'No matching groups', 'Messages', 'No matching messages'], function(result) { liveSearchTranslatedStrings = result; }); return { restrict: 'E', templateUrl: function(tElement, tAttrs) { if (tAttrs.templateUrl) return getTemplateUrl(tAttrs.templateUrl); else return getTemplateUrl('liveSearchControl.xml'); }, replace: true, scope: { type: '@', limit: '@', placeholder: '@', expandDirection: '@', onSelect: '&', templateOverride: '=?', ignoreBlur: '@', onBlur: "&?", ignoreList: "=" }, link: function(scope, element) { scope.triggerCreateConversation = function() { $rootScope.$broadcast("connect.show_create_conversation_screen"); $rootScope.$broadcast('connect.pane.close'); $rootScope.$broadcast("sn.aside.close", true); }; var suggestionScopes = []; var limit = scope.limit || 5; var searchURL = '/api/now/connect/search/' + scope.type + '?keywords={query}&limit=' + limit; if (!scope.onBlur) scope.onBlur = function() {}; function Search(table) { Search.promises = Search.promises || {}; var that = this; this.table = table; return function (query, sync, async) { that.debounce(function() { suggestionScopes.forEach(function (suggestionScope) { suggestionScope.$destroy(); }); that.getPromise(query).then(function (response) { if (response.data.result && response.data.result.length !== 0) { angular.forEach(response.data.result, function (result) { if (that.table !== result.table) return; async(result.searchResults); }); } else { async(); } return response; }); }); }; } Search.prototype.debounce = function(func) { $timeout.cancel(this.timeout); this.timeout = $timeout(func, MINIMUM_TYPING_WAIT); }; Search.prototype.removeStaleEntries = function() { var now = new Date(); for(var key in Search.promises) { if (!Search.promises.hasOwnProperty(key)) continue; var elapsed = now - Search.promises[key].time; if (elapsed > CACHE_TIME_LIMIT) { delete Search.promises[key]; } } }; Search.prototype.getPromise = function(query) { this.removeStaleEntries(); var url = searchURL.replace("{query}", encodeURIComponent(query)); if (scope.ignoreList) url += "&ignore=" + scope.ignoreList; var data = Search.promises[url]; if (!data) { data = Search.promises[url] = { promise: snHttp.get(url), time: new Date() }; } return data.promise; }; var templates = { sys_user:'<div class="sn-widget-list_v2"><div class="suggestion-user sn-widget-list-item"><div class="sn-widget-list-content sn-widget-list-content_static"><sn-avatar primary="::profile" class="avatar-small" nopopover="true"></sn-avatar></div><div class="sn-widget-list-content"><span class="name sn-widget-list-title">{{::profile.name}}</span><span class="suggestion-detail sn-widget-list-subtitle">{{::profile.email}}</span></div></div></div>', live_message:'<div class="sn-widget-list_v2"><div class="suggestion-message sn-widget-list-item"><div class="sn-widget-list-content sn-widget-list-content_static"><sn-avatar primary="::profile" class="avatar-small" nopopover="true"></sn-avatar></div><div class="details sn-widget-list-content"><span class="body sn-widget-list-title">{{::suggestion.formattedBody}}</span><span class="name sn-widget-list-subtitle">{{::profile.name}}</span></div></div></div>', live_group_profile:'<div class="sn-widget-list_v2"><div class="suggestion-group sn-widget-list-item"><div class="sn-widget-list-content sn-widget-list-content_static"><sn-avatar primary="::profile" members="::members" class="avatar-small" nopopover="true"></sn-avatar></div><div class="sn-widget-list-content"><span class="name sn-widget-list-title">{{::suggestion.name}}</span></div></div></div>' }; if(scope.templateOverride) angular.extend(templates, scope.templateOverride); var buildInitials = function(name) { if(!name) return "--"; var initials = name.split(" ").map(function(word) { return word.toUpperCase(); }).filter(function(word) { return word.match(/^[A-Z]/); }).map(function(word) { return word.substring(0,1); }).join(""); return initials.substr(0, 3); }; var isMember = function (member) { return (member && member.jid === userJID); }; var dataSet = function(table, displayKey, header, emptySuggestion) { return { name: table, limit: scope.limit, displayKey: displayKey, source: new Search(table), templates: { header: '<div id="valid_results" role="heading" aria-level="1" aria-live="polite" class="header sn-aside-group-title">' + header +'</div>', empty: '<div id="no_results" role="heading" aria-level="1" aria-live="polite" class="header sn-aside-group-title" aria-label="No search results found">' + emptySuggestion +'</div>', suggestion: function (suggestion) { var suggestionScope = scope.$new(); suggestionScopes.push(suggestionScope); suggestionScope.suggestion = suggestion; if (!isMember(suggestion.from) && !isMember(suggestion.to) && suggestion.to && suggestion.from) { suggestionScope.profile = { avatar: suggestion.from.avatarID, initials: buildInitials(suggestion.from.name), name: 'From: ' + suggestion.from.name }; } else if (isMember(suggestion.from) && suggestion.to && suggestion.to.name) { suggestionScope.profile = { avatar: suggestion.from.avatarID, initials: buildInitials(suggestion.from.name), name: 'To: ' + suggestion.to.name }; } else if (isMember(suggestion.to) && suggestion.from && suggestion.from.name) { suggestionScope.profile = { avatar: suggestion.from.avatarID, initials: buildInitials(suggestion.from.name), name: 'From: ' + suggestion.from.name }; } else { suggestionScope.profile = { avatar: suggestion.avatarID, initials: buildInitials(suggestion.name), name: suggestion.name, email: suggestion.email }; } if (suggestion.members) { suggestionScope.members = []; angular.forEach(suggestion.members, function (member) { suggestionScope.members.push({ avatar: member.avatarID, initials: buildInitials(suggestion.name), name: name }); }); } if(suggestion.body) { suggestion.formattedBody = suggestion.body.replace(/@\[[a-z0-9]{32}:([^\]]+?)\]/gi, "@$1"); } return $compile(templates[table])(suggestionScope); } } }; }; var selected = function (event, suggestion) { var id = ''; if (suggestion.jid.indexOf('live_message') === 0) { if (!isMember(suggestion.from) && !isMember(suggestion.to) && suggestion.to && suggestion.from) { id = suggestion.to.jid; } else if (isMember(suggestion.from) && suggestion.to) { id = suggestion.to.jid; } else if (isMember(suggestion.to) && suggestion.from) { id = suggestion.from.jid; } } else { id = suggestion.jid; } scope.onSelect({ id:id, suggestion: suggestion }); scope.$apply(); var target = angular.element(event.target); target.typeahead('close'); target.typeahead('val', ''); }; var options = [{ autoselect: 'first', hint: true, highlight: false, minLength: 2 }, dataSet('sys_user', 'name', liveSearchTranslatedStrings['People'], liveSearchTranslatedStrings['No matching people']) ]; if (scope.type !== 'user') { options.push(dataSet('live_message', 'body', liveSearchTranslatedStrings['Messages'], liveSearchTranslatedStrings['No matching messages'])); options.push(dataSet('live_group_profile', 'body', liveSearchTranslatedStrings['Groups'], liveSearchTranslatedStrings['No matching groups'])); } element.attr("aria-expanded", false); $timeout(function() { var input = element.find("input"); input.on("keydown", function(e) { if (input.val() !== "") return; if (e.keyCode === 8) scope.$emit("connect.search_control_key", "backspace"); else if (e.keyCode === 13) scope.$emit("connect.search_control_key", "enter"); else if (e.keyCode === 27) scope.$emit("connect.search_control_key", "escape"); }); function toggleAriaExpanded() { var resultsMenu = element.find('.tt-menu'); element.attr("aria-expanded", resultsMenu.css("display") !== "none"); } input.typeahead.apply(input, options); input.on('typeahead:selected', selected); input.on('typeahead:autocomplete', selected); input.on('typeahead:open', toggleAriaExpanded) input.on('typeahead:close', toggleAriaExpanded); input.on('keydown', function(e) { if (e.keyCode === 13) { var newEvent = angular.element.Event("keydown"); newEvent.keyCode = 9; input.trigger(newEvent); } }); scope.$emit("live.search.control.ready", input); if(scope.ignoreBlur) { var api = input.data('ttTypeahead'); api.input.off("blurred"); api._onBlurred = function() { this.isActivated = false; }; api.input.onSync("blurred", api._onBlurred, api); } input.on('typeahead:render', function() { var items = [].slice.apply(arguments).slice(1); if (items.length !== 0) { angular.element('#valid_results').attr('aria-label', (items.length + ' search results found, press down arrow to select from the list of items.')); toggleAriaExpanded(); } }); }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/search/directive.liveSearchPopover.js */ angular.module('sn.connect').directive('liveSearchPopover', function($timeout, $document, getTemplateUrl) { 'use strict'; var VK_ESC = 27; return { restrict : 'E', templateUrl: getTemplateUrl('liveSearchPopover.xml'), replace: true, scope : { type: '@', limit: '@', buttonId: '@', placeholder: '@', expandDirection: '@', onSelect: '&' }, link : function(scope, element) { element.detach(); var popoverButton; var getPopoverButton = function() { if (!popoverButton) { popoverButton = $document.find("#" + scope.buttonId); var toggleIgnore = function(event) { popoverButton.ignoreBlurHide = (event.type === 'mousedown'); }; popoverButton.mousedown(toggleIgnore); popoverButton.mouseup(toggleIgnore); } return popoverButton; }; scope.onSelectHidePopover = function(id) { scope.onSelect({id : id}); getPopoverButton().popover('hide'); }; scope.$on('live.search.control.ready', function (event, popoverInput) { popoverInput.data('ttTypeahead').input.off('blurred'); var hidePopover = function () { var popoverButton = getPopoverButton(); if (popoverButton.ignoreBlurHide) { return; } popoverButton.popover('hide'); }; popoverInput.on('blur', hidePopover); popoverInput.keyup(function (event) { var code = event.keyCode || event.which; if (code !== VK_ESC) { return; } hidePopover(); }); getPopoverButton().on('shown.bs.popover', function () { popoverInput.focus(); }); getPopoverButton().on('hidden.bs.popover', function () { popoverInput.typeahead('val', ''); }); }); $timeout(function() { getPopoverButton().popover({ container: 'body', placement: scope.expandDirection || 'right', html: true, content: function() { return angular.element('<div />').append(element); }, template: '<div class="sn-live-search-popover popover" role="tooltip">' + '<div class="arrow"></div>' + '<h3 class="popover-title"></h3>' + '<div class="popover-content"></div>' + '</div>' }); }); } }; }); ; /*! RESOURCE: /scripts/app.ng_chat/search/directive.snSearchButton.js */ angular.module('sn.connect').directive('snSearchButton', function(getTemplateUrl) { 'use strict'; return { restrict: 'E', templateUrl: getTemplateUrl('snSearchButton.xml'), replace: true, scope: { blockAside: '=', conversation: '=' }, controller: function($scope) { $scope.isActive = false; var asideView = { template: "<sn-aside-search></sn-aside-search>" }; $scope.openAside = function() { if(!$scope.buttons) $scope.buttons = angular.element('#conversationAsideButtons'); if($scope.blockAside || !$scope.conversation.sysID || $scope.conversation.isPending) return; if($scope.isActive) $scope.$emit("sn.aside.close"); else $scope.$emit("sn.aside.open", asideView, false, $scope.buttons.width()); }; $scope.$on("sn.aside.controls.active", function(e, data) { $scope.isActive = (data === "search"); }); $scope.$on("sn.aside.close", function() { $scope.isActive = false; }); } }; }); ; /*! RESOURCE: /scripts/doctype/CustomEventManager.js */ var NOW = NOW || {}; var CustomEventManager = (function (existingCustomEvent) { "use strict"; var events = (existingCustomEvent && existingCustomEvent.events) || {}; var isFiringFlag = false; var trace = false; var suppressEvents = false; var NOW_MSG = 'NOW.PostMessage'; function observe(eventName, fn){ if (trace) jslog("$CustomEventManager observing: " + eventName); on(eventName, fn); } function on(name, func) { if (!func || typeof func !== 'function') return; if (typeof name === 'undefined') return; if (!events[name]) events[name] = []; events[name].push(func); } function un(name, func) { if (!events[name]) return; var idx = -1; for (var i = 0; i < events[name].length; i++) { if (events[name][i] === func) { idx = i; break; } } if (idx >= 0) events[name].splice(idx, 1) } function unAll(name) { if (events[name]) delete events[name]; } function fire(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); return fireEvent.apply(null, arguments); } function fireUp(eventName, args){ var win = window; while (win){ try { if (win.CustomEvent.fireEvent.apply(null, arguments) === false) return; win = win.parent === win ? null : win.parent; }catch(e){ return; } } } function fireEvent() { if (suppressEvents) return true; var args = Array.prototype.slice.apply(arguments); var name = args.shift(); var eventList = events[name]; if (!eventList) return true; var event = eventList.slice(); isFiringFlag = true; for (var i = 0, l = event.length; i < l; i++) { var ev = event[i]; if (!ev) continue; if (ev.apply(null, args) === false) { isFiringFlag = false; return false; } } isFiringFlag = false; return true; } function isFiring() { return isFiringFlag; } function forward(name, element, func) { on(name, func); element.addEventListener(name, function(e) { fireEvent(e.type, this, e); }.bind(api)); } function isOriginInWhiteList(origin, whitelistStr) { if (!whitelistStr) { return false; } var delimiterRegex = /[\n, ]/; var whitelist = whitelistStr.split(delimiterRegex) .filter(function(whiteListedOrigin) { return whiteListedOrigin; }) .map(function(whiteListedOrigin) { return whiteListedOrigin.toLowerCase(); }); if (~whitelist.indexOf(origin.toLowerCase())) { return true; } return false; } function shouldProcessMessage(sourceOrigin) { if (!window.g_concourse_onmessage_enforce_same_origin || sourceOrigin === window.location.origin) { return true; } return isOriginInWhiteList(sourceOrigin, window.g_concourse_onmessage_enforce_same_origin_whitelist); } function registerPostMessageEvent() { if (NOW.registeredPostMessageEvent) { return; } if (!window.postMessage) { return; } window.addEventListener('message', function (event) { if (!shouldProcessMessage(event.origin)) { console.warn('Incoming message ignored due to origin mismatch.'); return; } var nowMessageJSON = event.data; var nowMessage; try { nowMessage = JSON.parse(nowMessageJSON.toString()); } catch (e) { return; } if (!nowMessage.type == NOW_MSG) { return; } fire(nowMessage.eventName, nowMessage.args); }, false); NOW.registeredPostMessageEvent = true; } function doPostMessage(win, event, msg, targetOrigin) { var nowMessage = {type: NOW_MSG, eventName: event, args: msg}; var nowMessageJSON; if (!win || !win.postMessage) { return } nowMessageJSON = JSON.stringify(nowMessage); win.postMessage(nowMessageJSON, targetOrigin); } function fireTop(eventName, args){ if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); fireEvent.apply(null, arguments); var t = getTopWindow(); if (t !== null && window !== t) t.CustomEvent.fire(eventName, args); } function fireAll(eventName, args) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + arguments.length); var topWindow = getTopWindow(); if (topWindow !== window.self) CustomEvent.fireEvent(eventName, args); notifyAllFrom(topWindow); function notifyAllFrom(rootFrame) { var childFrame; rootFrame.CustomEvent.fireEvent(eventName, args); for (var i = 0; i < rootFrame.frames.length; i++) { try { childFrame = rootFrame.frames[i]; if (!childFrame) continue; if (childFrame.CustomEvent && typeof childFrame.CustomEvent.fireEvent === "function") { notifyAllFrom(childFrame); } } catch(e) { } } } } function fireToWindow(targetWindow, eventName, args, usePostMessage, targetOrigin) { if (trace) jslog("$CustomEventManager firing: " + eventName + " args: " + args.length); if (usePostMessage) { doPostMessage(targetWindow, eventName, args, targetOrigin); } else { targetWindow.CustomEvent.fireEvent(eventName, args); } } function getTopWindow() { var topWindow = window.self; try { while (topWindow.CustomEvent.fireEvent && topWindow !== topWindow.parent && topWindow.parent.CustomEvent.fireEvent) { topWindow = topWindow.parent; } } catch (e) {} return topWindow; } function isTopWindow() { return getTopWindow() == window.self; } function jslog(msg, src, dateTime) { try { if (!src) { var path = window.self.location.pathname; src = path.substring(path.lastIndexOf('/') + 1); } if (window.self.opener && window != window.self.opener) { if (window.self.opener.jslog) { window.self.opener.jslog(msg, src, dateTime); } } else if (parent && parent.jslog && jslog != parent.jslog) { parent.jslog(msg, src, dateTime); } else { if (window.console && window.console.log) console.log(msg); } } catch (e) { } } var api = { set trace(value) { trace = !!value; }, get trace() { return trace; }, set suppressEvents(value) { suppressEvents = !!value; }, get suppressEvents() { return suppressEvents; }, get events() { return events; }, set events(value) { events = value; }, on: on, un: un, unAll: unAll, forward: forward, isFiring: isFiring, fireEvent: fireEvent, observe: observe, fire: fire, fireTop: fireTop, fireAll: fireAll, fireToWindow: fireToWindow, isTopWindow: isTopWindow, fireUp: fireUp, toString: function() { return 'CustomEventManager'; } }; registerPostMessageEvent(); return api; })(NOW.CustomEvent); NOW.CustomEvent = CustomEventManager; if (typeof CustomEvent !== "undefined") { CustomEvent.observe = NOW.CustomEvent.observe.bind(NOW.CustomEvent); CustomEvent.fire = NOW.CustomEvent.fire.bind(NOW.CustomEvent); CustomEvent.fireUp = NOW.CustomEvent.fireUp.bind(NOW.CustomEvent); CustomEvent.fireTop = NOW.CustomEvent.fireTop.bind(NOW.CustomEvent); CustomEvent.fireAll = NOW.CustomEvent.fireAll.bind(NOW.CustomEvent); CustomEvent.fireToWindow = NOW.CustomEvent.fireToWindow.bind(NOW.CustomEvent); CustomEvent.on = NOW.CustomEvent.on.bind(NOW.CustomEvent); CustomEvent.un = NOW.CustomEvent.un.bind(NOW.CustomEvent); CustomEvent.unAll = NOW.CustomEvent.unAll.bind(NOW.CustomEvent); CustomEvent.forward = NOW.CustomEvent.forward.bind(NOW.CustomEvent); CustomEvent.isFiring = NOW.CustomEvent.isFiring.bind(NOW.CustomEvent); CustomEvent.fireEvent = NOW.CustomEvent.fireEvent.bind(NOW.CustomEvent); CustomEvent.events = NOW.CustomEvent.events; CustomEvent.isTopWindow = NOW.CustomEvent.isTopWindow.bind(NOW.CustomEvent); } else { window.CustomEvent = NOW.CustomEvent; } ; ; /*! RESOURCE: /scripts/app.embedded_help/js_embedded_help_includes.js */ /*! RESOURCE: /scripts/app.embedded_help/app_embedded_help.js */ angular.module('sn.embedded_help', [ 'sn.base', 'ng.common', 'ngSanitize', 'sn.i18n' ]); ; /*! RESOURCE: /scripts/app.embedded_help/constants_embedded_help.js */ var EmbeddedHelpEvents = {}; EmbeddedHelpEvents.GUIDED_SETUP_ENABLE = "embedded_help.guided_setup.enable"; EmbeddedHelpEvents.GUIDED_SETUP_DISABLE = "embedded_help.guided_setup.disable"; EmbeddedHelpEvents.GUIDED_SETUP_ACTIONS_CHANGE = "embedded_help.guided_setup.actions_change"; EmbeddedHelpEvents.GUIDED_SETUP_ACTION_COMPLETE = "guided_setup:complete"; EmbeddedHelpEvents.GUIDED_SETUP_ACTION_INCOMPLETE = "guided_setup:incomplete"; EmbeddedHelpEvents.GUIDED_SETUP_ACTION_SKIP = "guided_setup:skip"; EmbeddedHelpEvents.GUIDED_SETUP_ACTION_EXIT = "guided_setup:exit"; EmbeddedHelpEvents.GUIDED_SETUP_ACTION_BACK = "guided_setup:back"; EmbeddedHelpEvents.TOUR_START = "embedded_help:tour.start"; EmbeddedHelpEvents.TOUR_END = "embedded_help:tour.end"; EmbeddedHelpEvents.TOUR_STATE = "embedded_help:tour:state"; EmbeddedHelpEvents.GT_API_START_TOUR = "embedded_help:tour:api:start"; EmbeddedHelpEvents.GT_API_END_TOUR = "embedded_help:tour:api:end"; EmbeddedHelpEvents.HOPSCOTCH_TOUR_START = "hopscotch.tour.start"; EmbeddedHelpEvents.HOPSCOTCH_TOUR_END = "hopscotch.tour.end"; EmbeddedHelpEvents.PANE_NAME = "embedded_help:help_pane"; EmbeddedHelpEvents.PANE_STATE = "embedded_help:help_pane:state"; EmbeddedHelpEvents.PANE_TOGGLE = "embedded_help:help_pane.toggle"; EmbeddedHelpEvents.PANE_LOAD = "magellanNavigator.permalink.set"; EmbeddedHelpEvents.CONTENT_LOAD = "embedded_help:content.load"; EmbeddedHelpEvents.DOCUMENT_LINK_CHANGE = "embedded_help:document_link.change"; EmbeddedHelpEvents.LOAD_EMBEDDED_HELP = "embedded_help:load_embedded_help"; var WebaEvents = {}; WebaEvents.CATEGORY = "EmbeddedHelp"; WebaEvents.TOUR_KEY = "Tour button"; WebaEvents.TOUR_VALUE = "Take a tour button clicked"; WebaEvents.HELP_PANE_KEY = "Help panel"; WebaEvents.HELP_PANE_VALUE = "Help panel opened"; WebaEvents.USER_GUIDE_KEY = "User guide"; WebaEvents.USER_GUIDE_VALUE = "User guide link clicked"; WebaEvents.SEARCH_DOC_KEY = "Search documentation"; WebaEvents.SEARCH_DOC_VALUE = "Search documentation link clicked"; ; /*! RESOURCE: /scripts/app.embedded_help/service.embeddedHelpService.js */ angular.module('sn.embedded_help').service('embeddedHelpService', ['$rootScope', '$http', '$q', '$window', '$location', '$cacheFactory', 'snCustomEvent', 'autoClosePane', 'persistGuidedSetupActions', 'helpUrl', function ($rootScope, $http, $q, $window, $location, $cacheFactory, snCustomEvent, autoClosePane, persistGuidedSetupActions, helpUrl) { "use strict"; var TOUR_SYS_ID_KEY = "embedded_help:tour:sys_id"; var TOUR_NAME_KEY="embedded_help:tour:name"; var GUIDED_SETUP_CONFIG_KEY = "embedded_help:guided_setup:config"; var DEFAULT_DOCUMENTATION_LINK = 'context_help.do'; var EMBEDDED_HELP_CONTENT = "sys_embedded_help_content.do"; var embeddedHelpLink = ""; var editArticleLink = ""; var resultCache = $cacheFactory('embedded_help_results'); var documentationLink = helpUrl || DEFAULT_DOCUMENTATION_LINK; var page = ""; var qualifier = ""; var modifier = "normal"; var guidedSetupConfig = getGuidedSetupConfig(); var activeTourSysId = getActiveTourSysId(); var activeTourName = getActiveTourName(); var queryString = ""; var sysId = ""; this.retrievePageDoc = function () { var deferred = $q.defer(); if (typeof page == 'undefined' || page == "") deferred.reject('page not set'); var endpoint = "/api/now/embeddedhelp/" + encodeURIComponent(page) + "/" + modifier; if (typeof qualifier != 'undefined' && qualifier != "" && qualifier !== "null") endpoint = endpoint + "/" + qualifier; else if (typeof queryString != 'undefined' && queryString != "" && queryString !== "null") endpoint = endpoint + queryString; var cachedItem = resultCache.get(endpoint); if (cachedItem) { deferred.resolve(cachedItem); return deferred.promise; } this.getEmbeddedHelp(endpoint).then(function success(response) { resultCache.put(endpoint, response.data); deferred.resolve(response.data); var result = response.data.result; if (typeof result != 'undefined' && result.length > 0) { for (var i = 0; i < result.length; i++) { if (result[i].type === 'content') { sysId = result[i].sysId; } } } $rootScope.$broadcast(EmbeddedHelpEvents.CONTENT_LOAD, '/nav_to.do?uri=/'+EMBEDDED_HELP_CONTENT+'?sys_id='+sysId); }, function error(response) { console.error(angular.toJson(response)); deferred.reject('Unknown error occurred'); }); return deferred.promise; } this.extractedLocationQuery = function (location) { var idxOfDo = -1; if (typeof location != 'undefined') { page = location; idxOfDo = page.indexOf('.do'); var idxOfHash = page.indexOf('#'); var pageStartsWithSlash = page.charAt(0) == '/'; if (idxOfDo >= 0) { page = pageStartsWithSlash ? page.substring(1, idxOfDo) : page.substring(0, idxOfDo); } else if (idxOfHash >= 0) { page = pageStartsWithSlash ? page.substring(1, idxOfHash) : page.substring(0, idxOfHash); } else if (pageStartsWithSlash) { page = page.substring(1); } } if (!helpUrl) { setDocumentationLink(location); $rootScope.$broadcast(EmbeddedHelpEvents.DOCUMENT_LINK_CHANGE, this.getDocumentationLink()); } setAddHelpArticle(location); return page; } this.getDocumentationLink = function() { return documentationLink; } function setDocumentationLink(location) { if (!location) { documentationLink = DEFAULT_DOCUMENTATION_LINK; return; } var urlParts = location.split('?'); var urlName= urlParts[0]; var urlParams = urlParts[1] || ''; var sysIdLoc = urlParams.search(/sys_id=[0-9a-f]{32}/i); var sysId = (sysIdLoc != -1) ? urlParams.substr(sysIdLoc, 39) : null; var urlSearch = '?sysparm_url=' + urlName; if (sysIdLoc != -1) urlSearch += '&' + sysId; documentationLink = DEFAULT_DOCUMENTATION_LINK + urlSearch; } this.addHelpArticle = function () { return embeddedHelpLink; } function setAddHelpArticle(location) { if (typeof qualifier == 'undefined' || qualifier == "" || qualifier == "null") { embeddedHelpLink = '/nav_to.do?uri=' + encodeURIComponent(EMBEDDED_HELP_CONTENT+'?sys_id=-1&sysparm_query=page='+page+'^modifier='+modifier+'^name='+page+'-'+modifier); } else { embeddedHelpLink = '/nav_to.do?uri=' + encodeURIComponent(EMBEDDED_HELP_CONTENT+'?sys_id=-1&sysparm_query=page='+page+'^modifier='+modifier+'^name='+page+'-'+modifier+'^qualifier='+qualifier); } } this.getEmbeddedHelp = function (endpoint) { return $http.get(endpoint); } this.setQualifier = function (qual) { qualifier = qual; } this.locationChange = function (location) { var locationValue = ""; if (location) { locationValue = location; locationValue = encodeURIComponent(locationValue); locationValue = '?uri=' + locationValue; } if (!isGuidedSetupSticky()) { modifier = "normal"; qualifier = ""; if(location) queryString = locationValue; } else { modifier = "setup"; var isSourceLocation = location && guidedSetupConfig.sourceLocation && normalizeUrlCompare(location, guidedSetupConfig.sourceLocation) !== -1; if (!guidedSetupConfig.sourceLocation) { guidedSetupConfig.sourceLocation = location; qualifier = qualifier || guidedSetupConfig.sourceQualifier; } else if (!persistGuidedSetupActions && (!isSourceLocation && !activeTourSysId)) { guidedSetupConfig.actions = []; } else if (isSourceLocation && !guidedSetupConfig.actions.length) { guidedSetupConfig.actions = createCopy(guidedSetupConfig.sourceActions); qualifier = guidedSetupConfig.sourceQualifier; } else if (typeof qualifier == 'undefined' || qualifier == "" || qualifier == "null") { queryString = locationValue; } } return this.extractedLocationQuery(location); } this.enableGuidedSetup = function (config) { modifier = "setup"; guidedSetupConfig = config || {}; guidedSetupConfig.sourceActions = createCopy(guidedSetupConfig.actions); if (config != null && typeof config != 'undefined') { if (config.qualifier != null && typeof config.qualifier != 'undefined') qualifier = guidedSetupConfig.sourceQualifier = config.qualifier; $window.sessionStorage.setItem(GUIDED_SETUP_CONFIG_KEY, angular.toJson(config)); } } this.disableGuidedSetup = function (eventName) { modifier = "normal"; guidedSetupConfig = {}; qualifier = ""; $window.sessionStorage.removeItem(GUIDED_SETUP_CONFIG_KEY); } this.getGuidedSetupConfig = function () { return getGuidedSetupConfig(); } this.isGuidedSetupSticky = function () { return isGuidedSetupSticky(); } this.handleGuidedSetupAction = function (action) { var backToGuidedSetupUrl = guidedSetupConfig.url; if (getActiveTourSysId()) this.endTour(); switch (action) { case EmbeddedHelpEvents.GUIDED_SETUP_ACTION_EXIT: this.disableGuidedSetup(); snCustomEvent.fireTop(EmbeddedHelpEvents.PANE_LOAD, { relativePath: $window.$location }); return; case EmbeddedHelpEvents.GUIDED_SETUP_ACTION_BACK: this.disableGuidedSetup(); goToGuidedSetupUrl(backToGuidedSetupUrl); break; default: var apiUrl = ""; angular.forEach(guidedSetupConfig.actions, function (value, key) { if (value.name === action) { apiUrl = value.apiUrl; return; } }); if (!apiUrl) { console.error('Guided Setup api url not provided for: ' + action); return; } $http.post(apiUrl).then(function success(response) { guidedSetupConfig.actions = guidedSetupConfig.sourceActions = response.data.result; $window.sessionStorage.setItem(GUIDED_SETUP_CONFIG_KEY, angular.toJson(guidedSetupConfig)); goToGuidedSetupUrl(backToGuidedSetupUrl); }, function error(response) { console.error(response); }); } } $rootScope.$watch(function () { return guidedSetupConfig.actions; }, function (newValue, oldValue) { $rootScope.$broadcast(EmbeddedHelpEvents.GUIDED_SETUP_ACTIONS_CHANGE, newValue); }); function getGuidedSetupConfig() { return angular.fromJson($window.sessionStorage.getItem(GUIDED_SETUP_CONFIG_KEY)) || {}; } function isGuidedSetupSticky() { return !angular.equals({}, guidedSetupConfig); } function goToGuidedSetupUrl(url) { var frame = angular.element('#gsft_main'); if (frame.length) frame[0].src = url; if (autoClosePane) $rootScope.$broadcast('help_pane.toggle_collapsed_state', true); } function createCopy(obj) { if (!obj) return null; return angular.fromJson(angular.toJson(obj)); } this.startTour = function (tour_sys_id, tour_step, tour_name, cbFunc) { $rootScope.$evalAsync(function () { if(top.NOW && top.NOW.guidedToursService){ top.NOW.guidedToursService.startTour(tour_sys_id, tour_step || 0, cbFunc); }else{ var counter = 0; var interval = setInterval(function(){ counter++; if(top.NOW && top.NOW.guidedToursService){ clearInterval(interval); top.NOW.guidedToursService.startTour(tour_sys_id, tour_step || 0, cbFunc); } if(counter == 5){ clearInterval(interval); } }, 2000); } }); $window.sessionStorage.setItem(TOUR_SYS_ID_KEY, tour_sys_id); $window.sessionStorage.setItem(TOUR_NAME_KEY, tour_name); activeTourSysId = tour_sys_id; activeTourName = tour_name; if (autoClosePane) $rootScope.$broadcast('help_pane.toggle_collapsed_state', true); } this.endTour = function () { $rootScope.$evalAsync(function () { top.NOW.guidedToursService.endTour(); }); $window.sessionStorage.removeItem(TOUR_SYS_ID_KEY); activeTourSysId = ""; $window.sessionStorage.removeItem(TOUR_NAME_KEY); activeTourName = ""; if (isGuidedSetupSticky() && !persistGuidedSetupActions) guidedSetupConfig.actions = guidedSetupConfig.sourceLocation.indexOf(page) >= 0 ? createCopy(guidedSetupConfig.sourceActions) : []; if (autoClosePane) $rootScope.$broadcast('help_pane.toggle_collapsed_state', false); } this.getActiveTourSysId = function () { return getActiveTourSysId(); } this.getActiveTourName = function() { return getActiveTourName(); } this.getCurrentPageUrl = function() { if (top.location.pathname === '/nav_to.do') { var search = decodeURIComponent(top.location.search); if (search.indexOf('?uri=/') === 0) { search = search.substring(6); } return search; } else { return top.location.href; } }; $rootScope.$watch(function () { return activeTourSysId; }, function (newValue, oldValue) { if (newValue !== oldValue) $rootScope.$broadcast(EmbeddedHelpEvents.TOUR_STATE_ID, newValue); }); $rootScope.$watch(function () { return activeTourName; }, function (newValue, oldValue) { if (newValue !== oldValue) { $rootScope.$broadcast(EmbeddedHelpEvents.TOUR_STATE_NAME,newValue); } }); function getActiveTourSysId() { if (typeof top.NOW.guidedToursService == 'undefined') { return null; } if (!top.NOW.guidedToursService.isTourRunning()) { activeTourSysId = ""; $window.sessionStorage.removeItem(TOUR_SYS_ID_KEY); } else { activeTourSysId = $window.sessionStorage.getItem(TOUR_SYS_ID_KEY); } return activeTourSysId; } function getActiveTourName() { if (typeof top.NOW.guidedToursService == 'undefined') { return null; } if (!top.NOW.guidedToursService.isTourRunning()) { activeTourName = ""; $window.sessionStorage.removeItem(TOUR_NAME_KEY); } else { activeTourName = $window.sessionStorage.getItem(TOUR_NAME_KEY); } return activeTourName; } function normalizeUrlCompare(url1, url2) { if (!url1 || !url2) return -1; else return normalizeUrl(url1).indexOf(normalizeUrl(url2)); } var IGNORE_PARAMS_ON_COMPARE = ['sysparm_list', 'sysparm_list_mode', 'sysparm_nameofstack', 'sysparm_clear_stack', 'sysparm_userpref_module', 'sysparm_offset', 'sysparm_first_row', 'sysparm_view', 'sysparm_query']; function normalizeUrl(url) { var i = url.indexOf('?'); if (i === -1) return url; var path = url.substring(0, i); var params = url.substring(i + 1).split('&'); params.sort(); var sortedAndUniqueParams = []; var lastParamName; for (var j = 0; j < params.length; j++) { var paramName = getParamName(params[j]); if (j > 0 && paramName === lastParamName) continue; if (IGNORE_PARAMS_ON_COMPARE.indexOf(paramName) === -1) sortedAndUniqueParams.push(params[j]); lastParamName = paramName; } url = path + '?' + sortedAndUniqueParams.join('&'); url = decodeURIComponent(url); return url; } function getParamName(p) { var idx = p.indexOf('='); if (idx > -1) return p.substring(0, idx); else return p; } } ]); ; /*! RESOURCE: /scripts/app.embedded_help/controller.embeddedHelp.js */ angular.module('sn.embedded_help').controller('embeddedHelp', ['$scope','$sce', '$rootScope', '$timeout', '$http', '$window', 'snCustomEvent', 'embeddedHelpService', 'userPreferences', 'paneManager', function ($scope, $sce, $rootScope, $timeout, $http, $window, snCustomEvent, embeddedHelpService, userPreferences, paneManager) { "use strict"; $scope.helpPaneCollapsed = true; $scope.loaded = false; $scope.content = ''; $scope.supressedTours = []; $scope.tours = []; $scope.showLanguageWarning = false; $scope.showAddHelpArticle = false; $scope.editArticleLink = ''; paneManager.registerPane(EmbeddedHelpEvents.PANE_NAME); userPreferences.getPreference('embedded_help:language_warning.suppress').then(function(value) { $scope.suppressLanguageWarning = value !== 'false'; }); snCustomEvent.observe(EmbeddedHelpEvents.GUIDED_SETUP_ENABLE, function (param) { embeddedHelpService.enableGuidedSetup(param); refreshEmbeddedHelp(); $scope.$broadcast('help_pane.toggle_collapsed_state', false); }); snCustomEvent.observe(EmbeddedHelpEvents.GUIDED_SETUP_DISABLE, function () { embeddedHelpService.disableGuidedSetup(); refreshEmbeddedHelp(); }); snCustomEvent.observe(EmbeddedHelpEvents.TOUR_START, function (tour_sys_id) { embeddedHelpService.startTour(tour_sys_id); }); snCustomEvent.observe(EmbeddedHelpEvents.TOUR_END, function () { embeddedHelpService.endTour(); refreshEmbeddedHelp(); }); snCustomEvent.observe(EmbeddedHelpEvents.GT_API_START_TOUR, function (tour_sys_id, step_num, cbFunc) { var tours = $scope.tours; var tour = []; if (tours.length>0) tour = tours.filter(function(tour){return tour.sysID==tour_sys_id;}); embeddedHelpService.startTour(tour_sys_id, step_num, (tour.length) ? tour[0].name : " ", cbFunc); refreshEmbeddedHelp(); }); snCustomEvent.observe(EmbeddedHelpEvents.GT_API_END_TOUR, function () { embeddedHelpService.endTour(); refreshEmbeddedHelp(); }); snCustomEvent.observe(EmbeddedHelpEvents.LOAD_EMBEDDED_HELP, function (qualifier) { embeddedHelpService.setQualifier(qualifier); refreshEmbeddedHelp(); $scope.$broadcast('help_pane.toggle_collapsed_state', false); }); snCustomEvent.observe(EmbeddedHelpEvents.PANE_LOAD, function (response) { var page = embeddedHelpService.locationChange(response.relativePath); if (page) { refreshEmbeddedHelp(); snCustomEvent.fireTop('gtd_child_iframe_loaded'); } }); function refreshEmbeddedHelp() { $scope.loaded = false; var formIFrame = document.getElementById('gsft_main'); if (formIFrame) { formIFrame = document.getElementById('gsft_main').contentDocument; var notTheDroids = formIFrame.getElementById('not_the_droids'); if (notTheDroids == null) { embeddedHelpService.retrievePageDoc().then(function success(response) { if (response && response.result) processEmbeddedHelp(response.result); }, function error(response) { console.error("Error retrieving embedded help content. " + angular.toJson(response)); }).finally(function () { $scope.loaded = true; }); } else { $scope.loaded = true; $scope.content = ''; } } } function processEmbeddedHelp(result) { var parsedResult = { sysid: '', content: '', default_language: false, add_help_card: false, tours: [] } if (typeof result != 'undefined' && result.length > 0) { for (var i = 0; i < result.length; i++) { if (result[i].type === 'content') { parsedResult.content = result[i].content; parsedResult.sysid = result[i].fSysId; parsedResult.default_language = result[i].default_language; parsedResult.add_help_card = result[i].add_help_card; } else if (result[i].type === 'tour') { parsedResult.tours.push(result[i]); } else { console.error("Unknown embedded help content type: " + result[i].type); } } } $scope.content = $sce.trustAsHtml(parsedResult.content); $scope.supressedTours = parsedResult.tours; $scope.showLanguageWarning = !$scope.suppressLanguageWarning && ($window.NOW.language != 'en' && parsedResult.default_language); $scope.showAddHelpArticle = parsedResult.add_help_card && !parsedResult.content; var AUTOSTART = $window.sessionStorage.getItem('AUTOSTART'); var TOURNAME= $window.sessionStorage.getItem('TOURNAME'); if(AUTOSTART != null){ var activeTourSysId=AUTOSTART; var activeTourName=TOURNAME; embeddedHelpService.startTour(activeTourSysId, 0, activeTourName); $window.sessionStorage.removeItem('AUTOSTART'); $window.sessionStorage.removeItem('TOURNAME'); } else{ var activeTourSysID = embeddedHelpService.getActiveTourSysId(); } if (activeTourSysID) { $scope.tours = [{ sysID: activeTourSysID }]; } else { $timeout(function() { $scope.tours = []; var url = embeddedHelpService.getCurrentPageUrl(); $scope.tours = parsedResult.tours.filter(function(t) { var params, splt, j; splt = t.context.split('?'); if (splt.length > 1) { params = splt[1].split('&'); for (j = 0; j < params.length; j++) { if (url.indexOf(params[j]) < 0) return false; } return true; } else { return url.indexOf(splt[0]) >= 0; } }); }, 500); } snCustomEvent.fireTop(EmbeddedHelpEvents.CONTENT_LOAD, typeof $scope.content !== 'undefined' && $scope.content != ''); } $rootScope.$on(EmbeddedHelpEvents.TOUR_STATE, function(event, activeTourSysId) { if (!activeTourSysId) refreshEmbeddedHelp(); }); $scope.$on('help_pane.toggle_collapsed_state', function(event, collapsedState) { if ($scope.helpPaneCollapsed !== collapsedState) paneManager.togglePane(EmbeddedHelpEvents.PANE_NAME); }); $rootScope.$broadcast('help_pane.collapsed', 'right', $scope.helpPaneCollapsed, false); snCustomEvent.observe(EmbeddedHelpEvents.PANE_TOGGLE, function (collapsed, autoFocusFirstItem) { $scope.helpPaneCollapsed = !$scope.helpPaneCollapsed; $rootScope.$broadcast('help_pane.collapsed', 'right', $scope.helpPaneCollapsed, autoFocusFirstItem); }); $scope.$watch('helpPaneCollapsed', function (listCollapsed) { snCustomEvent.fireTop(EmbeddedHelpEvents.PANE_STATE, (listCollapsed) ? 'closed' : 'open'); }); $scope.$on('help_pane.collapsed', function (event, position, collapsed, autoFocusFirstItem) { var $body = angular.element('body'); if ($body.data().layout) { if (collapsed) { $body.data().layout.hide('east'); } else { $body.data().layout.show('east'); $body.data().layout.sizePane('east', 285); } } else { var $layout = angular.element('.navpage-layout'), $pageRight = angular.element('.navpage-right'), $snEmbeddedHelp = angular.element('.sn-embedded-help-content'); if (collapsed) { $layout.addClass('navpage-right-hidden'); $pageRight.css('visibility', 'hidden'); $snEmbeddedHelp.addClass('sn-pane-hidden'); $snEmbeddedHelp.removeClass('sn-pane-visible'); } else { $layout.removeClass('navpage-right-hidden'); $pageRight.css('visibility', 'visible'); $snEmbeddedHelp.removeClass('sn-pane-hidden'); $snEmbeddedHelp.addClass('sn-pane-visible'); } if (autoFocusFirstItem) { $snEmbeddedHelp.one('transitionend', function() { if ($snEmbeddedHelp.hasClass('sn-pane-visible')) { $snEmbeddedHelp.find('.sn-widget-list-item') .filter(':visible') .filter(':first') .focus(); } }); } } }); $scope.$on('language-warning.confirmed', function (event, suppressLanguageWarning) { if (suppressLanguageWarning){ userPreferences.setPreference('embedded_help:language_warning.suppress', true); $scope.suppressLanguageWarning = true; } $scope.showLanguageWarning = false; }); } ]); ; /*! RESOURCE: /scripts/app.embedded_help/directive.embeddedHelpBarToggle.js */ angular.module('sn.embedded_help').directive('embeddedHelpBarToggle', ['getTemplateUrl', function (getTemplateUrl) { "use strict"; return { templateUrl: getTemplateUrl('embedded_help_bar_toggle.xml'), restrict: 'E', replace: true, scope: { state: '&' }, controller: ['$scope', 'snCustomEvent', 'paneManager', '$timeout', 'userPreferences', function ($scope, snCustomEvent, paneManager, $timeout, userPreferences) { $scope.state = "closed"; $scope.contentExists = false; $scope.toggleHelpPane = function () { paneManager.togglePane(EmbeddedHelpEvents.PANE_NAME, true); if ($scope.state === "closed") { window.GlideWebAnalytics.trackEvent(WebaEvents.CATEGORY, WebaEvents.HELP_PANE_KEY, WebaEvents.HELP_PANE_VALUE, 0); } }; userPreferences.getPreference('glide.ui.accessibility', false).then(function(val) { if (!!window.MSInputMethodContext && !!document.documentMode) { $scope.useIE11AccessibilitySpecialCase = val === "true" ? true : false; } }); function focusInput() { var btnToFocus = angular.element("#embeddedHelpDropdown"); if (btnToFocus.length > 0) btnToFocus.focus(); }; snCustomEvent.observe(EmbeddedHelpEvents.PANE_STATE, function (openState) { $scope.state = openState; var $snHelpPane = angular.element('.sn-embedded-help-content'); if (openState == 'open' && $snHelpPane.length > 0) { if ($scope.useIE11AccessibilitySpecialCase) { $timeout(function() { focusInput(); }, 425); } else { $snHelpPane.one('transitionend', function() { focusInput(); }); } } }); snCustomEvent.observe(EmbeddedHelpEvents.CONTENT_LOAD, function (contentExists) { $scope.contentExists = contentExists; }); }], link: function (scope, element) { scope.$on('help_pane.collapsed', function ($event, position, isCollapsed, autoFocus) { if (isCollapsed && autoFocus) { element.focus(); } }); } } } ]); ; /*! RESOURCE: /scripts/app.embedded_help/directive.snEmbeddedHelpPane.js */ angular.module('sn.embedded_help').directive('snEmbeddedHelpPane', function($timeout, getTemplateUrl, paneManager) { 'use strict'; return { restrict: 'E', replace: true, transclude: true, templateUrl: getTemplateUrl('sn_embedded_help_pane.xml'), scope: { paneCollapsed: '=', panePosition: '@', paneResizeable: '@', paneWidth: '=', paneToggle: '@' }, link: function(scope, element) { var scrollPromise; var mouseHeldDown = false; var mouseClicked = true; scope.$watch('paneWidth', function () { if (scope.paneWidth) { element.width(scope.paneWidth); } }); scope.isMobile = function () { return angular.element('html').width() <= 800; }; scope.scrollMousedown = function (moveBy) { scrollPromise = $timeout(function () { mouseHeldDown = true; mouseClicked = false; updateScrollPosition(moveBy); }, 300); }; scope.scrollMouseup = function () { $timeout.cancel(scrollPromise); scrollPromise = void(0); if (!mouseClicked) { mouseHeldDown = false; } }; scope.scrollUpCick = function () { if (mouseClicked) { var scrollContainer = element.find('.pane-scroll-container'); updateScrollPosition(-scrollContainer.height()); } mouseClicked = true; mouseHeldDown = false; }; scope.scrollDownCick = function () { if (mouseClicked) { var scrollContainer = element.find('.pane-scroll-container'); updateScrollPosition(scrollContainer.height()); } mouseClicked = true; mouseHeldDown = false; }; scope.actionClick = function(expression) { expression = expression.replace(/"/g, '\'' ); return eval(expression); } function updateScrollPosition (moveBy) { var scrollContainer = element.find('.pane-scroll-container'); scrollContainer.animate({scrollTop: scrollContainer[0].scrollTop + moveBy}, 300, 'linear', function () { if (mouseHeldDown) { updateScrollPosition(moveBy); } }); } function updateScrollButtons () { var scrollContainer = element.find('.pane-scroll-container'); if (scope.paneCollapsed && !scope.isMobile() && scrollContainer.get(0)) { if (scrollContainer.outerHeight() < scrollContainer.get(0).scrollHeight) { } else { } } else { } } scope.toggleHelpPane = function() { paneManager.togglePane(EmbeddedHelpEvents.PANE_NAME, true); updateScrollButtons(); } angular.element(window).on('resize', function() { updateScrollButtons(); }); $timeout(updateScrollButtons); } }; }); ; /*! RESOURCE: /scripts/app.embedded_help/directive.snEmbeddedHelpContent.js */ angular.module('sn.embedded_help').directive('snEmbeddedHelpContent', function(getTemplateUrl) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('sn_embedded_help_content.xml'), replace: true, scope : { collapsed: '=' }, link: function(scope, element) { element.removeClass("loading"); }, controller:['$scope', 'embeddedHelpService', function ($scope, embeddedHelpService) { $scope.suppressLanguageWarning = { suppress: false }; $scope.clicked = false; $scope.onConfirmLanguageWarningClick = function() { $scope.$emit('language-warning.confirmed', $scope.suppressLanguageWarning.suppress); } $scope.addHelpArticle = function() { window.open(embeddedHelpService.addHelpArticle()); } $scope.click = function() { if($scope.opened) angular.element('#embeddedHelpDropdown').blur(); else $scope.opened = true; } $scope.unclick = function() { $scope.opened = false; } }] }; }); ; /*! RESOURCE: /scripts/app.embedded_help/directive.snEmbeddedHelpActionList.js */ angular.module('sn.embedded_help').directive('snEmbeddedHelpActionList', ['getTemplateUrl', function(getTemplateUrl) { "use strict"; return { templateUrl : getTemplateUrl('sn_embedded_help_action_list.xml'), restrict : 'E', replace : true, controller : ['$scope', '$rootScope', 'embeddedHelpService', function($scope, $rootScope, embeddedHelpService) { $scope.helpEvents = EmbeddedHelpEvents; $scope.activeTourSysId = embeddedHelpService.getActiveTourSysId(); $scope.activeTourName = embeddedHelpService.getActiveTourName(); $scope.guidedSetupConfig = embeddedHelpService.getGuidedSetupConfig(); $scope.guidedSetupActions = $scope.guidedSetupConfig ? $scope.guidedSetupConfig.actions : []; $scope.isGuidedSetupSticky = isGuidedSetupSticky(); $scope.getTours = function () { return $scope.$parent.tours; } $scope.startTour = function(tour){ if(tour!=null){ embeddedHelpService.startTour(tour.sysID, 0, tour.name); $scope.activeTourName = tour.name; } } $scope.endTour = function() { embeddedHelpService.endTour(); } $rootScope.$on(EmbeddedHelpEvents.TOUR_STATE_ID, function(event, activeTourSysId) { $scope.activeTourSysId = activeTourSysId; }); $rootScope.$on(EmbeddedHelpEvents.TOUR_STATE_NAME, function(event, activeTourName) { $scope.activeTourName = activeTourName; }); $scope.trackTourEvent = function() { window.GlideWebAnalytics.trackEvent(WebaEvents.CATEGORY, WebaEvents.TOUR_KEY, WebaEvents.TOUR_VALUE, 0); } $scope.onGuidedSetupActionClick = function(action) { embeddedHelpService.handleGuidedSetupAction(action); } $rootScope.$on(EmbeddedHelpEvents.GUIDED_SETUP_ACTIONS_CHANGE, function(event, newGuidedSetupActions) { $scope.guidedSetupActions = newGuidedSetupActions; $scope.isGuidedSetupSticky = isGuidedSetupSticky(); }); function isGuidedSetupSticky() { $scope.guidedSetupConfig = embeddedHelpService.getGuidedSetupConfig(); return !angular.equals({}, $scope.guidedSetupConfig); } }] } } ]); ; /*! RESOURCE: /scripts/app.embedded_help/directive.snEmbeddedHelpMenu.js */ angular.module('sn.embedded_help').directive('snEmbeddedHelpMenu', ['getTemplateUrl', 'embeddedHelpService', function(getTemplateUrl, embeddedHelpService) { 'use strict'; return { restrict: 'E', replace: true, scope: { isContextMenu: '=', label: "@" }, templateUrl: getTemplateUrl('sn_embedded_help_menu.xml'), controller: function ($scope, $rootScope, snCustomEvent) { $scope.documentationLink = embeddedHelpService.getDocumentationLink(); $scope.isLeft = g_text_direction == 'ltr'; snCustomEvent.observe(EmbeddedHelpEvents.CONTENT_LOAD, function(contentExists) { $scope.contentExists = contentExists; }); $rootScope.$on(EmbeddedHelpEvents.DOCUMENT_LINK_CHANGE, function(event, documentLink) { $scope.documentationLink = documentLink; }); $rootScope.$on(EmbeddedHelpEvents.CONTENT_LOAD, function(event, link) { $scope.editArticleLink = link; }); $scope.trackUserGuideEvent = function() { window.GlideWebAnalytics.trackEvent(WebaEvents.CATEGORY, WebaEvents.USER_GUIDE_KEY, WebaEvents.USER_GUIDE_VALUE, 0); } $scope.trackSearchDocEvent = function() { window.GlideWebAnalytics.trackEvent(WebaEvents.CATEGORY, WebaEvents.SEARCH_DOC_KEY, WebaEvents.SEARCH_DOC_VALUE, 0); } } }; } ]); ; /*! RESOURCE: /scripts/js_includes_weba.js */ /*! RESOURCE: /scripts/doctype/GlideWebAnalytics.js */ var GlideWebAnalytics = (function() { function subscribe() { window.snWebaConfig = window.snWebaConfig || {}; if (window.snWebaConfig.subscribed && window.snWebaConfig.subscribed == true) return; var ambClient = getAMB(); if (ambClient == undefined || ambClient == "") return; var webaChannelId = "/weba/config"; var webaCh = ambClient.getChannel(webaChannelId); webaCh.subscribe(function(response) { if (window.snWebaConfig == undefined || window.snWebaConfig == null) window.snWebaConfig = {}; var oldConfig = { siteId : (window.snWebaConfig.siteId)? window.snWebaConfig.siteId: "0" , trackerURL : (window.snWebaConfig.trackerURL)? window.snWebaConfig.trackerURL: "" }; window.snWebaConfig.siteId = response.data.weba_site_id; window.snWebaConfig.trackerURL = response.data.weba_rx_url; window.snWebaConfig.webaScriptPath = response.data.weba_script_path; handleConfigUpdate(oldConfig, window.snWebaConfig); }); ambClient.connect(); window.snWebaConfig.subscribed = true; } function getAMB(){ var ambClient = window.snWebaConfig.ambClient; if (ambClient) return ambClient; window.snWebaConfig.ambClient = (window.g_ambClient) ? window.g_ambClient : ((window.amb)? window.amb.getClient(): ""); return window.snWebaConfig.ambClient; } function handleConfigUpdate(oldConfig, newConfig) { if (shouldRemoveTracker(oldConfig, newConfig)) removeTracker(); else if (shouldUpdateTracker(oldConfig, newConfig)) updateTracker(oldConfig, newConfig); else if (shouldInsertTracker(oldConfig, newConfig)) insertTracker(newConfig); } function shouldRemoveTracker(oldConfig, newConfig){ if (newConfig.siteId == "0" || newConfig.trackerURL == "") return true; return false; } function shouldUpdateTracker(oldConfig, newConfig){ if (oldConfig.siteId && oldConfig.siteId != "0" && oldConfig.siteId != newConfig.siteId) return true; if (oldConfig.trackerURL && oldConfig.trackerURL != newConfig.trackerURL) return true; return false; } function shouldInsertTracker(oldConfig, newConfig){ if (oldConfig.siteId == undefined || oldConfig.siteId == "0") return true; if (oldConfig.trackerURL == undefined || oldConfig.trackerURL == "") return true; return false; } function removeTracker() { if (!trackerExists()) return; removeWebaTracker(); removeWebaScript(); removeWebaElements(); } function removeWebaTracker() { var document = window.parent.document; var trackerScriptId = "webaTracker"; var trackEle = document.getElementById(trackerScriptId); trackEle.parentNode.removeChild(trackEle); } function removeWebaScript() { var document = window.parent.document; var asyncTrackEle = document.getElementById('webaScript'); if (asyncTrackEle == undefined) return; var src = asyncTrackEle.src; if (src != undefined && src.indexOf("piwik") > 0) asyncTrackEle.parentNode.removeChild(asyncTrackEle); } function removeWebaElements() { var document = window.parent.document; var webaEle = document.getElementsByClassName("weba"); var webaSize = webaEle.length - 1; while (webaSize >= 0){ webaEle[webaSize].parentNode.removeChild(webaEle[webaSize]); webaSize--; } } function updateTracker(oldConfig, newConfig) { if (!trackerExists()) return; var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; var updateScript = "_paq.push(['setSiteId', " + newConfig.siteId + "]);" + "_paq.push(['setTrackerUrl', " + "'" + newConfig.trackerURL + "'" + "]);"; var uEle = window.document.createElement("script"); uEle.text = updateScript; uEle.className = "weba"; head.appendChild(uEle); } function insertTracker(newConfig, additionalData) { var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; if (trackerExists()) return; if (!isConfigValid(newConfig)) return; var trackerScript = generateTrackerScript(newConfig, additionalData); var trackerElement = getOrCreateTracker(); trackerElement.text = trackerScript; head.appendChild(trackerElement); } function applyTracker(additionalData) { insertTracker(window.snWebaConfig, additionalData); subscribe(); } function applyTrackEvent(category, key, value, additionalValue) { insertEventTracker(category, key, value, additionalValue); subscribe(); } function insertEventTracker(category, key, value, additionalValue) { if (!isConfigValid(window.snWebaConfig)) return; if (!trackerExists()) insertTracker(window.snWebaConfig); if (typeof category != "string" || typeof key != "string" || typeof value != "string") return; if (additionalValue) additionalValue = (typeof additionalValue == "number")? additionalValue: 0; var eventItems = [ "trackEvent", category, key, value, additionalValue ]; var eventScript = "_paq.push(" + JSON.stringify(eventItems) + ");"; var document = window.parent.document; var head = document.head || document.getElementsByTagName('head')[0]; var scriptEle = window.document.createElement("script"); scriptEle.className = "weba"; scriptEle.text = eventScript; head.appendChild(scriptEle); } function trackerExists() { var document = window.parent.document; var trackEle = document.getElementById("webaTracker"); if (trackEle) return true; return false; } function isConfigValid(newConfig) { var zero = "0"; var webaSiteId = (newConfig && newConfig.siteId) ? newConfig.siteId : zero; var trackerURL = (newConfig && newConfig.trackerURL) ? newConfig.trackerURL : ""; if (webaSiteId == null || webaSiteId == "") return false; if (webaSiteId == zero ) return false; if (trackerURL == null || trackerURL == "") return false; return true; } function getOrCreateTracker() { var trackerScriptId = "webaTracker"; var document = window.parent.document; var trackEle = document.getElementById(trackerScriptId); if (trackEle) return trackEle; trackEle = document.createElement("script"); trackEle.id = trackerScriptId; trackEle.type = "text/javascript"; return trackEle; } function getUserId(additionalData) { if (window.NOW && window.NOW.user_id && window.NOW.user_id != "") return window.NOW.user_id; else if (additionalData && additionalData.userId){ return additionalData.userId; } else if (window.NOW && window.NOW.session_id) return window.NOW.session_id; else { var userObj = (window.NOW)? window.NOW.user: null; if (userObj && userObj.userID) return userObj.userID; } return ""; } function generateTrackerScript(webaConfig, additionalData) { var trackerURL = webaConfig.trackerURL; if (trackerURL.endsWith("/")) trackerURL = webaConfig.trackerURL.substring(0, trackerURL.length - 1); var userId = getUserId(additionalData); var script = "var _paq = _paq || [];"; if (userId && userId != ""){ script += "_paq.push(['setUserId', '" + userId + "']);"; } script += "_paq.push(['trackPageView']); _paq.push(['enableLinkTracking']);"; script += "(function() {_paq.push(['setTrackerUrl','" + trackerURL + "']);" + "_paq.push(['setSiteId', " + webaConfig.siteId + "]);" + "var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; " + "g.defer=true; g.src='" + webaConfig.webaScriptPath + "'; " + "g.id='webaScript';s.parentNode.insertBefore(g,s); })();"; return script; } var api = { trackPage: function(additionalData) { if (window.document.readyState == "complete") applyTracker(additionalData); else window.addEventListener("load", function() { applyTracker(additionalData); }, false); }, trackEvent: function(category, key, value, additionalValue, delayInMs) { if (delayInMs == undefined) delayInMs = 3000; window.setTimeout(function() { applyTrackEvent(category, key, value, additionalValue); }, delayInMs); } } return api; })(); ; ; ; /*! RESOURCE: /scripts/js_hopscotch_includes.js */ /*! RESOURCE: /scripts/hopscotch.min.js */ /**! hopscotch - v0.2.5 * * Copyright 2015 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !function(a,b){"use strict";if("function"==typeof define&&define.amd)define([],b);else if("object"==typeof exports)module.exports=b();else{var c="hopscotch";if(a[c])return;a[c]=b()}}(this,function(){var Hopscotch,HopscotchBubble,HopscotchCalloutManager,HopscotchI18N,customI18N,customRenderer,customEscape,utils,callbacks,helpers,winLoadHandler,defaultOpts,winHopscotch,templateToUse="bubble_default",Sizzle=window.Sizzle||null,undefinedStr="undefined",waitingToStart=!1,hasJquery=typeof jQuery!==undefinedStr,hasSessionStorage=!1,isStorageWritable=!1,document=window.document,validIdRegEx=/^[a-zA-Z]+[a-zA-Z0-9_-]*$/,rtlMatches={left:"right",right:"left"};try{typeof window.sessionStorage!==undefinedStr&&(hasSessionStorage=!0,sessionStorage.setItem("hopscotch.test.storage","ok"),sessionStorage.removeItem("hopscotch.test.storage"),isStorageWritable=!0)}catch(err){}return defaultOpts={smoothScroll:!0,scrollDuration:1e3,scrollTopMargin:200,showCloseButton:!0,showPrevButton:!1,showNextButton:!0,bubbleWidth:280,bubblePadding:15,arrowWidth:20,skipIfNoElement:!0,isRtl:!1,cookieName:"hopscotch.tour.state"},Array.isArray||(Array.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)}),winLoadHandler=function(){waitingToStart&&winHopscotch.startTour()},utils={addClass:function(a,b){var c,d,e,f;if(a.className){for(d=b.split(/\s+/),c=" "+a.className+" ",e=0,f=d.length;f>e;++e)c.indexOf(" "+d[e]+" ")<0&&(c+=d[e]+" ");a.className=c.replace(/^\s+|\s+$/g,"")}else a.className=b},removeClass:function(a,b){var c,d,e,f;for(d=b.split(/\s+/),c=" "+a.className+" ",e=0,f=d.length;f>e;++e)c=c.replace(" "+d[e]+" "," ");a.className=c.replace(/^\s+|\s+$/g,"")},hasClass:function(a,b){var c;return a.className?(c=" "+a.className+" ",-1!==c.indexOf(" "+b+" ")):!1},getPixelValue:function(a){var b=typeof a;return"number"===b?a:"string"===b?parseInt(a,10):0},valOrDefault:function(a,b){return typeof a!==undefinedStr?a:b},invokeCallbackArrayHelper:function(a){var b;return Array.isArray(a)&&(b=helpers[a[0]],"function"==typeof b)?b.apply(this,a.slice(1)):void 0},invokeCallbackArray:function(a){var b,c;if(Array.isArray(a)){if("string"==typeof a[0])return utils.invokeCallbackArrayHelper(a);for(b=0,c=a.length;c>b;++b)utils.invokeCallback(a[b])}},invokeCallback:function(a){return"function"==typeof a?a():"string"==typeof a&&helpers[a]?helpers[a]():utils.invokeCallbackArray(a)},invokeEventCallbacks:function(a,b){var c,d,e=callbacks[a];if(b)return this.invokeCallback(b);for(c=0,d=e.length;d>c;++c)this.invokeCallback(e[c].cb)},getScrollTop:function(){var a;return a=typeof window.pageYOffset!==undefinedStr?window.pageYOffset:document.documentElement.scrollTop},getScrollLeft:function(){var a;return a=typeof window.pageXOffset!==undefinedStr?window.pageXOffset:document.documentElement.scrollLeft},getWindowHeight:function(){return window.innerHeight||document.documentElement.clientHeight},addEvtListener:function(a,b,c){return a?a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent("on"+b,c):void 0},removeEvtListener:function(a,b,c){return a?a.removeEventListener?a.removeEventListener(b,c,!1):a.detachEvent("on"+b,c):void 0},documentIsReady:function(){return"complete"===document.readyState},evtPreventDefault:function(a){a.preventDefault?a.preventDefault():event&&(event.returnValue=!1)},extend:function(a,b){var c;for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c])},getStepTargetHelper:function(a){var b=document.getElementById(a);if(b)return b;if(hasJquery)return b=jQuery(a),b.length?b[0]:null;if(Sizzle)return b=new Sizzle(a),b.length?b[0]:null;if(document.querySelector)try{return document.querySelector(a)}catch(c){}return/^#[a-zA-Z][\w-_:.]*$/.test(a)?document.getElementById(a.substring(1)):null},getStepTarget:function(a){var b;if(!a||!a.target)return null;if("string"==typeof a.target)return utils.getStepTargetHelper(a.target);if(Array.isArray(a.target)){var c,d;for(c=0,d=a.target.length;d>c;c++)if("string"==typeof a.target[c]&&(b=utils.getStepTargetHelper(a.target[c])))return b;return null}return a.target},getI18NString:function(a){return customI18N[a]||HopscotchI18N[a]},setState:function(a,b,c){var d,e="";if(hasSessionStorage&&isStorageWritable)try{sessionStorage.setItem(a,b)}catch(f){isStorageWritable=!1,this.setState(a,b,c)}else hasSessionStorage&&sessionStorage.removeItem(a),c&&(d=new Date,d.setTime(d.getTime()+24*c*60*60*1e3),e="; expires="+d.toGMTString()),document.cookie=a+"="+b+e+"; path=/"},getState:function(a){var b,c,d,e=a+"=",f=document.cookie.split(";");if(hasSessionStorage&&(d=sessionStorage.getItem(a)))return d;for(b=0;b<f.length;b++){for(c=f[b];" "===c.charAt(0);)c=c.substring(1,c.length);if(0===c.indexOf(e)){d=c.substring(e.length,c.length);break}}return d},clearState:function(a){hasSessionStorage?sessionStorage.removeItem(a):this.setState(a,"",-1)},normalizePlacement:function(a){!a.placement&&a.orientation&&(a.placement=a.orientation)},flipPlacement:function(a){if(a.isRtl&&!a._isFlipped){var b,c,d=["orientation","placement"];a.xOffset&&(a.xOffset=-1*this.getPixelValue(a.xOffset));for(c in d)b=d[c],a.hasOwnProperty(b)&&rtlMatches.hasOwnProperty(a[b])&&(a[b]=rtlMatches[a[b]]);a._isFlipped=!0}}},utils.addEvtListener(window,"load",winLoadHandler),callbacks={next:[],prev:[],start:[],end:[],show:[],error:[],close:[]},helpers={},HopscotchI18N={stepNums:null,nextBtn:"Next",prevBtn:"Back",doneBtn:"Done",skipBtn:"Skip",closeTooltip:"Close"},customI18N={},HopscotchBubble=function(a){this.init(a)},HopscotchBubble.prototype={isShowing:!1,currStep:void 0,setPosition:function(a){var b,c,d,e,f,g,h,i=utils.getStepTarget(a),j=this.element,k=this.arrowEl,l=a.isRtl?"right":"left";if(utils.flipPlacement(a),utils.normalizePlacement(a),c=j.offsetWidth,b=j.offsetHeight,utils.removeClass(j,"fade-in-down fade-in-up fade-in-left fade-in-right"),d=i.getBoundingClientRect(),h=a.isRtl?d.right-c:d.left,"top"===a.placement)e=d.top-b-this.opt.arrowWidth,f=h;else if("bottom"===a.placement)e=d.bottom+this.opt.arrowWidth,f=h;else if("left"===a.placement)e=d.top,f=d.left-c-this.opt.arrowWidth;else{if("right"!==a.placement)throw new Error("Bubble placement failed because step.placement is invalid or undefined!");e=d.top,f=d.right+this.opt.arrowWidth}g="center"!==a.arrowOffset?utils.getPixelValue(a.arrowOffset):a.arrowOffset,g?"top"===a.placement||"bottom"===a.placement?(k.style.top="","center"===g?k.style[l]=Math.floor(c/2-k.offsetWidth/2)+"px":k.style[l]=g+"px"):("left"===a.placement||"right"===a.placement)&&(k.style[l]="","center"===g?k.style.top=Math.floor(b/2-k.offsetHeight/2)+"px":k.style.top=g+"px"):(k.style.top="",k.style[l]=""),"center"===a.xOffset?f=d.left+i.offsetWidth/2-c/2:f+=utils.getPixelValue(a.xOffset),"center"===a.yOffset?e=d.top+i.offsetHeight/2-b/2:e+=utils.getPixelValue(a.yOffset),a.fixedElement||(e+=utils.getScrollTop(),f+=utils.getScrollLeft()),j.style.position=a.fixedElement?"fixed":"absolute",j.style.top=e+"px",j.style.left=f+"px"},render:function(a,b,c){var d,e,f,g,h,j,k,l,m,n=this.element;if(a?this.currStep=a:this.currStep&&(a=this.currStep),this.opt.isTourBubble?(g=winHopscotch.getCurrTour(),g&&(e=g.customData,d=g.customRenderer,a.isRtl=a.hasOwnProperty("isRtl")?a.isRtl:g.hasOwnProperty("isRtl")?g.isRtl:this.opt.isRtl,f=g.unsafe,Array.isArray(g.steps)&&(h=g.steps.length,j=this._getStepI18nNum(this._getStepNum(h-1)),l=this._getStepNum(b)===this._getStepNum(h-1)))):(e=a.customData,d=a.customRenderer,f=a.unsafe,a.isRtl=a.hasOwnProperty("isRtl")?a.isRtl:this.opt.isRtl),k=utils.getI18NString(l?"doneBtn":a.showSkip?"skipBtn":"nextBtn"),utils.flipPlacement(a),utils.normalizePlacement(a),this.placement=a.placement,m={i18n:{prevBtn:utils.getI18NString("prevBtn"),nextBtn:k,closeTooltip:utils.getI18NString("closeTooltip"),stepNum:this._getStepI18nNum(this._getStepNum(b)),numSteps:j},buttons:{showPrev:utils.valOrDefault(a.showPrevButton,this.opt.showPrevButton)&&this._getStepNum(b)>0,showNext:utils.valOrDefault(a.showNextButton,this.opt.showNextButton),showCTA:utils.valOrDefault(a.showCTAButton&&a.ctaLabel,!1),ctaLabel:a.ctaLabel,showClose:utils.valOrDefault(this.opt.showCloseButton,!0)},step:{num:b,isLast:utils.valOrDefault(l,!1),title:a.title||"",content:a.content||"",isRtl:a.isRtl,placement:a.placement,padding:utils.valOrDefault(a.padding,this.opt.bubblePadding),width:utils.getPixelValue(a.width)||this.opt.bubbleWidth,customData:a.customData||{}},tour:{isTour:this.opt.isTourBubble,numSteps:h,unsafe:utils.valOrDefault(f,!1),customData:e||{}}},"function"==typeof d)n.innerHTML=d(m);else if("string"==typeof d){if(!winHopscotch.templates||"function"!=typeof winHopscotch.templates[d])throw new Error('Bubble rendering failed - template "'+d+'" is not a function.');n.innerHTML=winHopscotch.templates[d](m)}else if(customRenderer)n.innerHTML=customRenderer(m);else{if(!winHopscotch.templates||"function"!=typeof winHopscotch.templates[templateToUse])throw new Error('Bubble rendering failed - template "'+templateToUse+'" is not a function.');n.innerHTML=winHopscotch.templates[templateToUse](m)}for(children=n.children,numChildren=children.length,i=0;i<numChildren;i++)node=children[i],utils.hasClass(node,"hopscotch-arrow")&&(this.arrowEl=node);return n.style.zIndex="number"==typeof a.zindex?a.zindex:"",this._setArrow(a.placement),this.hide(!1),this.setPosition(a),c&&c(!a.fixedElement),this},_getStepNum:function(a){var b,c,d=0,e=winHopscotch.getSkippedStepsIndexes(),f=e.length;for(c=0;f>c;c++)b=e[c],a>b&&d++;return a-d},_getStepI18nNum:function(a){var b=utils.getI18NString("stepNums");return b&&a<b.length?a=b[a]:a+=1,a},_setArrow:function(a){utils.removeClass(this.arrowEl,"down up right left"),"top"===a?utils.addClass(this.arrowEl,"down"):"bottom"===a?utils.addClass(this.arrowEl,"up"):"left"===a?utils.addClass(this.arrowEl,"right"):"right"===a&&utils.addClass(this.arrowEl,"left")},_getArrowDirection:function(){return"top"===this.placement?"down":"bottom"===this.placement?"up":"left"===this.placement?"right":"right"===this.placement?"left":void 0},show:function(){var a=this,b="fade-in-"+this._getArrowDirection(),c=1e3;return utils.removeClass(this.element,"hide"),utils.addClass(this.element,b),setTimeout(function(){utils.removeClass(a.element,"invisible")},50),setTimeout(function(){utils.removeClass(a.element,b)},c),this.isShowing=!0,this},hide:function(a){var b=this.element;return a=utils.valOrDefault(a,!0),b.style.top="",b.style.left="",a?(utils.addClass(b,"hide"),utils.removeClass(b,"invisible")):(utils.removeClass(b,"hide"),utils.addClass(b,"invisible")),utils.removeClass(b,"animate fade-in-up fade-in-down fade-in-right fade-in-left"),this.isShowing=!1,this},destroy:function(){var a=this.element;a&&a.parentNode.removeChild(a),utils.removeEvtListener(a,"click",this.clickCb)},_handleBubbleClick:function(a){function b(c){return c===a.currentTarget?null:utils.hasClass(c,"hopscotch-cta")?"cta":utils.hasClass(c,"hopscotch-next")?"next":utils.hasClass(c,"hopscotch-prev")?"prev":utils.hasClass(c,"hopscotch-close")?"close":b(c.parentElement)}var c;a=a||window.event;var d=a.target||a.srcElement;if(c=b(d),"cta"===c)this.opt.isTourBubble||winHopscotch.getCalloutManager().removeCallout(this.currStep.id),this.currStep.onCTA&&utils.invokeCallback(this.currStep.onCTA);else if("next"===c)winHopscotch.nextStep(!0);else if("prev"===c)winHopscotch.prevStep(!0);else if("close"===c){if(this.opt.isTourBubble){var e=winHopscotch.getCurrStepNum(),f=winHopscotch.getCurrTour(),g=e===f.steps.length-1;utils.invokeEventCallbacks("close"),winHopscotch.endTour(!0,g)}else this.opt.onClose&&utils.invokeCallback(this.opt.onClose),this.opt.id&&!this.opt.isTourBubble?winHopscotch.getCalloutManager().removeCallout(this.opt.id):this.destroy();utils.evtPreventDefault(a)}},init:function(a){var b,c,d,e,f=document.createElement("div"),g=this,h=!1;this.element=f,e={showPrevButton:defaultOpts.showPrevButton,showNextButton:defaultOpts.showNextButton,bubbleWidth:defaultOpts.bubbleWidth,bubblePadding:defaultOpts.bubblePadding,arrowWidth:defaultOpts.arrowWidth,isRtl:defaultOpts.isRtl,showNumber:!0,isTourBubble:!0},a=typeof a===undefinedStr?{}:a,utils.extend(e,a),this.opt=e,f.className="hopscotch-bubble animated",e.isTourBubble?(d=winHopscotch.getCurrTour(),d&&utils.addClass(f,"tour-"+d.id)):utils.addClass(f,"hopscotch-callout no-number"),b=function(){!h&&g.isShowing&&(h=!0,setTimeout(function(){g.setPosition(g.currStep),h=!1},100))},utils.addEvtListener(window,"resize",b),this.clickCb=function(a){g._handleBubbleClick(a)},utils.addEvtListener(f,"click",this.clickCb),this.hide(),utils.documentIsReady()?document.body.appendChild(f):(document.addEventListener?(c=function(){document.removeEventListener("DOMContentLoaded",c),window.removeEventListener("load",c),document.body.appendChild(f)},document.addEventListener("DOMContentLoaded",c,!1)):(c=function(){"complete"===document.readyState&&(document.detachEvent("onreadystatechange",c),window.detachEvent("onload",c),document.body.appendChild(f))},document.attachEvent("onreadystatechange",c)),utils.addEvtListener(window,"load",c))}},HopscotchCalloutManager=function(){var a={},b={};this.createCallout=function(c){var d;if(!c.id)throw new Error("Must specify a callout id.");if(!validIdRegEx.test(c.id))throw new Error("Callout ID is using an invalid format. Use alphanumeric, underscores, and/or hyphens only. First character must be a letter.");if(a[c.id])throw new Error("Callout by that id already exists. Please choose a unique id.");if(!utils.getStepTarget(c))throw new Error("Must specify existing target element via 'target' option.");return c.showNextButton=c.showPrevButton=!1,c.isTourBubble=!1,d=new HopscotchBubble(c),a[c.id]=d,b[c.id]=c,d.render(c,null,function(){d.show(),c.onShow&&utils.invokeCallback(c.onShow)}),d},this.getCallout=function(b){return a[b]},this.removeAllCallouts=function(){var b;for(b in a)a.hasOwnProperty(b)&&this.removeCallout(b)},this.removeCallout=function(c){var d=a[c];a[c]=null,b[c]=null,d&&d.destroy()},this.refreshCalloutPositions=function(){var c,d,e;for(c in a)a.hasOwnProperty(c)&&b.hasOwnProperty(c)&&(d=a[c],e=b[c],d&&e&&d.setPosition(e))}},Hopscotch=function(a){var b,c,d,e,f,g,h,i,j=this,k={},l=[],m=function(a){return b&&b.element&&b.element.parentNode||(b=new HopscotchBubble(d)),a&&utils.extend(b.opt,{bubblePadding:o("bubblePadding"),bubbleWidth:o("bubbleWidth"),showNextButton:o("showNextButton"),showPrevButton:o("showPrevButton"),showCloseButton:o("showCloseButton"),arrowWidth:o("arrowWidth"),isRtl:o("isRtl")}),b},n=function(){b&&(b.destroy(),b=null)},o=function(a){return"undefined"==typeof d?defaultOpts[a]:utils.valOrDefault(d[a],defaultOpts[a])},p=function(){var a;return a=!e||0>f||f>=e.steps.length?null:e.steps[f]},q=function(){j.nextStep()},r=function(a){var b,c,d,e,f,g,h=m(),i=h.element,j=utils.getPixelValue(i.style.top),k=j+utils.getPixelValue(i.offsetHeight),l=utils.getStepTarget(p()),n=l.getBoundingClientRect(),q=n.top+utils.getScrollTop(),r=n.bottom+utils.getScrollTop(),s=q>j?j:q,t=k>r?k:r,u=utils.getScrollTop(),v=u+utils.getWindowHeight(),w=s-o("scrollTopMargin");s>=u&&(s<=u+o("scrollTopMargin")||v>=t)?a&&a():o("smoothScroll")?typeof YAHOO!==undefinedStr&&typeof YAHOO.env!==undefinedStr&&typeof YAHOO.env.ua!==undefinedStr&&typeof YAHOO.util!==undefinedStr&&typeof YAHOO.util.Scroll!==undefinedStr?(b=YAHOO.env.ua.webkit?document.body:document.documentElement,d=YAHOO.util.Easing?YAHOO.util.Easing.easeOut:void 0,c=new YAHOO.util.Scroll(b,{scroll:{to:[0,w]}},o("scrollDuration")/1e3,d),c.onComplete.subscribe(a),c.animate()):hasJquery?jQuery("body, html").animate({scrollTop:w},o("scrollDuration"),a):(0>w&&(w=0),e=u>s?-1:1,f=Math.abs(u-w)/(o("scrollDuration")/10),(g=function(){var b=utils.getScrollTop(),c=b+e*f;return e>0&&c>=w||0>e&&w>=c?(c=w,a&&a(),void window.scrollTo(0,c)):(window.scrollTo(0,c),utils.getScrollTop()===b?void(a&&a()):void setTimeout(g,10))})()):(window.scrollTo(0,w),a&&a())},s=function(a,b){var c,d,g;f+a>=0&&f+a<e.steps.length?(f+=a,d=p(),g=function(){c=utils.getStepTarget(d),c?(k[f]&&delete k[f],b(f)):(k[f]=!0,utils.invokeEventCallbacks("error"),s(a,b))},d.delay?setTimeout(g,d.delay):g()):b(-1)},t=function(a,b){var c,d,g,h,i=m(),j=this;if(i.hide(),a=utils.valOrDefault(a,!0),c=p(),c.nextOnTargetClick&&utils.removeEvtListener(utils.getStepTarget(c),"click",q),d=c,g=b>0?d.multipage:f>0&&e.steps[f-1].multipage,h=function(c){var e;if(-1===c)return this.endTour(!0);if(a&&(e=b>0?utils.invokeEventCallbacks("next",d.onNext):utils.invokeEventCallbacks("prev",d.onPrev)),c===f){if(g)return void x();e=utils.valOrDefault(e,!0),e?this.showStep(c):this.endTour(!1)}},!g&&o("skipIfNoElement"))s(b,function(a){h.call(j,a)});else if(f+b>=0&&f+b<e.steps.length){if(f+=b,c=p(),!utils.getStepTarget(c)&&!g)return utils.invokeEventCallbacks("error"),this.endTour(!0,!1);h.call(this,f)}else if(f+b===e.steps.length)return this.endTour();return this},u=function(a){var b,c,d,e={};for(b in a)a.hasOwnProperty(b)&&"id"!==b&&"steps"!==b&&(e[b]=a[b]);return i.call(this,e,!0),c=utils.getState(o("cookieName")),c&&(d=c.split(":"),g=d[0],h=d[1],d.length>2&&(l=d[2].split(",")),h=parseInt(h,10)),this},v=function(a,b,c){var d,e;if(f=a||0,k=b||{},d=p(),e=utils.getStepTarget(d))return void c(f);if(!e){if(utils.invokeEventCallbacks("error"),k[f]=!0,o("skipIfNoElement"))return void s(1,c);f=-1,c(f)}},w=function(a){function b(){d.show(),utils.invokeEventCallbacks("show",c.onShow)}var c=e.steps[a],d=m(),g=utils.getStepTarget(c);f!==a&&p().nextOnTargetClick&&utils.removeEvtListener(utils.getStepTarget(p()),"click",q),f=a,d.hide(!1),d.render(c,a,function(a){a?r(b):b(),c.nextOnTargetClick&&utils.addEvtListener(g,"click",q)}),x()},x=function(){var a=e.id+":"+f,b=winHopscotch.getSkippedStepsIndexes();b&&b.length>0&&(a+=":"+b.join(",")),utils.setState(o("cookieName"),a,1)},y=function(a){a&&this.configure(a)};this.getCalloutManager=function(){return typeof c===undefinedStr&&(c=new HopscotchCalloutManager),c},this.startTour=function(a,b){var c,d,f={},i=this;if(!e){if(!a)throw new Error("Tour data is required for startTour.");if(!a.id||!validIdRegEx.test(a.id))throw new Error("Tour ID is using an invalid format. Use alphanumeric, underscores, and/or hyphens only. First character must be a letter.");e=a,u.call(this,a)}if(typeof b!==undefinedStr){if(b>=e.steps.length)throw new Error("Specified step number out of bounds.");d=b}if(!utils.documentIsReady())return waitingToStart=!0,this;if("undefined"==typeof d&&e.id===g&&typeof h!==undefinedStr){if(d=h,l.length>0)for(var j=0,k=l.length;k>j;j++)f[l[j]]=!0}else d||(d=0);return v(d,f,function(a){var b=-1!==a&&utils.getStepTarget(e.steps[a]);return b?(utils.invokeEventCallbacks("start"),c=m(),c.hide(!1),i.isActive=!0,void(utils.getStepTarget(p())?i.showStep(a):(utils.invokeEventCallbacks("error"),o("skipIfNoElement")&&i.nextStep(!1)))):void i.endTour(!1,!1)}),this},this.showStep=function(a){var b=e.steps[a];if(utils.getStepTarget(b))return b.delay?setTimeout(function(){w(a)},b.delay):w(a),this},this.prevStep=function(a){return t.call(this,a,-1),this},this.nextStep=function(a){return t.call(this,a,1),this},this.endTour=function(a,b){var c,d=m();return a=utils.valOrDefault(a,!0),b=utils.valOrDefault(b,!0),e&&(c=p(),c&&c.nextOnTargetClick&&utils.removeEvtListener(utils.getStepTarget(c),"click",q)),f=0,h=void 0,d.hide(),a&&utils.clearState(o("cookieName")),this.isActive&&(this.isActive=!1,e&&b&&utils.invokeEventCallbacks("end")),this.removeCallbacks(null,!0),this.resetDefaultOptions(),n(),e=null,this},this.getCurrTour=function(){return e},this.getCurrTarget=function(){return utils.getStepTarget(p())},this.getCurrStepNum=function(){return f},this.getSkippedStepsIndexes=function(){var a,b=[];for(a in k)b.push(a);return b},this.refreshBubblePosition=function(){var a=p();return a&&m().setPosition(a),this.getCalloutManager().refreshCalloutPositions(),this},this.listen=function(a,b,c){return a&&callbacks[a].push({cb:b,fromTour:c}),this},this.unlisten=function(a,b){var c,d,e=callbacks[a];for(c=0,d=e.length;d>c;++c)e[c]===b&&e.splice(c,1);return this},this.removeCallbacks=function(a,b){var c,d,e,f;for(f in callbacks)if(!a||a===f)if(b)for(c=callbacks[f],d=0,e=c.length;e>d;++d)c[d].fromTour&&(c.splice(d--,1),--e);else callbacks[f]=[];return this},this.registerHelper=function(a,b){"string"==typeof a&&"function"==typeof b&&(helpers[a]=b)},this.unregisterHelper=function(a){helpers[a]=null},this.invokeHelper=function(a){var b,c,d=[];for(b=1,c=arguments.length;c>b;++b)d.push(arguments[b]);helpers[a]&&helpers[a].call(null,d)},this.setCookieName=function(a){return d.cookieName=a,this},this.resetDefaultOptions=function(){return d={},this},this.resetDefaultI18N=function(){return customI18N={},this},this.getState=function(){return utils.getState(o("cookieName"))},i=function(a,b){var c,e,f,g,h=["next","prev","start","end","show","error","close"];for(d||this.resetDefaultOptions(),utils.extend(d,a),a&&utils.extend(customI18N,a.i18n),f=0,g=h.length;g>f;++f)e="on"+h[f].charAt(0).toUpperCase()+h[f].substring(1),a[e]&&this.listen(h[f],a[e],b);return c=m(!0),this},this.configure=function(a){return i.call(this,a,!1)},this.setRenderer=function(a){var b=typeof a;return"string"===b?(templateToUse=a,customRenderer=void 0):"function"===b&&(customRenderer=a),this},this.setEscaper=function(a){return"function"==typeof a&&(customEscape=a),this},y.call(this,a)},winHopscotch=new Hopscotch,function(){var _={};_.escape=function(a){return customEscape?customEscape(a):null==a?"":(""+a).replace(new RegExp("[&<>\"']","g"),function(a){return"&"==a?"&":"<"==a?"<":">"==a?">":'"'==a?""":"'"==a?"'":void 0})},this.templates=this.templates||{},this.templates.bubble_default=function(obj){function optEscape(a,b){return b?_.escape(a):a}obj||(obj={});var __t,__p="";_.escape,Array.prototype.join;with(obj)__p+='\n<div class="hopscotch-bubble-container" style="width: '+(null==(__t=step.width)?"":__t)+"px; padding: "+(null==(__t=step.padding)?"":__t)+'px;">\n ',tour.isTour&&(__p+='<span class="hopscotch-bubble-number">'+(null==(__t=i18n.stepNum)?"":__t)+"</span>"),__p+='\n <div class="hopscotch-bubble-content">\n ',""!==step.title&&(__p+='<h3 class="hopscotch-title">'+(null==(__t=optEscape(step.title,tour.unsafe))?"":__t)+"</h3>"),__p+="\n ",""!==step.content&&(__p+='<div class="hopscotch-content">'+(null==(__t=optEscape(step.content,tour.unsafe))?"":__t)+"</div>"),__p+='\n </div>\n <div class="hopscotch-actions">\n ',buttons.showPrev&&(__p+='<button class="hopscotch-nav-button prev hopscotch-prev">'+(null==(__t=i18n.prevBtn)?"":__t)+"</button>"),__p+="\n ",buttons.showCTA&&(__p+='<button class="hopscotch-nav-button next hopscotch-cta">'+(null==(__t=buttons.ctaLabel)?"":__t)+"</button>"),__p+="\n ",buttons.showNext&&(__p+='<button class="hopscotch-nav-button next hopscotch-next">'+(null==(__t=i18n.nextBtn)?"":__t)+"</button>"),__p+="\n </div>\n ",buttons.showClose&&(__p+='<button class="hopscotch-bubble-close hopscotch-close">'+(null==(__t=i18n.closeTooltip)?"":__t)+"</button>"),__p+='\n</div>\n<div class="hopscotch-bubble-arrow-container hopscotch-arrow">\n <div class="hopscotch-bubble-arrow-border"></div>\n <div class="hopscotch-bubble-arrow"></div>\n</div>';return __p}}.call(winHopscotch),winHopscotch}); ; /*! RESOURCE: /scripts/app.guided_tours/js_guided_tours_includes.js */ !function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){"use strict";var _ajaxTransport2=_interopRequireDefault(require(3)),_dataService2=_interopRequireDefault(require(4)),_url=require(7),_guidedToursClientApi2=_interopRequireDefault(require(5)),_constants=require(8);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var LOAD_TOURS_ON_TOP="top-load-tours";function getConfig(){var config={};try{window.top&&(config.top=window.top),config.NOW=window.top.NOW,config.isTop=window.top===window,config.user=top.NOW&&top.NOW.user?top.NOW.user.name:null,config.userLoggedIn=!(!config.user||"guest"===config.user),config.designerMode=top&&top.NOW&&top.NOW.gtd&&top.NOW.gtd.gtdDesignerMode}catch(e){return null}return config}function _loadTours(){try{if(!(top!==window||NOW&&NOW.guidedToursService)){var versionUpdate=window.g_builddate?window.g_builddate:Date.now(),script=document.createElement("script");script.src="/scripts/app.guided_tours/guided_tours_player.js?v="+versionUpdate,script.type="text/javascript",script.async="true";var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)}}catch(e){console&&console.log("An error has occured. Guided Tours could not be loaded!\n %s",e)}}var cachedContexts=new Map;function loadToursIfPresent(config){if(top.NOW.isGtdEnabledForStandardUI&&((top!==window||!NOW.guidedToursService)&&config.userLoggedIn))if(0<=decodeURIComponent(location.search).indexOf("mode=preview"))CustomEvent.fireTop(LOAD_TOURS_ON_TOP,config);else{var stateGTours=sessionStorage.getItem("guided_tour:tour.state"),stateHopscotch=sessionStorage.getItem("hopscotch.tour.state");if(stateGTours||stateHopscotch)CustomEvent.fireTop(LOAD_TOURS_ON_TOP,config);else{var context=(0,_url.getContext)();0<=["navpage","gtb"].indexOf(context)||(cachedContexts.has(context)?config.tours=cachedContexts.get(context):(cachedContexts.set(context,""),function(context,cb){new _dataService2.default(new _ajaxTransport2.default).getToursForPage(context,null,cb)}(context,function(e,tours){if(tours){if(cachedContexts.set(context,tours),(config.tours=tours).length){for(var autoLaunchTour={isTourPresent:!1},i=0;i<tours.length;i++)if(tours[i].isAutoLaunchable){autoLaunchTour.name=tours[i].name,autoLaunchTour.options=tours[i].options,autoLaunchTour.type=tours[i].type,autoLaunchTour.tourId=tours[i].sysID,autoLaunchTour.isTourPresent=!0;break}sessionStorage.setItem(_constants.AUTO_LAUNCHABLE_SESSION_ID,JSON.stringify(autoLaunchTour))}CustomEvent.fireTop(LOAD_TOURS_ON_TOP,config)}})))}}}!function(){top.NOW.guided_tours||(top.NOW.guided_tours=new _guidedToursClientApi2.default(_loadTours));var config=getConfig();config.designerMode||(config&&config.isTop?function(config){var state=null;if(CustomEvent.on(LOAD_TOURS_ON_TOP,function(config){_loadTours()}),sessionStorage&&(state=sessionStorage.getItem("guided_tour:tour.state")))return config.tourState=state,CustomEvent.fireTop(LOAD_TOURS_ON_TOP,config);loadToursIfPresent(config),CustomEvent.observe("page_loaded_fully",function(){setTimeout(function(){loadToursIfPresent(getConfig())},1e3)}),CustomEvent.observe("gtd_child_iframe_loaded",function(){setTimeout(function(){loadToursIfPresent(getConfig())},1e3)})}(config):CustomEvent.fireTop("gtd_child_iframe_loaded"))}()},{3:3,4:4,5:5,7:7,8:8}],2:[function(require,module,exports){"use strict";module.exports={events:{hopscotch:{tourStart:"hopscotch.tour.start",tourEnd:"hopscotch.tour.end"},external:{pageLoaded:"gtd-sp-page-loaded",childFrameLoaded:"gtd_child_iframe_loaded"},page:{loaded:"page_loaded_fully"},tourService:{tourWillStart:"tourWillStart",tourStarted:"tourStarted",tourWillEnd:"tourWillEnd",tourEnded:"tourEnded",started:"started",completed:"completed",failed:"failed",dismissed:"dismissed",stepStarted:"step_started",abandoned:"abandoned",inTransit:"in_transit",skipped:"skipped",welcomeModalDismissed:"welcome_modal_dismissed",welcomeModalEndedTour:"welcome_modal_ended_tour",allTerminalEvents:["completed","failed","dismissed","abandoned"]},embeddedHelp:{TOUR_END:"embedded_help:tour.end",TOUR_START:"embedded_help:tour.start",TOUR_STATE:"embedded_help:tour:state"}},reasons:{none:"none",unknown:"unknown",explicit:"explicit",timeout:"timeout",elementHidden:"element_hidden",elementNotPresent:"element_not_present",navigatedOutOfApp:"navigated_out_of_application"},storeKeys:{tourStatus:"TOURSTATUS"},sessionKeys:{isNextNewPage:"guided_tour:tour_sp.isNextNewPage"},preference:{useConcourse:"use.concourse"},eventStream:"gt-event",webAnalytics:{category:"snc.gtd.clientAPI",eventStream:"gtd_client_api_event"}}},{}],3:[function(require,module,exports){"use strict";var _createClass=function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor};function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}var Service=function(){function Service(){!function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,Service)}return _createClass(Service,[{key:"send",value:function(url,data,cb){window.jQuery.ajax(url,{data:JSON.stringify(data),contentType:"application/json; charset=utf-8",dataType:"json",method:"POST",processData:!1}).done(function(d){return cb&&cb(null,d.result)}).fail(function(e){e&&200===e.status?cb&&cb(null,e):cb&&cb(e)})}},{key:"get",value:function(url,cb){window.jQuery.ajax(url,{dataType:"json",method:"GET",beforeSend:setHeader}).done(function(res){cb&&cb(null,res)}).fail(function(e){cb&&cb(e)})}}]),Service}();function setHeader(arg){arg.setRequestHeader("X-UserToken",window.g_ck)}module.exports=Service},{}],4:[function(require,module,exports){"use strict";var _createClass=function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor};function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}var tourUrl="/api/now/guided_tours/tours",templates_tourIdUrl=function(id){return tourUrl+"/"+id+"?detail=high"},templates_tourPageUrl=function(context){var urlParameters=window.location.href.replace(/^.*\/\/[^\\/]+/,""),encodedURIPath=encodeURIComponent(urlParameters);return tourUrl+"?page_id="+context+"&context="+encodedURIPath},DataService=function(){function DataService(transport){!function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,DataService),this.transport=transport}return _createClass(DataService,[{key:"getTourById",value:function(id,cb){this.transport.get(templates_tourIdUrl(id),function(err,data){err&&cb&&cb("Error getting tour guide info"),data&&data.result?cb&&cb(null,data.result):cb&&cb("No Guided Tour Info")})}},{key:"getToursForPage",value:function(context,filterFunc,cb){this.transport.get(templates_tourPageUrl(context),function(err,data){if(!err&&data.result&&data.result.length){var tourList=data.result;filterFunc&&(tourList=tourList.filter(filterFunc)),cb&&cb(null,tourList)}else cb&&cb(err)})}}]),DataService}();module.exports=DataService},{}],5:[function(require,module,exports){"use strict";var _createClass=function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor};function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}var _ajaxTransport2=_interopRequireDefault(require(3)),_dataService2=_interopRequireDefault(require(4)),_url=require(7),_constants2=_interopRequireDefault(require(2)),_i18n2=_interopRequireDefault(require(6));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var events=_constants2.default.events.tourService,webAnalytics=_constants2.default.webAnalytics,guidedToursEvents_TOUR_STARTED="tourStarted",guidedToursEvents_STEP_STARTED="stepStarted",guidedToursEvents_TOUR_ABANDONED="tourAbandoned",guidedToursEvents_TOUR_FAILED="tourFailed",guidedToursEvents_TOUR_COMPLETED="tourCompleted",guidedToursEvents_TOUR_ENDED="tourEnded",guidedToursEvents_TOUR_DISMISSED="tourDismissed",guidedToursEvents_GET_ALL_TOURS="getAllTours",GuidedToursClientAPI=function(){function GuidedToursClientAPI(_loadTours){!function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,GuidedToursClientAPI),this.api={startTour:this.startTour.bind(this),endTour:this.endTour.bind(this),applyListFilter:this.applyListFilter.bind(this),getAllTours:this.getAllTours.bind(this),loadPlayer:_loadTours},this.events={on:this._on,off:this._off},this._filterFunc,this._tourService,this._dataService=new _dataService2.default(new _ajaxTransport2.default)}return _createClass(GuidedToursClientAPI,[{key:"startTour",value:function(tourId,argument_1,argument_2){var stepNum=1<arguments.length&&void 0!==argument_1?argument_1:0,cbFunc=argument_2;this._trigger(webAnalytics.eventStream,{payload:tourId,event:guidedToursEvents_TOUR_STARTED}),this._tourService?this._tourService.currentTour?cbFunc&&cbFunc({success:!1,message:_i18n2.default.getMessage("Cannot start a new tour while another tour is in progress.")}):top.NOW.isEmbeddedHelpActive?CustomEvent.fireTop(top.EmbeddedHelpEvents.GT_API_START_TOUR,tourId,stepNum,cbFunc):this._tourService.startTour(tourId,stepNum,cbFunc):this._start_tour_task={tourId:tourId,stepNum:stepNum,cbFunc:cbFunc}}},{key:"endTour",value:function(){if(this._tourService){var sys_id=(this._tourService&&this._tourService.currentTour).sys_id;this._trigger(webAnalytics.eventStream,{payload:sys_id,event:guidedToursEvents_TOUR_ENDED}),top.NOW.isEmbeddedHelpActive?CustomEvent.fireTop(top.EmbeddedHelpEvents.GT_API_END_TOUR):this._tourService.endTour()}}},{key:"getAllTours",value:function(cbFunc){this._tourService&&(this._trigger(webAnalytics.eventStream,{payload:"",event:guidedToursEvents_GET_ALL_TOURS}),this._dataService.getToursForPage((0,_url.getContext)(),this._filterFunc,cbFunc))}},{key:"applyListFilter",value:function(filterFunc){this._filterFunc=filterFunc}},{key:"_registerEvents",value:function(tourService){var _this=this;if(this._tourService=tourService,this._tourService.on(events.tourStarted,function(args){return _this._trigger(guidedToursEvents_TOUR_STARTED,args)}),this._tourService.on(events.stepStarted,function(args){return _this._trigger(guidedToursEvents_STEP_STARTED,args)}),this._tourService.on(events.abandoned,function(args){return _this._trigger(guidedToursEvents_TOUR_ABANDONED,args)}),this._tourService.on(events.failed,function(args){return _this._trigger(guidedToursEvents_TOUR_FAILED,args)}),this._tourService.on(events.completed,function(args){return _this._trigger(guidedToursEvents_TOUR_COMPLETED,args)}),this._tourService.on(events.tourEnded,function(args){return _this._trigger(guidedToursEvents_TOUR_ENDED,args)}),this._tourService.on(events.dismissed,function(args){return _this._trigger(guidedToursEvents_TOUR_DISMISSED,args)}),this._start_tour_task){var _start_tour_task=this._start_tour_task,tourId=_start_tour_task.tourId,stepNum=_start_tour_task.stepNum,cbFunc=_start_tour_task.cbFunc;this._start_tour_task=null,this.startTour(tourId,stepNum,cbFunc)}}},{key:"_on",value:function(event,cbFunc){CustomEvent&&CustomEvent.on(event,cbFunc)}},{key:"_off",value:function(event,func){CustomEvent&&(func&&"function"==typeof func?CustomEvent.un(event,func):CustomEvent.unAll(event))}},{key:"_trigger",value:function(event,args){CustomEvent.fireTop(event,args)}}]),GuidedToursClientAPI}();module.exports=GuidedToursClientAPI},{2:2,3:3,4:4,6:6,7:7}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor};function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}var gtbGetMsg={},found=!1;if(window.GwtMessage)gtbGetMsg=new window.GwtMessage;else{for(var i=0;i<window.frames.length;i++)try{if(window.frames[i].getMessage&&window.frames[i].getMessages){gtbGetMsg.getMessage=window.frames[i].getMessage,gtbGetMsg.getMessages=window.frames[i].getMessages,found=!0;break}}catch(e){}if(!found){var spI18=top.NOW&&top.NOW.gtdConfig?top.NOW.gtdConfig.i18n:null;spI18?(gtbGetMsg.getMessage=spI18.getMessage,gtbGetMsg.getMessages=spI18.getMessages,found=!0):(gtbGetMsg.getMessage=function(){return arguments.length<=0?void 0:arguments[0]},gtbGetMsg.getMessages=function(arr){return arr.reduce(function(acc,current){return acc[current]=current,acc},{})})}}var i18n=function(){function i18n(){!function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,i18n)}return _createClass(i18n,null,[{key:"getMessages",value:function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];try{return gtbGetMsg.getMessages.apply(gtbGetMsg,args)}catch(e){return args}}},{key:"getMessage",value:function(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];try{return gtbGetMsg.getMessage.apply(gtbGetMsg,args)}catch(e){return args[0]}}}]),i18n}();exports.default=i18n},{}],7:[function(require,module,exports){"use strict";module.exports={isStepUrlMatchingForCurrentWindow:function(stepUrl,isMapped){var splt=stepUrl.split("?"),currentStepUrl=splt[0],params=1<splt.length?splt[1].split("&"):[],url=window.location.href,urlContainsId=0<=url.indexOf("id=");if(!isMapped&&urlContainsId)for(var i=0;i<params.length;i++)if(params[i].startsWith("id="))return-1<url.indexOf(currentStepUrl)&&-1<url.indexOf(params[i]);return-1<url.indexOf(currentStepUrl)},getContext:function(){var currLocation=top.window.location,currentPage=currLocation.pathname;return 0<=currentPage.indexOf("nav_to.do")&&0===(currentPage=decodeURIComponent(currLocation.search)).indexOf("?uri=")?-1!==(currentPage=currentPage.replace("?uri=","")).indexOf(".do")?currentPage.substr(1,currentPage.indexOf(".do")-1):currentPage:(currentPage=currLocation.pathname).substr(1,currentPage.indexOf(".do")-1)}}},{}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.TOUR_TYPES={STANDARD_UI:"platform",SERVICE_PORTAL:"service_portal",CUSTOM_UI:"custom_ui"},exports.AUTO_LAUNCHABLE_SESSION_ID="guided_tour:autolaunchable"},{}]},{},[1]); ; /*! RESOURCE: scripts/directive.snHRSidebarPane.js */ angular.module('sn.response_template_sidebar', []); angular.module('sn.response_template_sidebar').directive('snHrSidebarPane', function($timeout, getTemplateUrl, paneManager) { 'use strict'; return { restrict: 'E', replace: true, transclude: true, templateUrl: getTemplateUrl('sn_hr_sidebar_pane.xml'), scope: { paneCollapsed: '=', panePosition: '@', paneResizeable: '@', paneWidth: '=', paneToggle: '@' }, link: function(scope) { scope.togglePane = function() { paneManager.togglePane("hr_sidebar_pane", true); }; } }; }); angular.module('sn.response_template_sidebar').directive('snHrSidebarContent', function(getTemplateUrl, paneManager) { 'use strict'; return { restrict : 'E', templateUrl: getTemplateUrl('sn_hr_sidebar_content.xml'), replace: true, scope : { collapsed: '=', url: '=' }, link: function(scope) { scope.$on('sn:url_changed', function(e, data){ scope.url = data; scope.IframeSrcUrl = scope.url; }); scope.closePane = function() { paneManager.togglePane("hr_sidebar_pane", true); }; } }; }); ; /*! RESOURCE: scripts/controller.hrSidebar.js */ angular.module('sn.response_template_sidebar').controller('hrSidebar', function ($scope, $rootScope, $timeout, $http, $window, $location, $document, snCustomEvent, userPreferences, paneManager) { "use strict"; $scope.hrSidebarCollapsed = true; $scope.loaded = false; $scope.content = ''; $scope.actions = []; $scope.supressedTours = []; $scope.tours = []; $scope.showLanguageWarning = false; $scope.sysId = ""; $scope.tableName = ""; $scope.currentUrl = ""; $scope.firstLoad = true; $scope.slidePanelOpen = false; paneManager.registerPane("hr_sidebar_pane"); snCustomEvent.on("sn:hr_trigger_sidebar", function(args) { if (args.sysId != $scope.sysId || args.tableName != $scope.tableName) { $scope.currentUrl = "/sn_templated_snip_message_template.do?sysparm_sys_id="+ args.sysId + "&sysparm_table_name=" + args.tableName + "&sysparm_nostack=true"; $scope.sysId = args.sysId; $scope.tableName = args.tableName; } $scope.$broadcast('sn:url_changed', $scope.currentUrl); if($scope.hrSidebarCollapsed && !$scope.firstLoad){ $document[0].getElementById('templateIframe').contentDocument.location.reload(true); } $scope.firstLoad = false; $scope.slidePanelOpen = true; paneManager.togglePane("hr_sidebar_pane", $scope.hrSidebarCollapsed); }); snCustomEvent.on("sn:hr_sidebar_collapse", function() { if($scope.slidePanelOpen) paneManager.togglePane( "hr_sidebar_pane", true); }); snCustomEvent.observe('hr_sidebar_pane.toggle', function(collapsed, autoFocusFirstItem) { if (!$scope.hrSidebarCollapsed) $scope.slidePanelOpen = false; $scope.hrSidebarCollapsed = !$scope.hrSidebarCollapsed; $rootScope.$broadcast('hr_sidebar_pane.collapsed', 'right', $scope.hrSidebarCollapsed, autoFocusFirstItem); if($scope.firstLoad) { $rootScope.$broadcast('hr_sidebar_pane.collapsed', 'right', true, autoFocusFirstItem); $scope.firstLoad = false; } }); $scope.$on('hr_sidebar_pane.collapsed', function (event, position, collapsed, autoFocusFirstItem) { var $body = angular.element('body'); if ($body.data().layout) { if (collapsed) $body.data().layout.hide('east'); else { $body.data().layout.show('east'); $body.data().layout.sizePane('east', 285); } } else { var $layout = angular.element('.navpage-layout'), $pageRight = angular.element('.navpage-right'), $snHrSidebarContent = angular.element('.sn-hr-sidebar-pane-content'); if (collapsed) { $layout.addClass('navpage-right-hidden'); $pageRight.css('visibility', 'hidden'); $snHrSidebarContent.addClass('sn-pane-hidden'); $snHrSidebarContent.removeClass('sn-pane-visible'); } else { $layout.removeClass('navpage-right-hidden'); $pageRight.css('visibility', 'visible'); $snHrSidebarContent.removeClass('sn-pane-hidden'); $snHrSidebarContent.addClass('sn-pane-visible'); } if (autoFocusFirstItem) { $snHrSidebarContent.one('transitionend', function() { if ($snHrSidebarContent.hasClass('sn-pane-visible')) { $snHrSidebarContent.find('.sn-widget-list-item') .filter(':visible') .filter(':first') .focus(); } }); } } }); }); ; ;