outward.company.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. (function($) {
  2. var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
  3. function fnFormatResult(value, data, currentValue) {
  4. var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
  5. return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
  6. }
  7. function Autocomplete(el, options) {
  8. this.el = $(el);
  9. this.el.attr('autocomplete', 'off');
  10. this.suggestions = [];
  11. this.data = [];
  12. this.badQueries = [];
  13. this.selectedIndex = -1;
  14. this.currentValue = this.el.val();
  15. this.intervalId = 0;
  16. this.cachedResponse = [];
  17. this.onChangeInterval = null;
  18. this.ignoreValueChange = false;
  19. this.serviceUrl = options.serviceUrl;
  20. this.isLocal = false;
  21. this.options = {
  22. autoSubmit: false,
  23. minChars: 1,
  24. maxHeight: 300,
  25. deferRequestBy: 0,
  26. width: 0,
  27. highlight: true,
  28. params: {},
  29. fnFormatResult: fnFormatResult,
  30. delimiter: null,
  31. zIndex: 9999
  32. };
  33. this.initialize();
  34. this.setOptions(options);
  35. }
  36. $.fn.autocomplete = function(options) {
  37. return new Autocomplete(this.get(0)||$('<input />'), options);
  38. };
  39. Autocomplete.prototype = {
  40. killerFn: null,
  41. initialize: function() {
  42. var me, uid, autocompleteElId;
  43. me = this;
  44. uid = Math.floor(Math.random()*0x100000).toString(16);
  45. autocompleteElId = 'Autocomplete_' + uid;
  46. this.killerFn = function(e) {
  47. if ($(e.target).parents('.autocomplete').size() === 0) {
  48. me.killSuggestions();
  49. me.disableKillerFn();
  50. }
  51. };
  52. if (!this.options.width) { this.options.width = this.el.width(); }
  53. this.mainContainerId = 'AutocompleteContainter_' + uid;
  54. $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body');
  55. this.container = $('#' + autocompleteElId);
  56. this.fixPosition();
  57. if (window.opera) {
  58. this.el.keypress(function(e) { me.onKeyPress(e); });
  59. } else {
  60. this.el.keydown(function(e) { me.onKeyPress(e); });
  61. }
  62. this.el.keyup(function(e) { me.onKeyUp(e); });
  63. this.el.blur(function() { me.enableKillerFn(); });
  64. this.el.focus(function() { me.fixPosition(); });
  65. },
  66. setOptions: function(options){
  67. var o = this.options;
  68. $.extend(o, options);
  69. if(o.lookup){
  70. this.isLocal = true;
  71. if($.isArray(o.lookup)){ o.lookup = { suggestions:o.lookup, data:[] }; }
  72. }
  73. $('#'+this.mainContainerId).css({ zIndex:o.zIndex+9999 });
  74. this.container.css({ maxHeight: o.maxHeight + 'px', width:o.width});
  75. },
  76. clearCache: function(){
  77. this.cachedResponse = [];
  78. this.badQueries = [];
  79. },
  80. disable: function(){
  81. this.disabled = true;
  82. },
  83. enable: function(){
  84. this.disabled = false;
  85. },
  86. fixPosition: function() {
  87. var offset = this.el.offset();
  88. $('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight())-2 + 'px', left: offset.left + 'px' });
  89. },
  90. enableKillerFn: function() {
  91. var me = this;
  92. $(document).bind('click', me.killerFn);
  93. },
  94. disableKillerFn: function() {
  95. var me = this;
  96. $(document).unbind('click', me.killerFn);
  97. },
  98. killSuggestions: function() {
  99. var me = this;
  100. this.stopKillSuggestions();
  101. this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300);
  102. },
  103. stopKillSuggestions: function() {
  104. window.clearInterval(this.intervalId);
  105. },
  106. onKeyPress: function(e) {
  107. if (this.disabled || !this.enabled) { return; }
  108. // return will exit the function
  109. // and event will not be prevented
  110. switch (e.keyCode) {
  111. case 27: //KEY_ESC:
  112. this.el.val(this.currentValue);
  113. this.hide();
  114. break;
  115. case 9: //KEY_TAB:
  116. case 13: //KEY_RETURN:
  117. if (this.selectedIndex === -1) {
  118. this.hide();
  119. return;
  120. }
  121. this.select(this.selectedIndex);
  122. if(e.keyCode === 9){ return; }
  123. break;
  124. case 38: //KEY_UP:
  125. this.moveUp();
  126. break;
  127. case 40: //KEY_DOWN:
  128. this.moveDown();
  129. break;
  130. default:
  131. return;
  132. }
  133. e.stopImmediatePropagation();
  134. e.preventDefault();
  135. },
  136. onKeyUp: function(e) {
  137. if(this.disabled){ return; }
  138. switch (e.keyCode) {
  139. case 38: //KEY_UP:
  140. case 40: //KEY_DOWN:
  141. return;
  142. }
  143. clearInterval(this.onChangeInterval);
  144. if (this.currentValue !== this.el.val()) {
  145. if (this.options.deferRequestBy > 0) {
  146. // Defer lookup in case when value changes very quickly:
  147. var me = this;
  148. this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy);
  149. } else {
  150. this.onValueChange();
  151. }
  152. }
  153. },
  154. onValueChange: function() {
  155. clearInterval(this.onChangeInterval);
  156. this.currentValue = this.el.val();
  157. var q = this.getQuery(this.currentValue);
  158. this.selectedIndex = -1;
  159. if (this.ignoreValueChange) {
  160. this.ignoreValueChange = false;
  161. return;
  162. }
  163. if (q === '' || q.length < this.options.minChars) {
  164. this.hide();
  165. } else {
  166. this.getSuggestions(q);
  167. }
  168. },
  169. getQuery: function(val) {
  170. var d, arr;
  171. d = this.options.delimiter;
  172. if (!d) { return $.trim(val); }
  173. arr = val.split(d);
  174. return $.trim(arr[arr.length - 1]);
  175. },
  176. getSuggestionsLocal: function(q) {
  177. var ret, arr, len, val, i;
  178. arr = this.options.lookup;
  179. len = arr.suggestions.length;
  180. ret = { suggestions:[], data:[] };
  181. q = q.toLowerCase();
  182. for(i=0; i< len; i++){
  183. val = arr.suggestions[i];
  184. if(val.toLowerCase().indexOf(q) === 0){
  185. ret.suggestions.push(val);
  186. ret.data.push(arr.data[i]);
  187. }
  188. }
  189. return ret;
  190. },
  191. getSuggestions: function(q) {
  192. var cr, me;
  193. cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];
  194. if (cr && $.isArray(cr.suggestions)) {
  195. this.suggestions = cr.suggestions;
  196. this.data = cr.data;
  197. this.suggest();
  198. } else if (!this.isBadQuery(q)) {
  199. me = this;
  200. me.options.params.query = q;
  201. $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text');
  202. }
  203. },
  204. isBadQuery: function(q) {
  205. var i = this.badQueries.length;
  206. while (i--) {
  207. if (q.indexOf(this.badQueries[i]) === 0) { return true; }
  208. }
  209. return false;
  210. },
  211. hide: function() {
  212. this.enabled = false;
  213. this.selectedIndex = -1;
  214. this.container.hide();
  215. },
  216. suggest: function() {
  217. if (this.suggestions.list.length === 0) {
  218. this.hide();
  219. return;
  220. }
  221. var me, len, div, f, v, i, s, mOver, mClick;
  222. me = this;
  223. len = this.suggestions.list.length;
  224. f = this.options.fnFormatResult;
  225. v = this.getQuery(this.currentValue);
  226. mOver = function(xi) { return function() { me.activate(xi); }; };
  227. mClick = function(xi, id) { return function() {
  228. $("#company_id").val(id);
  229. me.select(xi); }; };
  230. this.container.hide().empty();
  231. for (i = 0; i < len; i++) {
  232. s = this.suggestions.list[i];
  233. div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + s.companyname + '">' + f(s.companyname, this.data[i], v) + '</div>');
  234. div.mouseover(mOver(i));
  235. div.click(mClick(i,s.id));
  236. this.container.append(div);
  237. }
  238. this.enabled = true;
  239. this.container.show();
  240. },
  241. processResponse: function(text) {
  242. var response;
  243. try {
  244. response = eval('(' + text + ')');
  245. } catch (err) { return; }
  246. if (!response.data) { return false; }
  247. if(!this.options.noCache){
  248. this.cachedResponse[response.data.query] = response;
  249. if (response.data.suggestions.length === 0) { this.badQueries.push(response.data.query); }
  250. }
  251. if (response.data.query === this.getQuery(this.currentValue)) {
  252. this.suggestions = response.data.suggestions;
  253. this.data = response.data;
  254. this.suggest();
  255. }
  256. },
  257. activate: function(index) {
  258. var divs, activeItem;
  259. divs = this.container.children();
  260. // Clear previous selection:
  261. if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
  262. $(divs.get(this.selectedIndex)).removeClass();
  263. }
  264. this.selectedIndex = index;
  265. if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
  266. activeItem = divs.get(this.selectedIndex);
  267. $(activeItem).addClass('selected');
  268. }
  269. return activeItem;
  270. },
  271. deactivate: function(div, index) {
  272. div.className = '';
  273. if (this.selectedIndex === index) { this.selectedIndex = -1; }
  274. },
  275. select: function(i) {
  276. var selectedValue, f;
  277. selectedValue = this.suggestions.list[i].companyname;
  278. if (selectedValue) {
  279. this.el.val(selectedValue);
  280. if (this.options.autoSubmit) {
  281. f = this.el.parents('form');
  282. if (f.length > 0) { f.get(0).submit(); }
  283. }
  284. this.ignoreValueChange = true;
  285. this.hide();
  286. this.onSelect(i);
  287. }
  288. },
  289. moveUp: function() {
  290. if (this.selectedIndex === -1) { return; }
  291. if (this.selectedIndex === 0) {
  292. this.container.children().get(0).className = '';
  293. this.selectedIndex = -1;
  294. this.el.val(this.currentValue);
  295. return;
  296. }
  297. this.adjustScroll(this.selectedIndex - 1);
  298. },
  299. moveDown: function() {
  300. if (this.selectedIndex === (this.suggestions.list.length - 1)) { return; }
  301. this.adjustScroll(this.selectedIndex + 1);
  302. },
  303. adjustScroll: function(i) {
  304. var activeItem, offsetTop, upperBound, lowerBound;
  305. activeItem = this.activate(i);
  306. offsetTop = activeItem.offsetTop;
  307. upperBound = this.container.scrollTop();
  308. lowerBound = upperBound + this.options.maxHeight - 25;
  309. if (offsetTop < upperBound) {
  310. this.container.scrollTop(offsetTop);
  311. } else if (offsetTop > lowerBound) {
  312. this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
  313. }
  314. this.el.val(this.getValue(this.suggestions.list[i]));
  315. },
  316. onSelect: function(i) {
  317. var me, fn, s, d;
  318. me = this;
  319. fn = me.options.onSelect;
  320. s = me.suggestions[i];
  321. d = me.data[i];
  322. me.el.val(me.getValue(s));
  323. if ($.isFunction(fn)) { fn(s, d, me.el); }
  324. },
  325. getValue: function(value){
  326. value = value.companyname;
  327. var del, currVal, arr, me;
  328. me = this;
  329. del = me.options.delimiter;
  330. if (!del) { return value; }
  331. currVal = me.currentValue;
  332. arr = currVal.split(del);
  333. if (arr.length === 1) { return value; }
  334. return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
  335. }
  336. };
  337. }(jQuery));