
	/** 
	 * handles autocomplete functionality
	 * uses JQuery UI autocomplete widget, ie. a UI build with the following components from http://jqueryui.com/download :
	 * CORE, WIDGET, POSITION, AUTOCOMPLETE
	 */
	 
	$(function(){
		
		var AUTOCOMPLETE = {
		
			filters : {} ,
		
			/* urlencode a single character, used by urlEncode() */
			urlEncodeCharacter  : function (c) {
				return '%' + c.charCodeAt(0).toString(16);
			} ,

			/* encode a string for use as URL - ie. equivalent to PHP's urlencode() */
			urlEncode : function (s) {
				s = (s+'').toString();
				return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /[!'()*]/g, AUTOCOMPLETE.urlEncodeCharacter);
			} ,
			
			/* Read a page's GET URL variables and return them as an associative array. */
			getUrlVars : function (arr) {
				if (!arr) {
					return [];
				}
				var vars = [], hash;
				var hashes = arr.split('&');
				for (var i = 0; i < hashes.length; i++) {
					hash = hashes[i].split('=');
					vars[hash[0]] = hash[1];
				}
				return vars;
			} ,

			/* create a URL query string from an associative array */
			urlFromArray : function (arr) {
				var url = '';
				for (var i in arr) {
					url += (url=='' || arr[i]=='') ? '' : '&';
					url += (arr[i]=='') || (arr[i].length == 0) ? '' : AUTOCOMPLETE.urlEncode(i) + '=' + AUTOCOMPLETE.urlEncode(arr[i]);
				}
				return url;
			} ,
			
			/* the setup function */
			setup : function () {
				$.prettyLoader({
					loader: 'images/prettyLoader/ajax-loader.gif' ,
					bind_to_ajax: true
				});
				//$(document).bind("ajaxStart", function(){ $.prettyLoader.show() }).bind("ajaxStop", function(){ $.prettyLoader.hide() });
				AUTOCOMPLETE.filter();
				AUTOCOMPLETE.suggest();
			} ,
			
			filter : function () {
				var $forms = $("form.grid");
				$forms.each (function() {
					/* grid data */
					
					var $id = $(this).attr('id');
					
					/* AJAX for filter */
					
					$('#'+$id).live('submit', function () {
						var $form = $(this);
						var $id = $form.attr('id');
						var $serial = $form.serialize();
						var $action = $form.attr('action');
						var $filters = AUTOCOMPLETE.getUrlVars($serial);
						var $url = AUTOCOMPLETE.urlFromArray($filters);
						$.get($action+'?'+$url, function (data) {
								AUTOCOMPLETE.filter_response($form.parent(), $id, $filters, data);
							}
						);
						return false;
					});
					
					/* AJAX for page jump */
					
					$('#grid_wrap_'+$id+' form.page_jump').live('submit', function () {
						var $form = $(this);
						var $serial = $form.serialize();
						var $action = $form.attr('action');
						var $filters = AUTOCOMPLETE.getUrlVars($serial);
						var $url = AUTOCOMPLETE.urlFromArray($filters);
						$.get($action+'?'+$url, function (data) {
								AUTOCOMPLETE.filter_response($('#grid_wrap_'+$id), $id, $filters, data);
							}
						);
						return false;
					});
					
					/* AJAX for page selection */
					
					$('#grid_wrap_'+$id+' div.meta a').live ( 'click', function () {
						var $a = $(this);
						var href = $a.attr('href');
						var $form = $('#'+$id);
						var $action = $form.attr('action');
						var $url, $filters;
						
						$filters = href.indexOf('?');
						$filters = ($filters==-1) ? [] : AUTOCOMPLETE.getUrlVars(href.slice($filters + 1));
						$url = AUTOCOMPLETE.urlFromArray($filters);
						
						$.get($action+'?'+$url, function (data) {
								AUTOCOMPLETE.filter_response($form.parent(), $id, $filters, $(data));
							}
						);
						
						return false;
					});
					
					/* AJAX for column ordering */
					
					$('#grid_wrap_'+$id+' th a').live ( 'click', function () {
						var $a = $(this);
						var href = $a.attr('href');
						var $form = $('#'+$id);
						var $action = $form.attr('action');
						var $url, $filters;
						
						$filters = href.indexOf('?');
						$filters = ($filters==-1) ? [] : AUTOCOMPLETE.getUrlVars(href.slice($filters + 1));
						$url = AUTOCOMPLETE.urlFromArray($filters);
						
						$.get($action+'?'+$url, function (data) {
								AUTOCOMPLETE.filter_response($form.parent(), $id, $filters, $(data));
							}
						);
						
						return false;
					});

				});
			} ,
			
			
			filter_response : function ($me, $id, $filters, $data) {
				$trs_new = $("tr", $data);

				if ($trs_new.length <= 3) {
					/* remove previous filters */
					AUTOCOMPLETE.filters[$id] = [];
				}
				else {
					/* remember the filters that have been applied */
					AUTOCOMPLETE.filters[$id] = $filters;
				}

				/* get old 2nd row from top = filter boxes */
				$trs = $('tr', $me).slice(1,2);
				
				/* remove new 2 top rows */
				$trs_new.slice(1,2).remove();
				/* insert old 2 rows before new rows */
				$("tr:first", $data).after($trs);
				/* replace grid with new grid */
				$me.replaceWith($data);
				AUTOCOMPLETE.suggest();
			} ,
			

			/* the main autocomplete setup function */
			suggest : function () {
			
				var $gets = window.location.href.indexOf('?');
				$gets = ($gets==-1) ? [] : AUTOCOMPLETE.getUrlVars(window.location.href.slice($gets + 1));
	
				var grid_data = {};
		
				var $forms = $("form.grid");
				
				$forms.each (function() {
					/* grid data */
					var $form = $(this);
					var $id = $form.attr('id');
					var $action = $form.attr('action');
					var $filters = $gets;
					grid_data[$id] = {
						action : $action ,
						filters : $filters
					};
					/* inputs */
					var $inputs = $("input:text", $form);
					$inputs.each (function() {
						var $me = $(this);
						var field = $(this).attr('name');
						
						$me.autocomplete({
							source: function(req, add) {
								$tmp = $filters;

								/* if filters have been set by previous AJAX filtering, apply them */
								if (AUTOCOMPLETE.filters[$id]) {
									$filters_prev = AUTOCOMPLETE.filters[$id];
									for (i in $filters_prev) {
										$tmp[i] = $filters_prev[i];
									}
								}
								/* do not use the field we are requesting an autocomplete for as a filter */
								delete $tmp[field];

								$url = AUTOCOMPLETE.urlFromArray($tmp);
								if ($url.length!=0) {
									$url += '&';
								}
								$url += 'field=' + field + '&value=' + AUTOCOMPLETE.urlEncode(req.term) + '&autocomplete=1';

								$.getJSON($action, $url, function(data) {
									var suggestions = [];
									var p;
									$.each(data, function(i, row){
										p = {};
										p.value = row.pop;
										p.label = row.box;
										suggestions.push(p);
									});
									add(suggestions);
								});
							} ,
							focus: function( event, ui ) {
								this.value =  ui.item.value;
								return false;
							}

						});
						
					});
				});
					
			}

		}
		
		AUTOCOMPLETE.setup();
		
	});

