PageSourceSearch

https://magazin.photosynthesis.bg/themes/photosynthesis/js/scripts/app.js?v=585

js photosynthesis.bg collected 2026-10-01 12:02:58 UTC 191,206 bytes, 4,545 lines download raw bytes

1! function(e) {
2    if (!e.hasInitialised) {
3        var t = {
4            escapeRegExp: function(e) {
5                return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
6            },
7            hasClass: function(e, t) {
8                var i = " ";
9                return 1 === e.nodeType && (i + e.className + i).replace(/[\n\t]/g, i).indexOf(i + t + i) >= 0
10            },
11            addClass: function(e, t) {
12                e.className += " " + t
13            },
14            removeClass: function(e, t) {
15                var i = new RegExp("\\b" + this.escapeRegExp(t) + "\\b");
16                e.className = e.className.replace(i, "")
17            },
18            interpolateString: function(e, t) {
19                var i = /{{([a-z][a-z0-9\-_]*)}}/gi;
20                return e.replace(i, function(e) {
21                    return t(arguments[1]) || ""
22                })
23            },
24            getCookie: function(e) {
25                var t = "; " + document.cookie,
26                    i = t.split("; " + e + "=");
27                return 2 != i.length ? void 0 : i.pop().split(";").shift()
28            },
29            setCookie: function(e, t, i, n, o) {
30                var s = new Date;
31                s.setDate(s.getDate() + (i || 365));
32                var r = [e + "=" + t, "expires=" + s.toUTCString(), "path=" + (o || "/")];
33                n && r.push("domain=" + n), document.cookie = r.join(";")
34            },
35            deepExtend: function(e, t) {
36                for (var i in t) t.hasOwnProperty(i) && (i in e && this.isPlainObject(e[i]) && this.isPlainObject(t[i]) ? this.deepExtend(e[i], t[i]) : e[i] = t[i]);
37                return e
38            },
39            throttle: function(e, t) {
40                var i = !1;
41                return function() {
42                    i || (e.apply(this, arguments), i = !0, setTimeout(function() {
43                        i = !1
44                    }, t))
45                }
46            },
47            hash: function(e) {
48                var t, i, n, o = 0;
49                if (0 === e.length) return o;
50                for (t = 0, n = e.length; t < n; ++t) i = e.charCodeAt(t), o = (o << 5) - o + i, o |= 0;
51                return o
52            },
53            normaliseHex: function(e) {
54                return "#" == e[0] && (e = e.substr(1)), 3 == e.length && (e = e[0] + e[0] + e[1] + e[1] + e[2] + e[2]), e
55            },
56            getContrast: function(e) {
57                e = this.normaliseHex(e);
58                var t = parseInt(e.substr(0, 2), 16),
59                    i = parseInt(e.substr(2, 2), 16),
60                    n = parseInt(e.substr(4, 2), 16),
61                    o = (299 * t + 587 * i + 114 * n) / 1e3;
62                return o >= 128 ? "#000" : "#fff"
63            },
64            getLuminance: function(e) {
65                var t = parseInt(this.normaliseHex(e), 16),
66                    i = 38,
67                    n = (t >> 16) + i,
68                    o = (t >> 8 & 255) + i,
69                    s = (255 & t) + i,
70                    r = (16777216 + 65536 * (n < 255 ? n < 1 ? 0 : n : 255) + 256 * (o < 255 ? o < 1 ? 0 : o : 255) + (s < 255 ? s < 1 ? 0 : s : 255)).toString(16).slice(1);
71                return "#" + r
72            },
73            isMobile: function() {
74                return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
75            },
76            isPlainObject: function(e) {
77                return "object" == typeof e && null !== e && e.constructor == Object
78            }
79        };
80        e.status = {
81            deny: "deny",
82            allow: "allow",
83            dismiss: "dismiss"
84        }, e.transitionEnd = function() {
85            var e = document.createElement("div"),
86                t = {
87                    t: "transitionend",
88                    OT: "oTransitionEnd",
89                    msT: "MSTransitionEnd",
90                    MozT: "transitionend",
91                    WebkitT: "webkitTransitionEnd"
92                };
93            for (var i in t)
94                if (t.hasOwnProperty(i) && "undefined" != typeof e.style[i + "ransition"]) return t[i];
95            return ""
96        }(), e.hasTransition = !!e.transitionEnd;
97        var i = Object.keys(e.status).map(t.escapeRegExp);
98        e.customStyles = {}, e.Popup = function() {
99            function n() {
100                this.initialise.apply(this, arguments)
101            }
102
103            function o(e) {
104                this.openingTimeout = null, t.removeClass(e, "cc-invisible")
105            }
106
107            function s(t) {
108                t.style.display = "none", t.removeEventListener(e.transitionEnd, this.afterTransition), this.afterTransition = null
109            }
110
111            function r() {
112                var t = this.options.onInitialise.bind(this);
113                if (!window.navigator.cookieEnabled) return t(e.status.deny), !0;
114                if (window.CookiesOK || window.navigator.CookiesOK) return t(e.status.allow), !0;
115                var i = Object.keys(e.status),
116                    n = this.getStatus(),
117                    o = i.indexOf(n) >= 0;
118                return o && t(n), o
119            }
120
121            function a() {
122                var e = this.options.position.split("-"),
123                    t = [];
124                return e.forEach(function(e) {
125                    t.push("cc-" + e)
126                }), t
127            }
128
129            function c() {
130                var e = this.options,
131                    i = "top" == e.position || "bottom" == e.position ? "banner" : "floating";
132                t.isMobile() && (i = "floating");
133                var n = ["cc-" + i, "cc-type-" + e.type, "cc-theme-" + e.theme];
134                e["static"] && n.push("cc-static"), n.push.apply(n, a.call(this));
135                h.call(this, this.options.palette);
136                return this.customStyleSelector && n.push(this.customStyleSelector), n
137            }
138
139            function l() {
140                var e = {},
141                    i = this.options;
142                i.showLink || (i.elements.link = "", i.elements.messagelink = i.elements.message), Object.keys(i.elements).forEach(function(n) {
143                    e[n] = t.interpolateString(i.elements[n], function(e) {
144                        var t = i.content[e];
145                        return e && "string" == typeof t && t.length ? t : ""
146                    })
147                });
148                var n = i.compliance[i.type];
149                n || (n = i.compliance.info), e.compliance = t.interpolateString(n, function(t) {
150                    return e[t]
151                });
152                var o = i.layouts[i.layout];
153                return o || (o = i.layouts.basic), t.interpolateString(o, function(t) {
154                    return e[t]
155                })
156            }
157
158            function u(i) {
159                var n = this.options,
160                    o = document.createElement("div"),
161                    s = n.container && 1 === n.container.nodeType ? n.container : document.body;
162                o.innerHTML = i;
163                var r = o.children[0];
164                return r.style.display = "none", t.hasClass(r, "cc-window") && e.hasTransition && t.addClass(r, "cc-invisible"), this.onButtonClick = p.bind(this), r.addEventListener("click", this.onButtonClick), n.autoAttach && (s.firstChild ? s.insertBefore(r, s.firstChild) : s.appendChild(r)), r
165            }
166
167            function p(n) {
168                var o = n.target;
169                if (t.hasClass(o, "cc-btn")) {
170                    var s = o.className.match(new RegExp("\\bcc-(" + i.join("|") + ")\\b")),
171                        r = s && s[1] || !1;
172                    r && (this.setStatus(r), this.close(!0))
173                }
174                t.hasClass(o, "cc-close") && (this.setStatus(e.status.dismiss), this.close(!0)), t.hasClass(o, "cc-revoke") && this.revokeChoice()
175            }
176
177            function h(e) {
178                var i = t.hash(JSON.stringify(e)),
179                    n = "cc-color-override-" + i,
180                    o = t.isPlainObject(e);
181                return this.customStyleSelector = o ? n : null, o && d(i, e, "." + n), o
182            }
183
184            function d(i, n, o) {
185                if (e.customStyles[i]) return void++e.customStyles[i].references;
186                var s = {},
187                    r = n.popup,
188                    a = n.button,
189                    c = n.highlight;
190                r && (r.text = r.text ? r.text : t.getContrast(r.background), r.link = r.link ? r.link : r.text, s[o + ".cc-window"] = ["color: " + r.text, "background-color: " + r.background], s[o + ".cc-revoke"] = ["color: " + r.text, "background-color: " + r.background], s[o + " .cc-link," + o + " .cc-link:active," + o + " .cc-link:visited"] = ["color: " + r.link], a && (a.text = a.text ? a.text : t.getContrast(a.background), a.border = a.border ? a.border : "transparent", s[o + " .cc-btn"] = ["color: " + a.text, "border-color: " + a.border, "background-color: " + a.background], "transparent" != a.background && (s[o + " .cc-btn:hover, " + o + " .cc-btn:focus"] = ["background-color: " + v(a.background)]), c ? (c.text = c.text ? c.text : t.getContrast(c.background), c.border = c.border ? c.border : "transparent", s[o + " .cc-highlight .cc-btn:first-child"] = ["color: " + c.text, "border-color: " + c.border, "background-color: " + c.background]) : s[o + " .cc-highlight .cc-btn:first-child"] = ["color: " + r.text]));
191                var l = document.createElement("style");
192                document.head.appendChild(l), e.customStyles[i] = {
193                    references: 1,
194                    element: l.sheet
195                };
196                var u = -1;
197                for (var p in s) s.hasOwnProperty(p) && l.sheet.insertRule(p + "{" + s[p].join(";") + "}", ++u)
198            }
199
200            function v(e) {
201                return e = t.normaliseHex(e), "000000" == e ? "#222" : t.getLuminance(e)
202            }
203
204            function f(i) {
205                if (t.isPlainObject(i)) {
206                    var n = t.hash(JSON.stringify(i)),
207                        o = e.customStyles[n];
208                    if (o && !--o.references) {
209                        var s = o.element.ownerNode;
210                        s && s.parentNode && s.parentNode.removeChild(s), e.customStyles[n] = null
211                    }
212                }
213            }
214
215            function m(e, t) {
216                for (var i = 0, n = e.length; i < n; ++i) {
217                    var o = e[i];
218                    if (o instanceof RegExp && o.test(t) || "string" == typeof o && o.length && o === t) return !0
219                }
220                return !1
221            }
222
223            function b() {
224                var t = this.setStatus.bind(this),
225                    i = this.options.dismissOnTimeout;
226                "number" == typeof i && i >
226= 0 && (this.dismissTimeout = window.setTimeout(function() {
227                    t(e.status.dismiss)
228                }, Math.floor(i)));
229                var n = this.options.dismissOnScroll;
230                if ("number" == typeof n && n >= 0) {
231                    var o = function(i) {
232                        window.pageYOffset > Math.floor(n) && (t(e.status.dismiss), window.removeEventListener("scroll", o), this.onWindowScroll = null)
233                    };
234                    this.onWindowScroll = o, window.addEventListener("scroll", o)
235                }
236            }
237
238            function y() {
239                if ("info" != this.options.type && (this.options.revokable = !0), t.isMobile() && (this.options.animateRevokable = !1), this.options.revokable) {
240                    var e = a.call(this);
241                    this.options.animateRevokable && e.push("cc-animate"), this.customStyleSelector && e.push(this.customStyleSelector);
242                    var i = this.options.revokeBtn.replace("{{classes}}", e.join(" "));
243                    this.revokeBtn = u.call(this, i);
244                    var n = this.revokeBtn;
245                    if (this.options.animateRevokable) {
246                        var o = t.throttle(function(e) {
247                            var i = !1,
248                                o = 20,
249                                s = window.innerHeight - 20;
250                            t.hasClass(n, "cc-top") && e.clientY < o && (i = !0), t.hasClass(n, "cc-bottom") && e.clientY > s && (i = !0), i ? t.hasClass(n, "cc-active") || t.addClass(n, "cc-active") : t.hasClass(n, "cc-active") && t.removeClass(n, "cc-active")
251                        }, 200);
252                        this.onMouseMove = o, window.addEventListener("mousemove", o)
253                    }
254                }
255            }
256            var g = {
257                enabled: !0,
258                container: null,
259                cookie: {
260                    name: "cookieconsent_status",
261                    path: "/",
262                    domain: "",
263                    expiryDays: 365
264                },
265                onPopupOpen: function() {},
266                onPopupClose: function() {},
267                onInitialise: function(e) {},
268                onStatusChange: function(e, t) {},
269                onRevokeChoice: function() {},
270                content: {
271                    header: "Cookies used on the website!",
272                    message: "This website uses cookies to ensure you get the best experience on our website.",
273                    dismiss: "Got it!",
274                    allow: "Allow cookies",
275                    deny: "Decline",
276                    link: "Learn more",
277                    href: "#",
278                    close: "&#x274c;"
279                },
280                elements: {
281                    header: '<span class="cc-header">{{header}}</span>&nbsp;',
282                    message: '<span id="cookieconsent:desc" class="cc-message">{{message}}</span>',
283                    messagelink: '<span id="cookieconsent:desc" class="cc-message">{{message}} <a aria-label="learn more about cookies" role=button tabindex="0" onclick="showGdpr();return false;" class="cc-link" href="{{href}}" target="_blank">{{link}}</a></span>',
284                    dismiss: '<a aria-label="dismiss cookie message" role=button tabindex="0" class="cc-btn cc-dismiss" onclick="saveClose();">{{dismiss}}</a>',
285                    allow: '<a aria-label="allow cookies" role=button tabindex="0"  class="cc-btn cc-allow">{{allow}}</a>',
286                    deny: '<a aria-label="deny cookies" role=button tabindex="0" class="cc-btn" style="font-weight:normal;flex:none;margin-left:45px;" onclick="showCookieSettings();return false;">{{deny}}</a>',
287                    link: '<a aria-label="learn more about cookies" role=button tabindex="0" class="cc-link" href="{{href}}" target="_blank">{{link}}</a>',
288                    close: '<span aria-label="dismiss cookie message" role=button tabindex="0" class="cc-close">{{close}}</span>'
289                },
290                window: '<div role="dialog" aria-live="polite" aria-label="cookieconsent" aria-describedby="cookieconsent:desc" class="cc-window {{classes}}"><!--googleoff: all-->{{children}}<!--googleon: all--></div>',
291                revokeBtn: '<div class="cc-revoke {{classes}}">Бисквитки</div>',
292                compliance: {
293                    info: '<div class="cc-compliance">{{dismiss}}{{allow}}</div>',
294                    "opt-in": '<div class="cc-compliance cc-highlight">{{deny}}{{allow}}</div>',
295                    "opt-out": '<div class="cc-compliance cc-highlight">{{deny}}{{dismiss}}</div>'
296                },
297                type: "info",
298                layouts: {
299                    basic: "{{messagelink}}{{compliance}}",
300                    "basic-close": "{{messagelink}}{{compliance}}{{close}}",
301                    "basic-header": "{{header}}{{message}}{{link}}{{compliance}}"
302                },
303                layout: "basic",
304                position: "bottom",
305                theme: "block",
306                "static": !1,
307                palette: null,
308                revokable: !1,
309                animateRevokable: !0,
310                showLink: !0,
311                dismissOnScroll: !1,
312                dismissOnTimeout: !1,
313                autoOpen: !0,
314                autoAttach: !0,
315                whitelistPage: [],
316                blacklistPage: [],
317                overrideHTML: null
318            };
319            return n.prototype.initialise = function(e) {
320                this.options && this.destroy(), t.deepExtend(this.options = {}, g), t.isPlainObject(e) && t.deepExtend(this.options, e), r.call(this) && (this.options.enabled = !1), m(this.options.blacklistPage, location.pathname) && (this.options.enabled = !1), m(this.options.whitelistPage, location.pathname) && (this.options.enabled = !0);
321                var i = this.options.window.replace("{{classes}}
321", c.call(this).join(" ")).replace("{{children}}", l.call(this)),
322                    n = this.options.overrideHTML;
323                if ("string" == typeof n && n.length && (i = n), this.options["static"]) {
324                    var o = u.call(this, '<div class="cc-grower">' + i + "</div>");
325                    o.style.display = "", this.element = o.firstChild, this.element.style.display = "none", t.addClass(this.element, "cc-invisible")
326                } else this.element = u.call(this, i);
327                b.call(this), y.call(this), this.options.autoOpen && this.autoOpen()
328            }, n.prototype.destroy = function() {
329                this.onButtonClick && this.element && (this.element.removeEventListener("click", this.onButtonClick), this.onButtonClick = null), this.dismissTimeout && (clearTimeout(this.dismissTimeout), this.dismissTimeout = null), this.onWindowScroll && (window.removeEventListener("scroll", this.onWindowScroll), this.onWindowScroll = null), this.onMouseMove && (window.removeEventListener("mousemove", this.onMouseMove), this.onMouseMove = null), this.element && this.element.parentNode && this.element.parentNode.removeChild(this.element), this.element = null, this.revokeBtn && this.revokeBtn.parentNode && this.revokeBtn.parentNode.removeChild(this.revokeBtn), this.revokeBtn = null, f(this.options.palette), this.options = null
330            }, n.prototype.open = function(t) {
331                if (this.element) return this.isOpen() || (e.hasTransition ? this.fadeIn() : this.element.style.display = "", this.options.revokable && this.toggleRevokeButton(), this.options.onPopupOpen.call(this)), this
332            }, n.prototype.close = function(t) {
333                if (this.element) return this.isOpen() && (e.hasTransition ? this.fadeOut() : this.element.style.display = "none", t && this.options.revokable && this.toggleRevokeButton(!0), this.options.onPopupClose.call(this)), this
334            }, n.prototype.fadeIn = function() {
335                var i = this.element;
336                if (e.hasTransition && i && (this.afterTransition && s.call(this, i), t.hasClass(i, "cc-invisible"))) {
337                    if (i.style.display = "", this.options["static"]) {
338                        var n = this.element.clientHeight;
339                        this.element.parentNode.style.maxHeight = n + "px"
340                    }
341                    var r = 20;
342                    this.openingTimeout = setTimeout(o.bind(this, i), r)
343                }
344            }, n.prototype.fadeOut = function() {
345                var i = this.element;
346                e.hasTransition && i && (this.openingTimeout && (clearTimeout(this.openingTimeout), o.bind(this, i)), t.hasClass(i, "cc-invisible") || (this.options["static"] && (this.element.parentNode.style.maxHeight = ""), this.afterTransition = s.bind(this, i), i.addEventListener(e.transitionEnd, this.afterTransition), t.addClass(i, "cc-invisible")))
347            }, n.prototype.isOpen = function() {
348                return this.element && "" == this.element.style.display && (!e.hasTransition || !t.hasClass(this.element, "cc-invisible"))
349            }, n.prototype.toggleRevokeButton = function(e) {
350                this.revokeBtn && (this.revokeBtn.style.display = e ? "" : "none")
351            }, n.prototype.revokeChoice = function(e) {
352                this.options.enabled = !0, this.clearStatus(), this.options.onRevokeChoice.call(this), e || this.autoOpen()
353            }, n.prototype.hasAnswered = function(t) {
vendor: 4,424 bytes, lines 354-435
354                return typeof this.getStatus() !== typeof undefined && this.getStatus() != 'undefined'
355            }, n.prototype.hasConsented = function(t) {
356                var i = this.getStatus();
357                return i == e.status.allow || i == e.status.dismiss
358            }, n.prototype.autoOpen = function(e) {
359                !this.hasAnswered() && this.options.enabled && this.open()
360            }, n.prototype.setStatus = function(i) {
361                var n = this.options.cookie,
362                    o = t.getCookie(n.name),
363                    s = Object.keys(e.status).indexOf(o) >= 0;
364                Object.keys(e.status).indexOf(i) >= 0 ? (t.setCookie(n.name, i, n.expiryDays, n.domain, n.path), this.options.onStatusChange.call(this, i, s)) : this.clearStatus()
365            }, n.prototype.getStatus = function() {
366                return t.getCookie(this.options.cookie.name)
367            }, n.prototype.clearStatus = function() {
368                var e = this.options.cookie;
369                t.setCookie(e.name, "", -1, e.domain, e.path)
370            }, n
371        }(), e.Location = function() {
372            function e(e) {
373                t.deepExtend(this.options = {}, s), t.isPlainObject(e) && t.deepExtend(this.options, e), this.currentServiceIndex = -1
374            }
375
376            function i(e, t, i) {
377                var n, o = document.createElement("script");
378                o.type = "text/" + (e.type || "javascript"), o.src = e.src || e, o.async = !1, o.onreadystatechange = o.onload = function() {
379                    var e = o.readyState;
380                    clearTimeout(n), t.done || e && !/loaded|complete/.test(e) || (t.done = !0, t(), o.onreadystatechange = o.onload = null)
381                }, document.body.appendChild(o), n = setTimeout(function() {
382                    t.done = !0, t(), o.onreadystatechange = o.onload = null
383                }, i)
384            }
385
386            function n(e, t, i, n, o) {
387                var s = new(window.XMLHttpRequest || window.ActiveXObject)("MSXML2.XMLHTTP.3.0");
388                if (s.open(n ? "POST" : "GET", e, 1), s.setRequestHeader("X-Requested-With", "XMLHttpRequest"), s.setRequestHeader("Content-type", "application/x-www-form-urlencoded"), Array.isArray(o))
389                    for (var r = 0, a = o.length; r < a; ++r) {
390                        var c = o[r].split(":", 2);
391                        s.setRequestHeader(c[0].replace(/^\s+|\s+$/g, ""), c[1].replace(/^\s+|\s+$/g, ""))
392                    }
393                "function" == typeof t && (s.onreadystatechange = function() {
394                    s.readyState > 3 && t(s)
395                }), s.send(n)
396            }
397
398            function o(e) {
399                return new Error("Error [" + (e.code || "UNKNOWN") + "]: " + e.error)
400            }
401            var s = {
402                timeout: 5e3,
403                services: ["freegeoip", "ipinfo", "maxmind"],
404                serviceDefinitions: {
405                    freegeoip: function() {
406                        return {
407                            url: "//freegeoip.net/json/?callback={callback}",
408                            isScript: !0,
409                            callback: function(e, t) {
410                                try {
411                                    var i = JSON.parse(t);
412                                    return i.error ? o(i) : {
413                                        code: i.country_code
414                                    }
415                                } catch (n) {
416                                    return o({
417                                        error: "Invalid response (" + n + ")"
418                                    })
419                                }
420                            }
421                        }
422                    },
423                    ipinfo: function() {
424                        return {
425                            url: "//ipinfo.io",
426                            headers: ["Accept: application/json"],
427                            callback: function(e, t) {
428                                try {
429                                    var i = JSON.parse(t);
430                                    return i.error ? o(i) : {
431                                        code: i.country
432                                    }
433                                } catch (n) {
434                                    return o({
435                                        error: "Invalid response 
435(" + n + ")"
436                                    })
437                                }
438                            }
439                        }
440                    },
441                    ipinfodb: function(e) {
442                        return {
443                            url: "//api.ipinfodb.com/v3/ip-country/?key={api_key}&format=json&callback={callback}",
444                            isScript: !0,
445                            callback: function(e, t) {
446                                try {
447                                    var i = JSON.parse(t);
448                                    return "ERROR" == i.statusCode ? o({
449                                        error: i.statusMessage
450                                    }) : {
451                                        code: i.countryCode
452                                    }
453                                } catch (n) {
454                                    return o({
455                                        error: "Invalid response (" + n + ")"
456                                    })
457                                }
458                            }
459                        }
460                    },
461                    maxmind: function() {
462                        return {
463                            url: "//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js",
464                            isScript: !0,
465                            callback: function(e) {
466                                return window.geoip2 ? void geoip2.country(function(t) {
467                                    e({
468                                        code: t.country.iso_code
469                                    })
470                                }, function(t) {
471                                    e(o(t))
472                                }) : void e(new Error("Unexpected response format. The downloaded script should have exported `geoip2` to the global scope"))
473                            }
474                        }
475                    }
476                }
477            };
478            return e.prototype.getNextService = function() {
479                var e;
480                do e = this.getServiceByIdx(++this.currentServiceIndex); while (!e);
481                return e
482            }, e.prototype.getServiceByIdx = function(e) {
483                var i = this.options.services[e];
484                if ("function" == typeof i) {
485                    var n = i();
486                    return n.name && t.deepExtend(n, this.options.serviceDefinitions[n.name](n)), n
487                }
488                return "string" == typeof i ? this.options.serviceDefinitions[i]() : t.isPlainObject(i) ? this.options.serviceDefinitions[i.name](i) : null
489            }, e.prototype.locate = function(e, t) {
490                var i = this.getNextService();
491                return i ? (this.callbackComplete = e, this.callbackError = t, void this.runService(i, this.runNextServiceOnError.bind(this))) : void t(new Error("No services to run"))
492            }, e.prototype.setupUrl = function(e) {
493                var t = this.getCurrentServiceOpts();
494                return e.url.replace(/\{(.*?)\}/g, function(i, n) {
495                    if ("callback" === n) {
496                        var o = "callback" + Date.now();
497                        return window[o] = function(t) {
498                            e.__JSONP_DATA = JSON.stringify(t)
499                        }, o
500                    }
501                    if (n in t.interpolateUrl) return t.interpolateUrl[n]
502                })
503            }, e.prototype.runService = function(e, t) {
504                var o = this;
505                if (e && e.url && e.callback) {
506                    var s = e.isScript ? i : n,
507                        r = this.setupUrl(e);
508                    s(r, function(i) {
509                        var n = i ? i.responseText : "";
510                        e.__JSONP_DATA && (n = e.__JSONP_DATA, delete e.__JSONP_DATA), o.runServiceCallback.call(o, t, e, n)
511                    }, this.options.timeout, e.data, e.headers)
512                }
513            }, e.prototype.runServiceCallback = function(e, t, i) {
514                var n = this,
515                    o = function(t) {
516                        s || n.onServiceResult.call(n, e, t)
517                    },
518                    s = t.callback(o, i);
519                s && this.onServiceResult.call(this, e, s)
520            }, e.prototype.onServiceResult = function(e, t) {
521                t instanceof Error || t && t.error ? e.call(this, t, null) : e.call(this, null, t)
522            }, e.prototype.runNextServiceOnError = function(e, t) {
523                if (e) {
524                    this.logError(e);
525                    var i = this.getNextService();
526                    i ? this.runService(i, this.runNextServiceOnError.bind(this)) : this.completeService.call(this, this.callbackError, new Error("All services failed"))
527                } else this.completeService.call(this, this.callbackComplete, t)
528            }, e.prototype.getCurrentServiceOpts = function() {
529                var e = this.options.services[this.currentServiceIndex];
530                return "string" == typeof e ? {
531                    name: e
532                } : "function" == typeof e ? e() : t.isPlainObject(e) ? e : {}
533            }, e.prototype.completeService = function(e, t) {
534                this.currentServiceIndex = -1, e && e(t)
535            }, e.prototype.logError = function(e) {
536                var t = this.currentServiceIndex,
537                    i = this.getServiceByIdx(t);
538                console.error("The service[" + t + "] (" + i.url + ") responded with the following error", e)
539            }, e
540        }(), e.Law = function() {
541            function e(e) {
542                this.initialise.apply(this, arguments)
543            }
544            var i = {
545                regionalLaw: !0,
546                hasLaw: ["AT", "BE", "BG", "HR", "CZ", "CY", "DK", "EE", "FI", "FR", "DE", "EL", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "SK", "SI", "ES", "SE", "GB", "UK"],
547                revokable: ["HR", "CY", "DK", "EE", "FR", "DE", "LV", "LT", "NL", "PT", "ES"],
548                explicitAction: ["HR", "IT", "ES"]
549            };
550            return e.prototype.initialise = function(e) {
551                t.deepExtend(this.options = {}, i), t.isPlainObject(e) && t.deepExtend(this.options, e)
552            }, e.prototype.get = function(e) {
553                var t = this.options;
554                return {
555                    hasLaw: t.hasLaw.indexOf(e) >= 0,
556                    revokable: t.revokable.indexOf(e) >= 0,
557                    explicitAction: t.explicitAction.indexOf(e) >= 0
558                }
559            }, e.prototype.applyLaw = function(e, t) {
560                var i = this.get(t);
561                return i.hasLaw || (e.enabled = !1), this.options.regionalLaw && (i.revokable && (e.revokable = !0), i.explicitAction && (e.dismissOnScroll = !1, e.dismissOnTimeout = !1)), e
562            }, e
563        }(), e.initialise = function(t, i, n) {
564            var o = new e.Law(t.law);
565            i || (i = function() {}), n || (n = function() {}), e.getCountryCode(t, function(n) {
566                delete t.law, delete t.location, n.code && (t = o.applyLaw(t, n.code)), i(new e.Popup(t))
567            }, function(i) {
568                delete t.law, delete t.location, n(i, new e.Popup(t))
569            })
570        }, e.getCountryCode = function(t, i, n) {
571            if (t.law && t.law.countryCode) return void i({
572                code: t.law.countryCode
573            });
574            if (t.location) {
575                var o = new e.Location(t.location);
576                return void o.locate(function(e) {
577                    i(e || {})
578                }, n)
579            }
580            i({})
581        }, e.utils = t, e.hasInitialised = !0, window.cookieconsent = e
582    }
583}(window.cookieconsent || {});
584// ========================= Social Login ============================================
585function fb_login(){
586	if(!($('a.already_in').length > 0) && !($('.profile-header').length > 0)){
587		$('div.half-buttons').after('<div class="login-error" style="margin-top:10px;margin-bottom:20px;color:#af0000;">Моля изчакайте...</div>');
588		FB.login(function(response) {
589			if (response.authResponse) {
590				access_token = response.authResponse.accessToken;
591				user_id = response.authResponse.userID;
592				FB.api('/me?fields=id, name, picture, email', function(response) {
593					user_email = response.email;   
594					var picture=response.picture;
595					$.ajax({
596						type: "POST",
597						url: location.protocol+'//'+location.hostname+'/login',
598						data: {social_login:1,ajax:1,user_id:response.id,name:response.name,picture:response.picture.data.url,email:response.email,newsletter:$('#reg_check').val(),agreed:$('#tos_check').is(":checked")?1:0},
599						success: function(data){
600							data=JSON.parse(data);
601							if(data.hasError === false){
602								$('div.login-error').remove(); 
603								location.reload();
604							}else{
605								$('div.login-error').html(data.errors[0]);
606								if(data.isSocial*1 > 0){
607									$('#reg_popup').trigger('click');
608								}
609							}
610
611						}
612					});				
613				});
614			}
615		}, {
616			scope: 'public_profile,email'
617		});
618	}
619}
620function showPopup(obj){
621	$(obj).addClass('active');
622	$('div.pop_up.scroller_div').fadeIn();
623	$('html, body').css({"overflow":"hidden","height":"100%"});
624	$('div.pop_up.scroller_div').css('top',$(document).scrollTop());
625	$('.dark_wrapper').show();
626}
627function showGdpr(obj){
628	$('div.privacy_notice').addClass('active');
629	$('div.pop_up.scroller_div').fadeIn();
630	$('html, body').css({"overflow":"hidden","height":"100%"});
631	$('div.pop_up.scroller_div').css('top',$(document).scrollTop());
632	$('.dark_wrapper').show();
633}
634function showCookieSettings(obj){
635	$('div.cookies_notice').addClass('active');
636	$('html, body').css({"overflow":"hidden","height":"100%"});
637	$('div.cc-window').hide();
638	$('.dark_wrapper').show();
639}
640(function() {
641    var e = document.createElement('script');
642    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
643    e.async = true;
644    //document.getElementById('fb-root').appendChild(e);
645}());
646
647
648
649
650function setCookie(cname, cvalue, exdays) {
651    var d = new Date();
652    d.setTime(d.getTime() + (exdays*24*60*60*1000));
653    var expires = "expires="+ d.toUTCString();
654    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
655}
656function getCookie(cname) {
657    var name = cname + "=";
658    var decodedCookie = decodeURIComponent(document.cookie);
659    var ca = decodedCookie.split(';');
660    for(var i = 0; i <ca.length; i++) {
661        var c = ca[i];
662        while (c.charAt(0) == ' ') {
663            c = c.substring(1);
664        }
665        if (c.indexOf(name) == 0) {
666            return c.substring(name.length, c.length);
667        }
668    }
669    return "";
670}
671function saveClose(){
672	$('body').append('<img style="position:absolute;width:1px;height:1px;opacity:0;bottom:0;left:0;" src="https://photosynthesis.bg/?addconcent=1" />');
673}
674// ========================= Compare Functions ============================================
675function addToCompare(productId)
676{
677	var totalValueNow = parseInt($('.bt_compare').next('.compare_product_count').val());
678	var action, totalVal;
679	if ($.inArray(parseInt(productId),comparedProductsIds) === -1)
680		action = 'add';
681	else
682		action = 'remove';
683	
684	$.ajax({
685		url: baseUri + '?controller=products-comparison&ajax=1&action=' + action + '&id_product=' + productId,
686		async: true,
687		cache: false,
688		success: function(data) {
689			if (action === 'add' && comparedProductsIds.length < comparator_max_item) {
690				comparedProductsIds.push(parseInt(productId)),
691				compareButtonsStatusRefresh(),
692				totalVal = totalValueNow +1,
693				$('.bt_compare').next('.compare_product_count').val(totalVal),
694				totalValue(totalVal);
695			}
696			else if (action === 'remove') {
697				comparedProductsIds.splice($.inArray(parseInt(productId), comparedProductsIds), 1),
698				compareButtonsStatusRefresh(),
699				totalVal = totalValueNow -1,
700				$('.bt_compare').next('.compare_product_count').val(totalVal),
701				totalValue(totalVal);
702			}
703			else
704			{
705				if (!!$.prototype.fancybox)
706					$.fancybox.open([{
707						type: 'inline',
708						autoScale: true,
709						minHeight: 30,
710						content: '<p class="fancybox-error">' + max_item + '</p>'
711					}], {
712						padding: 0
713					});
714				else
715					alert(max_item);
716			}
717			if(action === 'add'){
718				$($($('input[data-id-product="'+productId+'"]').parent().parent()).next()).addClass('isChecked');
719			}else{
720				$($($('input[data-id-product="'+productId+'"]').parent().parent()).next()).removeClass('isChecked');
721			}
722			
723			
724			if(action == 'add'){
725				$('div.item.empty').each(function(){
726					$(this).removeClass('empty'); 
727					$(this).attr('id','compare_'+productId); 
728					$(this).html('<a class="remove_compare" data-id-product="'+productId+'" href="#"></a><div class="img"><img src="'+$('#product_'+productId).find('img.product_image').attr('src')+'" /></div> <div class="name"><a href="'+$('#product_'+productId).find('a.product_link').attr('href')+'" class="nameLink underline-on-hover fourteen c5">'+$('#product_'+productId).find('a.product_link').html()+'</a></div> ');
729					return false; 
730				});
731				
732				if($('div.empty').length < 4 && !$('div.sticky_compare').is(':visible')){
733					$('div.sticky_compare').slideToggle(500);
734				}
735			}else{
736				$('#compare_'+productId).html('');
737				$('#compare_'+productId).addClass('empty'); 
738				
739				if($('div.item.empty').length > 3 && $('div.sticky_compare').is(':visible')){
740					$('div.sticky_compare').slideToggle(500);
741				}
742			}
743			totalCompareButtons();
744		},
745		error: function(){}
746	});
747}
748
749function reloadProductComparison()
750{
751	$(document).on('click', 'a.cmp_remove', function(e){
752		e.preventDefault();
753		var idProduct = parseInt($(this).data('id-product'));
754		$.ajax({
755			url: baseUri + '?controller=products-comparison&ajax=1&action=remove&id_product=' + idProduct,
756			async: false,
757			cache: false
758		});
759		$('td.product-' + idProduct).fadeOut(600);
760
761		var compare_product_list = get('compare_product_list');
762		var bak = compare_product_list;
763		var new_compare_product_list = [];
764		compare_product_list = decodeURIComponent(compare_product_list).split('|');
765		for (var i in compare_product_list)
766			if (parseInt(compare_product_list[i]) != idProduct)
767				new_compare_product_list.push(compare_product_list[i]);
768		if (new_compare_product_list.length)
769			window.location.search = window.location.search.replace(bak, new_compare_product_list.join(encodeURIComponent('|')));
770	});
771};
772
773function compareButtonsStatusRefresh()
774{
775	return false;
776	$('.add_to_compare').each(function() {
777		if ($.inArray(parseInt($(this).data('id-product')), comparedProductsIds) !== -1){
778			$(this).addClass('checked');
779			$($(this).next()).addClass('isChecked');
780		}else{
781			$(this).removeClass('checked');
782			
783		}
784	});
785}
786
787function totalCompareButtons()
788{
789	if($('form.compare-form div.empty').length > 2){
790		$('.bt_compare').addClass('disabled').attr("disabled",true);
791	}else{
792		$('.bt_compare').removeClass('disabled').attr("disabled",false);
793	}
794}
795
796function totalValue(value)
797{
798	$('.bt_compare').find('.total-compare-val').html(value);
799}
800
801function get(name)
802{
803	var regexS = "[\\?&]" + name + "=([^&#]*)";
804	var regex = new RegExp(regexS);
805	var results = regex.exec(window.location.search);
806
807	if (results == null)
808		return "";
809	else
810		return results[1];
811}
812function manageOrderAddresses(){
813	$('#inv_load_in').on('click', function(e){
814        e.preventDefault();
815		$("html, body").animate({ scrollTop: 0 },0);
816		$('.overlay_2').addClass('active');
817		$('div.popup-header h3.address').hide();
818		$('div.popup-header h3.invoice').show();
819		$('#address_form').load($('a.invoice_data').attr('href')+' #add_address',function(){
820			$('.popup-address').addClass('active');
821			selectDropdown($('#inv_id_country'));
822			$(this).addClass('active');
823			$('.overlay_2').addClass('active').css('z-index', '9999');
824			$('#add_address').submit(function(e){
825				$.ajax({
826					type: "POST",
827					url: $('#add_address').attr('action')+'?ajax=1',
828					data: $('#add_address').serialize(),
829					success: function(data){
830						if(data){
831							data=JSON.parse(data);
832							var errors = $.map(data.errors, function(el) { return el });
833						}else{
834							var errors=new Array();
835						}
836						if(errors.length > 0){
837							$('div.address_errors').html('');
838							for(var i=0;i<errors.length;i++){
839								$('div.address_errors').html($('div.address_errors').html()+'<br />'+errors[i]);
840							}
841						}else{
842							$('#inv_load_in').load(window.location.href+' #inv_load_of',function(){
843								manageOrderAddresses();
844							});
845							$('.overlay_2').removeClass('active');
846							$('.popup').removeClass('active');
847						}
848					}
849				});
850				 e.preventDefault();
851			});
852		});
853	});
854    $('a.show_address_popup').on('click', function(e){
855        e.preventDefault();
856		var invoice='';
857		if($(this).hasClass('invoice_data')){
858			invoice='inv_';
859		}
860		$("html, body").animate({ scrollTop: 0 },0);
861		$('.overlay_2').addClass('active');
862		$('div.popup-header h3.invoice').hide();
863		$('div.popup-header h3.address').show();
864		$('#address_form').load($(this).attr('href')+' #add_address',function(){
865			if($('input[name="phone_mobile"],input[name="inv_phone"]').length > 0){
866				$('input[name="phone_mobile"],input[name="inv_phone"]').keyup(function(){
867					$(this).val($(this).val().replace(/[^0-9]/g,'')); 
868				});
869			}
870			$('.popup-address').addClass('active');
871			selectDropdown($('#'+invoice+'id_country'));
872			$(this).addClass('active');
873			$('#city').chosen({width:'100%',height:38});
874			$('.overlay_2').addClass('active').css('z-index', '9999');
875			$('#add_address').submit(function(e){
876				$.ajax({
877					type: "POST",
878					url: $('#add_address').attr('action')+'?ajax=1',
879					data: $('#add_address').serialize(),
880					success: function(data){
881						if(data){
882							data=JSON.parse(data);
883							var errors = $.map(data.errors, function(el) { return el });
884						}else{
885							var errors=new Array();
886						}
887						if(errors.length > 0){
888							$('div.address_errors').html('');
889							for(var i=0;i<errors.length;i++){
890								$('div.address_errors').html($('div.address_errors').html()+'<br />'+errors[i]);
891							}
892						}else{
893							$('#'+invoice+'load_in').load(window.location.href+' #'+invoice+'load_of',function(){
894								manageOrderAddresses();
895							});
896							$('.overlay_2').removeClass('active');
897							$('.popup').removeClass('active');
898						}
899					}
900				});
901				 e.preventDefault();
902			});
903		});
904    });
905}
906function loadToOffice(){
907	$('#load_in_carrier').load(window.location.href.replace(/#.*$/,'') + '&city_id='+$('#city_id').val()+'&carrier_id='+$('#carrier_id').val()+' #load_of_carrier',function(){
908		//selectDropdown($('#city_id'));
909		$('#city_id').chosen({width:'100%',height:38});
910		if($('#office_id').length > 0){
911			$('#office_id').chosen({width:'100%',height:38});
912		}
913		
914		$('#city_id').on('change', function() {
915			loadToOffice();
916		});
917		selectDropdown($('#carrier_id'));
918		selectDropdown($('#office_id'));
919	});
920}
921function selectDropdown(obj){
922    $(obj).each(function() {
923		if($(this).attr('id') == 'city_id'){
924			$('#city_id').chosen({width:'100%',height:38});
925			$('#city_id').on('change', function() {
926				loadToOffice();
927			});
928			return true;
929		}
930		if($(this).attr('id') == 'office_id'){
931			$('#office_id').chosen({width:'100%',height:38});
932			return true;
933		}
934		if(($('form.return-form').length > 0 || $('form.reclamation-form').length > 0) && ($(this).attr('id') == 'city' || $(this).attr('id') == 'id_manufacturer') || ($('form#add_address').length > 0 && $(this).attr('id') == 'city')){
935			if($('#city').length > 0){
936				$('#city').chosen({width:'100%',height:38});
937			}
938			if($('#id_manufacturer').length > 0){
939				$('#id_manufacturer').chosen({width:'100%',height:38});
940			}
941			return true;
942		}
943        var $this = $(this),
944            numberOfOptions = $(this).children('option').length;
945        $this.addClass('s-hidden');
946        $this.wrap('<div class="select"></div>');
947        $this.after('<div class="styledSelect"></div>');
948        var $styledSelect = $this.next('div.styledSelect');
949        $styledSelect.text($this.children('option').eq(0).text());
950        var $list = $('<ul />', {
951            'class': 'options'
952        }).insertAfter($styledSelect);
953        for (var i = 0; i < numberOfOptions; i++) {
954            $('<li />', {
955                text: $this.children('option').eq(i).text(),
956                rel: $this.children('option').eq(i).val()
957            }).appendTo($list);
958			var attr = $this.children('option').eq(i).attr('selected');
959			if(typeof attr !== typeof undefined && attr !== false){
960				$styledSelect.text($this.children('option').eq(i).text());
961			}
962        }
963        var $listItems = $list.children('li');
964        $styledSelect.click(function(e) {
965            e.stopPropagation();
966            $('div.styledSelect.active').each(function() {
967                $(this).removeClass('active').next('ul.options').hide();
968            });
969            $(this).toggleClass('active').next('ul.options').toggle();
970
971			$('#mass_actions ul.options').find('li').click(function(){
972				$('select[name=mass_select]').val($(this).attr('rel'));
973				$('input.grouping').each(function(){
974					if($(this).is(':checked')){
975						$('#prod_'+$(this).val()).trigger('click');
976						$($(this).parent().parent().parent().parent().parent()).remove();
977					}
978				});
979			});
980        });
981		selectDropdown($('#door_office_id'));
982        $listItems.click(function(e) {
983            e.stopPropagation();
984            $styledSelect.text($(this).text()).removeClass('active');
985            $this.val($(this).attr('rel'));
986            $list.hide();
987			if($($($list).parent().parent()).attr('id') == 'setCurrency'){
988				$($($list).parent().parent()).submit();
989			}
990			if($this.attr('id') == 'carrier_id'){
991				loadToOffice();
992			}
993			if($this.attr('id') == 'city_id_2'){
994				$('#carrier_offices').find('li').hide();
995				var cityid=$(this).attr('rel');
996				$('#carrier_offices').find('li').each(function(){
997					if($(this).attr('rel').replace(/\:.*$/,'')*1 == cityid*1){
998						$(this).show();
999					}
1000				});
1001			}
1002			if($this.attr('id') == 'office_id'){
1003				if($('#address_kzp').length > 0){
1004					$('#address_kzp').val($(this).html());
1005				}
1006			}
1007			var discounts=($('#total_discount_codes').length > 0?parseInt($('#total_discount_codes b').html().replace(/,/,'.')):0);
1008			var the_total_price=parseInt($('#total_products').val());
1009			//if($this.attr('id') == 'carrier_id' && $this.val() == 1 && the_total_price < $('#free_shipping').val() && $('.change_delivery').find('b').html() != '8,00'){
1010			if($this.attr('id') == 'carrier_id' && $this.val() == 1 && $('.change_delivery').find('b').html() != ''+$('#econt_shipping').val()+',00'){
1011				$('.change_delivery').find('span').html('<b>'+$('#econt_shipping').val()+',00</b> '+$('#obs_currency_symbol').val()+'');
1012				var the_total=$('#total_products').val()*1 + $('#total_insurance').val()*1 + $('#econt_shipping').val()*1 - discounts;
1013				$('#total_no_tax').val(the_total);
1014				if($('.change_payment').is(':visible')){
1015					the_total=the_total + $('#total_handling_tax').val()*1;
1016				}
1017				the_total_fixed=the_total.toFixed(2);
1018				$('#total_order_price').val(the_total);
1019				$('.full_total').find('b').html(the_total_fixed);
1020				if($('.euro-price').length > 0){
1021					$($('.full_total').parent().find('.euro-price')).find('b').html(rou
1021ndEuroLaw(the_total/($('#euro_conv').val()*1)));
1022				}
1023			}
1024			if($this.attr('id') == 'carrier_id' && $this.val() == 2 && the_total_price < $('#free_shipping').val() && $('.change_delivery').find('b').html() != ''+$('#speedy_shipping').val()+',00'){
1025				$('.change_delivery').find('span').html('<b>'+$('#speedy_shipping').val()+',00</b> '+$('#obs_currency_symbol').val()+'');
1026				var the_total=$('#total_products').val()*1 + $('#total_insurance').val()*1 + $('#speedy_shipping').val()*1 - discounts;
1027				$('#total_no_tax').val(the_total);
1028				if($('.change_payment').is(':visible')){
1029					the_total=the_total + $('#total_handling_tax').val()*1;
1030				}
1031				the_total_fixed=the_total.toFixed(2);
1032				$('#total_order_price').val(the_total);
1033				$('.full_total').find('b').html(the_total_fixed);
1034				if($('.euro-price').length > 0){
1035					$($('.full_total').parent().find('.euro-price')).find('b').html(roundEuroLaw(the_total/($('#euro_conv').val()*1)));
1036				}
1037			}
1038			if($this.attr('id') == 'carrier_id' && $this.val() == 2 && parseInt($('#total_order_price').val()) >= $('#free_shipping').val()){
1039			//if($this.attr('id') == 'carrier_id' && ($this.val() == 2 || $this.val() == 1) && the_total_price >= $('#free_shipping').val()){
1040				$('.change_delivery').find('span').html('<b>БЕЗПЛАТНА</b>');
1041				var the_total=$('#total_products').val()*1 + $('#total_insurance').val()*1 - discounts;
1042				$('#total_no_tax').val(the_total);
1043				if($('.change_payment').is(':visible')){
1044					the_total=the_total + $('#total_handling_tax').val()*1;
1045				}
1046				the_total_fixed=the_total.toFixed(2);
1047				$('.full_total').find('b').html(the_total_fixed);
1048				$('#total_order_price').val(the_total);
1049				if($('.euro-price').length > 0){
1050					$($('.full_total').parent().find('.euro-price')).find('b').html(roundEuroLaw(the_total/($('#euro_conv').val()*1)));
1051				}
1052			}
1053			if($this.attr('id') == 'door_carrier_id' || $this.attr('id') == 'carrier_id'){
1054				if($this.attr('id') == 'door_carrier_id'){
1055					var the_txt_el=$('div.todoor_firm').prev();
1056				}else{
1057					var the_txt_el=$('div.todoor_firm').next();
1058				}
1059				if($('html').attr('lang') == 'en-US'){
1060					if($this.val() == 3){
1061						$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> You can check the delivery schedule to your town on the <a target="_blank" href="https://www.transpress.bg/en/for-clien/schedule-for-services-in-settlements-in-bulgaria">site of Transpress courier company</a>. All shipments have insurance and review option included.');
1062					}else if($this.val() == 1){
1063						$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> The delivery to an office of Econt is worth 4 € with VAT included. If you would like to take advantage of a free delivery for orders w
1063orth more than '+$('#free_shipping').val()+' €, please choose an office of Speedy. You can check the working hours of Econt offices <a href="https://www.econt.com/find-office" target="_blank">on the site of the company</a>. All shipments have insurance and review option included.');
1064						//$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> Delivery to the Econt office is free for orders over BGN '+$('#free_shipping').val()+' € until 12/31/23. For orders worth less than BGN '+$('#free_shipping').val()+' €, delivery to the Econt office costs 4 € including VAT. You can check the working hours of Econt offices <a href="https://www.econt.com/find-office" target="_blank">on the site of the company</a>. All shipments have insurance and review option included.');
1065					}else if($this.val() == 2){
1066						$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> You can check the working hours of Speedy offices <a href="https://www.speedy.bg/bg/speedy-offices" target="_blank">on the site of the company</a>. All shipments have insurance and review option included.');
1067					}
1068				}else{
1069					if($this.val() == 3){
1070						$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> Можете да проверите графика за доставки до вашето населено място на <a target="_blank" href="https://www.transpress.bg/bg/za-klienti/grafik-za-obslujvane">страницата на куриерска компания Транспрес</a>. Всички пратки са застраховани и с включена опция за преглед.');
1071					}else if($this.val() == 1){
1072						$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> Доставката до офис на фирма Еконт е на стойност 4 € с включен ДДС. Ако желаете да се възползвате от безплатна доставка за поръчки на стойност над '+$('#free_shipping').val()+' €, моля, изберете офис на фирма Спиди. Можете да проверите работното време на офисите на <a href="https://www.econt.com/find-office" target="_blank">страницата на куриерска компания Еконт</a>. Всички пратки са застраховани и с включена опция за преглед.');
1073						//$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> Доставката до офис на фирма Еконт е безплатна за поръчки на стойност над '+$('#free_shipping').val()+' € до 31.12.23. За поръчки на стойност под '+$('#free_shipping').val()+' € доставката до офис на фирма Еконт е на стойност 4 € с включен ДДС. Можете да проверите работното време на офисите на <a href="https://www.econt.com/find-office" target="_blank">страницата на куриерска компания Еконт</a>. Всички пратки са застраховани и с включена опция за преглед.');
1074					}else if($this.val() == 2){
1075						$(the_txt_el).find('p.currier_info').html('<img src="/themes/photosynthesis/img/info_icon.png"> Можете да проверите работното време на офисите на <a href="https://www.speedy.bg/bg/speedy-offices" target="_blank">страницата на куриерска компания Спиди</a>. Всички пратки са застраховани и с включена опция за преглед.');
1076					}
1077				}
1078			}
1079			 if($this.attr('id') == 'payment_tp'){
1080				if($this.val() == 2){
1081					$('div.payment_selected').find('div.has_advanced').fadeIn();
1082					$('#pay-methodcashondelivery').parent().hide();
1083					$('#pay-method-leasing').removeAttr('checked');
1084					$('#leasing').hide();
1085					//$('span.when_leasing').css('opacity','0');
1086				}else if($this.val() == 3){
1087					if(!($('#initial_special').val() > 0)){
1088						$('input[name="pay-method"]').parent().hide();
1089						$('#pay-method-leasing').trigger('click');
1090						$('input[id="pay-method-leasing"]').parent().fadeIn();
1091					}
1092					$('#leasing').fadeIn();
1093					
1094					//$('span.when_leasing').css('opacity','1');
1095				}else{
1096					$('#leasing').hide();
1097					//$('span.when_leasing').css('opacity','0');
1098					$('div.payment_selected').find('div.has_advanced').hide();
1099					$('input[name="pay-method"]').parent().fadeIn();
1100					$('input[id="pay-method-leasing"]').parent().hide();
1101					$('#pay-method-leasing').removeAttr('checked');
1102				}
1103			 }
1104			if($this.attr('id') == 'mass_action'){
1105				var action=$(this).attr('rel');
1106				$.ajax({
1107					type: "POST",
1108					url: '/index.php?controller=notifications',
1109					data: {mass_action:1,action:action},
1110					success:function(data){
1111						location.reload();
1112					}
1113				});
1114			}
1115			if($this.attr('id') == 'id_demand' && $('form.return-form').length > 0){
1116				var action=$(this).attr('rel');
1117				$($this).parent().parent().parent().find('.demand_f').next().html('');
1118				if(action == 1){
1119					$($this).parent().parent().parent().find('.demand_f').next().html('<input class="form-control grey" type="text"placeholder="Номер на сметка" required id="iban_'+$this.attr('data-id')+'" name="iban_'+$this.attr('data-id')+'" value="" />');
1120				}
1121				if(action == 2){
1122					$($this).parent().parent().parent().find('.demand_f').next().html('<input class="form-control grey" type="text" id="replacement_'+$this.attr('data-id')+'" placeholder="Въведете код или наименование" name="replacement_'+$this.attr('data-id')+'" value="" />');
1123				}
1124			}
1125			if($this.attr('id') == 'id_demand' && $('form.reclamation-form').length > 0){
1126				var action=$(this).attr('rel');
1127				$('#iban_container').hide();
1128				$('#iban').removeAttr('required');
1129				$('#replacement_container').hide();
1130				$('#other_container').hide();
1131				if(action == 1){
1132					$('#iban').attr('required','required');
1133					$('#iban_container').show();
1134				}
1135				if(action == 2){
1136					$('#replacement_container').show();
1137				}
1138				if(action == 5){
1139					$('#other_container').show();
1140				}
1141			}
1142        });
1143        $(document).click(function() {
1144            $styledSelect.removeClass('active');
1145            $list.hide();
1146
1147        });
1148		
1149
1150    });
1151}
1152// ========================= Articles Popup ===============================================
1153function resizeIframe() { 
1154	$('#iframe').iFrameResize({checkOrigin:false});
1155	$('div.popup_inner').animate({opacity:1},1000);
1156	$('#page_loading').hide();
1157}
1158function resizePopupIframe(obj) {
1159	obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
1160	$('div.popup_inner').animate({opacity:1},1000);
1161	$('#page_loading').hide();
1162}
1163function setMinHeight(){
1164	$(document).ready(function(){
1165		$('#iframe').css('min-height',$(window).height() - 180);
1166
1167	});
1168}
1169function getMinHeight(){
1170		return $(window).height() - 180;
1171}
1172setMinHeight();
1173
1174function loadPromotion(obj){
1175	$('#iframe').remove(); 
1176	$('div.article_container').fadeIn();
1177	$('div.scroller_div').fadeIn();
1178	$('div.article_container').css('position','absolute');
1179	$('div.article_container').css('top',50);
1180	$('html, body').css({"overflow":"hidden","height":"100%"});
1181	$('div.scroller_div').css('top',$(document).scrollTop());
1182	$('div.dark_wrapper').show();
1183	$('div.on_article').show();
1184	$('div.left_banner,div.top_banner').hide();
1185	var has_form=$(obj).attr('data-form');
1186	var href_naked=$(obj).attr('data-href');
1187	var href=href_naked+'?iframed=1&rand='+Math.round(Math.random()*10000);
1188	var iframe_href=$('#iframe').attr('href');
1189	//$('#page_loading').show();
1190	//$('div.popup_inner').css('opacity','0');
1191	//$("html, body").animate({ scrollTop: 0 },'fast');
1192	if(href != iframe_href){
1193		if(has_form > 0){
1194			$('div.promo_form').before('<iframe id="iframe" src="'+href+'" style="width: 100%; padding: 0px; margin: 0px; min-height: 786px; overflow: hidden;" scrolling="no" onload="resizeIframe()" frameborder="0"></iframe>');
1195		}else{
1196			$('div.popup_inner').append('<iframe id="iframe" src="'+href+'" style="width: 100%; padding: 0px; margin: 0px; min-height: 786px; overflow: hidden;" scrolling="no" onload="resizeIframe()" frameborder="0"></iframe>');
1197		}
1198		
1199	}
1200	if(has_form > 0){
1201		$('div.promo_form').show();
1202		$('#id_promotion_form').val($(obj).attr('data-id'));
1203	}else{
1204		$('div.promo_form').hide();
1205	}
1206	$('div.article_container iframe').attr('onload','resizePopupIframe(this)');
1207
1208	if($('html').attr('lang') == 'en-US'){
1209		var lang='en';
1210	}else{
1211		var lang='bg';
1212	}
1213	try {
1214		window.history.pushState("", "",'/bg/promotion/'+$(obj).attr('data-url'));  
1215	}
1216	catch(err) {
1217		location.href='/bg/promotion/'+$(obj).attr('data-url');
1218	}
1219
1220}
1221function loadStatic(obj){
1222	$('#iframe').remove(); 
1223	$('div.article_container').fadeIn();
1224	$('div.scroller_div').fadeIn();
1225	$('div.article_container').css('position','absolute');
1226	$('div.article_container').css('top',50);
1227	$('html, body').css({"overflow":"hidden","height":"100%"});
1228	$('div.scroller_div').css('top',$(document).scrollTop());
1229	$('div.dark_wrapper').show();
1230	$('div.on_article').show();
1231	$('div.left_banner,div.top_banner').hide();
1232	var href=$(obj).attr('href');
1233	var iframe_href=$('#iframe').attr('href');
1234	$('#orig_url').val(window.location.href);
1235	//$('#page_loading').show();
1236	//$('div.popup_inner').css('opacity','0');
1237	//$("html, body").animate({ scrollTop: 0 },'fast');
1238	
1239	if(href != iframe_href){
1240		$('div.popup_inner').append('<iframe id="iframe" src="'+(!href.match(/http/)?($('body').hasClass('lang_bg')?'/bg':'/en'):'')+href.replace(/^\/bg\//,'/').replace(/^\/en\//,'/')+'" style="width: 100%; padding: 0px; margin: 0px; min-height: 786px; overflow: hidden;" scrolling="no" onload="resizeIframe()" frameborder="0"></iframe>');
1241	}
1242	$('div.article_container iframe').attr('onload','resizePopupIframe(this)');
1243	try {
1244		window.history.pushState("", "",href.replace(/\?iframed=1/,''));  
1245	}
1246	catch(err) {
1247		location.href=href.replace(/\?iframed=1/,'');
1248	}
1249}
1250function loadFromUrl(URL){
1251	if(URL == ''){
1252		return false;
1253	}
1254	var article='';
1255	$('a.phs_article').each(function(){
1256		if($(this).attr('href').replace(/\/\/photosynthesis.bg\/statia\//,'') == URL){
1257			article=$(this).attr('data-id');
1258		}
1259	});
1260	
1261	if(article != ''){
1262		loadArticle(article);
1263	}else{
1264		$("html, body").animate({ scrollTop: 0 },'fast');
1265		$('#orig_url').val('index.php?controller=category&id_category='+$('input[name="id_category_layered"]').val()+'&id_lang=1&isolang=bg');
1266		$('div.article_container iframe').attr('src','//photosynthesis.bg/statia/'+URL+'?iframed=1');
1267		
1268		$('div.dark_wrapper').show();
1269		$('div.header').hide();
1270		$('div.sticky_sub').hide();
1271		$('div.on_article').show();
1272		$('div.sticky_header').show();
1273		$('div.scroller_div,div.dark_wrapper,a.close_window,a.go_home').click(function(e){
1274			e.preventDefault();
1275			if($(this).attr('class') == 'article_container' || $('div.gdpr').hasClass('active') || $(this).prop("tagName") == 'a'){
1276				return false;
1277			}
1278			closePopup();
1279		});
1280		$('div.article_container').click(function(e){
1281			e.stopImmediatePropagation();
1282			e.stopPropagation();
1283		});
1284
1285	}
1286}
1287function loadArticle(obj){
1288	$('#iframe').remove(); 
1289	//$("html, body").animate({ scrollTop: 0 },'fast');
1290	console.log(obj);
1291	var url=$('.'+obj).attr('href').replace(/\/\/photosynthesis.bg\/statia\//,'https://magazin.photosynthesis.bg/framing.php?url=');  
1292	$('div.popup_inner').append('<iframe id="iframe" src="'+url+'" style="width: 100%; padding: 0px; margin: 0px; min-height: 786px; overflow: hidden;" scrolling="no" onload="resizeIframe()" frameborder="0"></iframe>');
1293	$('div.article_container iframe').attr('onload','resizePopupIframe(this)');
1294	$('#orig_url').val(window.location.href);
1295	$('div.dark_wrapper').show();
1296	$('div.header').hide();
1297	$('div.sticky_sub').hide();
1298	$('div.on_article').show();
1299	$('div.sticky_header').show();
1300	var id=obj;
1301	var id=id.replace(/article_/,'');
1302	
1303	url=url.replace(/^.*url=/,'');  
1304	document.title=$($('.'+obj).parent()).find('h4 a').html();
1305	document.description=$($('.'+obj).parent()).find('p').html();
1306	
1307	if($('#category_'+id).val()){
1308	
1309		var cat=location.protocol+'//'+location.hostname+'/bg/'+$('#category_'+id).val();
1310	}else{
1311		var cat=window.location.href.replace(/-.*$/,'');
1312	}
1313	try {
1314		window.history.pushState("", "",cat+'/statia/'+url);  
1315	}
1316	catch(err) {
1317		location.href='http://shop.playground.photosynthesis.bg/bg/statia/'+url;
1318	}
1319	$('div.article_container').fadeIn();
1320	$('div.scroller_div').fadeIn();
1321	$('div.article_container').addClass('smaller');
1322	$('div.article_container').css('position','absolute');
1323	$('div.article_container').css('top',50);
1324	$('html, body').css({"overflow":"hidden","height":"100%"});
1325	$('div.scroller_div').css('top',$(document).scrollTop());
1326
1327	if($('#reg_data_'+id).length > 0){
1328		var reg_data=$('#reg_data_'+id).val();
1329		$('#city_id').val(reg_data.replace(/_.*$/,''));
1330		$('#event_nm').val(reg_data.replace(/\d_$/,''));
1331	}
1332	if($('#to_register_'+id).val() == 1){
1333		$('#reserve').show();
1334	}else{
1335		$('#reserve').hide();
1336	}
1337	var selClass='';
1338	var all_ids=$('#all_articles').val(); 
1339	ids_arr=all_ids.split(",");
1340	var pos=ids_arr.indexOf(id); 
1341	var prev=ids_arr[pos - 1];
1342	$('a.go_left').attr('class','go_left');
1343	$('a.go_left').unbind('click');
1344	$('a.go_right').attr('class','go_right');
1345	$('a.go_right').unbind('click');
1346	var next=ids_arr[pos*1 + 1];
1347	if(prev*1 > 0 && typeof(prev) !== 'undefined'){
1348		$('a.go_left').addClass("article_"+prev);
1349		$('a.go_left').attr('href',$('a.article_'+prev).attr('href'));
1350		$('a.go_left').show();
1351	}else{
1352		$('a.go_left').hide();
1353	}
1354	if(next*1 > 0 && typeof(next) !== 'undefined'){
1355		$('a.go_right').addClass("article_"+next);
1356		$('a.go_right').attr('href',$('a.article_'+next).attr('href'));
1357		$('a.go_right').show();
1358	}else{
1359		$('a.go_right').hide();
1360	}
1361	$('a.go_right,a.go_left').click(function(e){
1362		e.preventDefault();
1363		loadArticle($(this).attr('class').replace(/^.*\s/,''));
1364	});
1365}
1366function closePopup(){
1367	$('div.reg_msg').remove();
1368	//$('div.article_container iframe').attr('src','#');
1369	$('div.dark_wrapper').hide();
1370	try {
1371		window.history.pushState("", "",$('#orig_url').val());
1372	}
1373	catch(err) {
1374		location.href=window.location.href;
1375	}
1376	$('div.article_container').removeClass('smaller');
1377	$('html, body').css({"overflow":"auto","height":"auto"});
1378	$('div.scroller_div').fadeOut();
1379	$('div.article_container').fadeOut();
1380}
1381function accessoryPagination(page,id_category){
1382	if(!page){
1383		$('div.top.paggination').hide();
1384		return false;
1385	}
1386	var pages=parseInt($('#all_pages').html());
1387	var products=$('#all_products').html();
1388	var pagination=$('#top_pagination');
1389	var dist_begin=page - 1;
1390	//var dist_end= topPagination - page;
1391	var html='<li class="prev top_nav_prev"><a href="#">prev</a></li><li '+(1 == page?'class="active"':'class="regular"')+'><a href="#">1</a></li>';
1392	if(page >= 5 && page <= pages-4){
1393		html += '<li class="disable"><a href="#">...</a></li>';
1394		html += '<li class="regular"><a href="#">'+(page-2)+'</a></li>';
1395		html += '<li class="regular"><a href="#">'+(page-1)+'</a></li>';
1396		html += '<li class="active"><a href="#">'+page+'</a></li>';
1397		html += '<li class="regular"><a href="#">'+(page+1)+'</a></li>';
1398		html += '<li class="regular"><a href="#">'+(page+2)+'</a></li>';
1399		html += '<li class="disable"><a href="#">...</a></li>';
1400	}else if(page <=3 || pages <= 6){
1401		var cnt=6;
1402		if(pages < 6){
1403			cnt=pages;
1404		}
1405		for(var i=2;i<cnt;i++){
1406			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1407		}
1408		if(pages > 6){
1409			html += '<li class="disable"><a href="#">...</a></li>';
1410		}
1411	}else if(page == 4 && pages > 6){
1412		for(var i=2;i<7;i++){
1413			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1414		}
1415		if(pages > 6){
1416			html += '<li class="disable"><a href="#">...</a></li>';
1417		}
1418	}else if(page >= pages-2 && pages > 6){
1419
1420		html += '<li class="disable"><a href="#">...</a></li>';
1421		for(var i=pages-4;i<pages;i++){
1422			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1423		}
1424	}else if(page >= pages-3 && pages > 6){
1425		html += '<li class="disable"><a href="#">...</a></li>';
1426		for(var i=pages-5;i<pages;i++){
1427			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1428		}
1429	}
1430	html += '<li '+(pages == page?'class="active"':'class="regular"')+'><a href="#">'+pages+'</a></li><li class="next top_nav_next"><a href="#">next</a></li>';
1431	if(pages > 1){
1432		$(pagination).html(html);
1433	}else{
1434		$('div.paggination').hide();
1435	}
1436	if(page > 1){
1437		$(pagination).find('li.prev').show();
1438	}
1439	if(page == pages){
1440		$(pagination).find('li.next').hide();
1441	}
1442	//alert(html);
1443	$('#curr_page').html(page);
1444	var range_begin=(page-1)*$('#nb').val() + 1;
1445	var range_end = range_begin+($('#nb').val()-1);
1446	if(range_end > products){
1447		range_end=products;
1448	}
1449	$('#range').html(range_begin + ' - ' + range_end);
1450	
1451	if(page  == 1){
1452		$('li.top_nav_prev').hide();
1453	}
1454	if(page  == pages){
1455		$('li.top_nav_next').hide();
1456	}
1457	$('li.top_nav_next a').click(function(e){
1458		e.preventDefault();
1459		$("html, body").animate({
1460				scrollTop: $('#go_here').offset().top
1461		}, 300,function(){
1462			$('#load_container_'+id_category).css('opacity','0.3');
1463			$('#load_container_'+id_category).load(window.location.href.replace(/#.*$/,'').replace(/\?.*$/,'')+'?acc_cat_id='+id_category+'&page='+(page*1+1)+' #acc_grabber_'+id_category,function(data){
1464				//alert(data);
1465				accessoryPagination(page*1+1,id_category);
1466				$('#load_container_'+id_category).animate({opacity:1});
1467			})
1468		});
1469	});
1470	$('li.top_nav_prev a').click(function(e){
1471		e.preventDefault();
1472		$("html, body").animate({
1473				scrollTop: $('#go_here').offset().top
1474		}, 300,function(){
1475			$('#load_container_'+id_category).css('opacity','0.3');
1476			$('#load_container_'+id_category).load(window.location.href.replace(/#.*$/,'').replace(/\?.*$/,'')+'?acc_cat_id='+id_category+'&page='+(page*1-1)+' #acc_grabber_'+id_category,function(data){
1477				//alert(data);
1478				accessoryPagination(page*1-1,id_category);
1479				$('#load_container_'+id_category).animate({opacity:1});
1480			})
1481		});
1482	});
1483	$('#top_pagination li.active').find('a').click(function(e){
1484		e.preventDefault();
1485	});
1486	$('li.regular a').click(function(e){
1487		e.preventDefault();
1488		e.stopPropagation();
1489		var page=parseInt($(this).html());
1490		e.stopImmediatePropagation();
1491		$("html, body").animate({
1492				scrollTop: $('#go_here').offset().top
1493		}, 300,function(){
1494			$('#load_container_'+id_category).css('opacity','0.3');
1495			$('#load_container_'+id_category).load(window.location.href.replace(/#.*$/,'').replace(/\?.*$/,'')+'?acc_cat_id='+id_category+'&page='+page+' #acc_grabber_'+id_category,function(data){
1496				//alert(data);
1497				accessoryPagination(page,id_category);
1498				$('#load_container_'+id_category).animate({opacity:1});
1499			});
1500		});
1501
1502	});
1503}
1504function topPagination(page){
1505	init();
1506	if(!page){
1507		$('div.top.paggination').hide();
1508		return false;
1509	}
1510	console.log('3');
1511	var pages=parseInt($('#all_pages').html());
1512	var products=$('#all_products').html();
1513	var pagination=$('#top_pagination');
1514	var dist_begin=page - 1;
1515	var dist_end= topPagination - page;
1516	var html='<li class="prev top_nav_prev"><a href="#">prev</a></li><li '+(1 == page?'class="active"':'class="regular"')+'><a href="#">1</a></li>';
1517	if(page >= 5 && page <= pages-4){
1518		html += '<li class="disable"><a href="#">...</a></li>';
1519		html += '<li class="regular"><a href="#">'+(page-2)+'</a></li>';
1520		html += '<li class="regular"><a href="#">'+(page-1)+'</a></li>';
1521		html += '<li class="active"><a href="#">'+page+'</a></li>';
1522		html += '<li class="regular"><a href="#">'+(page+1)+'</a></li>';
1523		html += '<li class="regular"><a href="#">'+(page+2)+'</a></li>';
1524		html += '<li class="disable"><a href="#">...</a></li>';
1525	}else if(page <=3 || pages <= 6){
1526		var cnt=6;
1527		if(pages < 6){
1528			cnt=pages;
1529		}
1530		for(var i=2;i<cnt;i++){
1531			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1532		}
1533		if(pages > 6){
1534			html += '<li class="disable"><a href="#">...</a></li>';
1535		}
1536	}else if(page == 4 && pages > 6){
1537		for(var i=2;i<7;i++){
1538			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1539		}
1540		if(pages > 6){
1541			html += '<li class="disable"><a href="#">...</a></li>';
1542		}
1543	}else if(page >= pages-2 && pages > 6){
1544
1545		html += '<li class="disable"><a href="#">...</a></li>';
1546		for(var i=pages-4;i<pages;i++){
1547			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1548		}
1549	}else if(page >= pages-3 && pages > 6){
1550		html += '<li class="disable"><a href="#">...</a></li>';
1551		for(var i=pages-5;i<pages;i++){
1552			html +='<li '+(i == page?'class="active"':'class="regular"')+'><a href="#">'+i+'</a></li>';
1553		}
1554	}
1555	html += '<li '+(pages == page?'class="active"':'class="regular"')+'><a href="#">'+pages+'</a></li><li class="next top_nav_next"><a href="#">next</a></li>';
1556	
1557	if(page > 1){
1558		$(pagination).find('li.prev').show();
1559	}
1560	if(page == pages){
1561		$(pagination).find('li.next').hide();
1562		$('.top_vew_all').hide();
1563	}else{
1564		$('.top_vew_all').show();
1565	}
1566	//alert(html);
1567	$('#curr_page').html(page);
1568	var range_begin=(page-1)*$('#nb').val() + 1;
1569	var range_end = range_begin+($('#nb').val()-1);
1570	if(range_end > products){
1571		range_end=products;
1572	}
1573	$('#range').html(range_begin + ' - ' + range_end);
1574	if(pages > 1){
1575		$(pagination).html(html);
1576	}else{
1577		$('div.paggination').hide();
1578	}
1579	if(page  == 1){
1580		$('li.top_nav_prev').hide();
1581	}
1582	if(page  == pages){
1583		$('li.top_nav_next').hide();
1584	}
1585
1586	$('li.top_nav_next a').click(function(e){
1587		e.preventDefault();
1588		$("html, body").animate({
1589				scrollTop: $('#go_here').offset().top
1590		}, 300,function(){
1591			$('#load_container').css('opacity','0.3');
1592			$('#load_container').load(window.location.href.replace(/#/,'')+'?page='+(page*1+1)+' #special_grabber',function(data){
1593				//alert(data);
1594				topPagination(page*1+1);
1595				$('#load_container').animate({opacity:1});
1596				$('.item-bundles').on('click', '.toggle-btn', function(){
1597					$($(this).parent()).find('h3').hide();
1598					$(this).toggleClass('active', 200).parent().toggleClass('active', 200,function(){
1599						$($(this).parent()).find('h3').show();
1600					});
1601				});
1602			})
1603		});
1604	});
1605	$('li.top_nav_prev a').click(function(e){
1606		e.preventDefault();
1607		$("html, body").animate({
1608				scrollTop: $('#go_here').offset().top
1609		}, 300,function(){
1610			$('#load_container').css('opacity','0.3');
1611			$('#load_container').load(window.location.href.replace(/#/,'')+'?page='+(page*1-1)+' #special_grabber',function(data){
1612				//alert(data);
1613				topPagination(page*1-1);
1614				$('#load_container').animate({opacity:1});
1615				$('.item-bundles').on('click', '.toggle-btn', function(){
1616					$($(this).parent()).find('h3').hide();
1617					$(this).toggleClass('active', 200).parent().toggleClass('active', 200,function(){
1618						$($(this).parent()).find('h3').show();
1619					});
1620				});
1621
1622			})
1623		});
1624	});
1625	$('#top_pagination li.active').find('a').click(function(e){
1626		e.preventDefault();
1627	});
1628	$('li.regular a').click(function(e){
1629		e.preventDefault();
1630		e.stopImmediatePropagation();
1631		e.stopPropagation();
1632		var page=parseInt($(this).html());
1633		$("html, body").animate({
1634				scrollTop: $('#go_here').offset().top
1635		}, 300,function(){
1636			$('#load_container').css('opacity','0.3');
1637			$('#load_container').load(window.location.href.replace(/#/,'')+'?page='+page+' #special_grabber',function(data){
1638				//alert(data);
1639				
1640				topPagination(page);
1641				$('#load_container').animate({opacity:1});
1642				$('.item-bundles').on('click', '.toggle-btn', function(){
1643					$($(this).parent()).find('h3').hide();
1644					$(this).toggleClass('active', 200).parent().toggleClass('active', 200,function(){
1645						$($(this).parent()).find('h3').show();
1646					});
1647				});
1648
1649			})
1650		});
1651
1652	});
1653}
1654function loadTab(id_category,tab){
1655	$('div.clean_it').html('<p style="text-align:center;margin-top:15px;margin-bottom:15px;width:100%;font-size:13px;">Зареждат се аксесоари. Моля изкачайте...</p>');
1656	$('#'+tab).load(window.location.href.replace(/#.*$/,'').replace(/\?.*$/,'')+'?acc_cat_id='+id_category+'&page='+1+' #tab_loader_'+id_category,function(data){
1657		accessoryPagination(1,id_category);
1658		if($('#top_pagination').length > 0){
1659			accessoryPagination(1,id_category);
1660			$('a.top_vew_all').click(function(e){
1661				e.preventDefault();
1662				e.stopImmediatePropagation();
1663				e.stopPropagation();
1664				//alert('123');
1665				$("html, body").animate({
1666						scrollTop: $('#go_here').offset().top
1667				}, 300,function(){ 
1668					$('#load_container_'+id_category).css('opacity','0.3');
1669					$('#load_container_'+id_category).load(window.location.href.replace(/#.*$/,'').replace(/\?.*$/,'')+'?acc_cat_id='+id_category+'&view=all #acc_grabber_'+id_category,function(data){
1670						//alert(data);
1671						accessoryPagination(0,id_category);
1672						$('#load_container_'+id_category).animate({opacity:1});
1673					})
1674				});
1675			});
1676		}
1677	});
1678}
1679function promoForm(){
1680	$("#promo_form").submit(function(e) {
1681		$(this).find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
1682		if($('input[name="your-email"]').val() != '' && $('input[name="your-name"]:checked').val() != '' && $('input[name="your-phone"]').val() != ''){
1683		$.ajax({
1684			   type: "POST",
1685			   url: '/external/promoform.php',
1686			   data: $("#promo_form").serialize(),
1687			   success: function(data){
1688					$("#promo_form").find('input[type="submit"]').css('background','#91a719').val('Изпрати');
1689					if(data == 'success'){
1690						$("#result_msg").html('<span id="feedmsg" style="color:#2bc524;font-weight:normal;">Информацията е изпратена успешно.</span>');
1691					}else{
1692						$("#result_msg").html('<span id="feedmsg" style="color:#af0000;font-weight:normal;">Възникна грешка! Моля опитайте по-късно или се свържете с нас за съдействие.</span>');
1693					}
1694					$("#promo_form")[0].reset();
1695			   }
1696			 });
1697		}else{
1698			if($('input[name="your-email"]').val() == ''){
1699				$("#result_msg").html('<span id="feedmsg" style="color:#af0000;font-weight:normal;">Моля въведете вашия имейл.</span>');
1700			}
1701			if($('input[name="your-name"]').val() == ''){
1702				$("#result_msg").html('<span id="feedmsg" style="color:#af0000;font-weight:normal;">
1702Моля въведете вашето име.</span>');
1703			}
1704			if($('input[name="your-phone"]').val() == ''){
1705				$("#result_msg").html('<span id="feedmsg" style="color:#af0000;font-weight:normal;">Моля въведете вашия телефон.</span>');
1706			}
1707			$(this).find('input[type="submit"]').css('background','#91a719').val('Изпрати');
1708		}
1709		e.preventDefault();
1710	});
1711}
1712function addPaymentTax(){
1713	var currentTotal=$('#total_no_tax').val()*1;
1714	if(($('#delivery_option_12').is(':checked') || $('#delivery_option_15').is(':checked')) && currentTotal > 5112.41){
1715		$('#pay-methodcashondelivery').parent().hide();
1716	}else if(!$('#leasing_payment').is(':checked') && !$('#advance_payment').is(':checked')){
1717		$('#pay-methodcashondelivery').parent().show();
1718	}
1719	if(!$('#delivery_option_10').is(':checked') && $('#pay-methodcashondelivery').is(':checked')){
1720		$('.change_payment').show();
1721		var newTotal=currentTotal + $('#total_handling_tax').val()*1;
1722	}else{
1723		$('.change_payment').hide();
1724		var newTotal=currentTotal;
1725	}
1726	$('.full_total').find('b').html(newTotal.toFixed(2));
1727
1728	if($('.euro-price').length > 0){
1729		$($('.full_total').parent().find('.euro-price')).find('b').html(roundEuroLaw(newTotal/($('#euro_conv').val()*1)));
1730	}
1731}
1732function makeTop(){
1733	if($('a.make_top').length > 0){
1734		$('input.admin_priority').keyup(function(){
1735			var id=$($(this).parent().parent().parent().parent()).attr('id').replace(/product_/,'');
1736			var priority=$(this).val();
1737			$.ajax({
1738				type: "POST",
1739				url: '/external/make_top.php',
1740				data: {id_product:id,priority:priority,only_priority:1,top:1},
1741				success: function(data){
1742				}
1743			});
1744		});
1745		$('input.admin_priority').change(function(){
1746			var id=$($(this).parent().parent().parent().parent()).attr('id').replace(/product_/,'');
1747			var priority=$(this).val();
1748			$.ajax({
1749				type: "POST",
1750				url: '/external/make_top.php',
1751				data: {id_product:id,priority:priority,only_priority:1,top:1},
1752				success: function(data){
1753				}
1754			});
1755		});
1756		$('a.make_top').click(function(e){
1757			e.preventDefault();
1758			e.stopImmediatePropagation();
1759			e.stopPropagation();
1760			var link=$(this);
1761			
1762			var id=$($(this).parent().parent().parent().parent()).attr('id').replace(/product_/,'');
1763			var top=$($(this).parent().parent().parent()).find('img.top-price').length > 0?1:0;
1764			if($(link).hasClass('home_top')){
1765				var priority=$($(this).prev()).val();
1766				$.ajax({
1767					type: "POST",
1768					url: '/external/make_top.php',
1769					data: {id_product:id,top:1,priority:priority,home_top:($(link).hasClass('home_top') && !$(link).hasClass('remove')?1:2)},
1770					success: function(data){
1771						if($(link).hasClass('remove')){
1772							if($(link).hasClass('grid')){
1773								$(link).removeClass('remove');
1774							}else{
1775								$(link).removeClass('remove');
1776							}
1777						}else{
1778							$(link).addClass('remove');
1779						}
1780					}
1781				});
1782			}else if($(link).hasClass('on_promo')){
1783				$.ajax({
1784					type: "POST",
1785					url: '/external/make_top.php',
1786					data: {id_product:id,is_for_promo:1,action:$(link).hasClass('remove')?2:1},
1787					success: function(data){
1788						if($(link).hasClass('remove')){
1789							$(link).removeClass('remove');
1790						}else{
1791							$(link).addClass('remove');
1792						}
1793					}
1794				});
1795			}else{
1796				var priority=$($(this).prev().prev()).val(); 
1797				$.ajax({
1798					type: "POST",
1799					url: '/external/make_top.php',
1800					data: {id_product:id,top:top > 0?0:1,priority:priority},
1801					success: function(data){
1802						if(top){
1803							if($(link).hasClass('grid')){
1804								$($(link).parent().parent().parent()).find('img.top-price').remove();
1805								$(link).removeClass('remove');
1806							}else{
1807								$($(link).parent().parent().parent()).find('img.top-price').remove();
1808								$(link).removeClass('remove');
1809							}
1810						}else{
1811							$($(link).parent().parent().parent()).find('div.item-buy-info').prepend('<img src="/themes/photosynthesis/img/top-price-bg.png" class="top-price" />');
1812							$(link).addClass('remove');
1813						}
1814						
1815					}
1816				});
1817			}
1818
1819		});
1820	}
1821}
1822function init(){
1823	leasingPopup();
1824	const input = document.getElementById("numberOnly");
1825
1826    $('#inv_phone, #phone_mobile, #new_phone, #phone').on('paste', function(e) {
1827        e.preventDefault(); // спира paste
1828        let pastedText = (e.originalEvent.clipboardData || window.clipboardData).getData('text');
1829        let digitsOnly = pastedText.replace(/\D/g, '');
1830        document.execCommand("insertText", false, digitsOnly);
1831    });
1832
1833    $('#inv_phone, #phone_mobile, #new_phone, #phone').on('input', function() {
1834        this.value = this.value.replace(/\D/g, '');
1835    });
1836	if($('body').hasClass('order-opc') && $('#leasing_payment').is(':checked') && $('td.schema.selected').length > 0 && $('#monthly_payments').val() != $('td.schema.selected').attr('data-monthly-sum')){
1837		$('td.schema.selected').trigger('click');
1838		$('.click_remove').remove();
1839	}
1840	if($('#submitNewsletter_popup').length > 0){
1841		$('#submitNewsletter_popup').click(function(){
1842			$('#check').val(681);
1843		});
1844	}
1845	if($('#newsletter_send').length > 0){
1846		$('#newsletter_send').click(function(){
1847			$('#check_bf').val(681);
1848		});
1849	}
1850	$('#recovery_button').click(function(){
1851		$('#protect_password').val(681);
1852	});
1853	$('#login_button').click(function(){
1854		$('#protect_login').val(681);
1855	});
1856	$('#register_button').click(function(){
1857		$('#protect_register').val(681);
1858	});
1859	$('#guest_button').click(function(){
1860		$('#protect_guest').val(681);
1861	});
1862	$(document).mouseup(function(e) {
1863		var container = $('ul.auto-suggestion');
1864		if (!container.is(e.target) && container.has(e.target).length === 0 && !$( "#search_query_top" ).is(e.target) && $( "#search_query_top" ).has(e.target).length === 0){
1865			container.hide();
1866		}
1867	});
1868	$( "#search_query_top" ).focusin(function() {
1869		$('ul.auto-suggestion').show();
1870	});
1871	if($('li.share').length > 0){
1872		$('li.share a').click(function(e){
1873			e.preventDefault();
1874			if($('div.link2share').hasClass('active')){
1875				$(this).html('Вземи линк');
1876				$('div.link2share').removeClass('active');
1877			}else{
1878				$(this).html('Скрий линка');
1879				$('div.link2share').addClass('active');
1880			}
1881		});
1882	}
1883	if($('input[name="phone_mobile"],input[name="inv_phone"]').length > 0){
1884		$('input[name="phone_mobile"],input[name="inv_phone"]').keyup(function(){
1885			$(this).val($(this).val().replace(/[^0-9]/g,'')); 
1886		});
1887	}
1888	setTimeout(function(){ if($('a.sticky_product_icon').length > 0 && getCookie('feedback') != 1){$('a.sticky_product_icon').trigger('click');setCookie('feedback',1,365);} }, 4000);
1889	$("#wpcf7-f3662-o1").submit(function(e) {
1890		$(this).find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
1891		if($('input[name="option_id"]:checked').val() != '' && $('input[name="option_id"]:checked').length > 0 && $('input[name="option_id"]:checked') != 'undefined'){
1892		$.ajax({
1893			   type: "POST",
1894			   url: '/external/opinions.php',
1895			   data: $("#wpcf7-f3662-o1").serialize(),
1896			   success: function(data){
1897					$("#wpcf7-f3662-o1").find('input[type="submit"]').css('background','#91a719').val('Изпрати');
1898					$('#feedmsg').remove()
1899					$("#wpcf7-f3662-o1").find('input[type="submit"]').after('<span id="feedmsg" style="color:#91a719;font-weight:normal;"><br />Благодарим Ви! Информацията е изпратена успешно.</span>');
1900					setTimeout(function(){
1901						$('div.product_info').hide();
1902						$('div.sticky_product_container').animate({width:0},350,function(){
1903							$('a.sticky_product_icon').fadeIn();
1904							$('div.sticky_product_container').css('display','none');
1905						});
1906					}, 2000);
1907			   }
1908			 });
1909		}else{
1910			$("#wpcf7-f3662-o1").find('input[type="submit"]').after('<span id="feedmsg" style="color:#af0000;font-weight:normal;"><br />Моля изберете една от горните опции.</span>');
1911			$("#wpcf7-f3662-o1").find('input[type="submit"]').css('background','#91a719').val('Изпрати');
1912		}
1913		e.preventDefault();
1914	});
1915	promoForm();
1916	if(isMobile && screen.width < 500){ 
1917		$('div.product_info').show();
1918		$('a.sticky_product_icon').css('top',"170px");
1919	}
1920	$('a.sticky_product_icon').click(function(e){
1921		e.preventDefault();
1922
1923		$('#antispam').val(123);
1924		$('a.is_sticky').show().css('z-index','7999');
1925		$('div.stickybox').hide();
1926		$(this).css('z-index','8000').hide();
1927		$('div.sticky_product_container').css('display','block');
1928		$('div.sticky_product_container').animate({width:451},350,function(){
1929			if($('div.product_info').hasClass('always')){
1930				$('div.product_info').fadeIn();
1931			}
1932
1933		});
1934	});
1935	$('a.close_it').click(function(e){
1936		e.preventDefault();
1937		e.stopImmediatePropagation();
1938		e.stopPropagation();
1939		$('div.product_info').hide();
1940		$('div.sticky_product_container').animate({width:0},350,function(){
1941			$('a.sticky_product_icon').fadeIn();
1942			
1943		});
1944	});
1945	if($('a.sticky_product_icon.big_icon').length > 0){
1946		$('a.sticky_product_icon.big_icon').show();
1947		$('a.sticky_product_icon.big_icon').css('margin-top',$('a.sticky_product_icon.big_icon').width()/2);
1948		if($('a.sticky_product_icon.big_icon').hasClass('position_2')){
1949			$('a.sticky_product_icon.big_icon').css('right',-$('a.sticky_product_icon.big_icon').width()/2 + parseInt($('a.sticky_product_icon.big_icon').css('padding-left'))/2 -10);
1950		}else{
1951			$('a.sticky_product_icon.big_icon').css('left',-$('a.sticky_product_icon.big_icon').width()/2 + parseInt($('a.sticky_product_icon.big_icon').css('padding-left'))/2);
1952		}
1953	}
1954	$('#orig_url').val(window.location.href);
1955	if($('a.view_more_recomm').length > 0){
1956		$('a.view_more_recomm').click(function(e){
1957			e.preventDefault();
1958			$('#recomm_container').find('div.acc_wrap').append('<p style="text-align:center;margin-top:30px;width:100%;font-size:12px;">Зареждат се още аксесоари. Моля изкачайте...</p>');
1959			$('#recomm_container').load(window.location.href+(window.location.href.match(/\?/)?'&':'?')+'view_all=1 #recomm_container_inner');
1960		});
1961	}
1962	if($('a.delete_account').length > 0){
1963		$('a.delete_account').click(function(e){
1964			e.preventDefault();
1965			if(confirm('Сигурни ли сте, че искате да изтриете профила си?')){
1966				$.ajax({
1967					type: "POST",
1968					url: '/module/psgdpr/gdpr',
1969					data: {del_account:1},
1970					success: function(data){
1971						location.href='/bg/';
1972					}
1973				});
1974			}
1975
1976		});
1977	}
1978	$('a.fb_login').click(function(e){
1979		e.preventDefault();
1980		e.stopImmediatePropagation();
1981		fb_login();
1982	});
1983	$('div.g-signin2').click(function(e){
1984		$('body').addClass('go-login');
1985	});
1986	$('li.log-out a').click(function(e){
1987		signOut();
1988	});
1989	if($('a.promo_link').length > 0){
1990		$('a.promo_link').click(function(e){
1991			if($(this).attr('data-popup') > 0){
1992				e.preventDefault();
1993				if($('div.section-calculator').hasClass('active')){
1994					$('div.section-calculator,div.overlay_2').removeClass('active');
1995				}
1996				loadPromotion($(this));
1997			}
1998		});
1999	}
2000	if($('a.static-page').length > 0){
2001		$('a.static-page').click(function(e){
2002			e.preventDefault();
2003			e.stopImmediatePropagation();
2004			loadStatic($(this));
2005		});
2006	}
2007    $('.item-buy-info').on('click', '.toggle-arrow', function(e){
2008        e.preventDefault();
2009		e.stopImmediatePropagation();
2010        $(this).toggleClass('active', 200).parent().toggleClass('active', 200);
2011    });
2012	if($('a.availability_notification').length > 0){
2013		$('a.availability_notification').click(function(e){
2014			e.preventDefault();
2015			if($(this).attr('data-error')){
2016				alert($(this).attr('data-error'));
2017				return false;
2018			}
2019			var link=$(this);
2020			var id=$(this).attr('data-id');
2021			var user_id=$(this).attr('customer-id');
2022			$.ajax({
2023				type: "POST",
2024				url: '/external/notifications.php',
2025				data: {id_product:id,id_customer:user_id,tp:1,price:0},
2026				success: function(data){
2027					if($('html').attr('lang') == 'en-US'){
2028						$($(link).parent()).html('Subscribed');
2029					}else{
2030						$($(link).parent()).html('Абониран');
2031					}
2032					alert($(link).attr('data-success'));
2033				}
2034			});
2035		});
2036	}
2037	$('input[name="delivery_option"],input[name="pay-method"]').click(function(){
2038		addPaymentTax();
2039	});
2040	addPaymentTax();
2041	if($('li.save a').length > 0){
2042		$('li.save a').click(function(e){
2043			e.preventDefault();
2044			var link=$('li.save a');
2045			$.ajax({
2046				type: "POST",
2047				url: '/external/save_cart.php',
2048				data: {id_cart:$('#id_cart').val()},
2049				success: function(data){
2050					$(link).after('<div class="link2share save_msg active" style="color:#91a719;background:none;padding-right:0;">Количката е запазена за по-късно.</div>');
2051					setTimeout(function(){ $('div.save_msg').remove();$(link).remove(); }, 3000);
2052				}
2053			});
2054		});
2055	}
2056	makeTop();
2057	$('.status_popup_display').click(function(e){
2058		e.preventDefault();
2059		var id=$(this).attr('id').replace(/show-popup-/,'');
2060		$('.status-popup-'+id).addClass('active');
2061		$(this).addClass('active');
2062		$('.overlay_2').addClass('active').css('z-index', '9999');
2063	});
2064
2065    $('.close-popup,.overlay_2,.overlay,.close-leasing-popup,.dark_wrapper').on('click', function(e){
2066		e.preventDefault();
2067		if($('div.cc-window').length > 0){
2068			$('div.cc-window').show();
2069		}
2070        $('.overlay_2').removeClass('active');
2071		if($('.tab-popup').hasClass('active')){
2072			$('header').show();
2073			$('html, body').css({"overflow":"auto","height":"auto"});
2074			$('article.product_inner_page').hide();
2075			$($('.tab-popup').parent()).hide();
2076		}
2077		if($('html, body').css('overflow') == 'hidden'){
2078			$('html, body').css({"overflow":"auto","height":"auto"});
2079		}
2080		if($('.dark_wrapper').length > 0){
2081			$('.dark_wrapper').hide();	
2082		}
2083        $('.popup').removeClass('active');
2084    });
2085	if($('a.send_inquiry').length > 0){
2086		$('a.send_inquiry').click(function(e){
2087			e.preventDefault();
2088			var link=$(this);
2089			var id=$(this).attr('data-id');
2090			$('.request-popup-'+id).addClass('active');
2091			$(this).addClass('active');
2092			$('.overlay_2').addClass('active').css('z-index', '9999');
2093		});
2094		$("form.inquiry_form").submit(function(e) {
2095			e.stopImmediatePropagation();
2096			e.stopPropagation();
2097			//alert('123');
2098			var form=$(this);
2099			if($('html').attr('lang') == 'en-US'){
2100				$(form).find('input[type="submit"]').css('background','#990000').val('Please wait...');
2101			}else{
2102				$(form).find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
2103			}
2104			$.ajax({
2105				type: "POST",
2106				url: '/external/events.php',
2107				data: $(form).serialize(),
2108				success: function(data){
2109					console.log(data+'=============================');
2110					if(data == 'success'){
2111						if($('html').attr('lang') == 'en-US'){
2112							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">Your Inquiry has been sent successfully!</a>');
2113						}else{
2114							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">Вашето запитване беше изпратено успешно!</a>');
2115						}
2116					}else if(data == 'error'){
2117						if($('html').attr('lang') == 'en-US'){
2118							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">There was a server error, when trying to send to message. Please try again later!</a>');
2119						}else{
2120							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">Възникна проблем при изпращането на запитването! Моля опитайте по-късно</a>');
2121						}
2122					}
2123				}
2124			});
2125			e.preventDefault();
2126		});
2127	}
2128	if($('a.sh_contact_us').length > 0){
2129		$('a.sh_contact_us').click(function(e){
2130			e.preventDefault();
2131			var link=$(this);
2132			var id=$(this).attr('data-id');
2133			$('.contact-popup-'+id).addClass('active');
2134			$(this).addClass('active');
2135			$('.overlay_2').addClass('active').css('z-index', '9999');
2136		});
2137		$("form.sh_inquiry_form").submit(function(e) {
2138			e.stopImmediatePropagation();
2139			e.stopPropagation();
2140			//alert('123');
2141			var form=$(this);
2142			if($('html').attr('lang') == 'en-US'){
2143				$(form).find('input[type="submit"]').css('background','#990000').val('Please wait...');
2144			}else{
2145				$(form).find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
2146			}
2147			$.ajax({
2148				type: "POST",
2149				url: '/external/second_hand.php',
2150				data: $(form).serialize(),
2151				success: function(data){
2152					if(data == 'success'){
2153						if($('html').attr('lang') == 'en-US'){
2154							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">Your Inquiry has been sent successfully!</a>');
2155						}else{
2156							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">Вашето запитване беше изпратено успешно!</a>');
2157						}
2158					}else if(data == 'error'){
2159						if($('html').attr('lang') == 'en-US'){
2160							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">There was a server error, when trying to send to message. Please try again later!</a>');
2161						}else{
2162							$(form).html('<p style="color:#626c2f;text-align:center;margin-top:40px;padding:40px;">Възникна проблем при изпращането на запитването! Моля опитайте по-късно</a>');
2163						}
2164					}
2165				}
2166			});
2167			e.preventDefault();
2168		});
2169	}
2170}
2171function showSteps(tp){
2172	if($('input.delivery_option_radio').is(':checked')){
2173		$('div.disable_layer').hide();
2174	}else{
2175		$('div.disable_layer').show();
2176	}
2177}
2178function checkKey(e) {
2179    e = e || window.event;
2180	if($('ul.auto-suggestion').length > 0){
2181		
2182		if (e.keyCode == '38') {
2183			if($('ul.auto-suggestion').find('li.selected').length > 0){
2184				var selected=$('ul.auto-suggestion').find('li.selected');
2185				$('ul.auto-suggestion').find('li.selected').removeClass('selected');
2186				if($($(selected).prev()).attr('id')){
2187					$($(selected).prev().prev().prev()).addClass('selected');
2188				}else{
2189					$($(selected).prev()).addClass('selected');
2190				}
2191			}
2192		}else if (e.keyCode == '40') {
2193			if($('ul.auto-suggestion').find('li.selected').length > 0){
2194				var selected=$('ul.auto-suggestion').find('li.selected');
2195				$('ul.auto-suggestion').find('li.selected').removeClass('selected');
2196				if($($(selected).next()).hasClass('separator')){
2197					$($(selected).next().next().next()).addClass('selected');
2198				}else{
2199					$($(selected).next()).addClass('selected');
2200				}
2201			}else{
2202				$('ul.auto-suggestion').find('li:nth-child(2)').addClass('selected');
2203			}
2204		}else if (e.keyCode == '13') {
2205			if($('ul.auto-suggestion').find('li.selected').length > 0){
2206				//alert(e.keyCode);
2207				var selected=$('ul.auto-suggestion').find('li.selected');
2208				if($(selected).length > 0){
2209					$("#search_query_top").blur(); 
2210					if($(selected).find('a').hasClass('phs_article')){
2211						$(selected).find('a.phs_article').trigger('click');
2212					}else{
2213						location.href=$($(selected).find('a')).attr('href');
2214					}
2215				}
2216			}
2217		}
2218	}
2219
2220}
2221function showHideArrows(slideWidth){
2222	$('a.leasing-apply,a.go-apply').click(function(e){
2223		$('a.leasing-apply,a.go-apply').removeClass('active');
2224		$(this).addClass('active');
2225	});
2226	if($('td.schema').length > 0){
2227		$('td.schema').find('div.container1').click(function(){
2228			if($('.click_remove').length > 0 && !$($(this).parent()).hasClass('selected')){
2229				$('.click_remove').remove();
2230			}
2231			$('div.container1').css('background','#fff');
2232			$(this).css('background','#eaeed5');
2233		});
2234	}
2235	if($('#credit-table-schemes').css('left').replace(/px/,'') == 'auto'){
2236		var margin=0;
2237	}else{
2238		var margin= $('#credit-table-schemes').css('left').replace(/px/,'')*1;
2239	}
2240	if($( "#credit-table-schemes" ).width() <= (-1)*(margin - slideWidth)){
2241		$('a.switch_right').hide();
2242	}else{
2243		$('a.switch_right').show();
2244	}
2245	if(margin == 0){
2246		$('a.switch_left').hide();
2247	}else{
2248		$('a.switch_left').show();
2249	}
2250	$('a.switch_right').click(function(e){
2251		e.stopImmediatePropagation();
2252		e.preventDefault();
2253		var margin= $('#credit-table-schemes').css('left').replace(/px/,'')*1 - slideWidth;
2254		if($( "#credit-table-schemes" ).width() > margin){
2255			$( "#credit-table-schemes" ).animate({
2256				left: margin,
2257			}, 500, function() {
2258				showHideArrows(slideWidth);
2259			});
2260		}
2261
2262	});
2263	
2264	$('a.switch_left').click(function(e){
2265		e.stopImmediatePropagation();
2266		e.preventDefault();
2267		var margin= $('#credit-table-schemes').css('left').replace(/px/,'')*1 + slideWidth;
2268		$( "#credit-table-schemes" ).animate({
2269			left: margin,
2270		}, 500, function() {
2271			showHideArrows(slideWidth);
2272		});
2273	});
2274}
2275var displayedId = null;
2276var displayedLeasingId = null;
2277var schemas = new Array;
2278var initial = 0;
2279var stopclick = 0;
2280function roundEuroLaw(value) {
2281    const num = parseFloat(value);
2282    if (isNaN(num)) return '0.00';
2283
2284    const parts = num.toString().split('.');
2285    if (parts.length === 1) return num.toFixed(2); // Няма десетична част
2286
2287    let decimals = parts[1].padEnd(3, '0'); // гарантираме поне 3 цифри
2288    const thirdDigit = parseInt(decimals[2]);
2289
2290    // изходно число само с първите 2 знака
2291    let base = Math.floor(num * 100) / 100;
2292
2293    if (thirdDigit >= 5) {
2294        base += 0.01;
2295    }
2296
2297    return base.toFixed(2);
2298}
2299function reInitial(value,initial,stopclick){
2300	$('#initial_special').val(initial);
2301	if($('#initial_special').val() > 0 || 1){
2302		if (value > $('#full_amount').val()*1 || value < 0){
2303			value = 0;
2304		}
2305		if (value > 0){
2306		}else{
2307			value=0;
2308		}
2309		$('#leasingInitial').html(value+' '+($('#euro_conv').val()*1 > 1?'лв':'€'));
2310		if($('#leasingInitial_euro').length > 0){
2311			$('#leasingInitial_euro').html(roundEuroLaw(value/($('#euro_conv').val()*1))+' '+$('#obs_currency_symbol').val()+'');
2312		}
2313		$('#installment').val(value);
2314		initial = value;
2315		$('td.schema').each(function(){
2316			//alert(initial+'======'+$(this).attr('data-installment'));
2317			//console.log(initial+'============'+$(this).attr('full-amount')*1);
2318			if((parseInt(initial) >= $(this).attr('data-installment')*1 || $(this).attr('data-installment')*1 == 0) && $(this).attr('full-amount')*1 > 0){
2319				var amm=Math.round(100 * ($(this).attr('full-amount')*1 - value) * $(this).attr('data-coefficient') / $(this).attr('data-month')) / 100;
2320				amm=String(amm);
2321				$('#cost_' + $(this).attr('data-id')).html((amm.replace(/\..*$/,''))+'<sub>.'+(amm.replace(/^.*\./,''))+' '+($('#euro_conv').val()*1 > 1?'лв':'€')+' </sub>');
2322				$($('#cost_' + $(this).attr('data-id')).parent().parent()).attr('data-leasing-sum',($(this).attr('full-amount')*1 - value));
2323				$($('#cost_' + $(this).attr('data-id')).parent().parent()).attr('data-monthly-sum',amm);
2324				//console.log('==================1');
2325				if($('#euro_cost_' + $(this).attr('data-id')).length > 0){
2326					//console.log('==================2');
2327					amm=roundEuroLaw(amm/($('#euro_conv').val()*1));
2328					$('#euro_cost_' + $(this).attr('data-id')).html((amm.replace(/\..*$/,''))+'<sub>.'+(amm.replace(/^.*\./,''))+' '+($('#euro_conv').val()*1 < 1?'лв':'€')+' </sub>');
2329					$($('#euro_cost_' + $(this).attr('data-id')).parent().parent()).attr('data-leasing-sum',($(this).attr('full-amount')*1 - value));
2330					$($('#euro_cost_' + $(this).attr('data-id')).parent().parent()).attr('data-monthly-sum',amm);
2331				}
2332			}
2333		});
2334		if (displayedLeasingId!=null) {
2335			$('#logo_' + displayedLeasingId).hide();
2336			$('#info_' + displayedLeasingId).hide();
2337		}
2338		$('#amount_change').html($('span.cost_selected').html());
2339		if(stopclick == 0){
2340			$($('span.cost_selected').parent()).trigger('click');
2341		}
2342	}
2343}
2344
2345function recalculate(value) {
2346	if(!value*1){
2347		value=0;
2348	}	
2349	var initial=$('#initial_special').val();
2350	$('div.leasing-errors').html('');
2351	$('div.leasing-errors').hide();
2352	if($('#discount_name').val() != ''){
2353		
2354		if($('html').attr('lang') == 'en-US'){
2355			$('button.recalculate').css('background','#990000').html('Please wait...');
2356		}else{
2357			$('button.recalculate').css('background','#990000').html('Моля изчакайте...');
2358		}
2359		$.ajax({
2360			type: "POST",
2361			url: '/bg/quick-order',
2362			data: {discount_name:$('#discount_name').val(),is_promo_code:1},
2363			success: function(data){
2364				var data = JSON.parse(data); 
2365				if(parseInt(data.has_error) > 0){
2366					$('div.leasing-errors').html('');
2367					$('div.leasing-errors').show();
2368					for(var i=0;i<data.errors.length;i++){
2369						$('div.leasing-errors').html($('div.leasing-errors').html()+data.errors[i]);
2370					}
2371					reInitial(value,initial,0);
2372				}else{
2373					if($('#leasing_popup_holder').length > 0){
2374						var link=$('a[data-id-product="'+$('#product_id').val()+'"].leasing_go');
2375						$.ajax({
2376							type: "POST",
2377							url: '/external/calculator.php',
2378							data: {id_product:$(link).attr('data-id-product'),lang_iso:$(link).attr('data-lang-iso'),token:$(link).attr('data-token'),logged:$(link).attr('data-logged'),is_guest:$(link).attr('data-is-guest')},
2379							success: function(data){
2380								$('#leasing_popup_holder').html(data);
2381								$('.overlay_2').addClass('active').css('z-index', '9999');
2382								$('div.section-calculator').css('top',$(document).scrollTop()*1+50);
2383								$('div.section-calculator').css('overflow','auto');
2384								$('div.section-calculator').css('height',$(window).height());
2385								$('div.section-calculator').css('overflow','auto');
2386								if($('div.section-calculator div.left-section-side').innerHeight() <= $(window).height()){
2387									$('div.section-calculator').css('width','720px');
2388								}
2389								if($('div.credit-box').length > 0 && $('div.credit-box').is(':visible') && !$('div.shopping-cart').length){
2390									showHideArrows(564);
2391								}
2392								$('.close-popup,.overlay_2,.overlay,.close-leasing-popup').on('click', function(e){
2393									e.preventDefault();
2394									$('.overlay_2').removeClass('active');
2395									$('.popup').removeClass('active');
2396								});
2397								reInitial(value,initial,0);
2398							}
2399						});	
2400					}
2401				}
2402				if($('html').attr('lang') == 'en-US'){
2403					$('button.recalculate').css('background','#91a719').html('Recalculate');
2404				}else{
2405					$('button.recalculate').css('background','#91a719').html('Преизчисли');
2406				}
2407			}
2408		});
2409	}else{
2410		reInitial(value,initial,0);
2411	}
2412}
2413function setLeasingSums(sum,id,min_credit_sum,min_monthly_sum,el){
2414	var check_sum=$(el).attr('data-leasing-sum');
2415	var monthly_payment=$(el).attr('data-monthly-sum');
2416	$('#full_amount').val(sum);
2417	$('#id_cart_rule').val(id);
2418	$($('#full_amount').next()).find('b').html(sum);
2419	var has_error=0;
2420	$('div.leasing-errors').html('');
2421	$('.sum_error').remove();
2422	if(check_sum*1 < min_credit_sum*1){
2423		has_error=1;
2424		$('div.leasing-errors').show();
2425		if($('body').hasClass('lang_bg')){
2426			var error_msg1='Минималната сума за кандидатстване за кредит, според изискванията на кредитодателите, е '+min_credit_sum+' '+$('#obs_currency_symbol').val()+'';
2427		}else{
2428			var error_msg1='The minimum amount to apply for a loan, as required by lenders, is '+min_credit_sum+' lv';
2429		}
2430		if($('#id_cart').length > 0){
2431			$('a.go_step_3').before('<p class="order_error sum_error">'+error_msg1+'</p>');
2432		}else{
2433			if($('div.leasing-errors').length > 0){
2434				$('div.leasing-errors').prepend('<div class="sum_error" style="padding:0 20px;">'+error_msg1+'</div>');
2435			}else{
2436				$('div.head-info').after('<div class="leasing-errors"><div class="sum_error" style="padding:0 20px;">'+error_msg1+'</div></div>');
2437			}
2438		}
2439	}
2440	if(monthly_payment*1 < min_monthly_sum*1){
2441		has_error=1;
2442		$('div.leasing-errors').show();
2443		if($('body').hasClass('lang_bg')){
2444			var error_msg2='Минималната стойност на месечната вноска, според изискванията на кредитодателите, е '+min_monthly_sum+' '+$('#obs_currency_symbol').val()+'';
2445		}else{
2446			var error_msg2='The minimum monthly installment, as required by lenders, is '+min_monthly_sum+' lv';
2447		}
2448		if($('#id_cart').length > 0){
2449			$('a.go_step_3').before('<p class="order_error sum_error">'+error_msg2+'</p>');
2450		}else{
2451			if($('div.leasing-errors').length > 0){
2452				$('div.leasing-errors').prepend('<div class="sum_error" style="padding:0 20px;">'+error_msg2+'</div>');
2453			}else{
2454				$('div.head-info').after('<div class="leasing-errors"><div class="sum_error" style="padding:0 20px;">'+error_msg2+'</div></div>');
2455			}
2456		}
2457	}
2458	if(has_error > 0){
2459		$($('div.call_to_action').parent()).find('a').hide();
2460	}else{
2461		$($('div.call_to_action').parent()).find('a').show();
2462		$('div.leasing-errors').hide();
2463	}
2464}
2465function checkInitialValue(id,el){
2466	if($('#initial_special').val()*1 > $(el).attr('data-monthly-sum')*1 && $(el).attr('data-max-initial-payment') == 'month'){
2467		alert('Въведената първоначална вноска е по-висока от '+(Math.round(($(el).attr('data-monthly-sum')*1 + Number.EPSILON) * 100) / 100)+''+($('#euro_conv').val()*1 > 1?'лв':'€')+', което е максималната за избраната схема на изплащане');
2468		return 0;
2469	}
2470	if($('#initial_special').val()*1 < $(el).attr('data-monthly-sum')*1 && $(el).attr('data-min-initial-payment') == 'month'){
2471		alert('Въведената първоначална вноска е по-ниска от '+(Math.round(($(el).attr('data-monthly-sum')*1 + Number.EPSILON) * 100) / 100)+''+($('#euro_conv').val()*1 > 1?'лв':'€')+', което е минималната за избраната схема на изплащане');
2472		return 0;
2473	}
2474	if($('#initial_special').val()*1 > $(el).attr('data-max-initial-payment')*1 && $(el).attr('data-max-initial-payment')*1 > 0){
2475		alert('Въведената първоначална вноска е по-висока от '+$(el).attr('data-max-initial-payment')+''+($('#euro_conv').val()*1 > 1?'лв':'€')+', което е максималната за избраната схема на изплащане');
2476		return 0;
2477	}
2478	if($('#initial_special').val()*1 < $(el).attr('data-min-initial-payment')*1 && $(el).attr('data-min-initial-payment')*1 > 0){
2479		alert('Въведената първоначална вноска е по-ниска от '+$(el).attr('data-min-initial-payment')+''+($('#euro_conv').val()*1 > 1?'лв':'€')+', което е минималната за избраната схема на изплащане');
2480		return 0;
2481	}
2482	if($('#initial_special').val()*1 > 0 && $(el).attr('data-no-initial-payment')*1){
2483		alert('Избраната кредитна схема не позволява въвеждането на първоначална вноска. Моля премахнете я и след това изберете схемата, ако все още желаете.');
2484		$('#initial_special').val(0);
2485		recalculate(0);
2486		return 0;
2487	}
2488	return 1;
2489}
2490function selectSchema(id, leasingName, leasingLength, coefficient, leasingId, gpr, glp,provider,input_fields,need_docs,upload_text,file_list,confirm_docs,initial_payment,initial_payment_tp,promo,auto_start,el) {
2491	if(checkInitialValue(id,el)*1 == 0){
2492		$('#schema_'+id).css('background','#fff');
2493		$(el).removeClass('selected');
2494		return false;
2495	}
2496	if($('#allowed_schemas').length > 0){
2497		var allowed_data=$('#allowed_schemas').val();
2498		allowed_data=allowed_data.split('!!!');
2499		if(allowed_data.length > 0 && $('#allowed_schemas').val() != '' && promo*1){
2500			var allowed=1;
2501			if($('body').hasClass('lang_bg')){
2502				var error_msg='Промоционалната схема за покупка на изплащане "'+leasingName+'" не е валидна за следните продукти: ';
2503			}else{
2504				var error_msg='The promotional scheme for leasing "'+leasingName+'" is not valid for the following products: ';
2505			}
2506			for(var i=0;i<allowed_data.length;i++){
2507				var promo_schemas=allowed_data[i].replace(/;name:.*$/,'').replace(/^promo_schemas:/,'');
2508				var name=allowed_data[i].replace(/^.*;name:/,'');
2509				promo_schemas=promo_schemas.split(',');
2510				if(promo_schemas.indexOf(leasingId) <= -1){
2511					allowed=0;
2512					error_msg += name +',';
2513				}
2514			}
2515			if($('body').hasClass('lang_bg')){
2516				error_msg = error_msg.replace(/,$/,'.') +  ' Моля, изберете друга схема на изплащане или премахнете от количката продуктите, за които не е валидна избраната промоционална схема.';
2517			}else{
2518				error_msg = error_msg.replace(/,$/,'.') +  ' Please select another leasing scheme or remove the products for which the selected promotional scheme is not valid.';
2519			}
2520			if(!parseInt(allowed) && !parseInt(auto_start)){
2521				alert(error_msg);
2522				$('#schema_'+id).css('background','#fff');
2523				$($('#schema_'+id).parent()).removeClass('selected');
2524				$('td.schema.selected').find('div.box').css('background','#eaeed5');
2525				return false;
2526			}else if(parseInt(auto_start)){
2527				//alert(error_msg);
2528				$('div.order-now a.go_step_3').before('<p class="order_error">'+error_msg+'</p>');
2529				$('#schema_'+id).css('background','#fff');
2530				$($('#schema_'+id).parent()).removeClass('selected');
2531				$('td.schema.selected').find('div.box').css('background','#eaeed5');
2532				return false;
2533			}
2534		}
2535		if(initial_payment > 0){
2536			if(initial_payment_tp == 2){
2537
2538				var current=$('#initial_special').val();
2539				var sum=Math.round(($('#total_order_price').val()*initial_payment)/100);
2540				
2541				if(current < sum){
2542					$('div.head-info').after('<div class="leasing-errors">Този кредитен план изисква минимална първоначална вноска от '+sum+''+$('#obs_currency_symbol').val()+'</div>');
2543					reInitial(sum,sum,1);
2544					$('#initial_special').val(sum);
2545				}
2546			}else{
2547				var current=$('#initial_special').val();
2548				var sum=Math.round(initial_payment);
2549				
2550				if(current < initial_payment){
2551					$('div.head-info').after('<div class="leasing-errors">Този кредитен план изисква минимална първоначална вноска от '+Math.round(initial_payment)+''+$('#obs_currency_symbol').val()+'</div>');
2552					reInitial(sum,sum,1);
2553					$('#initial_special').val(sum);
2554				}
2555				
2556			}
2557		}else if(!$('div.sum_error').length){
2558			
2559			$('div.leasing-errors').html('');
2560			$('div.leasing-errors').hide();
2561		}
2562		if(upload_text != ''){
2563			$('div.input-file').find('div.text').html(upload_text);
2564		}
2565		var files=file_list.split(',');
2566		var mandatory=confirm_docs.split(',');
2567		//alert(mandatory);
2568		var build_html='';
2569		var not_confirm='';
2570		if(files.length > 0){
2571			$('div.cart-steps-box').find('div.checkbox').remove();
2572			for(var i=0;i <= files.length;i++){
2573				var cnt=i+1;
2574				if(files[i] && confirm_docs.indexOf(cnt) > -1){
2575					build_html+='<div class="input-group checkbox clearfix"><input type="checkbox" msg="Не можете да кандидатствате за лизинг, докато не прочетете и не се съгласите с '+files[i]+'" name="app_agree_'+cnt+'" class="app_agree comparator not_uniform" value="1" id="app_agree_'+cnt+'"><label for="app_agree_'+cnt+'"> <span>Прочетох и разбрах записаното в документа <a id="link_'+cnt+'" style="display:inline;" href="/download/credit/'+leasingId+'_document_'+cnt+'.pdf"  target="_blank">„'+files[i]+'”</a></label><div class="cleaner"></div></div>';
2576				}
2577				if(files[i] && confirm_docs.indexOf(cnt) <= -1){
2578					not_confirm+='<li><a id="link_'+cnt+'" style="display:inline;color:#333;" href="/download/credit/'+leasingId+'_document_'+cnt+'.pdf" target="_blank">'+files[i]+'</a></li>';
2579				}
2580			}
2581		}
2582		build_html+=(not_confirm?'<div class="cleaner"></div><div class="input-group checkbox clearfix"><br /><strong>Други документи:</strong><br /><ol>'+not_confirm:'');
2583		build_html+=(not_confirm?'</ol></div>':'');
2584		$('div.input-file').after(build_html+'<div class="cleaner"></div>');
2585		var fields=input_fields.split(',');
2586		if(fields.length > 0){
2587			for(var i=0;i < fields.length;i++){
2588				if(fields[i] == 'card_copy'){
2589					$('div.cart-steps-box').find('input[name="'+fields[i]+'"]').parent().parent().css('display','table');
2590					$($('div.cart-steps-box').find('input[name="'+fields[i]+'"]').parent()).append('<input type="hidden" name="files_cnt" id="files_cnt" value="'+need_docs+'">');
2591				}else{
2592					$('div.cart-steps-box').find('textarea[name="'+fields[i]+'"]').parent().css('display','block');
2593					$('div.cart-steps-box').find('input[name="'+fields[i]+'"]').parent().css('display','block');
2594					$('div.cart-steps-box').find('select[name="'+fields[i]+'"]').parent().parent().css('display','block');
2595				}
2596			}
2597		}
2598	}else{
2599		if(initial_payment > 0){
2600			var current=$('#initial_special').val();
2601			if(initial_payment_tp == 2){
2602				var sum=Math.round(($('#full_amount').val()*initial_payment)/100);
2603				$('#initial_special').val(sum);
2604				if(current < sum){
2605					recalculate(sum);
2606					$('div.leasing-errors').show();
2607					$('div.leasing-errors').html('Този кредитен план изисква минимална първоначална вноска от '+sum+''+$('#obs_currency_symbol').val()+'');
2608				}
2609
2610			}else{
2611				$('#initial_special').val(Math.round(initial_payment));
2612				if(current < Math.round(initial_payment)){
2613					recalculate(sum);
2614					recalculate(Math.round(initial_payment));
2615					$('div.leasing-errors').show();
2616					$('div.leasing-errors').html('Този кредитен план изисква минимална първоначална вноска от '+Math.round(initial_payment)+''+$('#obs_currency_symbol').val()+'');
2617				}
2618
2619			}
2620		}else{
2621			$('#initial_special').removeAttr('disabled')
2622		}
2623	}
2624
2625	$('#on_leasing').html(($('#full_amount').val()*1 - $('#installment').val()*1)+' '+($('#euro_conv').val()*1 > 1?'лв':'€')+'');
2626	if($('#on_leasing_euro').length > 0){
2627		$('#on_leasing_euro').html(roundEuroLaw(($('#full_amount').val()*1 - $('#installment').val()*1)/($('#euro_conv').val()*1))+' '+($('#euro_conv').val()*1 < 1?'лв':'€'));
2628	}
2629	if (displayedId!=null && displayedId!=id) {
2630		$('#selected_' + displayedId).hide();
2631		$('#selector_' + displayedId).show();
2632		$('#cost_' + displayedId).removeClass('cost_selected');
2633	}
2634	$('#selector_' + id).hide();
2635	$('#selected_' + id).show();
2636	$('#cost_' + id).addClass('cost_selected');
2637	displayedId = id;
2638
2639	if (displayedLeasingId!=null && displayedLeasingId!=leasingId) {
2640		$('#logo_' + displayedLeasingId).hide();
2641		$('#info_' + displayedLeasingId).hide();
2642	}
2643	$('#logo_' + leasingId).show();
2644	$('#info_' + leasingId).show();
2645	displayedLeasingId = leasingId;
2646	$('#leasingName').html(leasingName);
2647	if(!parseInt(initial) || 1){
2648		initial=$('#initial_special').val();
2649	}
2650	//alert(initial);
2651	$('#leasingMonths').html(leasingLength + ' X ' + Math.round(100 * ($('#full_amount').val()*1 - initial) * coefficient / leasingLength) / 100 + ' '+($('#euro_conv').val()*1 > 1?'лв':'€')+' ');
2652	if($('#leasingMonths_euro').length > 0){
2653		$('#leasingMonths_euro').html(leasingLength + ' X ' + roundEuroLaw((Math.round(100 * ($('#full_amount').val()*1 - initial) * coefficient / leasingLength) / 100)/($('#euro_conv').val()*1))+' '+($('#euro_conv').val()*1 < 1?'лв':'€'));
2654	}
2655	$('#leasingGPR').html(gpr +' %');
2656	$('#leasingGLP').html(glp +' %');
2657	$('#leasingGLPTotal').html(leasingLength*Math.round(100 * ($('#full_amount').val()*1 - initial) * coefficient / leasingLength) / 100 + ' '+($('#euro_conv').val()*1 > 1?'лв':'€')+' ');
2658	if($('#leasingGLPTotal_euro').length > 0){
2659		$('#leasingGLPTotal_euro').html(roundEuroLaw((leasingLength*Math.round(100 * ($('#full_amount').val()*1 - initial) * coefficient / leasingLength) / 100)/($('#euro_conv').val()*1)) + ' '+($('#euro_conv').val()*1 < 1?'лв':'€'));
2660	}
2661	$('#id_credit').val(leasingId);
2662	$('#monthly_payments').val(Math.round(100 * ($('#full_amount').val()*1 - initial) * coefficient / leasingLength) / 100);
2663	$('#months').val(leasingLength);
2664	$('#gpr').val(gpr);
2665	$('#id_payment').val(id);
2666	if(el){
2667		$('#credit-table-schemes').find('td.schema').removeClass('selected');
2668		$(el).addClass('selected');
2669	}
2670	$('#glp').val(glp);
2671	$('#result_column').show();
2672	if($('#allowed_schemas').length > 0){
2673		$('#creditor_logo').attr('src','/img/credit/l/'+leasingId+'.jpg');
2674		$('#link_1').attr('href','/download/credit/'+leasingId+'_document.pdf');
2675		$('#link_2').attr('href','/download/credit/'+leasingId+'_document_2.pdf');
2676		if(provider != 1){
2677			$('#leasing_form').fadeIn();
2678		}else{
2679			$('#leasing_form').hide();
2680		}
2681	}
2682}
2683function leasingPopup(){
2684	$('a.leasing_go').click(function(e){
2685		e.preventDefault();
2686		if(!($('.admin-controls').length > 0) && 0){
2687			$('.popup-block-orders').addClass('active');
2688			$('.overlay_2').addClass('active').css('z-index', '9999');
2689			return false;
2690		}
2691		if($('div.cant-leasing').length > 0){
2692			alert('Вече сте добавили в количката си продукт, който не може да бъде купен на изплащане. Можете да го премахнете или да направите отделна поръчка с продуктите, които искате да купите на изплащане.');
2693			return false;
2694		}
2695		if($('#leasing_popup_holder').length > 0){
2696			$.ajax({
2697				type: "POST",
2698				url: '/external/calculator.php',
2699				data: {id_product:$(this).attr('data-id-product'),lang_iso:$(this).attr('data-lang-iso'),token:$(this).attr('data-token'),logged:$(this).attr('data-logged'),is_guest:$(this).attr('data-is-guest')},
2700				success: function(data){
2701					$('#leasing_popup_holder').html(data);
2702					$('.overlay_2').addClass('active').css('z-index', '9999');
2703					$('div.section-calculator').css('top',$(document).scrollTop()*1+50);
2704					$('div.section-calculator').css('overflow','auto');
2705					$('div.section-calculator').css('height',$(window).height());
2706					$('div.section-calculator').css('overflow','auto');
2707					if($('div.section-calculator div.left-section-side').innerHeight() <= $(window).height()){
2708						$('div.section-calculator').css('width','720px');
2709					}
2710					if($('div.credit-box').length > 0 && $('div.credit-box').is(':visible') && !$('div.shopping-cart').length){
2711						showHideArrows(564);
2712					}
2713					$('.close-popup,.overlay_2,.overlay,.close-leasing-popup').on('click', function(e){
2714						e.preventDefault();
2715						$('.overlay_2').removeClass('active');
2716						$('.popup').removeClass('active');
2717					});
2718				}
2719			});	
2720		}else{
2721			var el = this.hash.replace(/#/,'');
2722			$('html, body').css({"overflow":"hidden","height":"100%"});
2723			$('#'+el).show();
2724			$('article.product_inner_page').show();
2725			$('.tab-popup.'+el).css('top',$(document).scrollTop()*1+50);
2726			$('.tab-popup.'+el).css('overflow','auto');
2727			$('.tab-popup.'+el).css('height',$(window).height());
2728			$('.tab-popup.'+el).addClass('active');
2729			$('.overlay_2').addClass('active').css('z-index', '9999');
2730			$('#mCSB_3_container').css('left','0');
2731			$('#mCSB_3_dragger_horizontal').css('left','0');
2732			if($('div.section-calculator div.left-section-side').innerHeight() <= $(window).height()){
2733				$('div.section-calculator').css('width','720px');
2734			}
2735			if($('div.credit-box').length > 0 && $('div.credit-box').is(':visible') && !$('div.shopping-cart').length){
2736				showHideArrows(564);
2737			}
2738		}
2739
2740	});
2741}
2742function ProductList(){
2743	var products='';
2744	$('#products_table').find('input.return_product').each(function(){
2745		if($(this).is(':checked')){
2746			var nm=$($(this).parent()).next().html();
2747			if(products == ''){
2748				products=nm;
2749			}else{
2750				products += ', '+nm;
2751			}
2752		}
2753	});
2754	$('#returned_kzp').val(products);
2755}
2756
2757// ========================================================================================
2758function shuffleWord(w) {
2759	if (w.length < 3) return w.split("").sort(() => Math.random() - 0.5).join("");
2760	const first = w[0], last = w[w.length - 1];
2761	const mid = w.slice(1, -1).split("");
2762	for (let i = mid.length - 1; i > 0; i--) {
2763	const j = Math.floor(Math.random() * (i + 1));
2764	[mid[i], mid[j]] = [mid[j], mid[i]];
2765	}
2766	return first + mid.join("") + last;
2767}
2768function scrambleTextShuffle(txt) {
2769	return txt.split(/(\s+|[.,!?;:"'()\[\]{}—–-]+)/u)
2770	.map(token => /^[\p{L}\p{N}]{2,}$/u.test(token) ? shuffleWord(token) : token)
2771	.join("");
2772}
2773function selectionInside(el) {
2774	const sel = window.getSelection();
2775	if (!sel || sel.isCollapsed) return false;
2776	const a = sel.anchorNode, f = sel.focusNode;
2777	return el.contains(a) && el.contains(f);
2778}
2779function onCopyLike(e) {
2780	const target = e.currentTarget;
2781	if (!selectionInside(target)) return;
2782	const sel = window.getSelection();
2783	const txt = sel.toString();
2784	if (!txt) return;
2785
2786	const garbled = scrambleTextShuffle(txt);
2787	e.preventDefault();
2788	if (e.clipboardData) {
2789		e.clipboardData.setData("text/plain", garbled);
2790		e.clipboardData.setData("text/html", `<span>${garbled.replace(/</g,"&lt;")}</span>`);
2791	}
2792}
2793function attach() {
2794	document.querySelectorAll('#section-description').forEach(el => {
2795		el.addEventListener("copy", onCopyLike);
2796		el.addEventListener("cut", onCopyLike);
2797	});
2798	document.querySelectorAll('#section-full-feature').forEach(el => {
2799		el.addEventListener("copy", onCopyLike);
2800		el.addEventListener("cut", onCopyLike);
2801	});
2802	document.querySelectorAll('#section-content-box').forEach(el => {
2803		el.addEventListener("copy", onCopyLike);
2804		el.addEventListener("cut", onCopyLike);
2805	});
2806}
2807
2808if (document.readyState === "loading") {
2809	document.addEventListener("DOMContentLoaded", attach);
2810} else {
2811	attach();
2812}
2813$(document).ready(function(){
2814	init();
2815
2816	if($('div.category-description').length > 0 && $('div.category-description div.description-inner').height() > 300){
2817		$('div.category-description div.description-inner').css('height','300px').css('overflow','hidden').css('padding-bottom','50px');
2818		$('div.category-description div.description-inner').after('<a href="#" class="show-more-desc" style="margin-top:20px;display:inline-block;">Виж повече</a>');
2819		$('a.show-more-desc').click(function(e){
2820			e.preventDefault();
2821			$(this).remove();
2822			$('div.description-inner').addClass('no-shadow');
2823			$('div.category-description div.description-inner').css('height','auto').css('overflow','auto').css('padding-bottom','0px');
2824		});
2825	}
2826	document.onkeydown = checkKey;
2827	if($('div.credit-box').length > 0 && $('div.shopping-cart').length > 0){
2828		showHideArrows(696);
2829		
2830	}
2831	if($('div.peak-video a').length > 0){
2832		$('div.peak-video a').click(function(e){
2833			e.preventDefault();
2834			$($(this).parent()).find('iframe').show();
2835			$(this).remove();
2836			
2837		});
2838	}
2839	if($('form.reclamation-form').length > 0){
2840		$('#add_address').click(function(){
2841			$('#new_address').show();
2842			$('#firstname').val($('#contact_firstname').val());
2843			$('#lastname').val($('#contact_lastname').val());
2844			$('#phone').val($('#contact_phone').val());
2845			$('#speedy_deliver').hide();
2846		});
2847		$('#speedy_office').click(function(){
2848			$('#new_address').hide();
2849			$('#speedy_deliver').show();
2850		});
2851		$('#contact_person').click(function(){
2852			$('#new_company_owner').hide();
2853			$('#new_owner').hide();
2854		});
2855		$('#add_owner').click(function(){
2856			$('#new_owner').show();
2857			$('#new_company_owner').hide();
2858		});
2859		$('#add_company_owner').click(function(){
2860			$('#new_company_owner').show();
2861			$('#new_owner').hide();
2862		});
2863		$('#city').chosen({width:'100%',height:38});
2864		$('#id_manufacturer').chosen({width:'100%',height:38});
2865		$('#send-reclamation').click(function(e){
2866			$('form.reclamation-form').prepend('<input type="hidden" name="savety" value="681">');
2867		});
2868	}
2869	if($('form.return-form').length > 0){
2870		ProductList();
2871		$('#add_address').click(function(){
2872			$('#new_address').show();
2873			$('#speedy_deliver').hide();
2874			$('#order_address').hide();
2875		});
2876		$('#id_address_delivery').click(function(){
2877			$('#new_address').hide();
2878			$('#speedy_deliver').hide();
2879			$('#order_address').show();
2880			$('#address_kzp').val($('#def-o-addr').html());
2881		});
2882		$('#speedy_office').click(function(){
2883			$('#new_address').hide();
2884			$('#order_address').hide();
2885			$('#speedy_deliver').show();
2886			if($('#address_kzp').length > 0){
2887				$('#address_kzp').val($('#office_id').val());
2888			}
2889		});
2890		$('#new_address').find('input').keyup(function(){
2891			$('#address_kzp').val($('#city').val()+($('#post_code').val() != ''?' '+$('#post_code').val():'')+($('#quarter').val() != ''?', кв. '+$('#quarter').val():'')+($('#street').val() != ''?', ул. '+$('#street').val():'')+($('#street_number').val() != ''?' '+$
2891('#street_number').val():'')+($('#block').val() != ''?', бл. '+$('#block').val():'')+($('#entrance').val() != ''?', вх. '+$('#entrance').val():'')+($('#apartment').val() != ''?', ап. '+$('#apartment').val():''));
2892		});
2893		$('#send-return').click(function(e){
2894			$('form.return-form').prepend('<input type="hidden" name="savety" value="681">');
2895		});
2896		$('#city').chosen({width:'100%',height:38});
2897
2898		$('.return_product').click(function(){	
2899			ProductList();
2900			if($(this).is(':checked')){
2901				$(this).parent().parent().find('td').css('background','#fff');
2902				$(this).parent().parent().find('td').css('color','#000');
2903				$(this).parent().parent().find('.select,input[type="text"]').show();
2904			}else{
2905				$(this).parent().parent().find('td').css('color','#999');
2906				$(this).parent().parent().find('td').css('background','#ccc');
2907				$(this).parent().parent().find('.select,input[type="text"]').hide();
2908			}
2909		});
2910		$('#searchOrder').click(function(){	
2911			$('#searchOrder').val('Моля изчакайте...');
2912			$('#searchOrder').attr('style','background:#333;');
2913			$.ajax({
2914				type: "POST",
2915				url: '/external/order-products.php?id_order='+$('#id_order').val(),
2916				data: {p:$('#protector').val()},
2917				success: function(data){
2918					$('#order-products').html(data);
2919					if($('#products_table').length > 0){
2920						$('#return_info').show();
2921						$('#hover_remove').show();
2922						$('#searchOrder').val('Търсене');
2923						$('#searchOrder').attr('style','background:#91a719;');
2924					}else{
2925						$('#return_info').hide();
2926						$('#hover_remove').hide();
2927						$('#searchOrder').val('Търсене');
2928						$('#searchOrder').attr('style','background:#91a719;');
2929					}
2930
2931
2932				}
2933			});
2934		});
2935
2936	}
2937	$('#section-description img').each(function(){
2938		if($(this).width() > 500){
2939			$(this).css('margin-left',0).css('margin-right',0);
2940		}
2941	});
2942	var discounts=($('#total_discount_codes').length > 0?parseInt($('#total_discount_codes b').html().replace(/,/,'.')):0);
2943	var the_total_price=parseInt($('#total_products').val());
2944	$('label.option_select').click(function(){
2945		if($(this).prev().val() == 10 && $('.change_delivery').find('b').html() != '0,00' && $('.change_delivery').find('b').html() != 'БЕЗПЛАТНА' && $('.change_delivery').find('b').html() != 'FREE'){
2946			$('#total_order_price').val($('#total_order_price').val()-$('.change_delivery').find('b').html().replace(/,/,'.')*1);
2947			var def_p=$('.full_total').find('b').html().replace(/,/,'.')*1-$('.change_delivery').find('b').html().replace(/,/,'.')*1;
2948			$('.full_total').find('b').html(def_p);
2949			if($('.euro-price').length > 0){
2950				$($('.full_total').parent().find('.euro-price')).find('b').html(roundEuroLaw(def_p/($('#euro_conv').val()*1)));
2951			}
2952			$('.change_delivery').find('span').html('<b>0,00</b> '+$('#obs_currency_symbol').val()+'');
2953		}else if($(this).prev().val() == 12 && $('#carrier_id').val() == 1 && $('.change_delivery').find('b').html() != ''+$('#econt_shipping').val()+',00'){
2954		//}else if($(this).prev().val() == 12 && $('#carrier_id').val() == 1 && the_total_price < $('#free_shipping').val() && $('.change_delivery').find('b').html() != '8,00'){
2955			$('.change_delivery').find('span').html('<b>'+$('#econt_shipping').val()+',00</b> '+$('#obs_currency_symbol').val()+'');
2956			var the_total=$('#total_products').val()*1 + $('#total_insurance').val()*1 + $('#econt_shipping').val()*1 - discounts;
2957			the_total_fixed=the_total.toFixed(2);
2958			$('#total_order_price').val(the_total);
2959			$('.full_total').find('b').html(the_total_fixed);
2960			if($('.euro-price').length > 0){
2961				$($('.full_total').parent().find('.euro-price')).find('b').html(roundEuroLaw(the_total/($('#euro_conv').val()*1)));
2962			}
2963		}else if(the_total_price < $('#free_shipping').val() && $('.change_delivery').find('b').html() != ''+$('#speedy_shipping').val()+',00'){
2964			$('.change_delivery').find('span').html('<b>'+$('#speedy_shipping').val()+',00</b> '+$('#obs_currency_symbol').val()+'');
2965			var the_total=$('#total_products').val()*1 + $('#total_insurance').val()*1 + $('#speedy_shipping').val()*1 - discounts;
2966			the_total_fixed=the_total.toFixed(2);
2967			$('#total_order_price').val(the_total);
2968			$('.full_total').find('b').html(the_total_fixed);
2969			if($('.euro-price').length > 0){
2970				$($('.full_total').parent().find('.euro-price')).find('b').html(rou
2970ndEuroLaw(the_total/($('#euro_conv').val()*1)));
2971			}
2972		}
2973		$('div.disable_layer').hide();
2974	});
2975	showSteps();
2976	$('input[name="card_copy"]').change(function() {
2977		var files_cnt=$('input[name="files_cnt"]').val();
2978		var file ='';
2979		for(var i=0;i<files_cnt;i++){
2980			file += (typeof $('input[name="card_copy"]')[0].files[i] != 'undefined'?$('input[name="card_copy"]')[0].files[i].name:'')+'<br />';
2981		}
2982		$($(this).parent()).next().html('<strong>Прикачен файл:</strong><br />'+file);
2983	});
2984	/*
2985	$('a.leasing_go').click(function(e){
2986		e.preventDefault();
2987		$("html, body").animate({
2988				scrollTop: $(this.hash).offset().top
2989		}, 600);
2990	});
2991	*/
2992	$('div.img-slider button.toggle-btn').click(function(){
2993		$(this).toggleClass('active');
2994		$('#rest_images').slideToggle('slow');
2995	});
2996	loadFromUrl($('#article_url').val());
2997	if($('div.notf-info').length > 0){
2998		$('div.notf-info a').click(function(e){
2999			//e.preventDefault();
3000			var notf_id=$($(this).parent()).attr('data-id');
3001			//alert(notf_id);
3002			$.ajax({
3003				type: "POST",
3004				url: '/external/notf_read.php',
3005				data: {id:notf_id}
3006			});
3007		});
3008		$('div.notf-edit a.remove-item').click(function(e){
3009			e.preventDefault();
3010			if(confirm('Наистина ли искате да изтриете съобщението?')){
3011				var id=$(this).attr('data-id');
3012				var row=$(this);
3013				$.ajax({
3014					type: "POST",
3015					url: '/index.php?controller=notifications',
3016					data: {delete_message:1,id:id},
3017					success:function(data){
3018						if($('#load_container').length > 0){
3019							$('#load_container').load('/my-account #load_container_inner');
3020						}else{
3021							$(row).parent().parent().remove();
3022						}
3023					}
3024				});
3025			}
3026		});
3027
3028		if($('#seach_field').length > 0){
3029		
3030			$('#seach_field').keyup(function(e){
3031				e.stopPropagation();
3032				e.stopImmediatePropagation();
3033				var search=$(this).val();
3034				
3035				$('div.notifications-row').each(function(){
3036					var toCheck=$(this).find('h3').html();
3037					re = new RegExp(search, 'gi');
3038					if(!toCheck.match(re)){
3039						$(this).hide();
3040					}else{
3041						$(this).show();
3042					}
3043				});
3044			});
3045		}
3046	}
3047	selectDropdown($('select'));
3048	if($('div.cart-steps').length > 0){
3049		manageOrderAddresses();
3050	}
3051	$('#section-calculator').show();
3052	if($('a.calculator').length > 0){
3053		$('a.calculator').click(function(e){
3054			e.preventDefault();
3055			$('.overlay_2').removeClass('active');
3056			$('.popup').removeClass('active');
3057			$('.insurance-popup').addClass('active');
3058			$(this).addClass('active');
3059			$('.overlay_2').addClass('active').css('z-index', '9999');
3060		});
3061	}
3062
3063	if($('#section-accessories').length > 0){
3064		$('#section-accessories nav.tabs-nav').find('a').click(function(){
3065			var id_category=$(this).attr('data-id');
3066			var tab=$(this).attr('href').replace(/#/,'');
3067			$("html, body").animate({
3068					scrollTop: $('#go_here').offset().top
3069			}, 300,function(){
3070				loadTab(id_category,tab);
3071			});
3072			
3073		});
3074		//console.log('======');
3075		var the_category=$('#section-accessories li.active').find('a').attr('data-id');
3076		loadTab(the_category,$('#section-accessories li.active').find('a').attr('href').replace(/#/,''));
3077	}
3078	if($('a.price_notification').length > 0){
3079		$('a.price_notification').click(function(e){
3080			e.preventDefault();
3081			
3082			var link=$(this);
3083			var id=$(this).attr('data-id');
3084			$('.price-popup-'+id).addClass('active');
3085			$(this).addClass('active');
3086			$('.overlay_2').addClass('active').css('z-index', '9999');
3087		});
3088		$("form.price_form").submit(function(e) {
3089			//alert('123');
3090			var form=$(this);
3091			if($('html').attr('lang') == 'en-US'){
3092				$(form).find('input[type="submit"]').css('background','#990000').val('Please wait...');
3093			}else{
3094				$(form).find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
3095			}
3096			$.ajax({
3097				type: "POST",
3098				url: '/external/notifications.php',
3099				data: $(form).serialize(),
3100				success: function(data){
3101					e.preventDefault();
3102					$('.overlay_2').removeClass('active');
3103					$('.popup').removeClass('active');
3104					if($('html').attr('lang') == 'en-US'){
3105						$(form).find('input[type="submit"]').css('background','#91a719').val('Subscribe for notifications');
3106					}else{
3107						$(form).find('input[type="submit"]').css('background','#91a719').val('Известие за цена');
3108					}
3109					alert($('a.price_notification').attr('data-success'));
3110				}
3111			});
3112			e.preventDefault();
3113		});
3114	}
3115	$(window).on("popstate", function () {
3116		location.href=window.location.href;
3117	});
3118	if($('.search_layered').length > 0 || $('body').hasClass('manufacturer') || $('body').hasClass('prices-drop') || $('body').hasClass('prices-top') || $('body').hasClass('prices-top-sub') || $('body').hasClass('promotion')){
3119		$('#enabled_filters li').find('a').each(function(){
3120			$(this).click(function(e){
3121				e.preventDefault();
3122				if($(this).attr('data-rel').match(/category/)){
3123					
3124					var id2remove=$(this).attr('data-rel').replace(/layered_category_/,'');
3125					
3126					var replace = "category_"+id2remove+"=.*?&";
3127					var replace2 = "&category_"+id2remove+"=.*$";
3128					var replace3 = "category_"+id2remove+"=.*$";
3129					var re = new RegExp(replace);
3130					var re2 = new RegExp(replace2);
3131					var re3 = new RegExp(replace3);
3132					window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(re,'').replace(re2,'').replace(re3,'').replace(/\?$/,''));
3133				}
3134				if($(this).attr('data-rel').match(/manufacturer/)){
3135					var id2remove=$(this).attr('data-rel').replace(/layered_manufacturer_/,'');
3136					var all_els=window.location.href.replace(/^.*manufacturer=/,'').replace(/&.*$/,'');
3137					all_els=all_els.split(',');
3138					var rest='';
3139					for(var i=0;i<all_els.length;i++){
3140						if(all_els[i] != id2remove){
3141							if(rest==''){
3142								rest=all_els[i];
3143							}else{
3144								rest += ','+all_els[i];
3145							}
3146						}
3147					}
3148					if(rest != ''){
3149						window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(/manufacturer=.*?&/,'manufacturer='+rest+'&').replace(/&manufacturer=.*$/,'&manufacturer='+rest));
3150					}else{
3151						window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(/manufacturer=.*?&/,'').replace(/&manufacturer=.*$/,'').replace(/\?manufacturer=\d+/,''));
3152					}
3153				}
3154				if($(this).attr('data-rel').match(/quantity/)){
3155					window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(/quantity=.*?&/,'').replace(/&quantity=.*$/,''));
3156				}
3157				if($(this).attr('data-rel').match(/promotion/)){
3158					window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(/offer.*?=.*?&/,'').replace(/&offer.*?=.*$/,''));
3159				}
3160				if($(this).attr('data-rel').match(/price/)){
3161					window.history.pushState("", "",window.location.href.replace(/\?p=\d+$/,'').replace(/p=.*?&/,'').replace(/(\?)?max_price=.*?&/,'').replace(/(\?)?(&)?max_price=.*$/,'').replace(/(\?)?min_price=.*?&/,'').replace(/(\?)?(&)?min_price=.*$/,''));
3162				}
3163				location.href=window.location.href;
3164			});
3165
3166		});
3167		$('#productsSortForm').find('li').click(function(){
3168			window.history.pushState("", "",window.location.href.replace(/#/,'').replace(/p=.*?&/,'').replace(/order_way=.*?&/g,'').replace(/&order_way=.*?$/g,'')+(window.location.href.match(/\?/)?'&':'?')+'order_way='+$(this).attr('rel'));
3169			location.href=window.location.href;
3170		});
3171		$('form.nbrItemPage').find('li').click(function(){
3172			window.history.pushState("", "",window.location.href.replace(/#/,'').replace(/p=.*?&/,'').replace(/n=.*?&/g,'').replace(/&n=.*?$/g,'')+(window.location.href.match(/\?/)?'&':'?')+'n='+$(this).attr('rel'));
3173			location.href=window.location.href;
3174		});
3175		var params='';
3176		params = window.location.href.split('?')[1];
3177		if(params){
3178			params = params.split('&');
3179		}else{
3180			params=new Array();
3181		}
3182		var has_order=0;
3183		var search_query='';
3184		for(var i=0;i<params.length;i++){
3185			if(params[i].match(/order_way/)){
3186				var sorting=params[i].replace(/order_way=/,'');
3187				if(sorting != ''){
3188					$('#productsSortForm').find('div.styledSelect').html($('#productsSortForm').find('li[rel="'+sorting+'"]').html());
3189					has_order=1;
3190				}
3191			}else if(params[i].match(/n=/)){
3192				var sorting=params[i].replace(/n=/,'');
3193				if(sorting != ''){
3194					$('form.nbrItemPage').find('div.styledSelect').html($('form.nbrItemPage').find('li[rel="'+sorting+'"]').html());
3195				}
3196			}else if(params[i].match(/search_query=/)){
3197				search_query=params[i].replace(/search_query=/,'');
3198			}	
3199		}
3200		$('a.clear_all').click(function(e){
3201			e.preventDefault();
3202			if($('body').hasClass('search')){
3203				window.history.pushState("", "","/search?controller=search&orderby=position&orderway=desc&search_query="+search_query);
3204			}else if($('body').hasClass('manufacturer')){
3205				window.history.pushState("", "",document.location.href.replace(/\?.*$/,''));
3206			}else if($('body').hasClass('prices-drop')){
3207				window.history.pushState("", "",document.location.href.replace(/\?.*$/,''));
3208			}else if($('body').hasClass('prices-top')){
3209				window.history.pushState("", "",document.location.href.replace(/\?.*$/,''));
3210			}else if($('body').hasClass('prices-top-sub')){
3211				window.history.pushState("", "",document.location.href.replace(/\?.*$/,''));
3212			}else if($('body').hasClass('promotion')){
3213				if(document.location.href.match(/pg|mc/)){
3214					window.history.pushState("", "",document.location.href.replace(/&.*$/,''));
3215				}else{
3216					window.history.pushState("", "",document.location.href.replace(/\?.*$/,''));
3217				}
3218				
3219			}
3220			location.href=window.location.href;
3221		});
3222		if(!has_order && !$('body').hasClass('manufacturer')){
3223			$('#productsSortForm').find('div.styledSelect').html('-- Избери критерии --');
3224		}
3225		$('#ul_layered_manufacturer_0').find('label').click(function(e){
3226			e.preventDefault();
3227			var $label = $(this);
3228			var $input = $label.prev();
3229			var value  = $input.val();
3230			var url = new URL(window.location.href);
3231			url.searchParams.delete('p');
3232			var manufacturers = url.searchParams.get('manufacturer');
3233			manufacturers = manufacturers ? manufacturers.split(',').filter(
3233Boolean) : [];
3234			if (!$label.hasClass('selected')) {
3235
3236				$label.addClass('selected');
3237				$input.prop('checked', true);
3238				if (manufacturers.indexOf(value) === -1) {
3239					manufacturers.push(value);
3240				}
3241			} else {
3242				$label.removeClass('selected');
3243				$input.prop('checked', false);
3244				manufacturers = manufacturers.filter(function(item) {
3245					return item !== value;
3246				});
3247			}
3248			if (manufacturers.length) {
3249				url.searchParams.set('manufacturer', manufacturers.join(','));
3250			} else {
3251				url.searchParams.delete('manufacturer');
3252			}
3253			url.hash = '';
3254
3255			window.location.href = url.toString();
3256		});
3257		$('#ul_layered_category_0').find('label').click(function(e){
3258			e.preventDefault();
3259			if(!$(this).hasClass('selected')){
3260				$(this).addClass('selected');
3261				$(this).prev().attr('checked','checked');
3262				var cats='';
3263				if($('#ids_category_'+$(this).prev().val()).val() != ''){
3264					var cats=$('#ids_category_'+$(this).prev().val()).val();
3265				}else{
3266					var cats=$(this).prev().val();
3267				}
3268				if(!window.location.href.match(/category/) || 1){
3269					window.history.pushState("", "",window.location.href.replace(/#/,'').replace(/p=.*?&/,'')+(window.location.href.match(/\?/)?'&':'?')+'category_'+$(this).prev().val()+'='+cats);
3270				}else{
3271					window.history.pushState("", "",window.location.href.replace(/#/,'').replace(/p=.*?&/,'').replace(/&category/,'&category_'+$(this).prev().val()+'='+cats+','));
3272				}
3273				location.href=window.location.href;
3274			}else{
3275				$(this).prev().removeAttr('checked');
3276				var re1 = new RegExp('category_'+$(this).prev().val()+'=.*?&',"g");
3277				var re2 = new RegExp('&category_'+$(this).prev().val()+'=.*$',"g");
3278				window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(re1,'').replace(re2,''));
3279				location.href=window.location.href;
3280			}
3281		});
3282		$('#search_price_range').click(function(e){
3283			e.preventDefault();
3284			var url=window.location.href.replace(/p=\d+$/,'').replace(/p=.*?&/,'').replace(/min_price\=.*?&max_price\=\d+/, "").replace(/\?$/,"").replace(/\&$/,"").replace(/\?&$/,"");
3285			window.history.pushState("", "",url.replace(/#/,'')+(url.match(/\?/)?'&':'?')+'min_price='+$('#layered_price_range_min').val()+'&max_price='+$('#layered_price_range_max').val());
3286			location.href=window.location.href;
3287		});
3288		$('#ul_layered_quantity_0').find('label').click(function(e){
3289			e.preventDefault();
3290			if(!$(this).hasClass('selected')){
3291				$(this).addClass('selected')
3292				$(this).prev().attr('checked','checked');
3293				window.history.pushState("", "",window.location.href.replace(/#/,'').replace(/p=.*?&/,'')+(window.location.href.match(/\?/)?'&':'?')+'quantity='+$(this).prev().val());
3294				location.href=window.location.href;
3295			}else{
3296				$(this).prev().removeAttr('checked');
3297				window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(/quantity=.*?&/,'').replace(/&quantity=.*$/,''));
3298				location.href=window.location.href;
3299			}
3300		});
3301		$('#ul_layered_condition_0').find('label').click(function(e){
3302			e.preventDefault();
3303			if(!$(this).hasClass('selected')){
3304				$(this).addClass('selected')
3305				$(this).prev().attr('checked','checked');
3306				window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(/quantity=.*?&/,'').replace(/&condition=.*$/,''));
3307				window.history.pushState("", "",window.location.href.replace(/#/,'').replace(/p=.*?&/,'')+(window.location.href.match(/\?/)?'&':'?')+'condition='+$(this).prev().val());
3308				location.href=window.location.href;
3309			}else{
3310				$(this).prev().removeAttr('checked');
3311				window.history.pushState("", "",window.location.href.replace(/p=.*?&/,'').replace(/quantity=.*?&/,'').replace(/&condition=.*$/,''));
3312				location.href=window.location.href;
3313			}
3314		});
3315		$('#ul_layered_promotion_0').find('label').click(function(e){
3316			e.preventDefault();
3317			var re = new RegExp('offer_'+$(this).prev().val()+'=1');
3318			var url=window.location.href.replace(/p=.*?&/,'').replace(re, "").replace(/\?$/, "").replace(/\&$/, "").replace(/\?&$/, "");
3319			if(!$(this).hasClass('selected')){
3320				$(this).addClass('selected')
3321				$(this).prev().attr('checked','checked');
3322				
3323				window.history.pushState("", "",url+(url.match(/\?/)?'&':'?')+'offer_'+$(this).prev().val()+'=1');
3324				location.href=window.location.href;
3325			}else{
3326				$(this).prev().removeAttr('checked');
3327				window.history.pushState("", "",url);
3328				location.href=window.location.href;
3329			}
3330		});
3331	}
3332	/*
3333	if($('#top_pagination').length > 0){
3334		topPagination(1);
3335		$('a.top_vew_all').click(function(e){
3336			e.preventDefault();
3337			$("html, body").animate({
3338					scrollTop: $('#go_here').offset().top
3339			}, 300,function(){
3340				$('#load_container').css('opacity','0.3');
3341				$('#load_container').load(window.location.href.replace(/#/,'')+'?view=all #special_grabber',function(data){
3342					topPagination(0);
3343					$('#load_container').animate({opacity:1});
3344				});
3345			});
3346
3347		});
3348	}
3349	*/
3350	function loadAllTopProducts(page,page_num){
3351		if(page > page_num){
3352			return false;
3353		}
3354		
3355		$('#load_container').append('<div id="view_all_container_'+page+'"><span class="top-all-loader"></span></div>');
3356		$('#view_all_container_'+page+'').load(window.location.href.replace(/#/,'')+'?page='+page+' #special_grabber',function(data){
3357			//yalert(data);
3358			topPagination(0);
3359			$('#load_container').animate({opacity:1});
3360			$(window).scroll(function(){
3361			//console.log((parseInt($(window).scrollTop() + $(window).height()))+'=='+parseInt($('#view_all_container_'+page+'').offset().top*1+$('#view_all_container_'+page+'').height()));
3362				if(parseInt($(window).scrollTop() + $(window).height()) > parseInt($('#view_all_container_'+page+'').offset().top*1+$('#view_all_container_'+page+'').height())) {
3363					if(!($('#view_all_container_'+(page+1)+'').length > 0)){
3364						loadAllTopProducts(page*1+1,page_num);
3365					}
3366				}
3367			});
3368		});
3369	}
3370	if($('#top_pagination').length > 0){
3371		topPagination(1);
3372		$('a.top_vew_all').click(function(e){
3373			e.preventDefault();
3374			e.stopImmediatePropagation();
3375			e.stopPropagation();
3376			$('#load_container').css('opacity','0.3');
3377			var page=($('#top_pagination li.active').find('a').html()*1+1);
3378			var page_num=$('#top_pagination li.top_nav_next').prev().find('a').html()*1;
3379			$('.top.paggination').remove();
3380			loadAllTopProducts(page,page_num);
3381			
3382
3383		});
3384	}
3385	$('#reg_popup,#reg_popup2').click(function(e){
3386		e.preventDefault();
3387		$('div.info_holder').hide();
3388		$('div.info_holder.register').fadeIn();
3389	});
3390	$('a.share-wishlist').click(function(e){
3391		e.preventDefault();
3392		if($('#link_share').is(':visible')){
3393			$('#link_share').hide();
3394		}else{
3395			$('#link_share').fadeIn();
3396		}
3397		
3398		$('#link_share').focus(function() { $(this).select(); } );
3399		$('#link_share').trigger('focus');
3400	});
3401	if($('#fast_search').length > 0){
3402		$('#fast_search').keyup(function(){
3403			var search=$(this).val();
3404			$('div.product_list div.item').each(function(){
3405				var toCheck=$($(this).find('h3')).find('a').html();
3406				re = new RegExp(search, 'gi');
3407				if(!toCheck.match(re)){
3408					$(this).hide();
3409				}else{
3410					$(this).show();
3411				}
3412			});
3413		});
3414		$('#select_all').click(function(e){
3415			e.preventDefault();
3416			$('div.product_list div.item').each(function(){
3417				$(this).find('input.grouping').attr('checked','checked');
3418			});
3419		});
3420
3421	}
3422	if($('#search_brand').length > 0){
3423		$('#search_brand').keyup(function(){
3424			var search=$(this).val();
3425			$('#manufacturers_list li').each(function(){
3426				var toCheck=$(this).find('img').attr('alt');
3427				re = new RegExp(search, 'gi');
3428				if(!toCheck.match(re)){
3429					$(this).hide();
3430				}else{
3431					$(this).show();
3432				}
3433			});
3434			$('#others_list li').each(function(){
3435				var toCheck=$(this).find('span').html();
3436				re = new RegExp(search, 'gi');
3437				if(!toCheck.match(re)){
3438					$(this).hide();
3439				}else{
3440					$(this).show();
3441				}
3442			});
3443		});
3444		$('#select_all').click(function(e){
3445			e.preventDefault();
3446			$('div.product_list div.item').each(function(){
3447				$(this).find('input.grouping').attr('checked','checked');
3448			});
3449		});
3450
3451	}
3452	$('#login_popup,#login_popup2').click(function(e){
3453		e.preventDefault();
3454		$('div.info_holder').hide();
3455		$('div.info_holder.login').fadeIn();
3456	});
3457	$('#forgotten_password').click(function(e){
3458		e.preventDefault();
3459		$('div.info_holder').hide();
3460		$('div.info_holder.password').fadeIn();
3461	});
3462	$("#login_form").submit(function(e) {
3463		if($('html').attr('lang') == 'en-US'){
3464			$("#login_form").find('input[type="submit"]').css('background','#990000').val('Please wait...');
3465		}else{
3466			$("#login_form").find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
3467		}
3468		var has_errors=0;
3469		$.ajax({
3470			type: "POST",
3471			url: '/external/working.php',
3472			data: {login:$('#login_form').find('input[name="email"]').val(),password:$('#login_form').find('input[name="passwd"]').val()},
3473			success: function(data){
3474				if(!data){
3475					has_errors=1;
3476				}
3477				//alert(data);
3478				$('#login_form').prepend(data);
3479				$.ajax({
3480					type: "POST",
3481					url: $("#login_form").attr('action'),
3482					data: $("#login_form").serialize(),
3483					success: function(data){
3484						data=JSON.parse(data);
3485						//alert(data.errors.length);
3486						if(data.errors.length > 0){
3487							$('div.login-errors').html('');
3488							$('div.login-errors').show();
3489							for(var i=0;i<data.errors.length;i++){
3490								$('div.login-errors').html($('div.login-errors').html()+data.errors[i]);
3491							}
3492							if($('html').attr('lang') == 'en-US'){
3493								$("#login_form").find('input[type="submit"]').css('background','#626c2f').val('Sign In');
3494							}else{
3495								$("#login_form").find('input[type="submit"]').css('background','#626c2f').val('Вход');
3496							}
3497						}else if($('div.shopping-cart').length > 0){
3498							location.href='/quick-order?step=2';
3499						}else{
3500							location.reload();
3501						}
3502					}
3503				});
3504			}
3505		});
3506
3507		e.preventDefault();
3508	});
3509	$("#create-account_form").submit(function(e) {
3510		if($('html').attr('lang') == 'en-US'){
3511			$("#create-account_form").find('input[type="submit"]').css('background','#990000').val('Please wait...');
3512		}else{
3513			$("#create-account_form").find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
3514		}
3515		$.ajax({
3516			type: "POST",
3517			url: $("#create-account_form").attr('action'),
3518			data: $("#create-account_form").serialize(),
3519			success: function(data){
3520				//alert(data);
3521				data=JSON.parse(data);
3522				if(data.errors.length > 0){
3523					$('div.register-errors').html('');
3524					for(var i=0;i<data.errors.length;i++){
3525						$('div.register-errors').html($('div.register-errors').html()+data.errors[i]);
3526					}
3527					if($('html').attr('lang') == 'en-US'){
3528						$("#create-account_form").find('input[type="submit"]').css('background','#626c2f').val('Sign Up');
3529					}else{
3530						$("#create-account_form").find('input[type="submit"]').css('background','#626c2f').val('Регистрация');
3531					}
3532				}else if($('div.shopping-cart').length > 0){
3533					location.href='/quick-order?step=2';
3534				}else{
3535					location.reload();
3536				}
3537			}
3538		});
3539		e.preventDefault();
3540	});
3541	$("#guest_account").submit(function(e) {
3542		var form=$("#guest_account");
3543		if($('html').attr('lang') == 'en-US'){
3544			$(form).find('input[type="submit"]').css('background','#990000').val('Please wait...');
3545		}else{
3546			$(form).find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
3547		}
3548		$.ajax({
3549			type: "POST",
3550			url: $(form).attr('action'),
3551			data: $(form).serialize(),
3552			success: function(data){
3553				data=JSON.parse(data);
3554				if(data.errors.length > 0){
3555					$('div.register-errors').html('');
3556					for(var i=0;i<data.errors.length;i++){
3557						$('div.register-errors').html($('div.register-errors').html()+data.errors[i]);
3558					}
3559					if($('html').attr('lang') == 'en-US'){
3560						$("#guest_account").find('input[type="submit"]').css('background','#626c2f').val('Continue with your order');
3561					}else{
3562						$("#guest_account").find('input[type="submit"]').css('background','#626c2f').val('Продължи с поръчката си');
3563					}
3564				}else if($('div.shopping-cart').length > 0){
3565					location.href='/quick-order?step=2';
3566				}else{
3567					location.reload();
3568				}
3569			}
3570		});
3571		e.preventDefault();
3572	});
3573	if($('form.insurance_policy').length > 0){
3574		$('form.insurance_policy').submit(function(e) {
3575			var form=$(this);
3576			var submitTxt=$(form).find('input[type="submit"]').css('background','#990000').val();
3577			if($('html').attr('lang') == 'en-US'){
3578				$(form).find('input[type="submit"]').css('background','#990000').val('Please wait...');
3579			}else{
3580				$(form).find('input[type="submit"]').css('background','#990000').val('Моля изчакайте...');
3581			}
3582			$.ajax({
3583				type: "POST",
3584				url: window.location.href,
3585				data: $(form).serialize(),
3586				success: function(data){
3587					$(form).find('input[type="submit"]').css('background','#626c2f').val(submitTxt);
3588					location.reload();
3589				}
3590			});
3591			e.preventDefault();
3592		});
3593		$('a.insurance_remove').click(function(e){
3594			if($('html').attr('lang') == 'en-US'){
3595				if(!confirm('Are you sure?')){
3596					return false;
3597				}
3598			}else{
3599				if(!confirm('Сигурни ли сте?')){
3600					return false;
3601				}
3602			}
3603			
3604			e.preventDefault();
3605			var values=$(this).attr('id').replace(/ins_/,'');
3606			var years=values.replace(/_.*$/,'');
3607			var id_product=values.replace(/^.*?_/,'');
3608			if(years == 2){
3609				var insurance_1=1;
3610				var insurance_2=0;
3611			}else if(years == 1){
3612				var insurance_1=0;
3613				var insurance_2=1;
3614			}else{
3615				var insurance_1=0;
3616				var insurance_2=0;
3617			}
3618			$.ajax({
3619				type: "POST",
3620				url: window.location.href,
3621				data: {action:'Insurance',ajax:1,id_cart:$('#id_cart').val(),id_product:id_product,insurance_1:insurance_1,insurance_2:insurance_2,del:1},
3622				success: function(data){
3623					location.reload();
3624				}
3625			});
3626		});
3627	}
3628	if($('div.order-now').length > 0){
3629		
3630		$('div.right-side').each(function(){
3631			if($(this).is(':visible')){
3632				$(this).attr('id','sticky_summary');
3633			}
3634		});
3635	}
3636	$('a.stick_msg').click(function(e){
3637		e.preventDefault();
3638		$(this).hide();
3639		$('div.system_message4all').fadeIn();
3640	});
3641	$(window).scroll(function(){
3642		if ($(this).scrollTop() > 500 && !$('.back2top').is(':visible')) {
3643			$('.back2top').fadeIn();
3644			$('a.stick_msg,div.system_message4all').css('right','62px');
3645		} else if($(this).scrollTop() < 500 && $('.back2top').is(':visible')) {
3646			$('.back2top').fadeOut();
3647			$('a.stick_msg,div.system_message4all').css('right','10px');
3648		}
3649		if($('div.order-now').length > 0){
3650            var window_top = $(window).scrollTop();
3651			var summary = $('#sticky_summary').offset().top;
3652			if (window_top > summary) {
3653				//alert($('#sticky_summary div.order-now').outerHeight());
3654				if (window_top > $('div.white-bg').offset().top-$('#sticky_summary div.order-now').outerHeight()) {
3655					$('div.order-now').removeClass('sticky');
3656					$('div.order-now').addClass('absolute');
3657				}else{
3658					$('div.right-side').height($($('#sticky_summary').prev()).height()-10);
3659					$('div.order-now').addClass('sticky');
3660					
3661					$('div.order-now').removeClass('absolute');
3662				}
3663			} else {
3664				$('div.order-now').removeClass('sticky');
3665				$('div.order-now').removeClass('absolute');
3666			}
3667		}
3668	});
3669
3670	 $('.back2top').click(function (e) {
3671			e.preventDefault();
3672			$("html, body").animate({
3673					scrollTop: 0
3674			}, 600);
3675			return false;
3676	 });
3677	if($('.image-link').length > 0){
3678		$('.image-link').magnificPopup({type:'image', gallery: { enabled: true}});
3679	}
3680    //shop popup in shopping cart step1
3681	$('div.recently-viewed-items a.clear-all').click(function(e){
3682		e.preventDefault();
3683		var el=$(this).parent().parent();
3684		$.ajax({
3685			type: "POST",
3686			url: '/external/clear.php',
3687			success: function(data){
3688				$(el).fadeOut();
3689			}
3690		});
3691	});
3692    $('#show_popup,#show_popup_guest').on('click', function(e){
3693        e.preventDefault();
3694        $('.popup-login-reg').addClass('active');
3695        $(this).addClass('active');
3696		$('.overlay_2').addClass('active').css('z-index', '9999');
3697    });
3698
3699	$('.ins_popup').on('click', function(e){
3700        e.preventDefault();
3701		var cnt=$($(this).parent().parent()).find('input.cart_quantity_input').val();
3702		//$('html, body').animate({ scrollTop: 0 });
3703        $('.'+$(this).attr('id')).addClass('active');
3704        $(this).addClass('active');
3705		$('.overlay_2').addClass('active').css('z-index', '9999');
3706		$('.insure_option').on('click', function(e){
3707			if(cnt == 1){
3708				if($($(this).prev()).attr('name') == 'insurance_1'){
3709					$($('input[name="insurance_2"]').next().next()).find('.quantity').hide();
3710					$($('input[name="insurance_2"]').next().next()).find('.remove-item').hide();
3711					$('input[name="insurance_2"]').prop('checked', false);
3712				}else if($($(this).prev()).attr('name') == 'insurance_2'){
3713					$($('input[name="insurance_1"]').next().next()).find('.quantity').hide();
3714					$($('input[name="insurance_1"]').next().next()).find('.remove-item').hide();
3715					$('input[name="insurance_1"]').prop('checked', false);
3716				}
3717				$($(this).next()).find('.remove-item').toggle();
3718				$($(this).next()).find('.quantity').hide();
3719			}else{
3720				//console.log('======2=====');
3721				$($(this).next()).find('.quantity').toggle();
3722				$($(this).next()).find('.remove-item').toggle();
3723			}
3724		});
3725		$('.quantity-up').on('click', function(e){
3726			$($(this).prev()).val($($(this).prev()).val()*1+1);
3727		});
3728		$('.quantity-down').on('click', function(e){
3729			$($(this).next()).val($($(this).next()).val()*1-1);
3730		});
3731    });
3732    $('.close-popup,.overlay_2,.overlay').on('click', function(e){
3733		e.preventDefault();
3734		if($('div.cc-window').length > 0){
3735			$('div.cc-window').show();
3736		}
3737        $('.overlay_2').removeClass('active');
3738		if($('.tab-popup').hasClass('active')){
3739			$('header').show();
3740			$('article.product_inner_page').hide();
3741			$('html, body').css({"overflow":"auto","height":"auto"});
3742			$($('.tab-popup').parent()).hide();
3743		}
3744		if($('html, body').css('overflow') == 'hidden'){
3745			$('html, body').css({"overflow":"auto","height":"auto"});
3746		}
3747		if($('.dark_wrapper').length > 0){
3748			$('.dark_wrapper').hide();	
3749		}
3750        $('.popup').removeClass('active');
3751    });
3752	var currentRequest = null; 
3753	$('#search_query_top').keyup(function(e){
3754		e.preventDefault();
3755		e.stopImmediatePropagation();
3756		e.stopPropagation();
3757		if(e.keyCode == '38' || e.keyCode == '40'){
3758			return false;
3759		}
3760		var search=$(this).val();
3761		if(search.length < 2){
3762			if($('ul.auto-suggestion').length > 0){
3763				$('ul.auto-suggestion').remove();
3764			}
3765			if(currentRequest != null) {
3766				currentRequest.abort();
3767			}
3768			return false;
3769		}
3770		var field=$(this).next();
3771		console.log('111111');
3772		currentRequest = $.ajax({
3773			   type: "POST",
3774			   url: '/external/autosuggest.php',
3775			   data: {search:search},
3776				beforeSend : function()    {           
3777					if(currentRequest != null) {
3778						currentRequest.abort();
3779					}
3780				},
3781			   success: function(data){
3782					//alert(data);
3783					if(!$('ul.auto-suggestion').length){
3784						$(field).after('<ul class="auto-suggestion"></ul>');
3785					}
3786					$('ul.auto-suggestion').html(data);
3787					$('a.phs_article').click(function(e){
3788						e.preventDefault();
3789						loadArticle($(this).attr('data-id'));
3790					});
3791			   }
3792			 });
3793
3794	});
3795	$(document).on('click', '.add_to_compare', function(e){
3796		e.preventDefault();
3797		if (typeof addToCompare != 'undefined')
3798			addToCompare(parseInt($(this).data('id-product')));
3799	});
3800	$(document).on('click', '.remove_compare', function(e){
3801		e.preventDefault();
3802		if (typeof addToCompare != 'undefined')
3803			addToCompare(parseInt($(this).data('id-product')));
3804	});
3805	reloadProductComparison();
3806	compareButtonsStatusRefresh();
3807	totalCompareButtons();
3808	$('a.close_msg').click(function(e){
3809		e.preventDefault();
3810		$('div.system_message4all').hide();
3811		$('a.stick_msg').fadeIn();
3812		setCookie('closed_msg',$('#msg_identifier').val());
3813	});
3814	// ========================= Articles Popup ===============================================
3815	$('div.scroller_div,div.dark_wrapper,a.close_window,a.go_home').
3815click(function(e){
3816		if(!($(this).find('.privacy_notice').length > 0)){
3817			e.preventDefault();
3818
3819			if($(this).attr('class') == 'article_container' || $('div.cookies_notice,div.privacy_notice').hasClass('active') || $('div.gdpr').hasClass('active') || $(this).prop("tagName") == 'a'){
3820				return false;
3821			}
3822			closePopup();
3823		}
3824	});
3825	$('div.article_container').click(function(e){
3826		e.stopImmediatePropagation();
3827		e.stopPropagation();
3828	});
3829	$('a.confirm,a.deny').click(function(e){
3830		e.preventDefault();
3831		var link=$(this);
3832		if($('#order-return').length > 0){
3833			if($(this).hasClass('confirm')){
3834				setCookie('gor',1,365);
3835				$('div.return-gdpr').removeClass('active');
3836				$('div.pop_up.scroller_div').hide();
3837				$('html, body').css({"overflow":"initial","height":"auto"});
3838				$('.dark_wrapper').hide();
3839			}else if(document.referrer != window.location){
3840				location.href=document.referrer;
3841			}else{
3842				location.href='/';
3843			}
3844			return false;
3845		}
3846		if($('#reclamation').length > 0){
3847			if($(this).hasClass('confirm')){
3848				setCookie('gor2',1,365);
3849				$('div.reclamation-gdpr').removeClass('active');
3850				$('div.pop_up.scroller_div').hide();
3851				$('html, body').css({"overflow":"initial","height":"auto"});
3852				$('.dark_wrapper').hide();
3853			}else if(document.referrer != window.location){
3854				location.href=document.referrer;
3855			}else{
3856				location.href='/';
3857			}
3858			return false;
3859		}
3860		$.ajax({
3861			type: "POST",
3862			url: '/external/gdpr.php',
3863			data: {id:$('#gdpr_id').val(),gdpr:$(link).hasClass('deny')?2:1},
3864			success: function(data){
3865				if($('div.shopping-cart').length && $('#id_cart').val()*1 > 0 && !$(link).hasClass('deny')){
3866					if(window.location.href.match(/step/)){
3867						location.href=window.location.href.replace(/#.*$/,'').replace(/step=1/,'step=2');
3868					}else if(window.location.href.match(/\?/)){
3869						location.href=window.location.href.replace(/#.*$/,'')+'&step=2';
3870					}else{
3871						location.href=window.location.href.replace(/#.*$/,'')+'?step=2';
3872					}
3873				}else if($('div.shopping-cart').length && $('#id_cart').val()*1 > 0 && $(link).hasClass('deny')){
3874					if(window.location.href.match(/step/)){
3875						location.href=window.location.href.replace(/#.*$/,'').replace(/step=2/,'step=1');
3876					}else if(window.location.href.match(/\?/)){
3877						location.href=window.location.href.replace(/#.*$/,'')+'&step=1';
3878					}else{
3879						location.href=window.location.href.replace(/#.*$/,'')+'?step=1';
3880					}
3881				}else{
3882					closePopup();
3883				}
3884			}
3885		});
3886	});
3887	$('a.phs_article').click(function(e){
3888		e.preventDefault();
3889		loadArticle($(this).attr('data-id'));
3890	});
3891	// ========================================================================================
3892	if(!($('#scroll_skipper').length > 0) && !$('body').hasClass('category')){
3893		$('#pagination_bottom a,#layered_form a').click(function(e){
3894			$("html, body").animate({ scrollTop: 0 }, "slow");
3895			$('#special_grabber').prepend('<span class="top-all-loader" style="position: absolute;left: 57%;margin-top: -36px;"></span>');
3896			$('.product_list').css('opacity', '0.3');
3897		});
3898		
3899	}
3900
3901	if($('#layered_form').length > 0){
3902		$('#layered_form div.checkbox').each(function(){
3903			$(this).click(function(){
3904				if($($(this).find('label')).hasClass('selected')){
3905					$($(this).find('label')).removeClass('selected');
3906				}else{
3907					$($(this).find('label')).addClass('selected');
3908				}
3909			});
3910		});
3911	}
3912    //replace all img with clas "svg" to svg element(html)
3913    $('img.svg').each(function() {
3914        var $img = jQuery(this);
3915        var imgID = $img.attr('id');
3916        var imgClass = $img.attr('class');
3917        var imgURL = $img.attr('src');
3918
3919        $.get(imgURL, function(data) {
3920            var $svg = jQuery(data).find('svg');
3921            if (typeof imgID !== 'undefined') {
3922                $svg = $svg.attr('id', imgID);
3923            }
3924            if (typeof imgClass !== 'undefined') {
3925                $svg = $svg.attr('class', imgClass + ' replaced-svg');
3926            }
3927            $svg = $svg.removeAttr('xmlns:a');
3928            $img.replaceWith($svg);
3929        }, 'xml');
3930    });
3931	var myVar;
3932    $('.sub-nav ul li.top-link').on('mouseenter', function(){
3933		var el=$(this);
3934		myVar = setTimeout(function(){
3935			$(el).addClass('hover');
3936			if ($(el).hasClass('hover')) {
3937				$('.overlay').addClass('active');
3938				$('.dropdown-menu').css('opacity',0).css('z-index',1).css('visibility','hidden');
3939				$('.sub-nav').css('z-index',99999);
3940				$(el).find('.dropdown-menu').css('opacity',1).css('z-index',99999).css('visibility','visible');
3941			}
3942		}, 500);
3943    });
3944    $('.sub-nav ul li.top-link').on('mouseleave', function(){
3945		 clearTimeout(myVar);
3946        //$(this).removeClass('hover');
3947    });
3948
3949    $('.sub-nav ul.nav').on('mouseleave', function(){
3950		var hasEntered=0;
3951		$('.sub-nav ul li.top-link').hover(function(){
3952			hasEntered=1;
3953		});
3954		setTimeout(function(){
3955			$('.sub-nav ul li.top-link').hover(function(){
3956				hasEntered=1;
3957			});
3958			if(!hasEntered){
3959
3960				$('.overlay').removeClass('active');
3961				$('.sub-nav').css('z-index',1);
3962				$('.dropdown-menu').css('opacity',0).css('z-index',1).css('visibility','hidden');
3963			}
3964		}, 50);
3965    });
3966    $('.dropdown.box').on('click', '.toggle-title', function(){
3967        $(this).parent().toggleClass('open', 200);
3968    });
3969
3970    $('.item-content').on('click', '.toggle-btn', function(){
3971        $(this).toggleClass('active', 200).prev('ul').toggleClass('toggle-hidden', 200);
3972		if($('div.colors').css('position') == 'absolute'){
3973			//$('div.colors').css('position','relative').css('width','auto').css('bottom','0'); 
3974		}else{
3975			//$('div.colors').css('position','absolute').css('width','calc(52% - 25px)').css('bottom','25px');
3976		}
3977    });
3978    $('.item-bundles').on('click', '.toggle-btn', function(){
3979		$($(this).parent()).find('h3').hide();
3980        $(this).toggleClass('active', 200).parent().toggleClass('active', 200,function(){
3981			$($(this).parent()).find('h3').show();
3982		});
3983    });
3984	$('div.more-offers a.toggle-more-btn').on('click', function(e){
3985		e.preventDefault();
3986		e.stopImmediatePropagation();
3987		e.stopPropagation();
3988		if($($(this).parent()).hasClass('active')){
3989			$("html, body").animate({ scrollTop: $($(this).parent()).offset().top-$($(this).parent()).prev().height() },'fast');
3990		}
3991		$($(this).parent()).toggleClass('active', 50).parent().toggleClass('active', 50);
3992	});
3993    $('.listing-srot li').on('click', function(e){
3994		e.preventDefault();
3995		e.stopImmediatePropagation();
3996		e.stopPropagation();
3997        $('.item, .more-offers').removeClass('active');
3998        $('.listing-srot li').removeClass('active');
3999        $(this).toggleClass('active');
4000        if($('.listing-srot .sort-grid').hasClass('active')){
4001            $('.listing-page').addClass('grid-items');
4002			$('.listing-page').removeClass('list-items');
4003        }else {
4004            $('.listing-page').removeClass('grid-items');
4005			$('.listing-page').addClass('list-items');
4006        }
4007    });
4008	if($('.small_little_slider').length > 0){
4009		
4010		$('.small_little_slider').each(function(){
4011			var id=$(this).attr('id').replace(/menu-slider_/,'');
4012			$('#menu-slider_'+id).owlCarousel({
4013				animateOut: 'fadeOut',
4014				animateIn: 'fadeIn',
4015				loop: $('#menu-slider_'+id).children().length > 1,
4016				nav: false,
4017				margin: 0,
4018				items: 1,
4019				autoplay:true,
4020				autoplayTimeout:1500,
4021				autoplayHoverPause:true,
4022				mouseDrag:false
4023			});
4024		});
4025	}
4026    var owl = $('.recently-carousel');
4027    owl.owlCarousel({
4028        loop: false,
4029        navRewind: false,
4030        nav: true,
4031		slideBy: 5,
4032        margin: 0,
4033        responsive:{
4034            0:{
4035                items: 1
4036            },
4037            600:{
4038                items: 3
4039            },
4040            1000:{
4041                items: 5
4042            }
4043        }
4044    });
4045    var owl = $('.majors-carousel');
4046    owl.owlCarousel({
4047        loop: false,
4048        navRewind: false,
4049        nav: true,
4050		slideBy: 5,
4051        margin: 0,
4052        responsive:{
4053            0:{
4054                items: 1
4055            },
4056            600:{
4057                items: 3
4058            },
4059            1000:{
4060                items: 5
4061            }
4062        }
4063    });
4064	$('.brands-carousel').show();
4065    var owl2 = $('.brands-carousel');
4066    owl2.owlCarousel({
4067        loop: false,
4068        navRewind: false,
4069        nav: true,
4070		slideBy: 4,
4071        margin: 0,
4072        responsive:{
4073            0:{
4074                items: 1
4075            },
4076            600:{
4077                items: 2
4078            },
4079            1000:{
4080                items: 4
4081            }
4082        }
4083    });
4084	$('.articles-carousel').show();
4085    var owl2 = $('.articles-carousel');
4086    owl2.owlCarousel({
4087        loop: false,
4088        navRewind: false,
4089        nav: true,
4090		slideBy: 4,
4091        margin: 0,
4092        responsive:{
4093            0:{
4094                items: 1
4095            },
4096            600:{
4097                items: 2
4098            },
4099            1000:{
4100                items: 4
4101            }
4102        }
4103    });
4104    $('.two-items-slider').owlCarousel({
4105        loop: true,
4106        nav: true,
4107        margin: 20,
4108        autoplay: true,
4109        autoplayTimeout: 5000,
4110        autoplayHoverPause: true,
4111        mouseDrag: false,
4112        responsiveClass:true,
4113        responsive:{
4114            0:{
4115                items:1,
4116                margin:0,
4117                nav:false
4118            },
4119            600:{
4120                items:1
4121            },
4122            1000:{
4123                items:2
4124            }
4125        }
4126    });
4127    $('.box-info, .select .options').mCustomScrollbar({
4128        theme: 'dark'
4129    });
4130    $('.horizontal-table-scroll').mCustomScrollbar({
4131        theme: 'dark',
4132        axis: 'x',
4133    });
4134    $('.add-fav').on('click', function(e){
4135        e.preventDefault();
4136        $(this).toggleClass('saved');
4137    });
4138    $('#toggle-price-range').on('click', function(e){
4139		e.preventDefault();
4140        $('#price-range').slideToggle(200);
4141    });
4142    $('.colors ul li').hover(function () {
4143        var datasrc = $(this).data('src');
4144        $('.show-img').attr('src', datasrc);
4145    },function(){
4146        var mainimg = $('.show-img').attr('data-img-src');
4147        $('.show-img').attr('src', mainimg);
4148    });
4149    $('.img-slider a').on('click', function (e) {
4150        e.preventDefault();
4151        var datasrc = $(this).data('img-click');
4152		var bigimg = $(this).data('big-img');
4153        $('.show-img').attr('src', datasrc);
4154		$('.main_img').attr('img-show', bigimg);
4155        $('.img-view').removeClass('active');
4156    });
4157	$('a.image-go-link').click(function(e){
4158		e.preventDefault();
4159		$('#'+$(this).attr('img-show')).trigger('click');
4160	});
4161    $('.play-icon').on('click', function(){
4162        $('.img-view').addClass('active');
4163    });
4164    var eventFired = 0;
4165    if ($(window).width() < 1024) {
4166        $('header .toggle-btn').on('click', function(){
4167            $(this).toggleClass('active');
4168            $('header ul.main-menu').toggleClass('active');
4169        });
4170    } else {
4171    }
4172    $(window).on('resize', function() {
4173        if (!eventFired) {
4174            if ($(window).width() < 1024) {
4175                $('header .toggle-btn').on('click', function(){
4176                    $(this).toggleClass('active');
4177                    $('header ul.main-menu').toggleClass('active');
4178                });
4179            } else {
4180            }
4181        }
4182    });
4183    jQuery('.tabs .tab-links a').on('click', function(e)  {
4184        var currentAttrValue = jQuery(this).attr('href');
4185        jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
4186        jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
4187        e.preventDefault();
4188    });
4189    if ($(window).width() <= 768) {
4190       $('.dropdown.box').removeClass('open');
4191       $('.head-inside-title').on('click', function(){
4192           $('.head-inside-content').toggleClass('active');
4193       });
4194       $('.filter-listing label').on('click', function(){
4195          $(this).next('.show-box').toggleClass('active');
4196       });
4197    }
4198
4199	// ======================================= ORDER ===================================================================
4200	if($('#suosId').length > 0){
4201		setTimeout(function(){ $('#goto_unicredit').submit(); }, 10000);
4202	}
4203	$('label.advance_payment').click(function(e){
4204		$('div.no-leasing').each(function(){
4205			if(!$(this).hasClass('pay_in_advance')){
4206				$(this).fadeIn();
4207			}
4208		});
4209		$('div.pay_in_advance').hide();
4210		$('#leasing').hide();
4211		$('div.payment_selected').find('div.has_advanced').show();
4212		$('#HOOK_ADVANCED_PAYMENT > div.is_leasing').hide();
4213		$('#order_bottom').prepend($('#invoice_comment'));
4214	});
4215	$('label.full_payment').click(function(e){
4216		if(($('#delivery_option_12').is(':checked') || $('#delivery_option_15').is(':checked')) && $('#total_order_price').val()*1 > 5112.41){
4217			$('div.no-leasing').each(function(){
4218				if(!$(this).hasClass('pay_in_advance')){
4219					$(this).fadeIn();
4220				}
4221			});
4222		}else{
4223			$('div.no-leasing').fadeIn();
4224			$('div.pay_in_advance').fadeIn();
4225		}
4226		$('div.has_advanced').hide();
4227		$('#leasing').hide();
4228		$('#order_bottom').prepend($('#invoice_comment'));
4229		$('#HOOK_ADVANCED_PAYMENT > div.is_leasing').hide();
4230	});
4231	$('label.leasing_payment').click(function(e){
4232		$('div.no-leasing').hide();
4233		$('#HOOK_ADVANCED_PAYMENT > div.is_leasing').fadeIn();
4234		$('#leasing').fadeIn();
4235		$('#login_column').prepend($('#invoice_comment'));
4236		$('#pay-method-leasing').attr('checked','checked');
4237		showHideArrows(696);
4238	});
4239	if($('#leasing_payment').is(':checked')){
4240		$('#login_column').prepend($('#invoice_comment'));
4241	}
4242	$('#order_sign_in').click(function(e){
4243		e.preventDefault();
4244		$('.register_order').removeClass('active');
4245		$('.regular_login').addClass('active');
4246		$('div.info_holder.login').fadeIn();
4247		$('div.info_holder.register').hide();
4248		$('div.info_holder.guest').hide();
4249	});
4250	$('#order_sign_up').click(function(e){
4251		e.preventDefault();
4252		$('.register_order').removeClass('active');
4253		$('.regular_login').addClass('active');
4254		$('div.info_holder.login').hide();
4255		$('div.info_holder.guest').hide();
4256		$('div.info_holder.register').fadeIn();
4257	});
4258	$('#order_guest').click(function(e){
4259		e.preventDefault();
4260		$('.register_order').removeClass('active');
4261		$('.regular_login').addClass('active');
4262		$('div.info_holder.login').hide();
4263		$('div.info_holder.register').hide();
4264		$('div.info_holder.guest').fadeIn();
4265	});
4266	$('div.order-now a.go_step_3').click(function(e){
4267		e.preventDefault();
4268		var new_phone=$('#new_phone').val()?$('#new_phone').val():'';
4269		if($('.sum_error').length > 0 && $('#leasing_payment').length > 0 && !$('input[name="pay-method"]').is(':checked')){
4270			return false;
4271		}
4272		if($('.special_error').length > 0 && $('#leasing_payment').length > 0){
4273			return false;
4274		}
4275		$('a.go_step_3').hide();
4276		$('p.order_error').remove();
4277		var has_error=0;
4278		if(!$('#cgv').is(':checked')){
4279			$(this).before('<p class="order_error">'+$('#cgv').attr('msg')+'</p>');
4280			has_error=1;
4281		}
4282		if(!$('input[name="delivery_option"]').is(':checked') || !$('input[name="delivery_option"]:checked').val()){
4283			$(this).before('<p class="order_error">'+$('input[name="delivery_option"]').attr('msg')+'</p>');
4284			has_error=1;
4285		}
4286		if($('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').attr('data-delivery')*1 == 1 && $('input[name="delivery_option"]:checked').val() == 15){
4287			$(this).before('<p class="order_error">'+$('input[name="delivery_option"]').attr('delivery-error')+'</p>');
4288			has_error=1;
4289		}
4290		if($('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() == 15 && !$('input[name="delivery-address"]').is(':checked')){
4291			$(this).before('<p class="order_error">'+$('a.show_address_popup').attr('msg')+'</p>');
4292			has_error=1;
4293		}
4294		if($('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() == 15 && $('input[name="delivery-address"]:checked').attr('data-phone') == '' && !new_phone){
4295			$(this).before('<p class="order_error">'+$('input[name="delivery-address"]:checked').attr('msg')+'<input type="text" name="new_phone" id="new_phone" value="'+new_phone+'" class="new_phone" placeholder="'+($('html').attr('lang') == 'en-US'?'Enter Phone Number':'Въведете телефонен номер')+'"></p>');
4296			has_error=1;
4297		}
4298		if($('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() == 12 && $('#office_id').attr('data-phone') == '' && !new_phone){
4299			$(this).before('<p class="order_error">'+$('#office_id').attr('msg')+'<input type="text" name="new_phone" id="new_phone" class="new_phone" value="'+new_phone+'" placeholder="'+($('html').attr('lang') == 'en-US'?'Enter Phone Number':'Въведете телефонен номер')+'"></p>');
4300			has_error=1;
4301		}
4302		if($('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() == 10 && !$('input[name="photo-sss"]').is(':checked')){
4303			$(this).before('<p class="order_error">'+$('input[name="photo-sss"]').attr('msg')+'</p>');
4304			has_error=1;
4305		}
4306		if($('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() == 10 && $('#client_phone').val() == '' && !new_phone){
4307			$(this).before('<p class="order_error">'+$('#client_phone').attr('msg')+'<input type="text" name="new_phone" id="new_phone" class="new_phone" value="'+new_phone+'" placeholder="'+($('html').attr('lang') == 'en-US'?'Enter Phone Number':'Въведете телефонен номер')+'"></p>');
4308			has_error=1;
4309		}
4310		if($('input[name="new_phone"]').length > 0){
4311			$('input[name="new_phone"]').keyup(function(){
4312				$(this).val($(this).val().replace(/[^0-9]/g,'')); 
4313			});
4314		}
4315		if($('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() == 15 && $('input[name="delivery-address"]:checked').attr('data-old-addr') == 1 && $('#door_carrier_id').val() == 2){
4316			$(this).before('<p class="order_error">'+($('html').attr('lang') == 'en-US'?'The address you selected is not compatible with the Speedy system. Please edit it and enter a neighborhood, street and / or block.':'Избраният адрес не е съвместим със системата на Спиди. Моля редактирайте го и въведете квартал, улица и/или блок.')+'</p>');
4317			has_error=1;
4318		}
4319		if(!$('input[name="pay-method"]').is(':checked')){
4320			$(this).before('<p class="order_error">'+$('input[name="pay-method"]').attr('msg')+'</p>');
4321			has_error=1;
4322		}
4323		var partial=$('#partial_payment_'+$('input[name="pay-method"]:checked').val()).val();
4324		var total_price=$('#total_order_price').val();
4325		if($('#advance_payment').is(':checked') && partial < 0.15*total_price){
4326			$(this).before('<p class="order_error">'+$('#partial_payment_'+$('input[name="pay-method"]:checked').val()).attr('msg')+'</p>');
4327			has_error=1;
4328		}
4329		if($('#first_name').val() == '' && $('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() != 15){
4330			$(this).before('<p class="order_error">'+$('#first_name').attr('msg')+'</p>');
4331			has_error=1;
4332		}
4333		if($('#last_name').val() == '' && $('input[name="delivery_option"]').is(':checked') && $('input[name="delivery_option"]:checked').val() != 15){
4334			$(this).before('<p class="order_error">'+$('#last_name').attr('msg')+'</p>');
4335			has_error=1;
4336		}
4337		if($('#id_payment').val()*1 == 0 && $('#id_credit').val()*1 == 0 && $('input[name="pay-method"]:checked').val() == 'leasing'){
4338			$(this).before('<p class="order_error">'+$('#id_payment').attr('msg')+'</p>');
4339			has_error=1;
4340		}
4341		if($('#leasing_name').val() == '' && $('input[name="pay-method"]:checked').val() == 'leasing' && $('#id_credit').val() != 12 && $('#id_credit').val() != 5){
4342			$(this).before('<p class="order_error">'+$('#leasing_name').attr('msg')+'</p>');
4343			has_error=1;
4344		}
4345		if($('#leasing_phone').val() == '' && $('input[name="pay-method"]:checked').val() == 'leasing' && $('#id_credit').val() != 12 && $('#id_credit').val() != 5){
4346			$(this).before('<p class="order_error">'+$('#leasing_phone').attr('msg')+'</p>');
4347			has_error=1;
4348		}
4349		if($('#leasing_email').val() == '' && $('input[name="pay-method"]:checked').val() == 'leasing' && $('#id_credit').val() != 12 && $('#id_credit').val() != 5){
4350			$(this).before('<p class="order_error">'+$('#leasing_email').attr('msg')+'</p>');
4351			has_error=1;
4352		}
4353		$('.app_agree').each(function(){
4354			if(!$(this).is(':checked') && $('input[name="pay-method"]:checked').val() == 'leasing' && $('#id_credit').val() != 12 && $('#id_credit').val() != 5){
4355				$('div.order-now a.go_step_3').before('<p class="order_error">'+$(this).attr('msg')+'</p>');
4356				has_error=1;
4357			}
4358		});
4359		$('#new_phone').on('paste', function(e) {
4360			e.preventDefault(); // спира paste
4361			let pastedText = (e.originalEvent.clipboardData || window.clipboardData).getData('text');
4362			let digitsOnly = pastedText.replace(/\D/g, '');
4363			document.execCommand("insertText", false, digitsOnly);
4364		});
4365
4366		$('#new_phone').on('input', function() {
4367			this.value = this.value.replace(/\D/g, '');
4368		});
4369		var missing_field_error=0;
4370		var credit_err=$('div.credit-form').attr('msg');
4371		$('div.credit-form div.input-group').each(function(){
4372			if($(this).is(':visible') && $(this).find('input').val() == ''){
4373				missing_field_error=1;
4374			}
4375			if($(this).is(':visible') && $(this).find('select').val() == ''){
4376				missing_field_error=1;
4377			}
4378			if($(this).is(':visible') && $(this).find('textarea').val() == ''){
4379				missing_field_error=1;
4380			}
4381		});
4382		if(missing_field_error == 1){
4383			$('div.order-now a.go_step_3').before('<p class="order_error">'+credit_err+'</p>');
4384			has_error=1;
4385		}
4386		if($($('#credit-table-schemes').find('td.selected')).length > 0){
4387			var el=$('#credit-table-schemes').find('td.selected');
4388			if(checkInitialValue($(el).attr('data-id'),el)*1 == 0){
4389				has_error=1;
4390			}
4391		}
4392		if(has_error){
4393			$('a.go_step_3').show();
4394			return false;
4395		}
4396		if($('#leasing_name').val() != '' && $('input[name="card_copy"]').prop('files')[0] != undefined && $('input[name="card_copy"]').prop('files')[0] != ''){
4397			var myFormData = new FormData();
4398			var files_cnt=$('input[name="files_cnt"]').val();
4399			var file ='';
4400			for(var i=0;i<files_cnt;i++){
4401				if(typeof $('input[name="card_copy"]').prop('files')[i] != 'undefined'){
4402					myFormData.append('IDcard_'+(i+1), $('input[name="card_copy"]').prop('files')[i]);
4403				}
4404			}
4405			myFormData.append('CardOwner', $('#leasing_name').val());
4406			myFormData.append('id_cart', $('#id_cart').val());
4407			myFormData.append('files_cnt', $('input[name="files_cnt"]').val());
4408
4409			$.ajax({
4410			  url: window.location.href.replace(/#.*$/,'')+'&upload_card=1',
4411			  type: 'POST',
4412			  processData: false, // important
4413			  contentType: false, // important
4414			  dataType : 'json',
4415			  data: myFormData,
4416				success: function(data){
4417					$.ajax({
4418						type: "POST",
4419						url: window.location.href.replace(/#.*$/,'')+'&save_order=1',
4420						data: {id_cart_rule:$('#id_cart_rule').val(),apllied_leasing:$('#apllied_leasing').val(),new_phone:new_phone,has_order:$('#has_order').val(),is_advanced:$('#advance_payment').is(':checked') || $('#has_order').val()?1:0,id_address_invoice:($('#vat').is(':checked')?$('#id_address_invoice').val():0),agreed:$('#app_agree').val(),first_name:$('div.credit-form').find('#first_name').val(),middle_name:$('#middle_name').val(),last_name:$('div.credit-form').find('#last_name').val(),egn:$('#app_egn').val(),card_id:$('#card_id').val(),issued_on:$('#issued_on').val(),issued_from:$('#issued_from').val(),live_in:$('#live_in').val(),live_since:$('#live_since').val(),mobile:$('#mobile').val(),landline:$('#landline').val(),email:$('#app_email').val(),city:$('#city').val(),postcode:$('#postcode').val(),address:$('#card_address').val(),marital_status:$('#marital_status').val(),education:$('#education').val(),leasing_id_payment:$('#id_payment').val(),leasing_glp:$('#glp').val(),leasing_gpr:$('#gpr').val(),leasing_monthly_payments:$('#monthly_payments').val(),leasing_id_credit:$('#id_credit').val(),leasing_months:$('#months').val(),leasing_full_amount:$('#full_amount').val(),leasing_installment:$('#installment').val(),leasing_name:$('#leasing_name').val(),leasing_phone:$('#leasing_phone').val(),leasing_email:$('#leasing_email').val(),payment_method:$('input[name="pay-method"]:checked').val(),delivery_company_id:($('input[name="delivery_option"]:checked').val() == 15?$('#door_carrier_id').val():$('#carrier_id').val()),delivery_city_id:$('#city_id').val(),id_cart:$('#id_cart').val(),id_carrier:$('input[name="delivery_option"]:checked').val(),id_address_delivery:$('input[name="delivery-address"]:checked').val(),payment_tp:$('#advance_payment').is(':checked') || $('#has_order').val()?2:1,partial_payment:$('#partial_payment_'+$('input[name="pay-method"]:checked').val()).val(),additional_info:$('#message').val(),phs_store_id:$('input[name="photo-sss"]:checked').val(),carrier_address_id:$('#office_id').val(),company_invoice:($('#vat').is(':checked')?1:0),cgv:$('#cgv').val()},
4421						success: function(data){
4422							if(data == 'ci'){
4423								location.href=window.location.href.replace(/#.*$/,'').replace(/step=2/,'step=1&ci=1');
4424							}else{
4425								location.href=window.location.href.replace(/#.*$/,'').replace(/step=2/,'step=3');
4426							}
4427						}
4428					});
4429				},
4430				error: function (xhr, ajaxOptions, thrownError) {
4431					$('div.order-now a.go_step_3').before('<p class="order_error">Грешка при прикачването на копието от личната карта</p>');
4432				}
4433			});
4434		}else{
4435			$.ajax({
4436				type: "POST",
4437				url: window.location.href.replace(/#.*$/,'')+'&save_order=1',
4438				data: {id_cart_rule:$('#id_cart_rule').val(),apllied_leasing:$('#apllied_leasing').val(),new_phone:new_phone,has_order:$('#has_order').val(),is_advanced:$('#advance_payment').is(':checked') || $('#has_order').val()?1:0,id_address_invoice:($('#vat').is(':checked')?$('#id_address_invoice').val():0),agreed:$('#app_agree').val(),first_name:$('div.credit-form').find('#first_name').val(),middle_name:$('#middle_name').val(),last_name:$('div.credit-form').find('#last_name').val(),egn:$('#app_egn').val(),card_id:$('#card_id').val(),issued_on:$('#issued_on').val(),issued_from:$('#issued_from').val(),live_in:$('#live_in').val(),live_since:$('#live_since').val(),mobile:$('#mobile').val(),landline:$('#landline').val(),email:$('#app_email').val(),city:$('#city').val(),postcode:$('#postcode').val(),address:$('#card_address').val(),marital_status:$('#marital_status').val(),education:$('#education').val(),leasing_id_payment:$('#id_payment').val(),leasing_glp:$('#glp').val(),leasing_gpr:$('#gpr').val(),leasing_monthly_payments:$('#monthly_payments').val(),leasing_id_credit:$('#id_credit').val(),leasing_months:$('#months').val(),leasing_full_amount:$('#full_amount').val(),leasing_installment:$('#installment').val(),leasing_name:$('#leasing_name').val(),leasing_phone:$('#leasing_phone').val(),leasing_email:$('#leasing_email').val(),payment_method:$('input[name="pay-method"]:checked').val(),delivery_company_id:($('input[name="delivery_option"]:checked').val() == 15?$('#door_carrier_id').val():$('#carrier_id').val()),delivery_city_id:$('#city_id').val(),id_cart:$('#id_cart').val(),id_carrier:$('input[name="delivery_option"]:checked').val(),id_address_delivery:$('input[name="delivery-address"]:checked').val(),payment_tp:$('#advance_payment').is(':checked') || $('#has_order').val()?2:1,partial_payment:$('#partial_payment_'+$('input[name="pay-method"]:checked').val()).val(),additional_info:$('#message').val(),phs_store_id:$('input[name="photo-sss"]:checked').val(),carrier_address_id:$('#office_id').val(),company_invoice:($('#vat').is(':checked')?1:0),cgv:$('#cgv').val()},
4439				success: function(data){
4440					if(data == 'ci'){
4441						location.href=window.location.href.replace(/#.*$/,'').replace(/step=2/,'step=1&ci=1');
4442					}else{
4443						location.href=window.location.href.replace(/#.*$/,'').replace(/step=2/,'step=3');
4444					}
4445				}
4446			});
4447		}
4448
4449		
4450		//alert(window.location.href);
4451
4452		
4453	});
4454	$('div.order-now a.go_step_2').click(function(e){
4455		e.preventDefault();
4456		var gotourl='';
4457		if(window.location.href.match(/step/)){
4458			gotourl=window.location.href.replace(/#.*$/,'').replace(/step=1/,'step=2');
4459		}else if(window.location.href.match(/\?/)){
4460			gotourl=window.location.href.replace(/#.*$/,'')+'&step=2';
4461		}else{
4462			gotourl=window.location.href.replace(/#.*$/,'')+'?step=2';
4463		}
4464		gtag_report_conversion(gotourl,$('#total_cart_price').val());
4465		if($('#gdpr_status').val()*1 == 2){
4466			$.ajax({
4467				type: "POST",
4468				url: '/external/fb.php',
4469				data: {id_cart:$('#id_cart').val(),device:'Phone'},
4470				success: function(data){
4471					console.log(data);
4472				}
4473			});
4474			showPopup($('div.gdpr'));
4475			return false;
4476		}
4477		if($(this).hasClass('not_logged')){
4478			$.ajax({
4479				type: "POST",
4480				url: '/external/fb.php',
4481				data: {id_cart:$('#id_cart').val(),device:'Phone'},
4482				success: function(data){
4483					console.log(data);
4484				}
4485			});
4486			$('.register_order').addClass('active');
4487			$('.overlay_2').addClass('active').css('z-index', '9999');
4488			return false;
4489		}else{
4490			$.ajax({
4491				type: "POST",
4492				url: '/external/fb.php',
4493				data: {id_cart:$('#id_cart').val(),device:'Desktop'},
4494				success: function(data){
4495					location.href=gotourl;
4496				}
4497			});
4498		}
4499	});
4500	$('#order_step a').click(function(e){
4501		if($(this).attr('href') == '#'){
4502			e.preventDefault();
4503		}
4504	});
4505	$('input[name="delivery_option"]').click(function(){
4506		if(!$('input[name="delivery-address"]').is(':checked')){
4507			$($('input[name="delivery-address"]').first()).attr('checked','checked');
4508		}
4509	});
4510	$('input.finish_order').click(function(e){
4511		e.preventDefault();
4512		$('div.payment_selected').find('form').submit();
4513	});
4514	if($('#HOOK_ADVANCED_PAYMENT').length > 0){
4515		$('#HOOK_ADVANCED_PAYMENT').find('input[name="pay-method"]').click(function(){
4516			$($(this).parent().parent()).find('.payment_selected').removeClass('payment_selected');
4517			$('#leasing').hide();
4518			$('.only_for_leasing').hide();
4519			if($(this).is(':checked')){
4520				$($(this).parent()).addClass('payment_selected');
4521				if($(this).attr('id') == 'pay-method-leasing' || ($('#initial_special').val() > 0 && !$('#has_order').val())){
4522					$('#leasing').show();
4523					$('.only_for_leasing').show();
4524				}else{
4525					$('#leasing').hide();
4526					$('.only_for_leasing').hide();
4527				}
4528			}
4529			if($('#advance_payment').is(':checked')){
4530				$($(this).parent()).find('div.has_advanced').fadeIn();
4531			}else{
4532				$($(this).parent()).find('div.has_advanced').hide();
4533			}
4534
4535		});
4536	}
4537	$('.slider_tabs a').click(function(e){
4538		e.preventDefault();
4539		var num=$(this).attr('data-number');
4540		$('#homepage-slider div.owl-item:nth-child('+num+')').trigger('click');
4541	});
4542	$('a.disabled_hover,div.delivery a').click(function(e){
4543		e.preventDefault();
4544	});
4545});

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.