PageSourceSearch

https://itec.es/login/scripts.6db052aec9e6212c2c99.js

js itec.es collected 2026-10-02 10:38:04 UTC 122,522 bytes, 2,802 lines download raw bytes

1// Login
2
3var objGetToken = {
4    checkUserFile: "checkUser.html?v=" + Date.now(),
5    crossDomainLocalStorageUrl: "https://itec.cat/login/js/xssUser.js?v=" + Date.now(),
6    allowedDomains: getAllowedDomains(),
7    url_base: "",
8    var_user_token: "",
9    var_app_token: "",
10    // idioma_url: "/ca/",
11    idioma_url: "/ca/",
12    auth_version: "v1",
13    url_login: "https://itec.cat/login",
14    date: new Date(),
15    expires: "",
16    running: false,
17    queue: [],
18    crides: 0,
19    waitValue: 2000,
20    lastAppCall: "",
21    retried401: false,
22    initializated_apps: [],
23    itec_apps:[
24                {
25                    api_name: 'tcqihome',
26                    api_prefix: 'api',
27                    cookie_name: 'authtcqihome',
28                    send_auth: true,
29                    logout_function: "j_spring_security_logout",
30                    api_version: "v1",
31                    domain: getLogOutDomain()
32                },
33                {
34                    api_name:'loadertcq',
35                    api_prefix: 'api',
36                    cookie_name: "authloadertcq",
37                    send_auth: true,
38                    logout_function: "j_spring_security_logout",
39                    api_version: "v1",
40                    domain: getLogOutDomain()
41                },
42                {
43                    api_name:'pressupost',
44                    api_prefix: 'api',
45                    cookie_name: "authpressupost",
46                    send_auth: true,
47                    logout_function: "j_spring_security_logout",
48                    api_version: "v1",
49                    domain: getLogOutDomain()
50                },
51                {
52                    api_name:'mediambient',
53                    api_prefix: 'api',
54                    cookie_name: "authmediambient",
55                    send_auth: true,
56                    logout_function: "j_spring_security_logout",
57                    api_version: "v1",
58                    domain: getLogOutDomain()
59                },
60                {
61                    api_name:'qualitat',
62                    api_prefix: 'api',
63                    cookie_name: "authqualitat",
64                    send_auth: true,
65                    logout_function: "j_spring_security_logout",
66                    api_version: "v1",
67                    domain: getLogOutDomain()
68                },
69                {
70                    api_name:'reportsmanteniment',
71                    api_prefix: 'api',
72                    cookie_name: "authreportsmanteniment",
73                    send_auth: true,
74                    logout_function: "j_spring_security_logout",
75                    api_version: "v1",
76                    domain: getLogOutDomain()
77                },
78                {
79                    api_name:'reportstcq',
80                    api_prefix: 'api',
81                    cookie_name: "authreportstcq",
82                    send_auth: true,
83                    logout_function: "j_spring_security_logout",
84                    api_version: "v1",
85                    domain: getLogOutDomain()
86                },
87                {
88                    api_name:'security',
89                    api_prefix: 'api',
90                    cookie_name: "authsecurity",
91                    send_auth: true,
92                    logout_function: "j_spring_security_logout",
93                    api_version: "v1",
94                    domain: 'tcqi.itec.cat'
95                },
96                {
97                    api_name:'planificacio',
98                    api_prefix: 'api',
99                    cookie_name: "authplanificacio",
100                    send_auth: true,
101                    logout_function: "j_spring_security_logout",
102                    api_version: "v1",
103                    domain: getLogOutDomain()
104                },
105                {
106                    api_name:'estimaciocostos',
107                    api_prefix: 'api',
108                    cookie_name: "authestimaciocostos",
109                    send_auth: true,
110                    logout_function: "j_spring_security_logout",
111                    api_version: "v1",
112                    domain: getLogOutDomain()
113                },
114                {
115                    api_name:'controlcostos',
116                    api_prefix: 'api',
117                    cookie_name: "authcontrolcostos",
118                    send_auth: true,
119                    logout_function: "j_spring_security_logout",
120                    api_version: "v1",
121                    domain: getLogOutDomain()
122                },
123                {
124                    api_name:'seguretatisalut',
125                    api_prefix: 'api',
126                    cookie_name: "authseguretatisalut",
127                    send_auth: true,
128                    logout_function: "j_spring_security_logout",
129                    api_version: "v1",
130                    domain: getLogOutDomain()
131                },
132                {
133                    api_name:'bimtcq',
134                    api_prefix: 'api',
135                    cookie_name: "authbimtcq",
136                    send_auth: true,
137                    logout_function: "j_spring_security_logout",
138                    api_version: "v1",
139                    domain: getLogOutDomain()
140                },
141                {
142                    api_name:'einacalculemissions',
143                    api_prefix: 'api',
144                    cookie_name: "autheinacalculemissions",
145                    send_auth: true,
146                    logout_function: "j_spring_security_logout",
147                    api_version: "v1",
148                    domain: getLogOutDomain()
149                },
150                {
151                    api_name:'seguimenteconomic',
152                    api_prefix: 'api',
153                    cookie_name: "authseguimenteconomic",
154                    send_auth: true,
155                    logout_function: "j_spring_security_logout",
156                    api_version: "v1",
157                    domain: getLogOutDomain()
158                },
159            
160                {
161                    api_name:'banctcq',
162                    api_prefix: 'api',
163                    cookie_name: "authbanctcq",
164                    send_auth: true,
165                    logout_function: "j_spring_security_logout",
166                    api_version: "v1",
167                    domain: getLogOutDomain()
168                },
169                {
170                    api_name:'manteniment',
171                    api_prefix: 'api',
172                    cookie_name: "authmanteniment",
173                    send_auth: true,
174                    logout_function: "j_spring_security_logout",
175                    api_version: "v1",
176                    domain: getLogOutDomain()
177                },
178                {
179                    api_name:'speedier',
180                    api_prefix: 'api',
181                    cookie_name: "authspeedier",
182                    send_auth: true,
183                    logout_function: "j_spring_security_logout",
184                    api_version: "v1",
185                    domain: getLogOutDomain()
186                },
187                {
188                    api_name:'manteniment',
189                    api_prefix: 'api',
190                    cookie_name: "authmanteniment",
191                    send_auth: true,
192                    logout_function: "j_spring_security_logout",
193                    api_version: "v1",
194                    domain: getLogOutDomain()
195                },
196                {
197                    api_name: 'pocityf',
198                    api_prefix: 'api',
199                    cookie_name: 'authpocityf',
200                    send_auth: true,
201                    logout_function: "j_spring_security_logout",
202                    api_version: "v2",
203                    domain: getLogOutDomain()
204                }
205    ]
206};
207
208objGetToken.date.setTime(objGetToken.date.getTime() + (7 * 24 * 60 * 60 * 1000));
209objGetToken.expires = "expires=" + objGetToken.date.toGMTString();
210
211function getLogOutDomain(){
212    const logOutDomain = isDevelopColor() ? 'tcqi.itec.cat' : 'tcqi.eu';
213    return logOutDomain;
214}
215
216function getAllowedDomains(){
217    const develop = ["https://itec.cat",  "https://itec.es", "https://tcqi.itec.cat"];
218    const prod = ["https://itec.cat",  "https://itec.es", "https://tcqi.eu"];
219    if(isDevelopColor()){
220        return develop;
221    }
222    return prod;
223}
224
225function setXssUser(authtoken) {
226
227    objGetToken.allowedDomains.forEach(function (item) {
228        var xss = new xssIFrame();
229        xss.init({
230            iframeUrl: item + "/docs/" + objGetToken.checkUserFile,
231            iframeId: item,
232            initCallback: function () {
233                //console.log('iframe ready in ' + item);
234                xss.setItem("authsecurity", authtoken, function (data) {
235                    //console.log("message sent to " + item);
236                });
237            }
238        });
239    });
240
241
242}
243
244function isDevelop() {
245    /* 
246    PER A CRIDES DIFERENTS EN VERSIÓ CI, TEST O PREVIEW.
247    var isD =  (navigator.userAgent.indexOf("rv:444") >0 || navigator.userAgent.indexOf("rv:555") >0 || navigator.userAgent.indexOf("rv:666") >0);
248    //console.log("[isDevelop: " + isD +"] Date:" + (new Date().toLocaleTimeString()) + " userAgent: " + navigator.userAgent);
249    */
250    var isD = true;
251    objGetToken.url_base = (isD) ?
252        "https://api.itec.cat/security/authorization" :
253        "https://api.itec.cat/security/v1/authorization";
254    return isD;
255};
256
257function isDevelopColor() {
258    return (
259
260        (navigator.userAgent.indexOf("rv:444") > 0 || navigator.userAgent.indexOf("rv:555") > 0 || navigator.userAgent.indexOf("rv:666") > 0)
261
262        ||
263
264        (sessionStorage.getItem("xitec") == "CI" || sessionStorage.getItem("xitec") == "Test" || sessionStorage.getItem("xitec") == "PrePro" || sessionStorage.getItem("xitec") == "iCat")
265
266    );
267}
268
269isDevelop();
270
271
272function insertPromiseScript() {
273    // Promise
274    ! function (t) {
275        function e() {}
276
277        function n(t, e) {
278            return function () {
279                t.apply(e, arguments)
280            }
281        }
282
283        function o(t) {
284            if ("object" != typeof this) throw new TypeError("Promises must be constructed via new");
285            if ("function" != typeof t) throw new TypeError("not a function");
286            this._state = 0, this._handled = !1, this._value = void 0, this._deferreds = [], a(t, this)
287        }
288
289        function r(t, e) {
290            for (; 3 === t._state;) t = t._value;
291            return 0 === t._state ? void t._deferreds.push(e) : (t._handled = !0, void l(function () {
292                var n = 1 === t._state ? e.onFulfilled : e.onRejected;
293                if (null === n) return void(1 === t._state ? i : u)(e.promise, t._value);
294                var o;
295                try {
296                    o = n(t._value)
297                } catch (r) {
298                    return void u(e.promise, r)
299                }
300                i(e.promise, o)
301            }))
302        }
303
304        function i(t, e) {
305            try {
306                if (e === t) throw new TypeError("A promise cannot be resolved with itself.");
307                if (e && ("object" == typeof e || "function" == typeof e)) {
308                    var r = e.then;
309                    if (e instanceof o) return t._state = 3, t._value = e, void f(t);
310                    if ("function" == typeof r) return void a(n(r, e), t)
311                }
312                t._state = 1, t._value = e, f(t)
313            } catch (i) {
314                u(t, i)
315            }
316        }
317
318        function u(t, e) {
319            t._state = 2, t._value = e, f(t)
320        }
321
322        function f(t) {
323            2 === t._state && 0 === t._deferreds.length && setTimeout(function () {
324                t._handled || o._onUnhandledRejection(t._value)
325            }, 1);
326            for (var e = 0, n = t._deferreds.length; n > e; e++) r(t, t._deferreds[e]);
327            t._deferreds = null
328        }
329
330        function c(t, e, n) {
331            this.onFulfilled = "function" == typeof t ? t : null, this.onRejected = "function" == typeof e ? e : null, this.promise = n
332        }
333
334        function a(t, e) {
335            var n = !1;
336            try {
337                t(function (t) {
338                    n || (n = !0, i(e, t))
339                }, function (t) {
340                    n || (n = !0, u(e, t))
341                })
342            } catch (o) {
343                if (n) return;
344                n = !0, u(e, o)
345            }
346        }
347        var s = setTimeout,
348            l = "function" == typeof setImmediate && setImmediate || function (t) {
349                s(t, 1)
350            },
351            d = Array.isArray || function (t) {
352                return "[object Array]" === Object.prototype.toString.call(t)
353            };
354        o.prototype["catch"] = function (t) {
355            return this.then(null, t)
356        }, o.prototype.then = function (t, n) {
357            var i = new o(e);
358            return r(this, new c(t, n, i)), i
359        }, o.all = function () {
360            var t = Array.prototype.slice.call(1 === arguments.length && d(arguments[0]) ? arguments[0] : arguments);
361            return new o(function (e, n) {
362                function o(i, u) {
363                    try {
364                        if (u && ("object" == typeof u || "function" == typeof u)) {
365                            var f = u.then;
366                            if ("function" == typeof f) return void f.call(u, function (t) {
367                                o(i, t)
368                            }, n)
369                        }
370                        t[i] = u, 0 === --r && e(t)
371                    } catch (c) {
372                        n(c)
373                    }
374                }
375                if (0 === t.length) return e([]);
376                for (var r = t.length, i = 0; i < t.length; i++) o(i, t[i])
377            })
378        }, o.resolve = function (t) {
379            return t && "object" == typeof t && t.constructor === o ? t : new o(function (e) {
380                e(t)
381            })
382        }, o.reject = function (t) {
383            return new o(function (e, n) {
384                n(t)
385            })
386        }, o.race = function (t) {
387            return new o(function (e, n) {
388                for (var o = 0, r = t.length; r > o; o++) t[o].then(e, n)
389            })
390        }, o._setImmediateFn = function (t) {
391            l = t
392        }, o._onUnhandledRejection = function (t) {
393            console.warn("Possible Unhandled Promise Rejection:", t)
394        }, "undefined" != typeof module && module.exports ? module.exports = o : t.Promise || (t.Promise = o)
395    }(this);
396
397    // CustomEvent
398    (function () {
399        function CustomEvent(event, params) {
400            params = params || {
401                bubbles: false,
402                cancelable: false,
403                detail: undefined
404            };
405            var evt = document.createEvent('CustomEvent');
406            evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
407            return evt;
408        }
409
410        CustomEvent.prototype = window.Event.prototype;
411
412        window.CustomEvent = CustomEvent;
413    })();
414}
415
416
417function getIdioma() {
418    var idioma = (document.location.href.indexOf("en.") > -1 ||
419            document.location.href.indexOf("lang=en") > -1 ||
420            document.location.href.indexOf("/en/") > 1
421        ) ? 2 :
422        (document.location.href.indexOf(".cat") > -1 ||
423            document.location.href.indexOf("lang=ca") > -1 ||
424            document.location.href.indexOf("/ca/") > 1
425        ) ? "0" :
426        (document.location.href.indexOf(".es") > -1 ||
427            document.location.href.indexOf("lang=es") > -1 ||
428            document.location.href.indexOf("/es/") > 1
429        ) ? 1 : 0;
430
431    if (document.location.href.indexOf("sites.itec.cat") > -1) {
432        idioma = (document.location.href.indexOf("lang=en") > -1) ? 2 :
433            (document.location.href.indexOf("lang=ca") > -1) ? "0" :
434            1;
435    }
436    if (document.location.href.indexOf("metabase.itec.cat") > -1) {
437        idioma = (document.location.href.indexOf("/en/") > -1) ? 2 :
438            (document.location.href.indexOf("/ca/") > -1) ? "0" :
439            1;
440    }
441    if (document.location.href.indexOf("ecobject.com") > -1) {
442        idioma = (document.location.href.indexOf("/en/") > -1) ? 2 :
443            (document.location.href.indexOf("/ca/") > -1) ? "0" :
444            1;
445    }
446    if (document.location.href.indexOf("store.itec.cat") > -1) {
447        idioma = 2;
448    }
449    
450    if (document.location.href.indexOf("tcqi.") > -1) {
451        var navLag = navigator.language;
452        if(navLag.indexOf('ca')>-1){
453            idioma = 0;
454        }
455        else if(navLag.indexOf('es')>-1){
456            idioma = 1;
457        }
458        else{
459            idioma = 2;
460        }
461        
462    }
463    if (document.location.href.indexOf("/login/") > -1) {
464        idioma = (document.location.href.indexOf("/en/") > -1) ? 2 :
465            (document.location.href.indexOf("/ca/") > -1) ? "0" :
466            1;
467    }
468
469    
470    return idioma;
471}
472
473
474function showLittleMan(json_position) {
475    //insertPromiseScript();
476    var idioma = 1;
477    if (json_position && json_position.idioma) {
478        idioma = (json_position.idioma.indexOf("en") > -1) ? 2 :
479            (json_position.idioma.indexOf("ca") > -1) ? 0 : 1;
480    } else {
481        idioma = getIdioma();
482
483    }
484    var top = 40;
485    var right = 20;
486    var position = "absolute";
487
488    if (json_position) {
489        top = (json_position.top) ? json_position.top : top;
490        right = (json_position.right) ? json_position.right : right;
491        position = (json_position.position) ? json_position.position : position;
492        json_position.app = (json_position.app) ? (json_position.app) : null;
493    } else {
494        json_position = {};
495        json_position.app = null;
496    }
497    var lblModificar = "";
498    var lblProductes = "";
499    var lblAdmin = "";
500    var lblSortir = "";
501    var lblLogIn = "";
502    
503    objGetToken.idioma_url = "/ca/";
504    var linkGestioLlicencies = "https://api.itec.cat/security/v1/administracio/inici?lang=es_ES";
505
506    if (isDevelop()) {
507        linkGestioLlicencies = "https://tcqi.itec.cat/v1/security/#/usuaris/";
508    }
509    
510    switch (idioma) {
511        case 1:
512            lblModificar = "<i class=\"fa fa-pencil\"></i> Perfil";
513            lblProductes = "<i class=\"fa fa-th\"></i> Productos";
514            lblAdmin = "<i class=\"fa fa-user-plus\"></i> Gestión licencias";
515            lblSortir = "<i class=\"fa fa-sign-out\"></i> Salir";
516            objGetToken.idioma_url = "/es/";
517            objGetToken.url_login = "https://itec.es/login";
518            lblLogIn = "Iniciar sesión";
519            break;
520        case 2:
521            lblModificar = "<i class=\"fa fa-pencil\"></i> Profile";
522            lblProductes = "<i class=\"fa fa-th\"></i> Products";
523            lblAdmin = "<i class=\"fa fa-user-plus\"></i> License management";
524            lblSortir = "<i class=\"fa fa-sign-out\"></i> Log out";
525            objGetToken.idioma_url = "/en/";
526            objGetToken.url_login = "https://en.itec.cat/login";
527            lblLogIn = "Sign in";
528            break;
529        default:
530            lblModificar = "<i class=\"fa fa-pencil\"></i> Perfil";
531            lblProductes = "<i class=\"fa fa-th\"></i> Productes";
532            lblAdmin = "<i class=\"fa fa-user-plus\"></i> Gestió llicències";
533            lblSortir = "<i class=\"fa fa-sign-out\"></i> Sortir";
534            objGetToken.idioma_url = "/ca/";
535            lblLogIn = "Inicia sessió";
536            linkGestioLlicencies = "https://api.itec.cat/security/v1/administracio/inici?lang=ca_ES";
537            if (isDevelop()) {
538                linkGestioLlicencies = "https://tcqi.itec.cat/v1/security/#/usuaris/";
539            }
540            objGetToken.url_login = "https://itec.cat/login";
541            break;
542    };
543
544    var head  = document.getElementsByTagName('head')[0];
545    /*
546    var link  = document.createElement('link');
547    link.rel  = 'stylesheet';
548    link.type = 'text/css';
549    link.href = 'https://metabase.itec.cat/bim/libs/css/font-awesome.min.css';
550    link.media = 'all';
551    head.appendChild(link);*/
552
553   // var head = document.getElementsByTagName('head')[0];
554   // var link = document.createElement('link');
555   // link.rel = 'stylesheet';
556   // link.type = 'text/css';
557   // link.href = 'https://use.fontawesome.com/releases/v5.8.1/css/all.css';
558   // link.integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf"; 
559   // link.crossorigin="anonymous;"
560   // link.media = 'all';
561   // link.id = "getTokenFontAwesome";
562   // head.appendChild(link);
563    if (!document.getElementById("login_style")){
564        var style = document.createElement("style");
565        style.type = 'text/css';
566        style.id = "login_style";
567        style.rel = "stylesheet";
568        style.media = "all";
569        style.appendChild(document.createTextNode(
570            [
571                "#LoginDivParent {",
572                "position:" + position + ";",
573                "right:" + right + "px;",
574                "top:" + top + "px;",
575                "z-index:10000000",
576                "}",
577                "#LoginDiv {",
578                "text-align:center;",
579                "cursor: pointer;",
580                "height: 22px;",
581                "}",
582                "#LoginDiv svg{ fill:currentColor; width: 22px;}",
583                "#menuLogin{",
584                "   border: 1px solid #bbb;",
585                "   background-color: #eee;",
586                "   font-family:sans-serif;",
587                "   position:absolute;",
588                "   right:0px;",
589                "   top:46px;",
590                "   font-size:12px;",
591                "   transition:opacity 200ms ease-in 200ms;",
592                "   z-index: 10000;",
593                "}",
594                "#menuLogin div{",
595                "   border-bottom: 1px solid #ddd;",
596                "   padding:8px;",
597                "   cursor:pointer;",
598                "   width:180px;",
599                "   transition:background-color 500ms;",
600                "}",
601                "#menuLogin div:hover{",
602                "   background-color: #ddd;",
603                "}",
604                "#menuLogin .fa {",
605                "padding-right: 6px;width: 18px;",
606                "}",
607                "div.itecwidget-menu{",
608                "   visibility: visible;opacity:1;",
609                "   transition:opacity 200ms ease-in 200ms, visibility 1s linear 400ms;",
610                "}",
611                "div.itecwidget-menu.amagat{",
612                "   visibility: hidden;opacity:0;",
613                "}",
614                "#snackbarRemain {",
615                "min-width: 250px;",
616                "margin-left: -125px;",
617                "background-color: #585858;",
618                "color: #fff;",
619                "text-align: center;",
620                "border-radius: 8px;",
621                "padding: 12px;",
622                "position: fixed;",
623                "z-index: 10000;",
624                "left: 50%;",
625                "bottom: 30px;",
626                "opacity: 0.96;",
627                "}",
628                "#snackbarRemain p{",
629                "margin: 2px;",
630                "font-size: 14px;",
631                "}",
632                "#snackbarRemain p.snackTitle{",
633                "font-weight: bold;",
634                "font-size: 17px;",
635                "padding-bottom: 5px;",
636                "}",
637                "#snackbarRemain a{",
638                "font-weight: bold;",
639                "padding: 5px;",
640                "border-radius: 4px;",
641                "background-color: #82cae2;",
642                "color: #444444;",
643                "font-size: 13px;",
644                "}",
645                "#snackbarRemain a:hover{",
646                "opacity: 0.82;",
647                "}",
648                "#snackbarRemain p.button{",
649                "padding-top: 10px;",
650                "}",
651                "#snackbarRemain p.snackClose{",
652                "position: absolute;",
653                "right: 6px;",
654                "top: 2px;",
655                "font-weight: bold;",
656                "cursor: pointer;",
657                "}"
658            ].join('')
659        ));
660        head.appendChild(style);
661    }
662    
663
664    var user_token = readCookie("authsecurity");
665
666    resolve_json = {
667        "token": user_token,
668        "getProductes": true
669    };
670
671    getUser(resolve_json).then(function (data) {
672        
673            //keepAlive(user_token);
674            loginSuccess(data);
675            if(json_position.app != null){
676                init_app(json_position.app, user_token).then(function (data) {
677                    //console.log("Init app OK");
678                }, function (data) {
679                    //console.log("Init app error. No licenses.");
680                });
681            }
682        },
683        function (data) {
684            //loginError();
685        }
686    );
687    
688    if (document.getElementById("LoginDivParent")){
689        document.getElementById("LoginDivParent").parentElement.removeChild(document.getElementById("LoginDivParent"));
690    }
691
692    var login = document.createElement("DIV");
693    login.id = "LoginDivParent";
694    login.innerHTML = [
695        "<div id='LoginDiv'>",
696        "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 448 512'><path d='M224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm89.6 32h-16.7c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16h-16.7C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48v-41.6c0-74.2-60.2-134.4-134.4-134.4z'/></svg>",
697        "<div id='userName' style='font-size: 10px; display: block; font-family: sans-serif;text-align: center;max-width:100px;max-height:25px;overflow:hidden;'>" + lblLogIn + "</div>",   
698        "</div>",
699        "<div id='menuLogin' class='itecwidget-menu amagat'>",
700        "<div onclick=\"modify_user()\">" + lblModificar + "</div> ",
701        "<div id='lblProductes' onclick=\"user_products()\">" + lblProductes + "</div> ",
702        "<div id='lblAdmin'onclick=\"user_licenses()\">" + lblAdmin + "</div> ",
703        "<div onclick=\"exit_user();\">" + lblSortir + "</div> ",
704        "</div>"
705
706    ].join('');
707
708    login.onclick = function () {
709        init({
710            user_data: true,
711            idioma: idioma,
712            app: json_position.app,
713            show_message: json_position.show_message,
714            init_message: json_position.init_message,
715            enhanced_design: json_position.enhanced_design,
716            logo: json_position.logo,
717            refresh: (json_position.refresh) ? json_position.refresh : false
718        }).then(
719            function (data) {
720                loginSuccess(data);
721
722            },
723            function (data) {
724                loginError();
725            }
726        );
727    };
728
729    document.getElementsByTagName("body")[0].appendChild(login);
730
731    amaga_menus_excepte = function (excepcio) {
732        var menus = document.querySelectorAll(".itecwidget-menu");
733        for (var i = 0; i < menus.length; i++) {
734            if (menus[i].id != excepcio) {
735                menus[i].className = "itecwidget-menu amagat";
736            }
737        }
738
739    }
740
741    modify_user = function () {
742        document.getElementById("menuLogin").className = "itecwidget-menu amagat";
743        document.location.href = objGetToken.url_login + objGetToken.idioma_url + "profile/data";
744    }
745
746    user_orders = function () {
747        document.getElementById("menuLogin").className = "itecwidget-menu amagat";
748        document.location.href = "https://botiga.itec.cat/my_account/orders/";
749    }
750
751    user_products = function () {
752        document.getElementById("menuLogin").className = "itecwidget-menu amagat";
753        document.location.href = objGetToken.url_login + objGetToken.idioma_url + "profile/products";
754    }
755
756    user_licenses = function () {
757        document.getElementById("menuLogin").className = "itecwidget-menu amagat";
758        document.location.href = linkGestioLlicencies;
759    }
760
761    exit_user = function () {
762
763        logout(readCookie("authsecurity"));
764
765        // document.getElementById("userName").parentElement.removeChild(document.getElementById("userName"));
766        document.getElementById("userName").innerHTML = lblLogIn;
767        document.getElementById("LoginDiv").style.color = "#000";
768        document.getElementById("menuLogin").className = "itecwidget-menu amagat";;
769        document.getElementById("LoginDiv").onclick = null;
770        document.getElementById("LoginDiv").onclick = function () {
771            init({
772                user_data: true
773            }).then(
774                function (data) {
775                    loginSuccess(data);
776
777                },
778                function (data) {
779                    loginError();
780                }
781            );
782        };
783
784    };
785
786    /*
787    loginSuccess = function(user_json){
788    document.getElementById("LoginDiv").style.color = (isDevelopColor
788())?"#FF69B4":"#080";
789            var user = document.createElement("DIV");
790            user.id = "userName";
791            user.innerHTML = user_json.user_data.data.nom;
792            user.style="font-size:10px;display:block;font-family:sans-serif;text-align:center;"
793            document.getElementById("LoginDiv").appendChild(user);
794            document.getElementById("LoginDiv").parentNode.removeAttribute("onclick");
795            document.getElementById("LoginDiv").parentNode.onclick=null;
796            document.getElementById("LoginDiv").onclick = function(){
797                document.getElementById("menuLogin").style.display = (document.getElementById("menuLogin").style.display=="block")?"none":"block";
798                //document.location.href= url_login + "/#/user";
799            };
800    };
801    */
802    loginError = function () {
803        if (document.getElementById("LoginDiv").childNodes[1]) {
804            document.getElementById("LoginDiv").removeChild(document.getElementById("LoginDiv").childNodes[1]);
805        }
806        document.getElementById("LoginDiv").style.color = (isDevelopColor()) ? "#ff99c2" : "#800";
807    };
808}
809
810function loginSuccess(user_json) {
811    if (typeof user_json.user_data.data.llicencies === 'undefined') {
812
813    }
814    else if(user_json.user_data.data.llicencies !== null){
815        var userLicencesCount = user_json.user_data.data.llicencies.length;
816        if ((!userLicencesCount || userLicencesCount < 1) && (document.getElementById("lblProductes"))){
817            document.getElementById("lblProductes").style.display = "none";
818        }
819    }
820    if (typeof user_json.user_data.data.administrador === 'undefined') {
821    }
822    else{
823        var userAdmin = user_json.user_data.data.administrador;
824        
825        if (!userAdmin && document.getElementById("lblAdmin")) {
826            document.getElementById("lblAdmin").style.display = "none";
827        }
828    }
829
830    keepAlive(user_json.token);
831    setXssUser(user_json.token); 
832    if (document.getElementById("LoginDiv")) {
833        document.getElementById("LoginDiv").style.color = (isDevelopColor()) ? "#ff99c2" : "#080";
834        //document.getElementById("LoginDiv").innerHTML = "";
835
836        let userLet = "<span style='font-size:12px;font-weight:bold'>" + user_json.user_data.data.nom.substring(0, 1).toUpperCase() + user_json.user_data.data.cognom.substring(0, 1).toUpperCase() + "</span>";
837        
838        if (document.getElementById("LoginDiv").children.length > 1){
839            document.getElementById("LoginDiv").removeChild(document.getElementById("LoginDiv").lastChild);
840        }
841        if(document.getElementById("userName")){
842            document.getElementById("userName").innerHTML = userLet;
843        }
844        else {
845            var user = document.createElement("DIV");
846            user.id = "userName";
847            user.innerHTML = user_json.user_data.data.nom;
848            user.innerHTML = userLet;
849            user.style = "font-size:10px;display:block;font-family:sans-serif;text-align:center;max-width:100px;max-height:25px;overflow:hidden;margin-top:-4px";
850            document.getElementById("LoginDiv").appendChild(user);
851        }
852        document.getElementById("LoginDiv").parentNode.removeAttribute("onclick");
853        document.getElementById("LoginDiv").parentNode.onclick = null;
854        document.getElementById("LoginDiv").onclick = function () {
855            amaga_menus_excepte("menuLogin");
856            var ml = document.getElementById("menuLogin");
857            ml.className = (ml.className.indexOf("amagat") > -1) ? ml.className.replace(" amagat", "") : "itecwidget-menu amagat";
858        };
859    }
860
861    // DAVID AQUI POSAR FALTEN DADES
862    if (typeof user_json !== 'undefined' && typeof user_json.user_data !== 'undefined' && typeof user_json.user_data.data !== 'undefined' && typeof user_json.user_data.data.nom !== 'undefined' && typeof user_json.user_data.data.idactivitat !== 'undefined' && typeof user_json.user_data.data.cp !== 'undefined' && typeof user_json.user_data.data.idioma !== 'undefined' && typeof user_json.user_data.data.country !== 'undefined') {
863
864        
865
866        if (sessionStorage.getItem("PopUpdadesUser") != "1"){
867
868            // guardem
869            sessionStorage.setItem("PopUpdadesUser", "1");
870
871             // url per cross domain
872            const url = window.location.hostname;
873            let domain = "//itec.cat";
874            if(url.indexOf("itec.es") > -1){
875                domain = "//itec.es";
876            }
877            else if(url.indexOf("en.itec.cat") > -1){
878                domain = "//en.itec.cat";
879            }
880            if(window.location.href.indexOf("/login/") < 0 && (user_json.user_data.data.idactivitat == null || user_json.user_data.data.idactivitat.length == 0 || user_json.user_data.data.cp == null || user_json.user_data.data.cp.length == 0 || user_json.user_data.data.country == null   || user_json.user_data.data.country.length == 0)){
881
882                let missingData = "";
883                let act = false;
884                let cp = false;
885                let activitatText = "";
886                let cpText = "";
887                let countryText = "";
888                let andText = "";
889                if(user_json.user_data.data.idioma == 0){
890                    activitatText = "Activitat";
891                    cpText = "Codi postal";
892                    countryText = "País";
893                    andText = " i ";
894                }
895                else if(user_json.user_data.data.idioma == 2){
896                    activitatText = "Activity";
897                    cpText = "Postal code";
898                    countryText = "Country";
899                    andText = " and ";
900                }
901                else{
902                    activitatText = "Actividad";
903                    cpText = "Código postal";
904                    countryText = "País";
905                    andText = " y ";
906                }
907                if(user_json.user_data.data.idactivitat == null || user_json.user_data.data.idactivitat.length == 0){
908                    missingData += activitatText;
909                    act = true;
910                }
911                if(user_json.user_data.data.cp == null || user_json.user_data.data.cp.length == 0){
912                    if(act){
913                        missingData += ", ";
914                    }
915                    missingData += cpText;
916                    cp = true;
917                }
918                if(user_json.user_data.data.country == null   || user_json.user_data.data.country.length == 0){
919                    if(cp){
920                        missingData += andText;
921                    }
922                    missingData += countryText;
923                }
924                missingData += "";
925                let text = "";
926                let img = "";
927                let textButton = "";
928                if(user_json.user_data.data.idioma == 0){
929                    img = "<img src=\'" + domain + "/wp-content/uploads/2014/10/itec.png' style='width: 73px;height: auto;'/>";
930                    img = "<img src=\'https://itec.cat/wp-content/uploads/2014/10/itec.png' style='width: 73px;height: auto;'/>";
931                    text += "<p>";
932                    text += "Hola " + user_json.user_data.data.nom + ",";
933                    text += "</p><p>";
934                    text += "al teu perfil d'usuari/ària li manquen algunes dades:";
935                    text += "</p><p>";
936                    text += missingData;
937                    text += "</p><p>";
938                    text += "Si us plau, completa-les perquè puguem oferir-te un millor servei.";
939                    text += "</p>";
940                    textButton = "<a href='" + domain + "/login/ca/profile/data?back=" + window.location.href + "' target='_blank'><b>Veure perfil usuari/ària</b>.</a>";
941                }
942                else if(user_json.user_data.data.idioma == 2){
943                    img = "<img src=\'" + domain + "/wp-content/uploads/2014/10/itec.png' style='width: 73px;height: auto;'/>";
944                    img = "<img src=\'https://itec.cat/wp-content/uploads/2014/10/itec.png' style='width: 73px;height: auto;'/>";
945                    text += "<p>";
946                    text += "Hi " + user_json.user_data.data.nom + ",";
947                    text += "</p><p>";
948                    text += "Your user profile is missing some information:";
949                    text += "</p><p>";
950                    text += missingData;
951                    text += "</p><p>";
952                    text += "Please, complete them so that we can offer you a better service.";
953                    text += "</p>";
954                    textButton = "<a href='" + domain + "/login/en/profile/data?back=" + window.location.href + "' target='_blank'><b>View user profile</b>.</a>";
955                }
956                else{
957                    img = "<img src=\'" + domain + "/wp-content/uploads/2014/10/itec.png' style='width: 73px;height: auto;'/>";
958                    img = "<img src=\'https://itec.cat/wp-content/uploads/2014/10/itec.png' style='width: 73px;height: auto;'/>";
959                    text += "<p>";
960                    text += "Hola " + user_json.user_data.data.nom + ",";
961                    text += "</p><p>";
962                    text += "a tu perfil de usuario/a le faltan algunos datos:";
963                    text += "</p><p>";
964                    text += missingData;
965                    text += "</p><p>";
966                    text += "Por favor, complétalas para que podamos ofrecerte un mejor servicio.";
967                    text += "</p>";
968                    textButton = "<a href='" + domain + "/login/es/profile/data?back=" + window.location.href + "' target='_blank'><b>Ver perfil usuario/a</b>.</a>";
969                }
970                let element = document.getElementById("modalMissingData");
971                if(typeof(element) != 'undefined' && element != null){}
972                else{
973                    let modal = document.createElement("div");
974                    modal.id = "modalMissingData";
975                    modal.innerHTML = [
976                        '<div class="modalMissingData-content">',
977                        '<div class="closeMissing"><span class="closeMissingSpan">&times;</span></div>',
978                        '<div class="modalMissingImg">' + img + '</div>',
979                        '<div class="modalMissingText">
979' + text + '</div>',
980                        '<div class="modalMissingButton">' + textButton + '</div>',
981                        '</div>',
982                        '<style>',
983                        '#modalMissingData {display: block;position: fixed;z-index: 9999;left: 0;top: 0;width: 100%;height: 100%;overflow: auto;background-color: rgb(0,0,0);background-color: rgba(0,0,0,0.4);text-align:center; }.modalMissingData-content{position:relative;background-color: #fefefe;margin: 10% auto;padding: 10px;border: 2px solid #888;width: 60%;border-radius: 6px;max-width: 650px;}@media only screen and (max-width: 600px) {.modalMissingData-content{width: 90%;}}.modalMissingData-content p{font-size: 17px;line-height: 20px;color: #626262;}.closeMissing {color: #555;position:absolute;right:10px;top:10px;}.closeMissingSpan {color: #555;font-size: 38px;font-weight: bold;padding: 0;margin: 0;}.closeMissingSpan:hover,.closeMissingSpan:focus {color: black;text-decoration: none;cursor: pointer;}.modalMissingText{margin:0 auto;text-align:center;width:90%;height: 100%;overflow: auto;}.modalMissingText p {margin: 12px;}.modalMissingText p:last-child {margin-top: 28px;margin-bottom: 22px;}.modalMissingImg{margin:0 auto;text-align:center;margin-bottom:20px;width: calc(100% - 65px);}.modalMissingData-content .modalMissingButton{color: #f4f4f4;background-color: #1e88e5;padding: 8px 10px;border-radius: 5px;font-size: 16px;margin:0 auto;width: fit-content;margin-bottom: 12px;}.modalMissingData-content .modalMissingButton:hover{color: #f4f4f4;background-color: #1e88e5e6;}.modalMissingData-content .modalMissingButton a,.modalMissingData-content .modalMissingButton a:hover {color: #f4f4f4;}',
984                        '</style>'
985                    ].join('');
986
987                    modal.addEventListener('click', function (event) {
988                        if(event.target.className == "closeMissing" || event.target.className == "closeMissingSpan"){
989                            let element = document.getElementById("modalMissingData");
990                            if(typeof(element) != 'undefined' && element != null){
991                                element.style.display = "none";
992                            }
993                        }
994                    });
995                    document.getElementsByTagName("body")[0].appendChild(modal);
996                }
997            }
998        }
999
1000       
1001    }
1002}
1003
1004
1005function readCookie(name) {
1006
1007    var nameEQ = name + "=";
1008    var ca = document.cookie.split(';');
1009    for (var i = 0; i < ca.length; i++) {
1010        var c = ca[i];
1011        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
1012        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
1013    }
1014    return null;
1015}
1016
1017function createCookie(name, value, days) {
1018    
1019    if (days) {
1020        objGetToken.date = new Date();
1021        objGetToken.date.setTime(objGetToken.date.getTime() + (days * 24 * 60 * 60 * 1000));
1022        objGetToken.expires = "; expires=" + objGetToken.date.toGMTString();
1023    } else var expires = "";
1024
1025    var hostName = window.location.hostname;
1026    var domainCookie = hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
1027
1028    document.cookie = name + "=" + value + objGetToken.expires + "; domain=." + domainCookie + ";path=/;";
1029
1030}
1031
1032
1033function logout(authsecurity) {
1034
1035    _logout = function (authsecurity) {
1036        return new Promise(function (resolve, reject) {
1037            document.cookie = "authsecurity" + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=itec.cat;max-age=0;path=/';
1038            // no utilitzem cookies. Utilitzem localStorage.
1039            //localStorage.removeItem("authsecurity");
1040            xhttp = new XMLHttpRequest();
1041            xhttp.onreadystatechange = function () {
1042                if (xhttp.readyState == 4) {
1043                    switch (xhttp.status) {
1044                        case 200:
1045                            resolve(true);
1046                            break;
1047                        default:
1048                            reject(false);
1049                            break;
1050                    }
1051                }
1052            };
1053
1054            xhttp.open("POST", objGetToken.url_base + "/logout");
1055            xhttp.setRequestHeader("authsecurity", authsecurity);
1056            if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
1057            //xhttp.setRequestHeader("authkey", authsecurity);
1058            xhttp.send();
1059        });
1060    };
1061
1062
1063
1064    currentDomain = window.location.hostname;
1065    loopCount = 1;
1066    //if(currentDomain != 'itec.cat' && currentDomain != 'itec.es'){
1067        objGetToken.itec_apps.forEach(function(app){
1068            
1069            var xhttp = new XMLHttpRequest();
1070            xhttp.onreadystatechange = function () {
1071                if (xhttp.readyState == 4) {
1072                    switch (xhttp.status) {
1073                        case 200:
1074                            break;
1075                        default:                         
1076                            break;
1077                    }
1078                    loopCount++;
1079                    if(loopCount == objGetToken.itec_apps.length){
1080                        _logout(authsecurity).then(function (data) {
1081                            document.location.reload(true);           
1082                        },
1083                        function (data) {
1084                            var E = new Error("Logout Error");
1085                            return E;
1086                        });
1087                    }
1088                }
1089            };
1090            xhttp.open("GET", "https://" + app.domain + "/" + ((app.api_prefix!="")?(app.api_prefix +"/"):"") + app.api_name + "/" + app.logout_function);
1091            xhttp.setRequestHeader(app.cookie_name, readCookie(app.cookie_name));
1092            xhttp.setRequestHeader("x-api-version", app.api_version);
1093            xhttp.send();
1094        });
1095    //} 
1096
1097
1098
1099
1100
1101
1102}
1103
1104objGetToken.user = {};
1105
1106function getUser(resolve_json) {
1107   
1108    return new Promise(function (resolve, reject) {
1109        if(objGetToken.user.user_data != null){
1110            if(!resolve_json.getProductes
1111                ||
1112                resolve_json.getProductes == objGetToken.user.getProductes
1113                ){
1114                resolve_json.user_data = objGetToken.user.user_data;
1115                resolve(resolve_json);
1116                return 
1117            }
1118            
1119        } 
1120
1121        if (resolve_json.token == null || resolve_json.token == "") {
1122            reject(Error("No login"));
1123            return;
1124        }
1125
1126
1127        var getProductes = (resolve_json.hasOwnProperty('getProductes')) ? resolve_json.getProductes : true;
1128        var xhttpx = new XMLHttpRequest();
1129        xhttpx.onreadystatechange = function () {
1130            if (xhttpx.readyState == 4) {
1131                switch (xhttpx.status) {
1132                    case 200:
1133                        resolve_json.user_data = JSON.parse(xhttpx.response);
1134                        objGetToken.user.user_data = resolve_json.user_data;
1135                        objGetToken.user.getProductes = resolve_json.getProductes;
1136
1137                        //exitLogin(true);
1138                        //if(refresh)document.location.reload(true);
1139                        resolve(resolve_json);
1140
1141                        break;
1142                    default:
1143                        //missatgeError(Msg.error_desconegut);
1144                        reject(Error("No login"));
1145                        break;
1146                }
1147            }
1148
1149        };
1150
1151        if (getProductes) {
1152            xhttpx.open("GET", objGetToken.url_base + "/userproducts", true);
1153        } else {
1154            xhttpx.open("GET", objGetToken.url_base + "/user", true);
1155        }
1156        xhttpx.setRequestHeader("Content-type", "application/json;charset=utf-8");
1157        xhttpx.setRequestHeader("authsecurity", resolve_json.token);
1158        if (isDevelop()) xhttpx.setRequestHeader("x-api-version", objGetToken.auth_version);
1159        //xhttpx.setRequestHeader("authkey", resolve_json.token);
1160        xhttpx.send();
1161    });
1162}
1163
1164
1165function showAds(prods) {
1166
1167    return new Promise(function (resolve, reject) {
1168
1169        var user_token = readCookie("authsecurity");
1170        resolve_json = {
1171            "token": user_token,
1172            "getProductes": true
1173        };
1174        getUser(resolve_json).then(function (data) {
1175                prods.forEach(function (prod) {
1176                    data.user_data.data.productes.forEach(function (producte) {
1177                        if (producte.codi == prod) {
1178                            resolve('ok');
1179                        }
1180                    });
1181                });
1182                reject('no_products')
1183
1184            },
1185            function (data) {
1186                reject('no_login');
1187            });
1188    });
1189}
1190
1191function removeInit() {
1192    if (document.getElementById("itec-login-curtain") !== null){
1193        document.getElementById("itec-login-curtain").parentNode.removeChild(document.getElementById("itec-login-curtain"));
1194    }
1195}
1196function removeCookieAuth(domain){
1197    document.cookie = "authsecurity" + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=" + domain + ";max-age=0;path=/";
1198}
1199
1200function init(input_json) {
1201    //insertPromiseScript();
1202    return new Promise(function (resolve, reject) {
1203
1204        var idioma;
1205        var refresh;
1206        var returnUrl;
1207        var logo;
1208
1209
1210        if (document.getElementById('ITeC-login-form') !== null) {
1211            return;
1212        }
1213
1214        _init = function () {
1215            //settings
1216            idioma = (input_json.idioma) ? input_json.idioma : (input_json.app?((input_json.app.idioma) ? input_json.app.idioma : 0):0);
1217            refresh = (input_json.refresh) ? input_json.refresh : false;
1218            var refresh_web = location.host;
1219            if(refresh_web.indexOf("itec.cat")== 0 || refresh_web.indexOf("itec.es")== 0 || refresh_web.indexOf("en.itec.cat")== 0){
1220                refresh = true;
1221            }
1222            returnUrl = (input_json.url) ? input_json.url : null;
1223            logo = (input_json.logo) ? input_json.logo : "https://itec.cat/wp-content/uploads/2014/10/itec.png";
1224            logo = (logo != "") ? "<img src='" + logo + "'/>" : "";
1225            user_data = (input_json.user_data) ? true : false;
1226            app = (input_json.app) ? input_json.app : null;
1227            show_message = (input_json.hasOwnProperty("show_message")) ? input_json.show_message : false;
1228            enhanced_design = (input_json.hasOwnProperty("enhanced_design")) ? input_json.enhanced_design : false;
1229            register_level = (input_json.hasOwnProperty("register_level")) ? input_json.register_level : 0;
1230            register_custom_url = (input_json.hasOwnProperty("register_custom_url")) ? input_json.register_custom_url : '';
1231            register_step = (input_json.hasOwnProperty("register_step")) ? input_json.register_step : 0;
1232            register_msg = (input_json.hasOwnProperty("register_msg")) ? input_json.register_msg : '';
1233
1234            /**********************************
1235            app = {
1236                id:12,
1237                version : v1,
1238                name: "authbotiga"
1239            }
1240            ********************************/
1241
1242            switch (idioma) {
1243                case 0:
1244                    Msg = idiomes.catala;
1245                    objGetToken.idioma_url = "/ca/";
1246                    break;
1247                case 1:
1248                    Msg = idiomes.castella;
1249                    objGetToken.idioma_url = "/es/";
1250                    break;
1251                case 2:
1252                    Msg = idiomes.angles;
1253                    objGetToken.idioma_url = "/en/";
1254                    break;
1255                default:
1256                    Msg = idiomes.catala;
1257                    break;
1258            };
1259
1260            init_message = (input_json.init_message) ? input_json.init_message : Msg.missatge_inicial;
1261
1262            var cortina = document.createElement("DIV");
1263            cortina.id = "itec-login-curtain"
1264            //cortina.style = styles.cortina;
1265
1266
1267            var form = document.createElement("DIV");
1268            form.id = "itec-login-pre-form";
1269            form.style = ((isDevelopColor()) ? "background-color:#ff99c2;" : "");
1270            //form.style = styles.form;
1271
1272            form.innerHTML = (!enhanced_design) ? ([
1273                "<div id='ITeC-login-form' style='text-align:center;' >",
1274                "<div style='width:100%;font-size:18px;position:relative;height:40px;'>",
1275                "<span style='width:50%;'>" + logo + "</span>",
1276                "<span style='width:50%;float:right;top:-20px;text-align:right;right:-11px;cursor:pointer;font-weight:bold;color:#880000;position:absolute;' onclick=\"exitLogin(false);\">x</span></div>",
1277                "<form id='formLogin' action='javascript:fn_login();'>",
1278                "<div style='margin-bottom:20px;font-weight:bold;font-size:16px;'> " + Msg.iniciar_sessio + "</div>",
1279                ((show_message) ? "<div style='margin-bottom:20px;'>" + init_message + "</div>" : ""),
1280                "<div class='ITeC-mdl-textfield'><input class='ITeC-mdl-textfield_input' type='email' placeholder='email' id='user_mail' name='user_mail' required >",
1281                "</div>",
1282                "<div class='ITeC-mdl-textfield'><input class='ITeC-mdl-textfield_input' type='password' placeholder='password' id='user_pwd' name='user_pwd' required><a  href=\"javascript:show_pwd();\" class='a_show_pwd_icon'><i id='user_pwd_icon' name='user_pwd_icon' class='fa fa-eye-slash' aria-hidden='true' class='show_pwd_icon'></i></a></div>",
1283                "<div style='padding:10px;display:none;' id='msgEmpreses'>",
1284                "<select id='selectEmpreses'></select>",
1285                "</div>",
1286                "<div style='color:red;padding:10px;height:20px;'><div id='msgError'></div></div>",
1287                "<div style='margin-top:10px;'><button type='submit'id='buttonlogin'>" + Msg.entrar + "</button></div>",
1288                "<div style='margin-top:15px;font-size:13px;text-align:right;'>",
1289                "<div style='float:left'><a href=\"" + Msg.login_help_url + "\" target='_blank' class='logo-info'><img src='https://itec.cat/login/libs/icon/info.svg' style='width:30px;height:30px'></a></div>",
1290                "<div style='float:right'><a id='registrar' href=\"javascript:registrar();\">" + Msg.registrar + "</a><br/>",
1291                "<a id='lostPassword' href=\"javascript:lost_pwd();\">" + Msg.no_password + "</a></div><div style='clear: both;'></div></div>",
1292                "<input type='hidden' id='authorization'/>",
1293                "</form>",
1294                "</div>"
1295                ].join('')) :
1296                ([
1297                    "<div id='ITeC-login-form' class='enhanced_design' style='text-align:center;' >",
1298                    "<div style='width:100%;font-size:18px;position:relative;height:40px;'>",
1299                    "<span style='width:50%;float:left;text-align:left;'>" + logo + "</span>",
1300
1301                    "<span style='width:50%;float:right;top:-20px;text-align:right;right:-11px;cursor:pointer;font-weight:bold;color:#880000;position:absolute;' onclick=\"exitLogin(false);\">x</span></div>",
1302
1303
1304                    "<form id='formLogin' action='javascript:fn_login();'>",
1305                    ((show_message) ? "<div style='margin-bottom:20px;'>" + init_message + "</div><hr/>" : ""),
1306                    "<div style='float:left; width:59%;'>",
1307
1308
1309                    "<div style='margin-top:15px;text-align:left;font-weight:bold;font-size:15px;'>" + Msg.iniciar_sessio + "</div>",
1310                    "<div class='ITeC-mdl-textfield'><input class='ITeC-mdl-textfield_input input_enhanced' type='email' placeholder='email' id='user_mail' name='user_mail' required >",
1311                    "</div>",
1312                    "<div class='ITeC-mdl-textfield'><input class='ITeC-mdl-textfield_input input_enhanced' type='password' placeholder='password' id='user_pwd' name='user_pwd' required><a  href=\"javascript:show_pwd();\" class='a_show_pwd_icon'><i id='user_pwd_icon' name='user_pwd_icon' class='fa fa-eye-slash' aria-hidden='true' class='show_pwd_icon'></i></a></div>",
1313                    "<div style='padding:10px;display:none;' id='msgEmpreses'>",
1314                    "<select id='selectEmpreses'></select>",
1315                    "</div>",
1316                    "<div style='text-align:left; font-size:10px;'><a id='lostPassword' href=\"javascript:lost_pwd();\">" + Msg.no_password + "</a></div>",
1317                    "</div>",
1318
1319                    "<div style='float:right; width:39%;'>",
1320                    "<div style='color:red;padding:10px;height:66px;'><div id='msgError'></div></div>",
1321                    "<div><button type='submit' id='buttonlogin'>" + Msg.entrar + "</button></div>",
1322                    "</div>",
1323
1324                    "<div style='float:none;width:100%;display:inline-block;'>",
1325                    "<div style='margin-top:15px;text-align:left;' id='registrar'><hr/>",
1326                    "<div style='margin-top:15px; margin-bottom:15px;font-weight:bold;font-size:15px;'>" + Msg.not_registered + "</div>",
1327                    "<div><button  type='button' onclick=\"location.href='javascript:registrar();'\">" + Msg.registrar + "</button></div>",
1328                    "</div>",
1329                    "</div>",
1330                    "<input type='hidden' id='authorization'/>",
1331                    "</form>",
1332                    "</div>"
1333                ].join(''));
1334
1335            //cortina.appendChild(style);
1336            cortina.appendChild(form);
1337            document.addEventListener("keydown", function (event) {
1338                var boton = document.getElementById("buttonlogin")
1339                // Verifica si la tecla presionada es Enter (código 13)
1340                if (event.key === "Enter") {
1341                  // Dispara un evento de clic en el botón
1342                  boton.click();
1343                }
1344              });
1345
1346
1347            document.getElementsByTagName("body")[0].appendChild(cortina);
1348            // document.getElementsByTagName("app-login")[0].appendChild(cortina);
1349
1350            // login enterkey submit
1351           /*
1352            var input = document.getElementById("formLogin");
1353
1354            if (input != null) {
1355                // Execute a function when the user presses a key on the keyboard
1356                input.addEventListener("keypress", function(event) {
1357                // If the user presses the "Enter" key on the keyboard
1358                console.dir("buttonlogin_click", event);
1359                if (event.key === "Enter") {
1360                    // Cancel the default action, if needed
1361                    event.preventDefault();
1362                    // Trigger the button element with a click
1363                    
1364                    document.getElementById("buttonlogin").click();
1365                }
1366                });
1367            }
1368
1369            */
1370        };
1371
1372        show_pwd = function () {
1373            var x = document.getElementById("user_pwd");
1374            var y = document.getElementById("user_pwd_icon");
1375            if (x.type === "password") {
1376                x.type = "text";
1377                y.classList.remove('fa-eye-slash');
1378                y.classList.add('fa-eye');
1379            } else {
1380                x.type = "password";
1381                y.classList.remove('fa-eye');
1382                y.classList.add('fa-eye-slash');
1383            }
1384        };
1385
1386        // ?log=ecob
1387        registrar = function () {
1388            exitLogin(true);
1389            if (register_level && register_level > 0){
1390                if (register_custom_url.length > 5){
1391                    document.location.href = register_custom_url;
1392                }
1393                else {
1394                    if (register_msg && register_msg.length > 0){
1395                        document.location.href = objGetToken.url_login + objGetToken.idioma_url + "profile/register?level=1&back=" + window.location.href + "&msg=" + register_msg;
1396                    }
1397                    else {
1398                        document.location.href = objGetToken.url_login + objGetToken.idioma_url + "profile/register?level=1&back=" + window.location.href;
1399                    }
1400                }
1401            }
1402            else {
1403                document.location.href = objGetToken.url_login + objGetToken.idioma_url + "profile/register?back=" + window.location.href;
1404            }
1405            
1406        };
1407
1408        lost_pwd = function () {
1409            exitLogin(true);
1410            document.location.href = objGetToken.url_login + objGetToken.idioma_url + "profile/lostpassword?back=" + window.location.href;
1411
1412        };
1413
1414
1415        /******************************************
1416        missatgeError. Ensenya missatge al DIV msgError
1417        ******************************************/
1418
1419        missatgeError = function (missatge) {
1420            document.getElementById("msgError").style.display = "block";
1421            document.getElementById("msgError").innerHTML = missatge;
1422        };
1423
1424
1425
1426
1427        exitLogin = function (valor) {
1428            document.getElementById("itec-login-curtain").parentNode.removeChild(document.getElementById("itec-login-curtain"));
1429            if (!valor) {
1430                // L'usuari tanca la finestra del login.
1431
1432                if (returnUrl != null) {
1433                    document.location.href = returnUrl;
1434                }
1435                reject(Error("No login"));
1436            }
1437
1438        };
1439
1440
1441
1442        var resolve_json = {};
1443
1444
1445        multidomini = function (user_token) {
1446            setXssUser(user_token);
1447
1448            exitLogin(true);
1449            if (refresh) {
1450                setTimeout(function () {
1451                    document.location.reload(true);
1452                }, 1000);
1453            }
1454
1455            /*
1456            //iteces = document.createElement("iframe");
1457            iteces2 = document.createElement("iframe");
1458            //iteccat = document.createElement("iframe");
1459            iteccat2 = document.createElement("iframe");
1460            //iteces.src = "http://itec.es/login/iframe.html?user_token=" + user_token;
1461            iteces2.src = "https://itec.es/login/iframe.html?user_token=" + user_token;
1462            //iteccat.src = "http://itec.cat/login/iframe.html?user_token=" + user_token;
1463            iteccat2.src = "https://itec.cat/login/iframe.html?user_token=" + user_token;
1464
1465            //iteces.style.display = "none";
1466            iteces2.style.display = "none";
1467            //iteccat.style.display = "none";
1468            iteccat2.style.display = "none";
1469
1470            //document.getElementsByTagName("body")[0].appendChild(iteces);
1471            document.getElementsByTagName("body")[0].appendChild(iteces2);
1472            //document.getElementsByTagName("body")[0].appendChild(iteccat);
1473            document.getElementsByTagName("body")[0].appendChild(iteccat2);
1474            */
1475
1476            // No utilitzem les cookies, utilitzem el localStorage. Evitem el conflicte de dominis.
1477            //localStorage.setItem("authsecurity", user_token);
1478            createCookie("authsecurity", user_token, 1);
1479            var loginEvent = document.createEvent('Event');
1480            loginEvent.initEvent('onItecLogin', true, true);
1481            window.dispatchEvent(loginEvent);
1482            resolve(resolve_json);
1483        };
1484
1485
1486
1487        /****************************************************
1488        setCookie. Posa la cookie i plega
1489        ****************************************************/
1490        setCookie = function (user_token) {
1491
1492            //document.cookie = "authsecurity=" + user_token + ";" + expires + ";path=/";
1493
1494            //var evt = new CustomEvent("authsecurity", {detail:{token: user_token}});
1495            //window.dispatchEvent(evt);
1496
1497            //        createCookie("authsecurity", user_token, 10);
1498
1499            //keepAlive(user_token);
1500
1501            // Sol·licitar l'inici de l'aplicació.
1502            resolve_json.token = user_token;
1503            objGetToken.var_user_token = user_token;
1504
1505            if (user_data) {
1506
1507                getUser(resolve_json).then(function (data) {
1508                        if (app != null) {
1509                            init_app(app, user_token).then(function (data) {
1510                                    resolve_json.app = data.app;
1511                                    multidomini(user_token);
1512
1513                                },
1514                                function (data) {
1515                                    resolve_json.app = data;
1516                                    multidomini(user_token);
1517
1518                                });
1519                        } else {
1520                            multidomini(user_token);
1521
1522                        }
1523
1524                    },
1525                    function (data) {
1526                        missatgeError(Msg.error_desconegut);
1527                        reject(data);
1528                    });
1529
1530            } else {
1531                if (app != null) {
1532                    init_app(app, user_token).then(function (data) {
1533                            resolve_json.app = data.app;
1534                            multidomini(user_token);
1535                        },
1536                        function (data) {
1537                            resolve_json.app = data;
1538                            multidomini(user_token);
1539                        });
1540                } else {
1541                    multidomini(user_token);
1542                }
1543
1544            }
1545        };
1546
1547
1548
1549
1550        /****************************************************
1551        loginEmpresa. Segona part del login per si hi ha més d'una empresa
1552        ****************************************************/
1553        loginEmpresa = function () {
1554            if (document.getElementById("selectEmpreses").value != "-1") {
1555                var xhttp = new XMLHttpRequest();
1556                xhttp.onreadystatechange = function () {
1557                    if (xhttp.readyState == 4) {
1558                        switch (xhttp.status) {
1559                            case 200:
1560                                setCookie(xhttp.getResponseHeader("authsecurity"));
1561                                break;
1562                            default:
1563                                missatgeError(Msg.no_llicencia_entitat);
1564                                break;
1565                        }
1566                    }
1567                };
1568
1569                xhttp.open("POST", objGetToken.url_base + "/login", true);
1570                xhttp.setRequestHeader("Content-type", "application/json;charset=utf-8");
1571                if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
1572                //xhttp.setRequestHeader("authsecurity", document.getElementById("authorization").value);
1573                var user = document.getElementById("user_mail").value;
1574                var pwd = JSON.stringify(document.getElementById("user_pwd").value.trim());
1575
1576                xhttp.send("{\"entitat\": \"" + document.getElementById("selectEmpreses").value + "\", \"user\":\"" + user + "\",\"pwd\":" + pwd + " }");
1577
1578            } else {
1579                missatgeError(Msg.selecciona_entitat)
1580            }
1581        };
1582
1583        
1584        
1585        /****************************************************
1586        login Principal
1587        ****************************************************/
1588        fn_login = function () {
1589
1590            var pwd = document.getElementById("user_pwd").value;
1591            if (pwd.replace(/\s/g, '').length) {
1592                missatgeError("<div class=\"sp sp-circle\"></div>");
1593                
1594                //alert("wait");
1595                var xhttp = new XMLHttpRequest();
1596              xhttp.onreadystatechange = function () {
1597                  if (xhttp.readyState == 4) {
1598                      var response = JSON.parse(xhttp.response);
1599                      switch (xhttp.status) {
1600                          case 200:
1601                              if (response.data.length > 1) {
1602                                  // Tenim més d'una empresa.
1603                                  document.getElementById("formLogin").action = "javascript:loginEmpresa();";
1604                                  document.getElementById("user_mail").parentElement.style.display =
1605                                      document.getElementById("user_pwd").parentElement.style.display =
1606                                      document.getElementById("msgError").style.display =
1607                                      document.getElementById("registrar").style.display =
1608                                      document.getElementById("lostPassword").style.display = "none";
1609                                  //document.getElementById("authorization").value = xhttp.getResponseHeader("authsecurity");
1610  
1611                                  var selectEmpreses = document.getElementById("selectEmpreses");
1612                                  // borrem child nodes
1613                                  while (selectEmpreses.hasChildNodes()) {
1614                                    selectEmpreses.removeChild(selectEmpreses.firstChild);
1615                                  }
1616
1617                                  var option = document.createElement("option");
1618                                  
1619                                  option.text = Msg.selecciona_entitat;
1620                                  option.value = "-1";
1621                                  selectEmpreses.add(option);
1622                                  for (x = 0; x < response.data.length; x++) {
1623                                      var option = document.createElement("option");
1624                                      option.text = response.data[x].nom;
1625                                      option.value = response.data[x].id;
1626                                      selectEmpreses.add(option);
1627                                  }
1628                                  document.getElementById("msgEmpreses").style.display = "block";
1629                              } else {
1630                                  // L'usuari és bo
1631                                  setCookie(xhttp.getResponseHeader("authsecurity"));
1632                              }
1633                              break;
1634  
1635                          default:
1636                              //alert("error de registre");
1637                              missatgeError(Msg.error_desconegut);
1638                              if (typeof response.validations !== 'undefined' && response.validations[0] !== 'undefined' && response.validations[0].field !== 'undefined') {
1639                                  switch (response.validations[0].field) {
1640                                      case "12":
1641                                          missatgeError(Msg.usuari_no_existeix);
1642                                          break;
1643                                      case "10":
1644                                          missatgeError(Msg.password_incorrecte);
1645                                          break;
1646                                      case "3":
1647                                          missatgeError(Msg.usuari_esborrat);
1648                                          break;
1649                                      case "31":
1650                                          missatgeError(Msg.usuari_bloquejat);
1651                                          break;
1652                                      case "1":
1653                                          missatgeError(Msg.usuari_no_existeix);
1654
1655                                        break;
1656                                      default:
1657                                          missatgeError(Msg.error_desconegut);
1658                                          break;
1659                                  }
1660                              }
1661                              break;
1662                      }
1663                  }
1664              };
1665  
1666  
1667              xhttp.open("POST", objGetToken.url_base + "/login", true);
1668              xhttp.setRequestHeader("Content-type", "application/json;charset=utf-8");
1669              xhttp.setRequestHeader("authsecurity", null);
1670              if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
1671  
1672              var user = document.getElementById("user_mail").value.trim();
1673              var pwd = JSON.stringify(document.getElementById("user_pwd").value.trim());
1674  
1675  
1676              xhttp.send("{\"user\": \"" + user + "\", \"pwd\":" + pwd + "}");              }
1677              else{
1678                missatgeError(Msg.password_incorrecte);
1679
1680              }
1681            
1682
1683        };
1684
1685        /*****************************************************************
1686        IDIOMES
1687        *****************************************************************/
1688        var idiomes = {
1689            catala: {
1690                "usuari_no_existeix": "L'usuari no existeix",
1691                "password_incorrecte": "Password incorrecte",
1692                "error_desconegut": "S'ha produït un error. Poseu-vos en contacte amb nosaltres",
1693                "selecciona_entitat": "Selecciona una entitat",
1694                "no_llicencia_entitat": "No hi ha llicències disponibles",
1695                "iniciar_sessio": "Iniciar sessió",
1696                "entrar": "Entrar",
1697                "registrar": "Registrar-se",
1698                "no_password": "No recordo el password",
1699                "usuari_esborrat": "Usuari esborrat",
1700                "usuari_no_confirmat": "Usuari no confirmat",
1701                "missatge_inicial": "Aquesta informació és restringida a usuaris identificats.",
1702                "confirm_sent": "Hem enviat un mail de confirmació a l'adreça indicada.",
1703                "not_registered": "Encara no estic registrat/da",
1704                "usuari_bloquejat": "Usuari bloquejat temporalment. Torneu-ho a provar més tard",
1705                "login_help_url" : "https://wiki.itec.cat/doku.php?id=ca:faqs-preguntas-frecuentes:como-registrarse-pagina-web-itec"
1706            },
1707            castella: {
1708                "usuari_no_existeix": "El usuario no existe",
1709                "password_incorrecte": "Password incorrecto",
1710                "error_desconegut": "Se ha producido un error. Póngase en contacto con nosotros",
1711                "selecciona_entitat": "Selecciona una entidad",
1712                "no_llicencia_entitat": "No hay licencias disponibles",
1713                "iniciar_sessio": "Iniciar sesión",
1714                "entrar": "Entrar",
1715                "registrar": "Registrarse",
1716                "no_password": "No recuerdo el password",
1717                "usuari_esborrat": "Usuario borrado",
1718                "usuari_no_confirmat": "Usuari no confirmado",
1719                "missatge_inicial": "Esta información está restringida a usuarios identificados.",
1720                "confirm_sent": "Hemos enviado un mail de confirmación a la dirección indicada.",
1721                "not_registered": "Todavía no estoy registrado/a",
1722                "usuari_bloquejat": "Usuario bloqueado temporalmente. Vuelva a intentarlo más tarde",
1723                "login_help_url" : "https://wiki.itec.cat/doku.php?id=faqs-preguntas-frecuentes:como-registrarse-pagina-web-itec"
1724            },
1725            angles: {
1726                "usuari_no_existeix": "User does not exist",
1727                "password_incorrecte": "Bad password",
1728                "error_desconegut": "There was an error. Please contact us",
1729                "selecciona_entitat": "Select one entity",
1730                "no_llicencia_entitat": "There are not more licences",
1731                "iniciar_sessio": "Login",
1732                "entrar": "Submit",
1733                "registrar": "Register",
1734                "no_password": "I forget my password",
1735                "usuari_esborrat": "User deleted",
1736                "usuari_no_confirmat": "User no confirmed yet",
1737                "missatge_inicial": "This information is for identified users only.",
1738                "confirm_sent": "We sent a confirmation mail to you",
1739                "not_registered": "I'm not registered",
1740                "usuari_bloquejat": "User blocked. Try again later.",
1741                "login_help_url" : "https://wiki.itec.cat/doku.php?id=faqs-preguntas-frecuentes:como-registrarse-pagina-web-itec"
1742            }
1743
1744        };
1745
1746
1747
1748
1749
1750        _http = function () {
1751            var xhttp;
1752            if (window.XMLHttpRequest) {
1753                xhttp = new XMLHttpRequest();
1754            } else {
1755                // code for IE6, IE5
1756                xhttp = new ActiveXObject("Microsoft.XMLHTTP");
1757                return xhttp;
1758            }
1759        };
1760        _init();
1761    });
1762}
1763
1764function enviarMailConfirmacio(email) {
1765    return new Promise(function (resolve, reject) {
1766        var xhttp = new XMLHttpRequest();
1767
1768        xhttp.onreadystatechange = function () {
1769            if (xhttp.readyState == 4) {
1770                switch (xhttp.status) {
1771                    case 200:
1772
1773                        resolve(true);
1774
1775                        break;
1776                    default:
1777                        reject(false);
1778                        break;
1779                }
1780            }
1781        };
1782        xhttp.open("POST", objGetToken.url_base + "/sendmailconfirmuser", true);
1783        xhttp.setRequestHeader("Content-type", "application/json;charset=utf-8");
1784        xhttp.setRequestHeader("authsecurity", null);
1785        if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
1786
1787        xhttp.send("{\"user\": \"" + email + "\"}");
1788    });
1789
1790}
1791
1792objGetToken.init_apps = [];
1793
1794function init_app(app, user_token) {
1795    //insertPromiseScript();
1796    var resolve_json = {};
1797    if (app) {
1798
1799        return new Promise(function (resolve, reject) {
1800           if(!objGetToken.retried401){
1801                for(x=0;x<objGetToken.init_apps.length; x++){
1802                    if(objGetToken.init_apps[x].app.name == app.name){
1803                        resolve(objGetToken.init_apps[x]);
1804                        return;
1805                    }
1806                }
1807            }
1808            
1809
1810            var xhttp = new XMLHttpRequest();
1811            xhttp.onreadystatechange = function () {
1812                if (xhttp.readyState == 4) {
1813                    switch (xhttp.status) {
1814                        case 200:
1815                            /* Missatges llicència caducada */
1816                            r = JSON.parse(xhttp.responseText).data;
1817
1818                            // Parxe per a la comprovació de quota al bedec mentre el tyk falli.
1819                            objGetToken.initializated_apps.push({
1820                                app: app,
1821                                data: r
1822                            });
1823                           
1824
1825                            if(app.name=="bedec" && app.version=="v2"){
1826                                objGetToken.last_init_app = {};
1827                                objGetToken.last_init_app.request = app;
1828                                objGetToken.last_init_app.response = r;
1829                            }
1830                            // final parxe
1831
1832                            if (!r.funcionasensellicencia) {
1833                                
1834                                //if (r.demo) {
1835                                if (!r.demo) {
1836                                    if (!r.tellicencies){
1837                                        //usuari demo
1838                                        if(r.llicenciescalculades && r.numllicencies == 0){
1839                                            reject(xhttp);
1840                                            showNoLicenseMessage(xhttp, app, "demo");
1841                                            return;
1842                                        }
1843                                        //?
1844                                        if(r.llicenciescalculades && r.numllicencies){
1845                                            reject(xhttp);
1846                                            showNoLicenseMessage(xhttp, app, "no_lliures");
1847                                            return;
1848                                        }
1849                                    } 
1850                                    else {
1851                                        //caducades
1852                                        if (r.totesllicenciescaducades && r.llicenciescalculades) {
1853                                            reject(xhttp);
1854                                            showNoLicenseMessage(xhttp, app, "caducades");
1855                                            return;
1856
1857                                        }
1858                                        //totes agafades
1859                                        if (!r.totesllicenciescaducades && r.totesllicenciesagafades) {
1860                                            reject(xhttp);
1861                                            showNoLicenseMessage(xhttp, app, "agafades");
1862                                            return;
1863                                        }
1864                                    }
1865                                }
1866
1867                            }
1868
1869                            resolve_json.app = {
1870                                name: app.name,
1871                                auth: JSON.parse(xhttp.responseText).data.usuari_token
1872                            };
1873
1874                            objGetToken.var_app_token = resolve_json.app.auth;
1875                            //document.cookie = "auth" + app.name + "=" + resolve_json.app.auth + ";" + expires + ";path=/";
1876                            createCookie("auth" + app.name, resolve_json.app.auth, 1);
1877                            //keepAlive(user_token);
1878                            objGetToken.init_apps.push(resolve_json);
1879                            resolve(resolve_json);
1880
1881                            break;
1882                        default:
1883
1884                            reject(xhttp);
1885                            break;
1886                    }
1887                    objGetToken.running = false;
1888                }
1889            };
1890            xhttp.open("GET", objGetToken.url_base + "/init?application=" + app.name.toLowerCase() + "&version=" + app.version, true);
1891            xhttp.setRequestHeader("Content-type", "application/json;charset=utf-8");
1892            xhttp.setRequestHeader("authsecurity", user_token);
1893            if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
1894            // xhttp.setRequestHeader("authkey", user_token);
1895
1896            //Esperem 2 segons abans de l'init d'app.
1897
1898            xhttp.send();
1899
1900
1901        });
1902
1903    }
1904}
1905
1906
1907function showNoLicenseMessage(xhttp, app, tipus) {
1908    //tipus = "no-lliures", "agafades" ó "caducades"
1909    var divCortina = document.createElement("DIV");
1910    divCortina.id = "itec-login-curtain";
1911
1912    var msg = document.createElement("DIV");
1913    msg.id = "itec-login-pre-form";
1914    msg.className = "no-license"
1915    
1916    // Missatges NO-LLICÈNCIA
1917    var missatges = {
1918        catala: {
1919            no_lliures: "No hi ha llicències disponibles per l'aplicació ",
1920            agafades: "Totes les llicències d'aquest producte estan en ús per a aquesta entitat.<br/><br/>Estàs navegant com a Usuari Registrat que permet consultar 15 pàgines de contingut restringit al mes.",
1921            caducades: "La vigència d'aquest servei ha finalitzat",
1922            app: "Aplicació sol·licitada: ",
1923            link_botiga: "https://botiga.itec.cat/",
1924            link_text: "Anar a la Botiga",
1925            link_productes: "https://itec.es/login/ca/products",
1926            link_productes_text: "Productes i llicències",
1927            logo: "https://itec.cat/wp-content/uploads/2014/10/itec.png",
1928            demo: "Estàs navegant com a Usuari Registrat que permet consultar 15 pàgines de contingut restringit al mes."
1929        },
1930
1931        castella: {
1932            no_lliures: "No hay licencias disponibles para la aplicación ",
1933            agafades: "Todas las licencias de este producto están en uso en esta entidad.<br/><br/>Estás navegando como Usuario Registrado que permite consultar 15 páginas de contenido restringido al mes.",
1934            caducades: "La vigència de este servicio ha finalizado",
1935            app: "Aplicación solicitada: ",
1936            link_botiga: "https://tienda.itec.es/",
1937            link_text: "Ir a la Tienda",
1938            link_productes: "https://itec.es/login/es/products",
1939            link_productes_text: "Productos y licencias",
1940            logo: "https://itec.cat/wp-content/uploads/2014/10/itec.png",
1941            demo: "Estás navegando como Usuario Registrado que permite consultar 15 páginas de contenido restringido al mes.",
1942        },
1943
1944
1945        english: {
1946            no_lliures: "There are not free product licences for application: ",
1947            agafades: "All the licences of this product are been used in your entity.<br/><br/>You are navigating as a Registered User that allows you to see 15 pages of restricted content per month.",
1948            caducades: "The use time of this service is finalised",
1949            app: "Requested application: ",
1950            link_botiga: "https://store.itec.cat/",
1951            link_text: "Go to Store",
1952            link_productes: "https://itec.es/login/en/products",
1953            link_productes_text: "Products and licences",
1954            logo: "https://itec.cat/wp-content/uploads/2014/10/itec.png",
1955            demo: "You are navigating as a Registered User that allows you to see 15 pages of restricted content per month.",
1956        },
1957    };
1958
1959
1960    var missatge = {};
1961    switch (getIdioma()) {
1962        case 0:
1963        default:
1964            missatge = missatges.catala;
1965            break;
1966        case 1:
1967            missatge = missatges.castella;
1968            break;
1969        case 2:
1970            missatge = missatges.english;
1971            break;
1972    }
1973
1974    missatge.app += (app.app_name)?app.app_name:app.name;
1975
1976    if (app.no_licence_messages) {
1977        if (app.no_licence_messages.no_licences) {
1978            missatge.no_lliures = app.no_licence_messages.no_licences;
1979        }
1980        if (app.no_licence_messages.no_free) {
1981            missatge.agafades = app.no_licence_messages.no_free;
1982        }
1983        if (app.no_licence_messages.expired) {
1984            missatge.caducades = app.no_licence_messages.expired;
1985        }
1986        if (app.no_licence_messages.app_title) {
1987            missatge.app = app.no_licence_messages.app_title;
1988        }
1989        if (app.no_licence_messages.link) {
1990            missatge.link_botiga = app.no_licence_messages.link;
1991        }
1992        if (app.no_licence_messages.text_link) {
1993            missatge.link_text = app.no_licence_messages.text_link;
1994        }
1995        if (app.no_licence_messages.logo) {
1996            missatge.logo = app.no_licence_messages.logo;
1997        }
1998    }
1999
2000    msg.innerHTML = "";
2001    divCortina.appendChild(msg);
2002    var r = JSON.parse(xhttp.responseText).data;
2003
2004    msg.innerHTML += "<div style=\"float:right;margin:-14px -2px\"><div onclick=\"(function remove(){ document.getElementById('itec-login-curtain').parentNode.removeChild(document.getElementById('itec-login-curtain'));})();\" style=\"position:absolute;font-weight:bold;cursor: pointer;\">X</div></div>";
2005
2006    msg.innerHTML += "<div style=\"text-align:center;margin-bottom:20px;\"><img src=\'" + missatge.logo + "'   style='width: 73px;height: auto;'/></div>";
2007    msg.innerHTML += "<div style=\"text-align:center;margin-bottom:15px;font-weight:bold\">" + app.name.toUpperCase() + " </div>";
2008    msg.innerHTML += "<div style=\"text-align:center\">" + missatge[tipus] + "</div>";
2009    msg.innerHTML += "<div class=\"bottom\" style=\"padding-top:35px\"> <button onclick=\"(function remove(){ document.getElementById('itec-login-curtain').parentNode.removeChild(document.getElementById('itec-login-curtain'));window.open('" + missatge.link_productes + "','_blank')})();\" style=\"margin-right:10px\"/>" + missatge.link_productes_text + "</button><button onclick=\"(function remove(){ document.getElementById('itec-login-curtain').parentNode.removeChild(document.getElementById('itec-login-curtain'));document.location.href='" + missatge.link_botiga + "'})();\"/>" + missatge.link_text + "</button></div>";
2010
2011    if (!document.getElementById("itec-login-pre-form")) {
2012        document.getElementsByTagName("body")[0].appendChild(divCortina);
2013    }
2014}
2015
2016function getQuotes(response, app){
2017    quota = {};
2018    //Pedaç per a obtenir la quota a la bedec.v2
2019    return new Promise(function(resolve, reject){
2020        if( objGetToken.last_init_app
2021            &&
2022            objGetToken.last_init_app.request
2023            &&
2024            objGetToken.last_init_app.response.demo
2025            &&
2026            app.version == "v2"
2027            &&
2028            app.name=="bedec"
2029            ){
2030                var app_quota = {
2031                    name: "bedec",
2032                    version: "v1",
2033                    method: "GET",
2034                    api_url: "https://api.itec.cat/bedec/quota",
2035                    app_name:"bedec"
2036                };
2037
2038                api_bridge(app_quota).then(function(data){
2039
2040                    quota.limit = data.quota.quota_max;
2040 //data.getResponseHeader("X-Ratelimit-Limit");
2041                    quota.remaining = data.quota.quota_remaining;  //data.getResponseHeader("X-Ratelimit-Remaining");
2042                    resolve(quota);
2043                });
2044                
2045            }
2046            else{
2047                quota.limit = response.getResponseHeader("X-Ratelimit-Limit");
2048                quota.remaining = response.getResponseHeader("X-Ratelimit-Remaining");
2049
2050                if(quota.limit == 0) quota.limit=-1;
2051                if(quota.remaining==0) quota.remaining = -1;
2052                resolve(quota);
2053            }
2054
2055    });
2056}
2057
2058
2059
2060
2061function getMaxQuota(response) {
2062    
2063    return objGetToken.quota.limit;
2064    // Versió original que retorna el header. Activar quan funcioni el Tyk
2065    //return response.getResponseHeader("X-Ratelimit-Limit");
2066
2067}
2068
2069function getRemainingQuota(response) {
2070    
2071    return objGetToken.quota.remaining;
2072    
2073    // Versió original que retorna el header. Activar quan funcioni el Tyk
2074    //return response.getResponseHeader("X-Ratelimit-Remaining");
2075}
2076
2077function setRequestHeaders(request, appName, auth_security, auth_app) {
2078    if (appName == "security") {
2079        request.setRequestHeader("authsecurity", auth_security);
2080        // request.setRequestHeader("authkey", auth_security);
2081    } else {
2082        request.setRequestHeader("auth" + appName, auth_app);
2083        //  request.setRequestHeader("authkey", auth_app);
2084    }
2085}
2086
2087function isUnauthorizedByTyk(http_error) {
2088    if (typeof http_error == "string") {
2089        if (http_error.indexOf("aut_security:") > -1 && http_error.indexOf("auth_app:") > 0) {
2090            return true;
2091        }
2092    }
2093
2094
2095    var r = false;
2096    objToString = function (obj, ndeep) {
2097        switch (typeof obj) {
2098            case "string":
2099                return '"' + obj + '"';
2100            case "function":
2101                return obj.name || obj.toString();
2102            case "object":
2103                var indent = Array(ndeep || 1).join('\t'),
2104                    isArray = Array.isArray(obj);
2105                return ('{[' [+isArray] + Object.keys(obj).map(function (key) {
2106                    return '\n\t' + indent + (isArray ? '' : key + ': ') + objToString(obj[key], (ndeep || 1) + 1);
2107                }).join(',') + '\n' + indent + '}]' [+isArray]).replace(/[\s\t\n]+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/g, '');
2108            default:
2109                return obj.toString();
2110        }
2111    };
2112    // 
2113    str_error = "";
2114    if (typeof http_error.getResponseHeader === "function") {
2115        // L'error és del tipus XMLHttpRequest
2116        r = ((http_error.getResponseHeader("X-Generator") == "tyk.io" &&
2117                (http_error.status == 401 || http_error.status == 403)
2118            ) ||
2119            ((http_error.data) && (http_error.data.indexOf("Estado HTTP 401 - Authentication Failed: Maximum sessions of 1 for this principal exceeded") > 0))
2120        );
2121    } else {
2122        if (typeof http_error.headers === "function") {
2123            // L'error ve d'un $http d'angular.
2124            r = ((
2125                    http_error.headers(0)["x-generator"] == "tyk.io" &&
2126                    (http_error.status == 401 || http_error.status == 403)
2127                )
2128                // ||
2129                //  (http_error.data.indexOf("Estado HTTP 401 - Authentication Failed: Maximum sessions of 1 for this principal exceeded")>0)
2130            );
2131        } else {
2132            str_error = objToString(http_error);
2133            r = (
2134                (
2135                    (str_error.indexOf("401") > -1 || str_error.indexOf("403") > -1) &&
2136                    (str_error.indexOf("x-generator") > -1 && str_error.indexOf("tyk.io") > -1)
2137                ) ||
2138                (str_error.indexOf("Estado HTTP 401 - Authentication Failed: Maximum sessions of 1 for this principal exceeded") > 0)
2139
2140            );
2141        }
2142    }
2143    return r;
2144}
2145
2146function api_bridge(app) {
2147
2148
2149    objGetToken.queue.push({
2150        app: app,
2151        crida: objGetToken.crides
2152    });
2153    objGetToken.crides++;
2154
2155    waitForToken = function () {
2156        return new Promise(function (resolve, reject) {
2157
2158
2159            if (objGetToken.var_app_token == "" && objGetToken.var_user_token == "" && !objGetToken.running) {
2160                objGetToken.running = true;
2161                _api_bridge(app).then(function (data) {
2162                    resolve(data);
2163                }, function (data) {
2164                    reject(data);
2165                })
2166            } else {
2167                setTimeout(function () {
2168                    reject(false);
2169                }, objGetToken.waitValue);
2170            }
2171        });
2172    }
2173
2174
2175    return new Promise(function (resolve, reject) {
2176
2177        if (objGetToken.var_user_token != "" && objGetToken.var_app_token != "") {
2178            pila = objGetToken.queue.length;
2179            s = objGetToken.queue.shift();
2180            _api_bridge(app).then(function (data) {
2181                resolve(data);
2182            }, function (data) {
2183                reject(data);
2184            })
2185
2186
2187        } else {
2188            waitForToken().then(function (data) {
2189
2190                    //         console.log("API_BRIDGE wait for token resolved");
2191                    resolve(data);
2192                },
2193                function (data) {
2194                    //    console.log("API_BRIDGE wait for token rejected");
2195                    try {
2196                        resolve((function () {
2197                            return new Promise(function (resolve, reject) {
2198                                pila = objGetToken.queue.length;
2199                                s = objGetToken.queue.shift();
2200
2201                                //              console.log("API_BRIDGE wait for token rejected promise [" + s.crida + "]. Enviem:" + JSON.stringify(s));
2202                                _api_bridge(app).then(function (data) {
2203                                        //                console.log("API_BRIDGE wait for token rejected promise resolved [" + s.crida + "].  Rebem:" + JSON.stringify(data.config));
2204                                        resolve(data);
2205
2206                                    },
2207                                    function (data) {
2208                                        //              console.log("API_BRIDGE wait for token rejected promise rejected");
2209                                        reject(data);
2210                                    });
2211                            });
2212                        })())
2213                    } catch (e) {
2214                        //    console.log("API_BRIDGE wait for token rejected promise catch");
2215                        reject(error);
2216                    };
2217                });
2218        }
2219    });
2220}
2221
2222
2223
2224
2225function _api_bridge(app) {
2226
2227    //insertPromiseScript();
2228    app.json = (app.hasOwnProperty('json')) ? (app.json) : true;
2229    app.form = (app.hasOwnProperty('form')) ? (app.form) : false;
2230    app.refresh = (app.hasOwnProperty('refresh')) ? (app.refresh) : false;
2231    app.auth_security_header = (app.hasOwnProperty('auth_security_header')) ? (app.auth_security_header) : false;
2232    show_message = (app.hasOwnProperty("show_message")) ? app.show_message : false;
2233    init_message = (app.init_message) ? app.init_message : null;
2234    enhanced_design = (app.hasOwnProperty("enhanced_design")) ? app.enhanced_design : false;
2235    logo = (app.hasOwnProperty("logo")) ? app.logo : "";
2236
2237    return new Promise(function (resolve, reject) {
2238        if (!app) reject(false);
2239
2240        //   console.log("[_api_bridge] last:" + objGetToken.lastAppCall + "->current:" + app.name + " [" + (new Date().toJSON()) + "]");
2241
2242        // Controlem si la crida és a la mateixa app
2243        // Si no ho és, cal reinicialtzar tokens.
2244        
2245        if (objGetToken.lastAppCall != app.name) {
2246            //    console.log("[inizialize tokens] last:" + objGetToken.lastAppCall + "->current:" + app.name + " [" + (new Date().toJSON()) + "]");
2247            objGetToken.var_app_token = "";
2248            objGetToken.var_user_token = "";
2249            objGetToken.lastAppCall = app.name;
2250        }
2251        
2252
2253
2254
2255        init_bridge = function () {
2256            //  console.log("[init_bridge] last:" + objGetToken.lastAppCall + "->current:" + app.name + " [" + (new Date().toJSON()) + "]");
2257
2258            call_api(objGetToken.var_user_token, objGetToken.var_app_token, app).then(function (data) {
2259                    //       console.log("[call_api resolved] last:" + objGetToken.lastAppCall + "->current:" + app.name + " [" + (new Date().toJSON()) + "]");
2260                    resolve(data);
2261                },
2262                function (http_error) {
2263                    //       console.log("[call_api rejected] last:" + objGetToken.lastAppCall + "->current:" + app.name + " [" + (new Date().toJSON()) + "]");
2264                    if (isUnauthorizedByTyk(http_error)) {
2265
2266                        // L'error prové del Tyk. Provem de logar-nos.
2267                        objGetToken.var_user_token = auth_security = readCookie("authsecurity");
2268                        //auth_app = readCookie("auth" + app.name);
2269
2270                        // return call_api(auth_security,auth_app);
2271
2272                        getUser({
2273                            token: auth_security,
2274                            getProductes: false
2275                        }).then(function (data) {
2276                                // token d'usuari vàlid
2277                                //        console.log("[getUser done] last:" + objGetToken.lastAppCall + "->
2277current:" + app.name + " [" + (new Date().toJSON()) + "]");
2278                                loginSuccess(data);
2279                                //resolve_json.token = auth_security;
2280                                init_app(app, auth_security).then(function (data) {
2281                                    //       console.log("[init_app done] last:" + objGetToken.lastAppCall + "->current:" + app.name + " [" + (new Date().toJSON()) + "]");
2282                                    objGetToken.var_app_token = auth_app = data.app.auth;
2283                                    if (app.execute !== undefined) {
2284                                        return resolve(app.execute(auth_security, auth_app));
2285                                    } else {
2286                                        call_api(auth_security, auth_app, app).then(function (data) {
2287                                                resolve(data);
2288                                            },
2289                                            function (data) {
2290                                                // el call_api() ha tornat un error.
2291                                                reject(data);
2292                                            });
2293                                    }
2294                                }, function (data) {
2295                                    // no s'ha pogut fer l'init de l'aplicació
2296                                    return reject(data);
2297                                });
2298                            },
2299                            function (data) {
2300                                //token d'usuari invàlid.
2301                                init({
2302                                    app: app,
2303                                    refresh: app.refresh,
2304                                    user_data: true,
2305                                    show_message: show_message,
2306                                    init_message: init_message,
2307                                    logo: logo,
2308                                    enhanced_design: enhanced_design
2309                                }).then(function (data) {
2310                                    // usuari validat.
2311                                    loginSuccess(data);
2312                                    objGetToken.var_user_token = auth_security = data.token;
2313                                    objGetToken.var_app_token = auth_app = data.app.auth;
2314                                    if (app.execute !== undefined) {
2315                                        return resolve(app.execute(auth_security, auth_app));
2316                                    } else {
2317                                        call_api(auth_security, auth_app, app).then(function (data) {
2318                                                resolve(data);
2319                                            },
2320                                            function (data) {
2321                                                reject(data);
2322                                            });
2323                                    }
2324
2325                                }, function (data) {
2326                                    // usuari invàlid
2327                                    // Hauríem de tornar data;
2328                                    reject(data);
2329                                });
2330                            });
2331
2332                    } else {
2333                        // L'error no prové del tyk.
2334                        reject(http_error);
2335                    }
2336
2337                });
2338        };
2339
2340
2341        checkquota = function (auth_security, auth_app) {
2342            // No es fa servir. Ara es comproven els headers de retorn de la crida a l'api.
2343            // TODO - Esborrar.
2344
2345            return new Promise(function (resolve, reject) {
2346                var xhttp = new XMLHttpRequest();
2347                var jsonRetorn = {};
2348                xhttp.onreadystatechange = function () {
2349                    if (xhttp.readyState == 4) {
2350                        if (xhttp.status == 200) {
2351                            var jsonFromServer = JSON.parse(xhttp.responseText);
2352                            jsonRetorn.quota = jsonFromServer.data;
2353                        } else {
2354                            jsonRetorn.quota.quota_max = -2;
2355                            jsonRetorn.quota.quota_remaining = -2;
2356                        }
2357                        resolve(jsonRetorn);
2358                    }
2359                };
2360
2361                xhttp.open("GET", objGetToken.url_base + "/quota?token=" + auth_app);
2362                //xhttp.setRequestHeader("authkey", auth_app);
2363                xhttp.setRequestHeader("authsecurity", auth_security);
2364                if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
2365                xhttp.send();
2366
2367            });
2368
2369        };
2370
2371
2372        init_bridge();
2373    });
2374}
2375
2376
2377
2378function call_api(auth_secutity, auth_app, app) {
2379    //insertPromiseScript();
2380    return new Promise(function (resolve, reject) {
2381        if ((auth_secutity == null || auth_secutity == "") || (auth_app == null || auth_app == "")) {
2382            reject("aut_security:  " + auth_secutity + ", auth_app:" + auth_app);
2383            return;
2384            //throw TypeError("aut_security:  " + auth_secutity + ", auth_app:" + auth_app );
2385
2386        }
2387        if (app.execute !== undefined) {
2388            app.execute(auth_secutity, auth_app).then(
2389                function (data) {
2390                    resolve(data);
2391                    objGetToken.retried401 = false;
2392                },
2393                function (data) {
2394                    // OJU!!!! TCQi peta aquí si el token d'app no és vàlid!
2395                    // només si tenim un token caducat. 
2396                    if (data.status == 401  && !objGetToken.retried401) {
2397                        objGetToken.retried401 = true;
2398                        //console.log("token caducat: init_app execute:function()");
2399                        init_app(app, auth_secutity).then(function (data) {
2400                            
2401                            call_api(auth_secutity, data.app.auth, app).then(function (data) {
2402                                resolve(data);
2403                                return;
2404                            }, function (data) {
2405                                reject(data);
2406                                return;
2407                            });
2408                        }, function (data) {
2409                            reject(data);
2410                        });
2411                    } else {
2412                        reject(data);
2413                    }
2414
2415                }
2416            )
2417        } else {
2418
2419
2420            var xhttp = new XMLHttpRequest();
2421
2422            xhttp.onreadystatechange = function () {
2423                //console.log("readyState:" + xhttp.readyState);
2424                if (xhttp.readyState == 4) {
2425                    if (xhttp.status == 200) {
2426                        objGetToken.retried401 = false;
2427                        if (app.json) {
2428                            var jsonRetorn = xhttp.responseText ? JSON.parse(xhttp.responseText) : {};
2429                            jsonRetorn.quota = {
2430                                quota_max: xhttp.getResponseHeader("X-Ratelimit-Limit"),
2431                                quota_remaining: xhttp.getResponseHeader("X-Ratelimit-Remaining")
2432                            };
2433                            resolve(jsonRetorn);
2434                           
2435//                            getQuotes(xhttp, app).then(function(data){
2436//                                jsonRetorn.quota = {};
2437//                                jsonRetorn.quota.quota_max = data.limit;
2438//                                jsonRetorn.quota.quota_remaining = data.remaining;
2439//                                resolve(jsonRetorn);
2440//    
2441//                            })
2442
2443//                            jsonRetorn.quota = {};
2444//                            jsonRetorn.quota.quota_max = getMaxQuota(xhttp);
2445//                            jsonRetorn.quota.quota_remaining = getRemainingQuota(xhttp);
2446//
2447
2448                            // add snackbar
2449                            /*
2450                            if(jsonRetorn.quota.quota_remaining != null){
2451                                var snackbarRemain = document.getElementById("snackbarRemain");
2452                                if(snackbarRemain != null){
2453                                    document.getElementsByTagName("body")[0].removeChild(snackbarRemain);
2454                                }
2455                                else{
2456                                    var newScript = document.createElement("script");
2457                                    var inlineScript = document.createTextNode("function closeSnackRemain(){ var x = document.getElementById('snackbarRemain');if(x != null){ document.getElementsByTagName('body')[0].removeChild(x);}}");
2458                                    newScript.appendChild(inlineScript); 
2459                                    document.getElementsByTagName("body")[0].appendChild(newScript);
2460                                }
2461
2462                                var idioma = 1;
2463                                idioma = getIdioma();
2464                                var snackTitle = "Usuario Registrado";
2465                                var snackText = "Has consumido " + jsonRetorn.quota.quota_remaining + " de las " + jsonRetorn.quota.quota_max + " consultas disponibles de información restringida";
2466                                var snackButtonTxt = "Más información";
2467                                var snackButtonUrl = "https://tienda.itec.es/comparativa-servicios/";
2468                                if(idioma == 0){
2469                                    snackTitle = 'Usuari Registrat';
2470                                    snackText = "Has consumit " + jsonRetorn.quota.quota_remaining + " de les " + jsonRetorn.quota.quota_max + " consultes disponibles d'informació restringida";
2471                                    snackButtonTxt = "Més informació";
2472                                    snackButtonUrl = "https://botiga.itec.cat/comparativa-serveis/";
2473                                }
2474                                else if(idioma == 2){
2475                                    snackTitle = 'Registered User';
2476                                    snackText = "Has consumido " + jsonRetorn.quota.quota_remaining + " de las " + jsonRetorn.quota.quota_max + " consultas disponibles de información restringida";
2477                                    snackButtonTxt = "Más información";
2478                                    snackButtonUrl = "https://tienda.itec.es/comparativa-servicios/";
2479                                }
2480
2481                                snackbarRemain = document.createElement("DIV");
2482                                snackbarRemain.id = "snackbarRemain";
2483                                snackbarRemain.innerHTML += "<div id='snackbarRemain'><p class='snackClose' onclick='closeSnackRemain()'>X</p><p class='snackTitle'>" + snackTitle + "</p><p>
2483" + snackText + "</p><p class='button'><a href='" + snackButtonUrl + "' target='_blank'>" + snackButtonTxt + "</a></p></div>";
2484                                 document.getElementsByTagName("body")[0].appendChild(snackbarRemain);
2485                            }
2486
2487                            //console.log("jsonRetorn.quota.quota_max: " + jsonRetorn.quota.quota_max + " jsonRetorn.quota.quota_remaining: " + jsonRetorn.quota.quota_remaining);
2488                            */
2489
2490                            //resolve(jsonRetorn);
2491                            
2492                        } else {
2493                            resolve(xhttp.response);
2494                        }
2495                    } else {
2496                        if ((xhttp.status == 401 || xhttp.status == 403) && !objGetToken.retried401) {
2497                            objGetToken.retried401 = true;
2498                            // El token actual està desautoritzat.
2499                            //console.log("token caducat: init_app execute:null");
2500                            init_app(app, auth_secutity).then(function (data) {
2501                                    
2502                                    call_api(auth_secutity, data.app.auth, app).then(function (data) {
2503                                        resolve(data);
2504                                        return;
2505                                    }, function (data) {
2506                                        reject(data);
2507                                        return;
2508                                    });
2509                                },
2510                                function (data) {
2511                                    reject(data);
2512                                });
2513                        } else {
2514                            if (xhttp.status == 403) {
2515                                showNoLicenseMessage(xhttp, app, "no_lliures");
2516                                reject(xhttp);
2517
2518                            } else {
2519                                reject(xhttp);
2520                            }
2521                        }
2522                    };
2523
2524                }
2525            }
2526
2527            //console.log(JSON.stringify(app));
2528
2529            xhttp.open(app.method, app.api_url, true);
2530
2531            if (app.json) {
2532                xhttp.setRequestHeader("Content-type", "application/json;charset=utf-8");
2533                app_send = (app.request_body) ? JSON.stringify(app.request_body) : null;
2534            } else {
2535                xhttp.setRequestHeader("Accept", "text/html;type=ajax");
2536                app_send = (app.request_body) ? app.request_body : null;
2537            }
2538
2539            if (app.form) {
2540                xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
2541            }
2542
2543            setRequestHeaders(xhttp, app.name, auth_secutity, auth_app);
2544
2545            if (app.auth_security_header) {
2546                xhttp.setRequestHeader("authsecurity", auth_secutity);
2547            }
2548
2549            if (app.headers) {
2550                for (x = 0; x < app.headers.length; x++) {
2551                    xhttp.setRequestHeader(app.headers[x].name, app.headers[x].value);
2552                }
2553            }
2554
2555            if (isDevelop()) xhttp.setRequestHeader("x-api-version", app.version);
2556
2557            //console.log("app_send:" + app_send);
2558            xhttp.send(app_send);
2559        }
2560    });
2561}
2562
2563
2564
2565objGetToken.keepAliveRunning = false;
2566function keepAlive(user_token) {
2567    
2568    
2569    keep = function () {
2570        //console.log("keepAlive is running...");
2571        var xhttp = new XMLHttpRequest();
2572        xhttp.open("GET", objGetToken.url_base + "/keepalive");
2573        //xhttp.setRequestHeader("authkey", user_token);
2574        xhttp.setRequestHeader("authsecurity", user_token);
2575        if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
2576        xhttp.send();
2577        setTimeout("keep()", 480000);
2578    };
2579
2580    if(!objGetToken.keepAliveRunning){
2581        objGetToken.keepAliveRunning = true;
2582        //console.log("keepAlive initialized");
2583        setTimeout("keep()", 480000);
2584    }
2585}
2586
2587objGetToken.userPermissions = {};
2588
2589function getUserPermissions(jsonUser) {
2590
2591
2592    return new Promise(function (resolve, reject) {
2593        // Comento aquest retorn perquè està fallant això a la crida de permisos de vide des de tcqi. 25/11/2021 - #63103
2594       /* if(objGetToken.userPermissions.userToken == jsonUser.userToken
2595            &&
2596           objGetToken.userPermissions.appName == jsonUser.appName
2597            &&
2598           objGetToken.userPermissions.appVersion == jsonUser.appVersion
2599            ){
2600                resolve(objGetToken.userPermissions.data);
2601                return;
2602            }
2603        */
2604
2605        var userToken = jsonUser.userToken;
2606        var appName = jsonUser.appName;
2607        var appVersion = jsonUser.appVersion;
2608
2609
2610        var url_permissions = objGetToken.url_base + "/permissions?application=" + appName.toLowerCase() + "&version=" + jsonUser.appVersion.toLowerCase();
2611        var xhttp = new XMLHttpRequest();
2612
2613        xhttp.onreadystatechange = function () {
2614            if (xhttp.readyState == 4) {
2615                if (xhttp.status == 200) {
2616                    objGetToken.userPermissions.userToken = userToken;
2617                    objGetToken.userPermissions.appName = appName;
2618                    objGetToken.userPermissions.appVersion = appVersion;
2619                    objGetToken.userPermissions.data = xhttp.responseText;
2620                    resolve(xhttp.responseText);
2621                } else {
2622                    reject(xhttp.response);
2623                }
2624            }
2625        };
2626        xhttp.open("GET", url_permissions);
2627        xhttp.setRequestHeader("authsecurity", userToken);
2628        if (isDevelop()) xhttp.setRequestHeader("x-api-version", objGetToken.auth_version);
2629        xhttp.send();
2630
2631    })
2632
2633}
2634
2635
2636
2637(function init_getToken() {
2638    insertPromiseScript();
2639
2640    var styles = [
2641        "#itec-login-curtain{",
2642        " display: block;  ",
2643        "position: fixed; ",
2644        "z-index: 2147483647;",
2645        "left: 0;",
2646        "top: 0;",
2647        "width: 100%; ",
2648        "height: 100%; ",
2649        "overflow: auto; ",
2650        "background-color: rgb(0,0,0); ",
2651        "background-color: rgba(0,0,0,0.6);",
2652        "}",
2653        "#itec-login-pre-form{",
2654        " background-color: #fefefe;",
2655        " margin: 10% auto; ",
2656        " padding: 20px;",
2657        " border: 1px solid #888;",
2658        " max-width: 360px;",
2659        " min-width: 270px;",
2660        " font-family: sans-serif;",
2661        " font-size: 12px;",
2662        " border-radius: 6px;",
2663        " box-shadow: 0px 0px 14px;",
2664        " max-height:420px;",
2665        "}",
2666        "#ITeC-login-form select{",
2667        "    background-color:#fff; ",
2668        "    color:#000; ",
2669        "    height:auto; ",
2670        "    width:auto; ",
2671        "    text-indent:0px; ",
2672        "}               ",
2673        "#itec-login-pre-form.no-license div{",
2674        " margin-bottom: 20px;",
2675        " font-size:15px;",
2676
2677        "}",
2678        "#itec-login-pre-form.no-license div.bottom{",
2679        " text-align:right;",
2680        "}",
2681        "#ITeC-login-form button, #itec-login-pre-form.no-license button{",
2682        "                       background: 0 0;",
2683        "                       border: none;border-radius: 2px;",
2684        "                       color: #000;",
2685        "                       position: relative;",
2686        "                       height: 36px;",
2687        "                       margin: 0;",
2688        "                       min-width: 64px;",
2689        "                       padding: 0 16px;",
2690        "                       display: inline-block;",
2691        "                       font-family: sans-serif;",
2692        "                       font-size: 12px;",
2693        "                       font-weight: 500;",
2694        "                       text-transform: uppercase;",
2695        "                       letter-spacing: 0;",
2696        "                       overflow: hidden;",
2697        "                       will-change: box-shadow;",
2698        "                       transition: box-shadow .2s cubic-bezier(.4,0,1,1),background-color .2s cubic-bezier(.4,0,.2,1),color .2s cubic-bezier(.4,0,.2,1);",
2699        "                       outline: none;",
2700        "                       cursor: pointer;",
2701        "                       text-decoration: none;",
2702        "                       text-align: center;",
2703        "                       line-height: 36px;",
2704        "                       vertical-align: middle;",
2705        "                       background: rgba(158,158,158,.2);",
2706        "                       box-shadow: 0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);",
2707        "                       }",
2708        "#ITeC-login-form .ITeC-mdl-textfield{",
2709        "                       position: relative;",
2710        "                       font-size: 16px;display: inline-block;",
2711        "                       box-sizing: border-box;",
2712        "                       width: 100%;",
2713        "                       max-width: 100%;",
2714        "                       margin: 0;",
2715        "                       padding: 5px 0 20px;",
2716        "                       }",
2717        "#ITeC-login-form .ITeC-mdl-textfield_input{",
2718        "                       border: none;",
2719        "                       border-bottom: 1px solid rgba(0,0,0,.12);",
2720        "                       display: block;font-size: 14px;",
2721        "                       font-family: sans-serif;",
2722        "                       margin: 0;",
2723        "                       padding: 4px 0;",
2724        "                       width: 100%;",
2725        "                       background: 0 0;",
2726        "                       text-align: left;",
2727        "                       color: inherit;",
2728        "                        }",
2729        "#ITeC-login-form img {width:50px;}",
2730        "#ITeC-login-form .sp {                                                 ",
2731        "  width: 20px;                                        ",
2732        "  height: 20px;                                       ",
2733        "  clear: both;                                        ",
2734        "  margin: 0px auto;                                  ",
2735        "}                                                     ",
2736        "                                                      ",
2737        "#ITeC-login-form .sp-circle {                                          ",
2738        "  border: 4px rgba(0, 0, 136, 0.25) solid;            ",
2739        "  border-top: 4px #000088 solid;                      ",
2740        "  border-radius: 50%;                                 ",
2741        "  -webkit-animation: spCircRot .9s infinite linear;   ",
2742        "  animation: spCircRot .9s infinite linear;           ",
2743        "}                                                     ",
2744        "                                                      ",
2745        " /* DISSENY MILLORAT */                               ",
2746        " #ITeC-login-form .input_enhanced {                   ",
2747        "    width: 100%;                                      ",
2748        "    width: 100%;                                      ",
2749        "}                                                     ",
2750        " #ITeC-login-form.enhanced_design button {    ",
2751        "      font-size:11px;                                 ",
2752        " }                                                    ",
2753        " /* FINAL DISSENY MILLORAT */                         ",
2754        "@-webkit-keyframes spCircRot {                        ",
2755        "  from {                                              ",
2756        "    -webkit-transform: rotate(0deg);                  ",
2757        "  }                                                   ",
2758        "  to {                                                ",
2759        "    -webkit-transform: rotate(359deg);                ",
2760        "  }                                                   ",
2761        "}                                                     ",
2762        "@keyframes spCircRot {                                ",
2763        "  from {                                              ",
2764        "    transform: rotate(0deg);                          ",
2765        "  }                                                   ",
2766        "  to {                                                ",
2767        "    transform: rotate(359deg);                        ",
2768        "  }                                                   ",
2769        "}                                                     ",
2770        ".form-label-div{                                      ",
2771        "width:100%;text-align:left;font-size:14px             ",
2772        "  }                                                   ",
2773        ".a_show_pwd_icon{                                     ",
2774        "margin-left: -20px; position: absolute; right: 2px; top: 9px; color:#333;cursor: pointer;                                            ",
2775        "  }                                                   ",
2776        ".a_show_pwd_icon i{                                       ",
2777        "font-size: 14px;                                      ",
2778        "  }                                                   "
2779    ].join('');
2780
2781    var style = document.createElement("STYLE");
2782    style.type = "text/css";
2783    try {
2784        style.appendChild(document.createTextNode(styles));
2785        document.getElementsByTagName('head')[0].appendChild(style);
2786
2787
2788        // load xss iframe library
2789        // és la mateixa que fem servir per a connectar vide i tcqi
2790        var fileref = document.createElement("script");
2791        fileref.setAttribute("type", "text/javascript");
2792        fileref.setAttribute("src", objGetToken.crossDomainLocalStorageUrl);
2793        document.getElementsByTagName("head")[0].appendChild(fileref);
2794
2795
2796    } catch (e) {
2797        document.location = "old_browser.html";
2798    }
2799
2800})();
2801
2802;

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.