/*
#
#	Auto complete search system
#	by Marc Qualie
#	designed to work with Mootools 1.2.3
#
*/

var aComplete = {
	
	dUrl		: 'ajax/search.php',					// Default URL
	bx			: {},									// Search boxes will appear here when created
	cache		: {},
	rLim		: 10,
	
	// Create new auto search
	create : function(objID, options) {
		
		// Check if already defined, or invalid
		if (objID.indexOf('_') > -1) return console.warn('You cannot use underscores in ID\'s for aComplete Class ('+objID+')');
		if (aComplete.bx[objID]) return;
		aComplete.bx[objID] = {};
		
		// Define
		var obj = $(objID);
		if (!obj) return;
		if (!options) var options = {};
		obj.addEvent('keyup', aComplete.show);
		obj.addEvent('focus', function() {
			aComplete.bx[this.id].robj.fade('in');
			aComplete.show(this);
			if (aComplete.bx[this.id].options.onfocus) aComplete.bx[this.id].options.onfocus(this);
		});
		obj.addEvent('blur', function() {
			aComplete.bx[this.id].robj.fade('out');
			aComplete.show(this);
			if (aComplete.bx[this.id].options.onblur) aComplete.bx[this.id].options.onblur(this);
		});
		obj.coords = obj.getCoordinates();
		obj.setAttribute('autocomplete', 'off');
		aComplete.bx[objID].obj = obj;
		aComplete.bx[objID].options = options;
		aComplete.bx[objID].status = 'loading';
		
		// Create result box
		var rb = $(document.createElement('div'));
		rb.setStyles({
			position: 'absolute',
			opacity: 0,
			textAlign: 'left',
			padding: obj.getStyle('padding-left'),
			borderStyle: obj.getStyle('border-style'),
			borderWidth: obj.getStyle('border-width'),
			borderColor: obj.getStyle('border-color'),
			borderTop: 'none',
			left: (obj.coords.left) + 'px',
			width: parseInt(obj.getStyle('width')) + 'px',
			top: ((obj.coords.top + obj.clientHeight) + 'px')
		});
		rb.className = 'ac_container';
		rb.innerHTML = "<div id='cache_"+objID+"_st' class='ac_st'>Start typing..</div>";
		//rb.inject(obj, 'after');
		document.body.appendChild(rb);
		aComplete.bx[objID].robj = rb;
		
		// Get data, set variables
		var r = new Request.JSON({
			url: (options.url ? options.url : aComplete.dUrl),
			onSuccess: aComplete.result,
			secure: true
		}).send('objID=' + objID + (options.postData  ? "&" + options.postData : ''));
		
	},
	
	// Show results
	show : function(this_obj) {
		var t = this_obj.target ? this_obj.target : this_obj;
		if (aComplete.bx[t.id].status != 'ready') return console.info('Not ready yet..');
		var rc = 0;
		var mb = $('cache_' + t.id + '_st');
		for (var c = 0; c < aComplete.cache[t.id]['data'].length; c++) {
			var cb = $('cache_' + t.id + '_' + c);
			var mt = false;
			
			// Loop through searching
			if (t.value.length > 0 && rc < aComplete.rLim) {
				var s = aComplete.cache[t.id]['data'][c].title.toString().toLowerCase().split(' ');
				var vs = t.value.toLowerCase().match(/(\w+)/g);
				var vc = 0;
				for (var i2 = 0; i2 < vs.length; i2++ ) {
					for (var i = 0; i < s.length; i++ ) {
						if (s[i].indexOf(vs[i2]) === 0 && s[i].length > 0 && vs[i2].length > 0)  vc++;
					}
				}
				if (vc == vs.length) mt = true;
			}
			
			if (mt) {
				if (cb.style.display != 'block') cb.style.display = 'block';
				rc ++;
			} else {
				if (cb.style.display != 'none') cb.style.display = 'none';
			}
		}
		if (rc < 1 && t.value.length > 0) { mb.style.display = 'block'; mb.innerHTML = 'No results, press enter to do full search.'; }
		else if (rc < 1 && t.value.length < 1) { mb.style.display = 'block'; mb.innerHTML = 'Start typing..'; }
		else { mb.style.display = 'none'; mb.innerHTML = ''; }
	},
	click : function() {
		var s = this.id.split('_');
		/*
		var u = aComplete.cache[s[1]]['data'][s[2]].url;
		if (u) document.location.href = u;
		*/
		aComplete.cache[s[1]].root.value = aComplete.cache[s[1]]['data'][s[2]].title;
	},
	
	// Default result functions, any can be used
	//	function({ objID, data: [{ id, title, url, icon, count }] })
	result : function(rJSON, rText) {
		if (!rJSON || !rJSON.objID) return;
		aComplete.cache[rJSON.objID] = { root: $(rJSON.objID), data: [] };
		for (var i = 0; i < rJSON.data.length; i++ ) {
			aComplete.cache[rJSON.objID]['data'][i] = rJSON.data[i];
			var cb = $(document.createElement('div'));
			cb.id = "cache_" + rJSON.objID + "_" + i;
			cb.className = 'ac_res';
			cb.style.display = 'none';
			cb.addEvent('click', aComplete.click);
			cb.innerHTML = typeof (rJSON.data[i].title) == 'string' ? (rJSON.data[i].title.length > 0 ? rJSON.data[i].title : 'invalid-title') : 'no-title';
			if (rJSON.data[i].url) cb.title = rJSON.data[i].url;
			if (rJSON.data[i].icon) { cb.addClass('ac_icon'); cb.style.backgroundImage = "url(" + rJSON.data[i].icon + ")"; }
			aComplete.bx[rJSON.objID].robj.appendChild(cb);
		}
		aComplete.bx[rJSON.objID].status = 'ready';
	}
	
}