(function ($, window, localStorage) { var $searchBox, $searchInput, $searchSubmit, $searchClear, $suggestionBox, inputTiming, suggestTiming, suggestReq, prevQuery, suggestCache, queryStrings, origin; try { // Try to get prev cache, it will throw error when failed suggestCache = JSON.parse(localStorage.getItem('suggestions')); for (var i = 0; i < suggestCache.length; i++) { if (getDateDiffWithNow(suggestCache[i].datetime) >= 1440) { delete suggestCache[i]; i -= 1; } } } catch (e) { suggestCache = []; } queryStrings = getQueryStrings(); $(function () { // Find all elements previously $searchBox = $('#advan-header .search-Mainbox, .old-search-portal .search-Mainbox'); $searchInput = $searchBox.find('.search-input'); $searchSubmit = $searchBox.find('.search-btnSubmit'); $searchClear = $searchBox.find('.search-btnClear'); $suggestionBox = $('#advan-header .search-suggestionBox, .old-search-portal .search-suggestionBox'); var $toggleSearch = $('#header-search'); if ($toggleSearch.attr('data-api-baseurl')) { origin = $toggleSearch.attr('data-api-baseurl'); } else { origin = window.location.protocol + '//' + window.location.host; } bindEvents(); prepareTemplate(); }); function bindEvents() { $('#advan-header').find('#search-panel') .on('headerSearch.advantech', function (e, isVisible) { var $elem = $(this), $input = $elem.find('.search-input'); if (isVisible) { $input.focus(); } }) .find('form').on('submit', function (e) { var $elem = $(this), $input = $elem.find('.search-input'), val = $.trim($input.val()); if (val) { clearSuggestRequest(); clearSuggestTiming(); gotoResults(val); } e.preventDefault(); return false; }); $searchInput .on('keyup change', function (e) { var $elem = $(this), $suggestionBox = $elem.parents('.search-Mainbox').next('.search-suggestionBox'), val = $elem.val(); // Enable suggestion to be selected by up or down key if (!$suggestionBox.is(':empty')) { var $suggestions = $suggestionBox.find('.search-suggestion-select'), selectedIndex = -1; $suggestions.each(function (i) { var $suggestion = $(this); if ($suggestion.hasClass('search-select-focus')) { selectedIndex = i; return false; } }); if (e.keyCode === 38) { // up key $suggestions.removeClass('search-select-focus'); if (selectedIndex === -1) { $suggestions.eq($suggestions.length - 1).addClass('search-select-focus'); } else if (selectedIndex !== 0) { $suggestions.eq(selectedIndex - 1).addClass('search-select-focus'); } return false; } else if (e.keyCode === 40) { // down key $suggestions.removeClass('search-select-focus'); if (selectedIndex !== $suggestions.length + 1) { $suggestions.eq(selectedIndex + 1).addClass('search-select-focus'); } return false; } else if (e.keyCode === 13) { // If user already selected any item in suggestion list, go to the url of selected item when press enter key if (selectedIndex !== -1) { var url = $suggestions.eq(selectedIndex).attr('href'); window.location.href = url; return false; } } } // Ignored searching when value is not changed and has searched if (prevQuery === val && !$suggestionBox.is(':empty')) { return; } else { prevQuery = val; } if (val) { $elem.siblings('.search-btnClear').show(); } else { $elem.siblings('.search-btnClear').hide(); } if (val && val.length > 2) { clearSuggestTiming(); suggestTiming = window.setTimeout(function () { suggestTiming = null; suggest(val, $suggestionBox); }, 250); } else { clearSuggestRequest(); clearSuggestTiming(); clearSuggestBox($suggestionBox); } }) .on('focus', function () { var $elem = $(this), $suggestionBox = $elem.parents('.search-Mainbox').next('.search-suggestionBox'), val = $elem.val(); if (val && val.length > 2 && val === prevQuery) { if ($suggestionBox.is(':empty')) { $elem.trigger('change'); } else { $suggestionBox.slideDown(); } } //This interval is for detects cut or past situations on input inputTiming = window.setInterval(function () { var val = $elem.val(); if (val && val.length > 2 && prevQuery !== val) { $elem.trigger('change'); } }, 50); }) .on('blur', function () { window.clearInterval(inputTiming); }) .on('abortSuggest.advantech', function () { var $elem = $(this), $suggestionBox = $elem.parents('.search-Mainbox').next('.search-suggestionBox'); clearSuggestRequest(); clearSuggestTiming(); $suggestionBox.slideUp(); }); $searchClear.on('click', function () { var $elem = $(this), $input = $elem.siblings('.search-input'), $suggestionBox = $elem.parents('.search-Mainbox').next('.search-suggestionBox'); $elem.hide(); $input.val('').focus(); clearSuggestBox($suggestionBox); }); $suggestionBox.on('mouseenter', 'a.search-suggestion-select', function (e) { var $suggestionBox = $(e.delegateTarget), $entered = $(this); $suggestionBox.find('.search-suggestion-select').removeClass('search-select-focus'); $entered.addClass('search-select-focus'); }); $suggestionBox.on('click', 'a', function (e) { if (window.ga) { ga('send', 'event', 'CorpSearchItem', 'click', 'HeaderAutocomplete'); } }); $('#header-search').on('click', function () { var $searchPanel = $('#advan-header').find('#search-panel'); if ($searchPanel.is(':visible')) { $searchPanel.find('.search-input').trigger('focus'); } }); } function gotoResults(q) { var domain = (queryStrings['domain']) ? queryStrings['domain'] : window.location.hostname; q = encodeQuery(q); if (domain.toLowerCase() === 'www.advantech.com.cn') { window.location.href = 'http://so.advantech.com.cn/cse/search?s=7885849405176408867&q=' + q; } else { if (window.history && window.history.pushState) { window.location.href = origin + '/products/search/?q=' + q; } else { window.location.href = origin + '/products/search/#?q=' + q; } } } function suggest(term, $suggestionBox) { if ($suggestionBox.length === 0) { return; } var q = encodeQuery(term); getSuggests( q, function (data) { renderSuggest(data, $suggestionBox); } ); } function getSuggests(q, success, error) { clearSuggestRequest(); // Find prev cache var cacheData = findCache(q); if (cacheData) { if ($.isFunction(success)) { success(cacheData); } } else { suggestReq = $.ajax({ url: origin + '/api/search/getsuggests', data: { q: q, domain: (queryStrings['domain']) ? queryStrings['domain'] : '' }, timeout: 180000, success: function (data) { suggestReq = null; cacheSuggest(q, data); if ($.isFunction(success)) { success(data); } }, error: function (xhr, status, err) { suggestReq = null; if ($.isFunction(error)) { error(xhr, status, err); } } }); } } function renderSuggest(data, $suggestionBox) { var $productTemplate = $suggestionBox.data('productTemplate'), $resourceTemplate = $suggestionBox.data('resourceTemplate'), $separateTemplate = $suggestionBox.data('separateTemplate'), products = data.products, resources = data.resources, downloads = data.downloads, i, $template; $suggestionBox.empty(); if (products.length === 0 && resources.length === 0 && downloads.length === 0) { $suggestionBox.slideUp(); return; } if (products.length > 0) { for (i = 0; i < products.length; i++) { $template = $productTemplate.clone(); renderSuggestProduct($template, products[i]); $suggestionBox.append($template); } } if (resources.length > 0) { if (products.length > 0) { $suggestionBox.append($separateTemplate.clone()); } for (i = 0; i < resources.length; i++) { $template = $resourceTemplate.clone(); renderSuggestResource($template, resources[i]); $suggestionBox.append($template); } } $suggestionBox.slideDown(); } function renderSuggestProduct($template, data) { $template.attr('href', data.url); $template.find('[data-products-title]').text(data.name); $template.find('[data-products-desc]').html(data.desc); } function renderSuggestResource($template, data) { $template.attr('href', data.url); $template.find('[data-resouces-title]').text(data.name); $template.find('[data-resouces-desc]').html(data.desc); $template.find('[data-resouces-type]').text(data.type_second); } function clearSuggestBox($suggestionBox) { $suggestionBox.slideUp(function () { $(this).empty(); }); } function clearSuggestTiming() { if (suggestTiming) { window.clearTimeout(suggestTiming); suggestTiming = null; } } function clearSuggestRequest() { if (suggestReq) { suggestReq.abort(); suggestReq = null; } } function encodeQuery(val) { return window.encodeURIComponent(val).replace(/\%20/g, '+'); } function prepareTemplate() { $searchBox.each(function () { var $elem = $(this), $suggestionBox = $elem.next('.search-suggestionBox'), $productTemplate = $suggestionBox.find('#suggest-products-template').removeAttr('id style'), $resourceTemplate = $suggestionBox.find('#suggest-resources-template').removeAttr('id style'), $separateTemplate = $suggestionBox.find('#suggest-separate-template').removeAttr('id style'); $suggestionBox.data('productTemplate', $productTemplate.detach()); $suggestionBox.data('resourceTemplate', $resourceTemplate.detach()); $suggestionBox.data('separateTemplate', $separateTemplate.detach()); $suggestionBox.empty(); }); } function cacheSuggest(q, data) { if (suggestCache.length > 30) { suggestCache.pop(); } suggestCache.push({ q: q, results: data, datetime: new Date() }); try { localStorage.setItem('suggestions', JSON.stringify(suggestCache)); } catch (e) { } } function findCache(q) { var dataIndex = -1, i = 0, len = suggestCache.length, data = null, temp; for (; i < len; i++) { if (suggestCache[i].q === q) { dataIndex = i; data = suggestCache[i].results; break; } } if (dataIndex > 0 && suggestCache.length > 1) { temp = suggestCache[dataIndex]; suggestCache[dataIndex] = suggestCache[dataIndex - 1]; suggestCache[dataIndex - 1] = temp; } return data; } function getDateDiffWithNow(date) { if (typeof date === 'string') { date = new Date(date); } return Math.round(Math.abs((new Date() - date) / 1000) / 60); } function getQueryStrings() { var searchStr = window.location.search.substring(1), result = {}; if (searchStr) { var searchs = searchStr.split('&'); $.each(searchs, function (k, v) { if (!$.trim(v)) return true; var pairs = $.trim(v).split('='); if (pairs.length === 2 && pairs[0]) { result[pairs[0]] = pairs[1]; } }); } return result; } }(jQuery, window, window.localStorage));