Skip to content
Snippets Groups Projects
Commit 28b64167 authored by Kevin Abel's avatar Kevin Abel
Browse files

Port the search javascipt into a 4.0 style module

parent dfa7753c
Branches
No related tags found
No related merge requests found
(function(window) {
"use strict";
// Load the Google Search AJAX API var
google.load("search", "1"); initCallback = 'searchInit',
function searchInit() { // Service server (defaults to //directory.unl.edu)
UNL_Search.peoplefinderCache = new UNL_Search.Cache(); directoryServer = null,
//Parse the querystring for q unlContext = '015236299699564929946:nk1siew10ie',
var qs = window.location.search.substr(1);
var args = qs.split('&'); transitionDelay = 400,
UNL_Search.query = "";
for (var i = 0; i < args.length; i++) { inputSel = '#search_q',
var pair = args[i].split('='); formSel = '#searchform form',
if (decodeURIComponent(pair[0]) == "q") { resultSel = '.search-results',
if (pair.length == 2) { googleSel = '.google-results',
UNL_Search.query = decodeURIComponent(pair[1].replace(/\+/g, ' '));
} wrapperMain = '#search_wrapper',
break; wrapperWeb = '#search_results',
wrapperDir = '#directory_results',
dirResults = 'ppl_results',
unlResults = 'unl_results',
localResults = 'local_results';
window[initCallback] = function() {
delete window[initCallback];
require(['jquery', 'analytics'], function($, analytics) {
// Caching Class
var Cache = function() {
this.storage = {};
};
Cache.prototype.get = function(key) {
return this.storage[key] || undefined;
};
Cache.prototype.save = function(key, value) {
this.storage[key] = value;
return this;
};
// Directory Controller Class
var Directory = function(server, containerId) {
var cntSel = '#' + containerId;
this._server = server || '//directory.unl.edu';
this._cache = new Cache();
this._searchCanceled = false;
this._viewState = 0;
this._renderTo = cntSel;
$(function() {
$(cntSel).on('click', '.fn a', function() {
if (this.target !== '_blank') {
this.target = '_blank';
} }
});
});
};
Directory.prototype._render = function(data) {
if (this._searchCanceled) {
return;
} }
var unl_search = new google.search.CustomSearchControl("015236299699564929946:nk1siew10ie"); $(this._renderTo)
unl_search.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); .html(data)
unl_search.setSearchCompleteCallback(UNL_Search, UNL_Search.onSearchComplete); .addClass('active');
unl_search.setSearchStartingCallback(UNL_Search, UNL_Search.onSearchStart);
UNL_Search.unl_search = unl_search; this._renderState(0);
};
Directory.prototype._renderState = function(duration) {
var $innerRes = $('.results', $(this._renderTo)),
depFilter = '.departments';
drawOp = new google.search.DrawOptions(); $innerRes.slideUp(duration);
drawOp.enableSearchResultsOnly(); if (this._viewState === 0) {
$innerRes.not(depFilter).slideDown();
} else {
$innerRes.filter(depFilter).slideDown();
}
};
Directory.prototype.cancelSearch = function() {
this._searchCanceled = true;
};
Directory.prototype.execute = function(q) {
var cacheData = this._cache.get(q),
self = this;
unl_search.draw('unl_results', drawOp); this._searchCanceled = false;
if (UNL_Search.do_local_search) { if (cacheData) {
var local_search = new google.search.CustomSearchControl(UNL_Search.local_search_context); this._render(cacheData);
local_search.setResultSetSize('small');
local_search.setSearchCompleteCallback(UNL_Search, UNL_Search.onSearchComplete);
local_search.draw('local_results', drawOp);
UNL_Search.local_search = local_search;
}
WDN.loadJQuery(function() {
var $ = WDN.jQuery;
$('#search_q').attr('autocomplete', 'off').val(UNL_Search.query);
$('#searchform form').submit(function() {
var q = $.trim($('#search_q').val());
UNL_Search.query = q;
UNL_Search.pfCancelFlag = false;
if (q !== '') {
unl_search.execute(q);
} else { } else {
unl_search.cancelSearch(); $.get(this._server + '/service.php?q=' + encodeURIComponent(q), function(data) {
unl_search.clearAllResults(); self._cache.save(q, data);
if (UNL_Search.do_local_search) { self._render(data);
local_search.cancelSearch(); });
local_search.clearAllResults();
} }
UNL_Search.pfCancelFlag = true; };
$('#ppl_results').empty(); Directory.prototype.changeViewState = function(state) {
if (this._viewState == state) {
return;
} }
return false; this._viewState = state;
}); this._renderState();
}); };
Directory.prototype.clearAllResults = function() {
$(this._renderTo).empty();
};
var
// query related
query = '',
firstQ = window['INITIAL_QUERY'],
actCls = 'active',
// CustomSearchControl instances and config
unlSearch,
localSearch,
activeSearch,
directorySearch,
localContext = window['LOCAL_SEARCH_CONTEXT'],
drawOp = new google.search.DrawOptions(),
trackQuery = function(q) {
var loc = window.location,
qs = loc.search.replace(/(?:(\?)|&)q=[^&]*(?:&|$)/, '$1'),
page = [
loc.pathname,
qs || '?',
(qs && qs != '?') ? '&' : '',
'q=',
encodeURIComponent(q)
].join('');
//analytics.trackPageview(page);
// Execute an inital search if (window.history.pushState) {
if (UNL_Search.query) { window.history.pushState({query: q}, '', page);
unl_search.execute(UNL_Search.query);
} }
},
queryComplete = function(control) {
$(control.root).closest(resultSel).addClass(actCls).end()
.closest(googleSel).slideDown();
},
fullQuery = function(q, track) {
if (track !== false) {
trackQuery(q);
} }
activeSearch.execute(q);
directorySearch.execute(q);
$(wrapperMain).fadeIn();
},
fullStop = function() {
activeSearch.cancelSearch();
directorySearch.cancelSearch();
$(resultSel).removeClass(actCls);
$(wrapperMain).fadeOut();
setTimeout(function() {
activeSearch.clearAllResults();
directorySearch.clearAllResults();
}, transitionDelay);
},
queryStart = function(control, searcher, q) {
$(control.root).closest(googleSel).slideUp(0);
if (q !== query) {
trackQuery(q);
directorySearch.execute(q);
}
};
//Attach search initializer to onLoad drawOp.enableSearchResultsOnly();
google.setOnLoadCallback(searchInit, true);
unlSearch = activeSearch = new google.search.CustomSearchControl(unlContext);
unlSearch.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
unlSearch.setSearchCompleteCallback(window, queryComplete);
unlSearch.setSearchStartingCallback(window, queryStart);
// if (localContext) {
// UNL_Search Namespace localSearch = activeSearch = new google.search.CustomSearchControl(localContext);
// localSearch.setResultSetSize('small');
if (typeof(UNL_Search) == "undefined") localSearch.setSearchCompleteCallback(window, queryComplete);
UNL_Search = {}; localSearch.setSearchStartingCallback(window, queryStart);
}
UNL_Search.query = null; directorySearch = new Directory(directoryServer, dirResults);
UNL_Search.do_local_search = false;
UNL_Search.unl_search = null;
UNL_Search.local_search = null;
UNL_Search.local_search_context = null;
UNL_Search.peoplefinderCache = null;
UNL_Search.pfCancelFlag = false;
//Caching Class // Setup DOM on ready
// $(function() {
UNL_Search.Cache = {}; var $q = $(inputSel),
UNL_Search.Cache = function() {
this.storage = new Object();
};
UNL_Search.Cache.prototype.save = function(key, data) { tabsSel = '.result-tab',
this.storage[key] = data; selCls = 'selected',
}; stateClsPfx = 'state-',
$resTabs = $('.result-tab'),
UNL_Search.Cache.prototype.get = function (key) { googleOrigin = /^https?:\/\/www\.google\.com$/,
var val = null;
if (this.storage[key] != null) { passiveQuery = function(q, track) {
val = this.storage[key]; if (query === q) {
return;
} }
return val; query = q;
}; $q.val(q);
UNL_Search.onSearchStart = function(control, searcher, query) { if (q) {
UNL_Search.doPeoplefinderQuery(query); fullQuery(q, track);
if (UNL_Search.do_local_search) { } else {
UNL_Search.local_search.execute(query); fullStop();
} }
UNL_Search.trackQuery(control, searcher, query);
}; };
UNL_Search.onSearchComplete = function(control, searcher) { // draw the Google search controls
var $ = WDN.jQuery; unlSearch.draw(unlResults, drawOp);
/* The more URL no longer works on google's host
if (searcher && searcher.cursor && searcher.cursor.pages.length >= 8) {
var $moreDiv = $("<div />").html('More&hellip;').addClass('gsc-cursor-page').click(function() {
window.location.href = searcher.cursor.moreResultsUrl;
return false;
});
$('.gsc-cursor-box .gsc-cursor', control.root).append($moreDiv);
}
*/
if (searcher.cursor && searcher.cursor.estimatedResultCount) { if (localContext) {
var $resultHead = $("<div />").addClass('result_head').text('About ' + searcher.cursor.estimatedResultCount + ' results'); localSearch.draw(localResults, drawOp);
$('.result_head', control.root).remove();
$('.gsc-results', control.root).before($resultHead);
} }
if (mobileSearch) { //if we're doing a mobile search, rewrite link URLs to use mobile proxy // setup the tab-like result filters
$('a.gs-title', control.root).each(function() { $('li:first-child', $resTabs).addClass(selCls);
$(this).attr('href', function(i, val) { $($resTabs).on('click', 'li', function(e) {
return 'http://m.unl.edu/?view=proxy&u=' + encodeURIComponent(val); e.preventDefault();
})
}); if ($(this).hasClass(selCls)) {
} return;
} }
UNL_Search.trackQuery = function(control, searcher, query) { var i = $(this).index(),
var loc = document.location; j = $(this).siblings('.' + selCls).index(),
var url = [ $tab = $(this).closest(tabsSel),
loc.pathname, $par = $(this).parents('.results-group');
loc.search,
loc.search ? '&' : '?', $tab.removeClass(stateClsPfx + j);
'q=', $tab.addClass(stateClsPfx + i);
encodeURIComponent(query)
].join(''); $(this).siblings().removeClass(selCls);
$(this).addClass(selCls);
try { if ($par.is(wrapperDir)) {
if (typeof WDN.analytics !== 'undefined') { directorySearch.changeViewState(i);
WDN.analytics.callTrackPageview(url); } else if ($par.is(wrapperWeb)) {
$(activeSearch.root).closest(googleSel).slideUp();
if (i === 0) {
activeSearch = localSearch;
} else { } else {
_gaq.push(["_trackPageview", url]); activeSearch = unlSearch;
} }
} catch (e) {
// do nothing activeSearch.execute(query);
} }
}; });
UNL_Search.doPeoplefinderQuery = function (val) { // listen for the submit event
var cacheData = this.peoplefinderCache.get(val) $(formSel).submit(function(e) {
if (cacheData) { e.preventDefault();
this.handlePeoplefinderResults(cacheData);
} else { var q = $.trim($q.val());
var pointer = this; passiveQuery(q);
WDN.loadJQuery(function(){
WDN.get("http://directory.unl.edu/service.php?q=" + encodeURIComponent(val), null, function(data, textStatus) {
pointer.peoplefinderCache.save(val, data);
UNL_Search.handlePeoplefinderResults(data);
}); });
// issue an inital query
if (firstQ) {
passiveQuery(firstQ, false);
}
// listen for message from parent frames
$(window).on('message', function(e) {
var oEvent = e.originalEvent, q;
if (googleOrigin.test(oEvent.origin)) {
return;
}
q = $.trim(oEvent.data);
passiveQuery(q);
}); });
$(window).on('popstate', function(e) {
var oEvent = e.originalEvent,
q = firstQ || '';
if (oEvent.state) {
q = oEvent.state.query || '';
} }
passiveQuery(q, false);
});
});
});
}; };
UNL_Search.handlePeoplefinderResults = function (peoplefinderText) { window['pf_getUID'] = function() {
if (!UNL_Search.pfCancelFlag) { return true;
document.getElementById("ppl_results").innerHTML = peoplefinderText;
}
}; };
}(window));
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment