PageSourceSearch

https://manodelfriki.com/modules/pm_advancedsearch4/views/js/pm_advancedsearch.js

js manodelfriki.com collected 2026-10-04 13:24:59 UTC 14,696 bytes, 286 lines download raw bytes

1/**
2 *
3 * Advanced Search 5 Pro
4 *
5 * @author Presta-Module.com <[email protected]>
6 * @copyright Presta-Module
7 *
8 *           ____     __  __
9 *          |  _ \   |  \/  |
10 *          | |_) |  | |\/| |
11 *          |  __/   | |  | |
12 *          |_|      |_|  |_|
13 *
14 ****/
15
16/* Events than can be implemented for custom integration or interaction (with Google Analytics Events for example) */
17/*
18$(document).on('as4-Before-Init-Search-Block', function(e, idSearch, searchMethod, stepSearch) {});
19$(document).on('as4-After-Init-Search-Block', function(e, idSearch, searchMethod, stepSearch) {});
20$(document).on('as4-Criterion-Change', function(e, idSearch, idCriterionGroup, idCriterion, criterionName, groupType) {});
21$(document).on('as4-Before-Response-Callback', function(e) {});
22$(document).on('as4-After-Response-Callback', function(e) {});
23$(document).on('as4-Before-Set-Results-Contents', function(e, idSearch, context) {});
24$(document).on('as4-After-Set-Results-Contents', function(e, idSearch, context) {});
25$(document).on('as4-Search-Reset', function(e, idSearch) {});
26$(document).on('as4-Criterion-Group-Reset', function(e, idSearch, idCriterionGroup) {});
27$(document).on('as4-Criterion-Group-Skip', function(e, idSearch, idCriterionGroup, searchMethod) {});
28*/
29
30/*!
31 * hoverIntent v1.8.0 // 2014.06.29 // jQuery v1.9.1+
32 * http://cherne.net/brian/resources/jquery.hoverIntent.html
33 *
34 * You may use hoverIntent under the terms of the MIT license. Basically that
35 * means you are free to use hoverIntent as long as this header is left intact.
36 * Copyright 2007, 2014 Brian Cherne
37 */
38(function($){$.fn.hoverIntent=function(handlerIn,handlerOut,selector){var cfg={interval:100,sensitivity:6,timeout:0};if(typeof handlerIn==="object"){cfg=$.extend(cfg,handlerIn)}else{if($.isFunction(handlerOut)){cfg=$.extend(cfg,{over:handlerIn,out:handlerOut,selector:selector})}else{cfg=$.extend(cfg,{over:handlerIn,out:handlerIn,selector:handlerOut})}}var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if(Math.sqrt((pX-cX)*(pX-cX)+(pY-cY)*(pY-cY))<cfg.sensitivity){$(ob).off("mousemove.hoverIntent",track);ob.hoverIntent_s=true;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=false;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=$.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type==="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).on("mousemove.hoverIntent",track);if(!ob.hoverIntent_s){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).off("mousemove.hoverIntent",track);if(ob.hoverIntent_s){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.on({"mouseenter.hoverIntent":handleHover,"mouseleave.hoverIntent":handleHover},cfg.selector)}})(jQuery);
39
40/**
41 * https://github.com/SaneMethod/jquery-ajax-localstorage-cache
42 */
43;
44(function($, window) {
45    /**
46     * Generate the cache key under which to store the local data - either the cache key supplied,
47     * or one generated from the url, the type and, if present, the data.
48     */
49    var genCacheKey = function(options) {
50        var url = options.url.replace(/jQuery.*/, '');
51
52        // Strip _={timestamp}, if cache is set to false
53        if (options.cache === false) {
54            url = url.replace(/([?&])_=[^&]*/, '');
55        }
56        if (options.data) {
57            return (as4Plugin.localCacheKey || '') + (options.cacheKey || url + '?' + options.data + options.type);
58        } else {
59            return (as4Plugin.localCacheKey || '') + (options.cacheKey || url + options.type + (options.data || ''));
60        }
61    };
62    /**
63     * Prefilter for caching ajax calls.
64     * See also $.ajaxTransport for the elements that make this compatible with jQuery Deferred.
65     * New parameters available on the ajax call:
66     * localCache   : true // required - either a boolean (in which case localStorage is used), or an object
67     * implementing the Storage interface, in which case that object is used instead.
68     * cacheTTL     : 5,           // optional - cache time in hours, default is 5.
69     * cacheKey     : 'post',      // optional - key under which cached string will be stored
70     * isCacheValid : function  // optional - return true for valid, false for invalid
71     * @method $.ajaxPrefilter
72     * @param options {Object} Options for the ajax call, modified with ajax standard settings
73     */
74    $.ajaxPrefilter(function(options) {
75        var storage = (options.localCache === true) ? window.localStorage : options.localCache,
76            hourstl = options.cacheTTL || 5,
77            cacheKey = genCacheKey(options),
78            cacheValid = options.isCacheValid,
79            ttl,
80            value;
81
82        // Check if localStorage is available
83        if (!storage || (storage && !as4Plugin.isLocalStorageAvailable())) {
84            return;
85        }
86        ttl = storage.getItem(cacheKey + 'cachettl');
87
88        if (cacheValid && typeof cacheValid === 'function' && !cacheValid()) {
89            storage.removeItem(cacheKey);
90        }
91
92        if (ttl && ttl < +new Date()) {
93            storage.removeItem(cacheKey);
94            storage.removeItem(cacheKey + 'cachettl');
95            ttl = 0;
96        }
97
98        value = storage.getItem(cacheKey);
99        if (!value) {
100            // If it not in the cache, we store the data, add success callback - normal callback will proceed
101            if (options.success) {
102                options.realsuccess = options.success;
103            }
104            options.success = function(data) {
105                var strdata = data;
106                if (this.dataType.toLowerCase().indexOf('json') === 0) strdata = JSON.stringify(data);
107
108                // Save the data to storage catching exceptions (possibly QUOTA_EXCEEDED_ERR)
109                try {
110                    storage.setItem(cacheKey, strdata);
111                } catch (e) {
112                    // Remove any incomplete data that may have been saved before the exception was caught
113                    storage.removeItem(cacheKey);
114                    storage.removeItem(cacheKey + 'cachettl');
115                }
116
117                if (options.realsuccess) options.realsuccess(data);
118            };
119
120            // store timestamp
121            if (!ttl) {
122                storage.setItem(cacheKey + 'cachettl', +new Date() + 1000 * 60 * 60 * hourstl);
123            }
124        }
125    });
126
127    /**
128     * This function performs the fetch from cache portion of the functionality needed to cache ajax
129     * calls and still fulfill the jqXHR Deferred Promise interface.
130     * See also $.ajaxPrefilter
131     * @method $.ajaxTransport
132     * @params options {Object} Options for the ajax call, modified with ajax standard settings
133     */
134    $.ajaxTransport("+*", function(options) {
135        if (options.localCache) {
136            var cacheKey = genCacheKey(options),
137                storage = (options.localCache === true) ? window.localStorage : options.localCache,
138                value = (storage) ? storage.getItem(cacheKey) : false;
139
140            if (value) {
141                // In the cache? Get it, parse it to json if the dataType is JSON,
142                // and call the completeCallback with the fetched value.
143                if (options.dataType.toLowerCase().indexOf('json') === 0) value = JSON.parse(value);
144                return {
145                    send: function(headers, completeCallback) {
146                        var response = {};
147                        response[options.dataType] = value;
148                        completeCallback(200, 'success', response, '');
149                    },
150                    abort: function() {
151                        console.log("Aborted ajax transport for json cache.");
152                    }
153                };
154            }
155        }
156    });
157})(jQuery, window);
158
159window.addEventListener('load', function () {
160    // Fix Safari issue that is firing onpopstate on page load (instead of all other browsers)
161    setTimeout(function() {
162        window.addEventListener('popstate', function (event) {
163            if (typeof(event.state) != 'undefined' && event.state != null && typeof(event.state.id_search) != 'undefined' && !isNaN(event.state.id_search)) {
164                if (typeof(event.state.stateFromInit) != 'undefined' && event.state.stateFromInit && as4Plugin.isSafari()) {
165                    if (!isNaN(as4Plugin.previousOnPopState) && as4Plugin.previousOnPopState != null && as4Plugin.previousOnPopState > 0) {
166                        // Previous page was generated by AS4, refresh this one
167                        as4Plugin.previousOnPopState = null;
168                        // Reload current page
169                        location.reload();
170                    } else {
171                        as4Plugin.previousOnPopState = null;
172                    }
173                    return;
174                }
175                // Set event source flag
176                as4Plugin.fromBackForwardEvent = true;
177                formOptionsObject = as4Plugin.getASFormOptions(event.state.id_search);
178                // Replace data from the old one
179                formOptionsObject.data = $.param(event.state.formSerializedArray) + '&' + $.param(event.state.formOptionsData);
180                formOptionsObject.url = $('#PM_ASForm_' + event.state.id_search).attr('action');
181                formOptionsObject.form = $('#PM_ASForm_' + event.state.id_search);
182                // Submit new search query (data from history)
183                $.ajax(formOptionsObject);
184                as4Plugin.previousOnPopState = event.state.id_search;
185            } else {
186                if (typeof(prestashop) != 'object') {
187                    if (!isNaN(as4Plugin.previousOnPopState) && as4Plugin.previousOnPopState != null && as4Plugin.previousOnPopState > 0) {
188                        // Previous page was generated by AS4, refresh this one
189                        as4Plugin.previousOnPopState = null;
190                        // Reload current page
191                        location.reload();
192                    } else {
193                        as4Plugin.previousOnPopState = null;
194                    }
195                }
196            }
197        });
198    }, 500);
199});
200
201$(document).on('as4-After-Init-Search-Block', function(e, idSearch, searchMethod, stepSearch) {
202    // Let's save form state after search engine init, only if it's not coming from a back/forward browser event
203    if (typeof(prestashop) == 'object') {
204        if (!as4Plugin.fromBackForwardEvent) {
205            as4Plugin.pushNewState(idSearch, true);
206        }
207    }
208});
209
210$(document).on('as4-Before-Set-Results-Contents', function(e, idSearch, context) {
211    // Let's save form state just before result is updated, only if it's not coming from a back/forward browser event
212    if (!as4Plugin.fromBackForwardEvent) {
213        as4Plugin.pushNewState(idSearch);
214    }
215
216    // Let's prepare GA event to announce a that search results is available
217    eventLabel = [];
218    availableCriterionsGroups = as4Plugin.getParamValue(idSearch, 'availableCriterionsGroups');
219    $.each(as4Plugin.getParamValue(idSearch, 'selectedCriterions'), function(idCriterionGroup, selectedCriterions) {
220        $.each(selectedCriterions, function(index2, selectedCriterion) {
221            eventLabel.push(availableCriterionsGroups[idCriterionGroup] + ': ' + selectedCriterion.value);
222        });
223    });
224    // Send GA Event
225    as4Plugin.sendGAEvent('Advanced Search', 'Show Results', eventLabel.join(', '))
226});
227
228// Do something when a new criterion is selected
229$(document).on('as4-Criterion-Change', function(e, idSearch, idCriterionGroup, idCriterion, criterionName, groupType) {
230    step_search = as4Plugin.getParamValue(idSearch, 'stepSearch');
231    search_method = as4Plugin.getParamValue(idSearch, 'searchMethod');
232
233    // Send GA Event
234    availableCriterionsGroups = as4Plugin.getParamValue(idSearch, 'availableCriterionsGroups');
235    as4Plugin.sendGAEvent('Advanced Search', 'Criterion Selected', availableCriterionsGroups[idCriterionGroup] + ': ' + criterionName)
236
237    if (step_search == 1) {
238        as4Plugin.nextStep(idSearch, search_method);
239    } else {
240        as4Plugin.runSearch(idSearch, search_method);
241    }
242});
243
244// PrestaShop 1.7 specific
245if (typeof(prestashop) == 'object') {
246    prestashop.on('responsive update', function(event) {
247        as4Plugin.initMobileStyles();
248    });
249    prestashop.on('updateProductList', function(event) {
250        if (typeof(as4Plugin) == 'object' && typeof(event.id_search) != 'undefined' && !isNaN(event.id_search)) {
251            scrollTopActive = as4Plugin.getParamValue(event.id_search, 'scrollTopActive');
252            if (!scrollTopActive) {
253                if (typeof(event.without_products) == 'undefined') {
254                    // Native ajax call
255                    as4Plugin.scrollTop(event.id_search, 'updateProductList', (scrollTopActive == false));
256                }
257            } else {
258                if (typeof(event.without_products) == 'undefined') {
259                    as4Plugin.scrollTop(event.id_search, 'updateProductList', (scrollTopActive == false));
260                } else {
261                    if (!event.without_products) {
262                        as4Plugin.scrollTop(event.id_search, 'updateProductList', (event.without_products == false));
263                    }
264                }
265            }
266        }
267        // Retrieve 'order' parameter from URL in case the order is changed by the user
268        // and assign it to our 'orderby' hidden input
269        if (typeof(as4Plugin) == 'object') {
270            setTimeout(function() {
271                var currentUrlParams = window.location.href.substring(window.location.href.indexOf('?', 0));
272                var orderRegexp = new RegExp(/[?&]order=\w+\.\w+\.\w+/);
273
274                // If we find a order parameter in the URL, we retrieve its value, and assign it to our input
275                if (currentUrlParams.match(orderRegexp)) {
276                    var matchedOrder = currentUrlParams.match(orderRegexp)[0];
277                    var cleanedMatchedOrder = matchedOrder.substr(matchedOrder.indexOf('=', 0) + 1);
278                    if (cleanedMatchedOrder.length > 0) {
279                        $('.PM_ASForm input[name="orderby"]').prop('disabled', false);
280                        $('.PM_ASForm input[name="orderby"]').val(cleanedMatchedOrder);
281                    }
282                }
283            }, 100);
284        }
285    });
286}

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.